three.webgpu.js 1.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '167dev';
  7. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  8. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  9. const CullFaceNone = 0;
  10. const CullFaceBack = 1;
  11. const CullFaceFront = 2;
  12. const CullFaceFrontBack = 3;
  13. const BasicShadowMap = 0;
  14. const PCFShadowMap = 1;
  15. const PCFSoftShadowMap = 2;
  16. const VSMShadowMap = 3;
  17. const FrontSide = 0;
  18. const BackSide = 1;
  19. const DoubleSide = 2;
  20. const NoBlending = 0;
  21. const NormalBlending = 1;
  22. const AdditiveBlending = 2;
  23. const SubtractiveBlending = 3;
  24. const MultiplyBlending = 4;
  25. const CustomBlending = 5;
  26. const AddEquation = 100;
  27. const SubtractEquation = 101;
  28. const ReverseSubtractEquation = 102;
  29. const MinEquation = 103;
  30. const MaxEquation = 104;
  31. const ZeroFactor = 200;
  32. const OneFactor = 201;
  33. const SrcColorFactor = 202;
  34. const OneMinusSrcColorFactor = 203;
  35. const SrcAlphaFactor = 204;
  36. const OneMinusSrcAlphaFactor = 205;
  37. const DstAlphaFactor = 206;
  38. const OneMinusDstAlphaFactor = 207;
  39. const DstColorFactor = 208;
  40. const OneMinusDstColorFactor = 209;
  41. const SrcAlphaSaturateFactor = 210;
  42. const ConstantColorFactor = 211;
  43. const OneMinusConstantColorFactor = 212;
  44. const ConstantAlphaFactor = 213;
  45. const OneMinusConstantAlphaFactor = 214;
  46. const NeverDepth = 0;
  47. const AlwaysDepth = 1;
  48. const LessDepth = 2;
  49. const LessEqualDepth = 3;
  50. const EqualDepth = 4;
  51. const GreaterEqualDepth = 5;
  52. const GreaterDepth = 6;
  53. const NotEqualDepth = 7;
  54. const MultiplyOperation = 0;
  55. const MixOperation = 1;
  56. const AddOperation = 2;
  57. const NoToneMapping = 0;
  58. const LinearToneMapping = 1;
  59. const ReinhardToneMapping = 2;
  60. const CineonToneMapping = 3;
  61. const ACESFilmicToneMapping = 4;
  62. const CustomToneMapping = 5;
  63. const AgXToneMapping = 6;
  64. const NeutralToneMapping = 7;
  65. const AttachedBindMode = 'attached';
  66. const DetachedBindMode = 'detached';
  67. const UVMapping = 300;
  68. const CubeReflectionMapping = 301;
  69. const CubeRefractionMapping = 302;
  70. const EquirectangularReflectionMapping = 303;
  71. const EquirectangularRefractionMapping = 304;
  72. const CubeUVReflectionMapping = 306;
  73. const RepeatWrapping = 1000;
  74. const ClampToEdgeWrapping = 1001;
  75. const MirroredRepeatWrapping = 1002;
  76. const NearestFilter = 1003;
  77. const NearestMipmapNearestFilter = 1004;
  78. const NearestMipMapNearestFilter = 1004;
  79. const NearestMipmapLinearFilter = 1005;
  80. const NearestMipMapLinearFilter = 1005;
  81. const LinearFilter = 1006;
  82. const LinearMipmapNearestFilter = 1007;
  83. const LinearMipMapNearestFilter = 1007;
  84. const LinearMipmapLinearFilter = 1008;
  85. const LinearMipMapLinearFilter = 1008;
  86. const UnsignedByteType = 1009;
  87. const ByteType = 1010;
  88. const ShortType = 1011;
  89. const UnsignedShortType = 1012;
  90. const IntType = 1013;
  91. const UnsignedIntType = 1014;
  92. const FloatType = 1015;
  93. const HalfFloatType = 1016;
  94. const UnsignedShort4444Type = 1017;
  95. const UnsignedShort5551Type = 1018;
  96. const UnsignedInt248Type = 1020;
  97. const UnsignedInt5999Type = 35902;
  98. const AlphaFormat = 1021;
  99. const RGBFormat = 1022;
  100. const RGBAFormat = 1023;
  101. const LuminanceFormat = 1024;
  102. const LuminanceAlphaFormat = 1025;
  103. const DepthFormat = 1026;
  104. const DepthStencilFormat = 1027;
  105. const RedFormat = 1028;
  106. const RedIntegerFormat = 1029;
  107. const RGFormat = 1030;
  108. const RGIntegerFormat = 1031;
  109. const RGBIntegerFormat = 1032;
  110. const RGBAIntegerFormat = 1033;
  111. const RGB_S3TC_DXT1_Format = 33776;
  112. const RGBA_S3TC_DXT1_Format = 33777;
  113. const RGBA_S3TC_DXT3_Format = 33778;
  114. const RGBA_S3TC_DXT5_Format = 33779;
  115. const RGB_PVRTC_4BPPV1_Format = 35840;
  116. const RGB_PVRTC_2BPPV1_Format = 35841;
  117. const RGBA_PVRTC_4BPPV1_Format = 35842;
  118. const RGBA_PVRTC_2BPPV1_Format = 35843;
  119. const RGB_ETC1_Format = 36196;
  120. const RGB_ETC2_Format = 37492;
  121. const RGBA_ETC2_EAC_Format = 37496;
  122. const RGBA_ASTC_4x4_Format = 37808;
  123. const RGBA_ASTC_5x4_Format = 37809;
  124. const RGBA_ASTC_5x5_Format = 37810;
  125. const RGBA_ASTC_6x5_Format = 37811;
  126. const RGBA_ASTC_6x6_Format = 37812;
  127. const RGBA_ASTC_8x5_Format = 37813;
  128. const RGBA_ASTC_8x6_Format = 37814;
  129. const RGBA_ASTC_8x8_Format = 37815;
  130. const RGBA_ASTC_10x5_Format = 37816;
  131. const RGBA_ASTC_10x6_Format = 37817;
  132. const RGBA_ASTC_10x8_Format = 37818;
  133. const RGBA_ASTC_10x10_Format = 37819;
  134. const RGBA_ASTC_12x10_Format = 37820;
  135. const RGBA_ASTC_12x12_Format = 37821;
  136. const RGBA_BPTC_Format = 36492;
  137. const RGB_BPTC_SIGNED_Format = 36494;
  138. const RGB_BPTC_UNSIGNED_Format = 36495;
  139. const RED_RGTC1_Format = 36283;
  140. const SIGNED_RED_RGTC1_Format = 36284;
  141. const RED_GREEN_RGTC2_Format = 36285;
  142. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  143. const LoopOnce = 2200;
  144. const LoopRepeat = 2201;
  145. const LoopPingPong = 2202;
  146. const InterpolateDiscrete = 2300;
  147. const InterpolateLinear = 2301;
  148. const InterpolateSmooth = 2302;
  149. const ZeroCurvatureEnding = 2400;
  150. const ZeroSlopeEnding = 2401;
  151. const WrapAroundEnding = 2402;
  152. const NormalAnimationBlendMode = 2500;
  153. const AdditiveAnimationBlendMode = 2501;
  154. const TrianglesDrawMode = 0;
  155. const TriangleStripDrawMode = 1;
  156. const TriangleFanDrawMode = 2;
  157. const BasicDepthPacking = 3200;
  158. const RGBADepthPacking = 3201;
  159. const TangentSpaceNormalMap = 0;
  160. const ObjectSpaceNormalMap = 1;
  161. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  162. const NoColorSpace = '';
  163. const SRGBColorSpace = 'srgb';
  164. const LinearSRGBColorSpace = 'srgb-linear';
  165. const DisplayP3ColorSpace = 'display-p3';
  166. const LinearDisplayP3ColorSpace = 'display-p3-linear';
  167. const LinearTransfer = 'linear';
  168. const SRGBTransfer = 'srgb';
  169. const Rec709Primaries = 'rec709';
  170. const P3Primaries = 'p3';
  171. const ZeroStencilOp = 0;
  172. const KeepStencilOp = 7680;
  173. const ReplaceStencilOp = 7681;
  174. const IncrementStencilOp = 7682;
  175. const DecrementStencilOp = 7683;
  176. const IncrementWrapStencilOp = 34055;
  177. const DecrementWrapStencilOp = 34056;
  178. const InvertStencilOp = 5386;
  179. const NeverStencilFunc = 512;
  180. const LessStencilFunc = 513;
  181. const EqualStencilFunc = 514;
  182. const LessEqualStencilFunc = 515;
  183. const GreaterStencilFunc = 516;
  184. const NotEqualStencilFunc = 517;
  185. const GreaterEqualStencilFunc = 518;
  186. const AlwaysStencilFunc = 519;
  187. const NeverCompare = 512;
  188. const LessCompare = 513;
  189. const EqualCompare = 514;
  190. const LessEqualCompare = 515;
  191. const GreaterCompare = 516;
  192. const NotEqualCompare = 517;
  193. const GreaterEqualCompare = 518;
  194. const AlwaysCompare = 519;
  195. const StaticDrawUsage = 35044;
  196. const DynamicDrawUsage = 35048;
  197. const StreamDrawUsage = 35040;
  198. const StaticReadUsage = 35045;
  199. const DynamicReadUsage = 35049;
  200. const StreamReadUsage = 35041;
  201. const StaticCopyUsage = 35046;
  202. const DynamicCopyUsage = 35050;
  203. const StreamCopyUsage = 35042;
  204. const GLSL1 = '100';
  205. const GLSL3 = '300 es';
  206. const WebGLCoordinateSystem = 2000;
  207. const WebGPUCoordinateSystem = 2001;
  208. /**
  209. * https://github.com/mrdoob/eventdispatcher.js/
  210. */
  211. class EventDispatcher {
  212. addEventListener( type, listener ) {
  213. if ( this._listeners === undefined ) this._listeners = {};
  214. const listeners = this._listeners;
  215. if ( listeners[ type ] === undefined ) {
  216. listeners[ type ] = [];
  217. }
  218. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  219. listeners[ type ].push( listener );
  220. }
  221. }
  222. hasEventListener( type, listener ) {
  223. if ( this._listeners === undefined ) return false;
  224. const listeners = this._listeners;
  225. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  226. }
  227. removeEventListener( type, listener ) {
  228. if ( this._listeners === undefined ) return;
  229. const listeners = this._listeners;
  230. const listenerArray = listeners[ type ];
  231. if ( listenerArray !== undefined ) {
  232. const index = listenerArray.indexOf( listener );
  233. if ( index !== - 1 ) {
  234. listenerArray.splice( index, 1 );
  235. }
  236. }
  237. }
  238. dispatchEvent( event ) {
  239. if ( this._listeners === undefined ) return;
  240. const listeners = this._listeners;
  241. const listenerArray = listeners[ event.type ];
  242. if ( listenerArray !== undefined ) {
  243. event.target = this;
  244. // Make a copy, in case listeners are removed while iterating.
  245. const array = listenerArray.slice( 0 );
  246. for ( let i = 0, l = array.length; i < l; i ++ ) {
  247. array[ i ].call( this, event );
  248. }
  249. event.target = null;
  250. }
  251. }
  252. }
  253. const _lut = [ '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff' ];
  254. let _seed = 1234567;
  255. const DEG2RAD = Math.PI / 180;
  256. const RAD2DEG = 180 / Math.PI;
  257. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  258. function generateUUID() {
  259. const d0 = Math.random() * 0xffffffff | 0;
  260. const d1 = Math.random() * 0xffffffff | 0;
  261. const d2 = Math.random() * 0xffffffff | 0;
  262. const d3 = Math.random() * 0xffffffff | 0;
  263. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  264. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  265. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  266. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  267. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  268. return uuid.toLowerCase();
  269. }
  270. function clamp$1( value, min, max ) {
  271. return Math.max( min, Math.min( max, value ) );
  272. }
  273. // compute euclidean modulo of m % n
  274. // https://en.wikipedia.org/wiki/Modulo_operation
  275. function euclideanModulo( n, m ) {
  276. return ( ( n % m ) + m ) % m;
  277. }
  278. // Linear mapping from range <a1, a2> to range <b1, b2>
  279. function mapLinear( x, a1, a2, b1, b2 ) {
  280. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  281. }
  282. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  283. function inverseLerp( x, y, value ) {
  284. if ( x !== y ) {
  285. return ( value - x ) / ( y - x );
  286. } else {
  287. return 0;
  288. }
  289. }
  290. // https://en.wikipedia.org/wiki/Linear_interpolation
  291. function lerp( x, y, t ) {
  292. return ( 1 - t ) * x + t * y;
  293. }
  294. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  295. function damp( x, y, lambda, dt ) {
  296. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  297. }
  298. // https://www.desmos.com/calculator/vcsjnyz7x4
  299. function pingpong( x, length = 1 ) {
  300. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  301. }
  302. // http://en.wikipedia.org/wiki/Smoothstep
  303. function smoothstep$1( x, min, max ) {
  304. if ( x <= min ) return 0;
  305. if ( x >= max ) return 1;
  306. x = ( x - min ) / ( max - min );
  307. return x * x * ( 3 - 2 * x );
  308. }
  309. function smootherstep( x, min, max ) {
  310. if ( x <= min ) return 0;
  311. if ( x >= max ) return 1;
  312. x = ( x - min ) / ( max - min );
  313. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  314. }
  315. // Random integer from <low, high> interval
  316. function randInt( low, high ) {
  317. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  318. }
  319. // Random float from <low, high> interval
  320. function randFloat( low, high ) {
  321. return low + Math.random() * ( high - low );
  322. }
  323. // Random float from <-range/2, range/2> interval
  324. function randFloatSpread( range ) {
  325. return range * ( 0.5 - Math.random() );
  326. }
  327. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  328. function seededRandom( s ) {
  329. if ( s !== undefined ) _seed = s;
  330. // Mulberry32 generator
  331. let t = _seed += 0x6D2B79F5;
  332. t = Math.imul( t ^ t >>> 15, t | 1 );
  333. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  334. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  335. }
  336. function degToRad( degrees ) {
  337. return degrees * DEG2RAD;
  338. }
  339. function radToDeg( radians ) {
  340. return radians * RAD2DEG;
  341. }
  342. function isPowerOfTwo( value ) {
  343. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  344. }
  345. function ceilPowerOfTwo( value ) {
  346. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  347. }
  348. function floorPowerOfTwo( value ) {
  349. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  350. }
  351. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  352. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  353. // rotations are applied to the axes in the order specified by 'order'
  354. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  355. // angles are in radians
  356. const cos = Math.cos;
  357. const sin = Math.sin;
  358. const c2 = cos( b / 2 );
  359. const s2 = sin( b / 2 );
  360. const c13 = cos( ( a + c ) / 2 );
  361. const s13 = sin( ( a + c ) / 2 );
  362. const c1_3 = cos( ( a - c ) / 2 );
  363. const s1_3 = sin( ( a - c ) / 2 );
  364. const c3_1 = cos( ( c - a ) / 2 );
  365. const s3_1 = sin( ( c - a ) / 2 );
  366. switch ( order ) {
  367. case 'XYX':
  368. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  369. break;
  370. case 'YZY':
  371. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  372. break;
  373. case 'ZXZ':
  374. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  375. break;
  376. case 'XZX':
  377. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  378. break;
  379. case 'YXY':
  380. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  381. break;
  382. case 'ZYZ':
  383. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  384. break;
  385. default:
  386. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  387. }
  388. }
  389. function denormalize( value, array ) {
  390. switch ( array.constructor ) {
  391. case Float32Array:
  392. return value;
  393. case Uint32Array:
  394. return value / 4294967295.0;
  395. case Uint16Array:
  396. return value / 65535.0;
  397. case Uint8Array:
  398. return value / 255.0;
  399. case Int32Array:
  400. return Math.max( value / 2147483647.0, - 1.0 );
  401. case Int16Array:
  402. return Math.max( value / 32767.0, - 1.0 );
  403. case Int8Array:
  404. return Math.max( value / 127.0, - 1.0 );
  405. default:
  406. throw new Error( 'Invalid component type.' );
  407. }
  408. }
  409. function normalize$1( value, array ) {
  410. switch ( array.constructor ) {
  411. case Float32Array:
  412. return value;
  413. case Uint32Array:
  414. return Math.round( value * 4294967295.0 );
  415. case Uint16Array:
  416. return Math.round( value * 65535.0 );
  417. case Uint8Array:
  418. return Math.round( value * 255.0 );
  419. case Int32Array:
  420. return Math.round( value * 2147483647.0 );
  421. case Int16Array:
  422. return Math.round( value * 32767.0 );
  423. case Int8Array:
  424. return Math.round( value * 127.0 );
  425. default:
  426. throw new Error( 'Invalid component type.' );
  427. }
  428. }
  429. const MathUtils = {
  430. DEG2RAD: DEG2RAD,
  431. RAD2DEG: RAD2DEG,
  432. generateUUID: generateUUID,
  433. clamp: clamp$1,
  434. euclideanModulo: euclideanModulo,
  435. mapLinear: mapLinear,
  436. inverseLerp: inverseLerp,
  437. lerp: lerp,
  438. damp: damp,
  439. pingpong: pingpong,
  440. smoothstep: smoothstep$1,
  441. smootherstep: smootherstep,
  442. randInt: randInt,
  443. randFloat: randFloat,
  444. randFloatSpread: randFloatSpread,
  445. seededRandom: seededRandom,
  446. degToRad: degToRad,
  447. radToDeg: radToDeg,
  448. isPowerOfTwo: isPowerOfTwo,
  449. ceilPowerOfTwo: ceilPowerOfTwo,
  450. floorPowerOfTwo: floorPowerOfTwo,
  451. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  452. normalize: normalize$1,
  453. denormalize: denormalize
  454. };
  455. class Vector2 {
  456. constructor( x = 0, y = 0 ) {
  457. Vector2.prototype.isVector2 = true;
  458. this.x = x;
  459. this.y = y;
  460. }
  461. get width() {
  462. return this.x;
  463. }
  464. set width( value ) {
  465. this.x = value;
  466. }
  467. get height() {
  468. return this.y;
  469. }
  470. set height( value ) {
  471. this.y = value;
  472. }
  473. set( x, y ) {
  474. this.x = x;
  475. this.y = y;
  476. return this;
  477. }
  478. setScalar( scalar ) {
  479. this.x = scalar;
  480. this.y = scalar;
  481. return this;
  482. }
  483. setX( x ) {
  484. this.x = x;
  485. return this;
  486. }
  487. setY( y ) {
  488. this.y = y;
  489. return this;
  490. }
  491. setComponent( index, value ) {
  492. switch ( index ) {
  493. case 0: this.x = value; break;
  494. case 1: this.y = value; break;
  495. default: throw new Error( 'index is out of range: ' + index );
  496. }
  497. return this;
  498. }
  499. getComponent( index ) {
  500. switch ( index ) {
  501. case 0: return this.x;
  502. case 1: return this.y;
  503. default: throw new Error( 'index is out of range: ' + index );
  504. }
  505. }
  506. clone() {
  507. return new this.constructor( this.x, this.y );
  508. }
  509. copy( v ) {
  510. this.x = v.x;
  511. this.y = v.y;
  512. return this;
  513. }
  514. add( v ) {
  515. this.x += v.x;
  516. this.y += v.y;
  517. return this;
  518. }
  519. addScalar( s ) {
  520. this.x += s;
  521. this.y += s;
  522. return this;
  523. }
  524. addVectors( a, b ) {
  525. this.x = a.x + b.x;
  526. this.y = a.y + b.y;
  527. return this;
  528. }
  529. addScaledVector( v, s ) {
  530. this.x += v.x * s;
  531. this.y += v.y * s;
  532. return this;
  533. }
  534. sub( v ) {
  535. this.x -= v.x;
  536. this.y -= v.y;
  537. return this;
  538. }
  539. subScalar( s ) {
  540. this.x -= s;
  541. this.y -= s;
  542. return this;
  543. }
  544. subVectors( a, b ) {
  545. this.x = a.x - b.x;
  546. this.y = a.y - b.y;
  547. return this;
  548. }
  549. multiply( v ) {
  550. this.x *= v.x;
  551. this.y *= v.y;
  552. return this;
  553. }
  554. multiplyScalar( scalar ) {
  555. this.x *= scalar;
  556. this.y *= scalar;
  557. return this;
  558. }
  559. divide( v ) {
  560. this.x /= v.x;
  561. this.y /= v.y;
  562. return this;
  563. }
  564. divideScalar( scalar ) {
  565. return this.multiplyScalar( 1 / scalar );
  566. }
  567. applyMatrix3( m ) {
  568. const x = this.x, y = this.y;
  569. const e = m.elements;
  570. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  571. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  572. return this;
  573. }
  574. min( v ) {
  575. this.x = Math.min( this.x, v.x );
  576. this.y = Math.min( this.y, v.y );
  577. return this;
  578. }
  579. max( v ) {
  580. this.x = Math.max( this.x, v.x );
  581. this.y = Math.max( this.y, v.y );
  582. return this;
  583. }
  584. clamp( min, max ) {
  585. // assumes min < max, componentwise
  586. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  587. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  588. return this;
  589. }
  590. clampScalar( minVal, maxVal ) {
  591. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  592. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  593. return this;
  594. }
  595. clampLength( min, max ) {
  596. const length = this.length();
  597. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  598. }
  599. floor() {
  600. this.x = Math.floor( this.x );
  601. this.y = Math.floor( this.y );
  602. return this;
  603. }
  604. ceil() {
  605. this.x = Math.ceil( this.x );
  606. this.y = Math.ceil( this.y );
  607. return this;
  608. }
  609. round() {
  610. this.x = Math.round( this.x );
  611. this.y = Math.round( this.y );
  612. return this;
  613. }
  614. roundToZero() {
  615. this.x = Math.trunc( this.x );
  616. this.y = Math.trunc( this.y );
  617. return this;
  618. }
  619. negate() {
  620. this.x = - this.x;
  621. this.y = - this.y;
  622. return this;
  623. }
  624. dot( v ) {
  625. return this.x * v.x + this.y * v.y;
  626. }
  627. cross( v ) {
  628. return this.x * v.y - this.y * v.x;
  629. }
  630. lengthSq() {
  631. return this.x * this.x + this.y * this.y;
  632. }
  633. length() {
  634. return Math.sqrt( this.x * this.x + this.y * this.y );
  635. }
  636. manhattanLength() {
  637. return Math.abs( this.x ) + Math.abs( this.y );
  638. }
  639. normalize() {
  640. return this.divideScalar( this.length() || 1 );
  641. }
  642. angle() {
  643. // computes the angle in radians with respect to the positive x-axis
  644. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  645. return angle;
  646. }
  647. angleTo( v ) {
  648. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  649. if ( denominator === 0 ) return Math.PI / 2;
  650. const theta = this.dot( v ) / denominator;
  651. // clamp, to handle numerical problems
  652. return Math.acos( clamp$1( theta, - 1, 1 ) );
  653. }
  654. distanceTo( v ) {
  655. return Math.sqrt( this.distanceToSquared( v ) );
  656. }
  657. distanceToSquared( v ) {
  658. const dx = this.x - v.x, dy = this.y - v.y;
  659. return dx * dx + dy * dy;
  660. }
  661. manhattanDistanceTo( v ) {
  662. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  663. }
  664. setLength( length ) {
  665. return this.normalize().multiplyScalar( length );
  666. }
  667. lerp( v, alpha ) {
  668. this.x += ( v.x - this.x ) * alpha;
  669. this.y += ( v.y - this.y ) * alpha;
  670. return this;
  671. }
  672. lerpVectors( v1, v2, alpha ) {
  673. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  674. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  675. return this;
  676. }
  677. equals( v ) {
  678. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  679. }
  680. fromArray( array, offset = 0 ) {
  681. this.x = array[ offset ];
  682. this.y = array[ offset + 1 ];
  683. return this;
  684. }
  685. toArray( array = [], offset = 0 ) {
  686. array[ offset ] = this.x;
  687. array[ offset + 1 ] = this.y;
  688. return array;
  689. }
  690. fromBufferAttribute( attribute, index ) {
  691. this.x = attribute.getX( index );
  692. this.y = attribute.getY( index );
  693. return this;
  694. }
  695. rotateAround( center, angle ) {
  696. const c = Math.cos( angle ), s = Math.sin( angle );
  697. const x = this.x - center.x;
  698. const y = this.y - center.y;
  699. this.x = x * c - y * s + center.x;
  700. this.y = x * s + y * c + center.y;
  701. return this;
  702. }
  703. random() {
  704. this.x = Math.random();
  705. this.y = Math.random();
  706. return this;
  707. }
  708. *[ Symbol.iterator ]() {
  709. yield this.x;
  710. yield this.y;
  711. }
  712. }
  713. class Matrix3 {
  714. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  715. Matrix3.prototype.isMatrix3 = true;
  716. this.elements = [
  717. 1, 0, 0,
  718. 0, 1, 0,
  719. 0, 0, 1
  720. ];
  721. if ( n11 !== undefined ) {
  722. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  723. }
  724. }
  725. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  726. const te = this.elements;
  727. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  728. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  729. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  730. return this;
  731. }
  732. identity() {
  733. this.set(
  734. 1, 0, 0,
  735. 0, 1, 0,
  736. 0, 0, 1
  737. );
  738. return this;
  739. }
  740. copy( m ) {
  741. const te = this.elements;
  742. const me = m.elements;
  743. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  744. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  745. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  746. return this;
  747. }
  748. extractBasis( xAxis, yAxis, zAxis ) {
  749. xAxis.setFromMatrix3Column( this, 0 );
  750. yAxis.setFromMatrix3Column( this, 1 );
  751. zAxis.setFromMatrix3Column( this, 2 );
  752. return this;
  753. }
  754. setFromMatrix4( m ) {
  755. const me = m.elements;
  756. this.set(
  757. me[ 0 ], me[ 4 ], me[ 8 ],
  758. me[ 1 ], me[ 5 ], me[ 9 ],
  759. me[ 2 ], me[ 6 ], me[ 10 ]
  760. );
  761. return this;
  762. }
  763. multiply( m ) {
  764. return this.multiplyMatrices( this, m );
  765. }
  766. premultiply( m ) {
  767. return this.multiplyMatrices( m, this );
  768. }
  769. multiplyMatrices( a, b ) {
  770. const ae = a.elements;
  771. const be = b.elements;
  772. const te = this.elements;
  773. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  774. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  775. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  776. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  777. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  778. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  779. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  780. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  781. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  782. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  783. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  784. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  785. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  786. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  787. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  788. return this;
  789. }
  790. multiplyScalar( s ) {
  791. const te = this.elements;
  792. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  793. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  794. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  795. return this;
  796. }
  797. determinant() {
  798. const te = this.elements;
  799. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  800. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  801. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  802. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  803. }
  804. invert() {
  805. const te = this.elements,
  806. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  807. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  808. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  809. t11 = n33 * n22 - n32 * n23,
  810. t12 = n32 * n13 - n33 * n12,
  811. t13 = n23 * n12 - n22 * n13,
  812. det = n11 * t11 + n21 * t12 + n31 * t13;
  813. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  814. const detInv = 1 / det;
  815. te[ 0 ] = t11 * detInv;
  816. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  817. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  818. te[ 3 ] = t12 * detInv;
  819. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  820. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  821. te[ 6 ] = t13 * detInv;
  822. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  823. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  824. return this;
  825. }
  826. transpose() {
  827. let tmp;
  828. const m = this.elements;
  829. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  830. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  831. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  832. return this;
  833. }
  834. getNormalMatrix( matrix4 ) {
  835. return this.setFromMatrix4( matrix4 ).invert().transpose();
  836. }
  837. transposeIntoArray( r ) {
  838. const m = this.elements;
  839. r[ 0 ] = m[ 0 ];
  840. r[ 1 ] = m[ 3 ];
  841. r[ 2 ] = m[ 6 ];
  842. r[ 3 ] = m[ 1 ];
  843. r[ 4 ] = m[ 4 ];
  844. r[ 5 ] = m[ 7 ];
  845. r[ 6 ] = m[ 2 ];
  846. r[ 7 ] = m[ 5 ];
  847. r[ 8 ] = m[ 8 ];
  848. return this;
  849. }
  850. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  851. const c = Math.cos( rotation );
  852. const s = Math.sin( rotation );
  853. this.set(
  854. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  855. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  856. 0, 0, 1
  857. );
  858. return this;
  859. }
  860. //
  861. scale( sx, sy ) {
  862. this.premultiply( _m3.makeScale( sx, sy ) );
  863. return this;
  864. }
  865. rotate( theta ) {
  866. this.premultiply( _m3.makeRotation( - theta ) );
  867. return this;
  868. }
  869. translate( tx, ty ) {
  870. this.premultiply( _m3.makeTranslation( tx, ty ) );
  871. return this;
  872. }
  873. // for 2D Transforms
  874. makeTranslation( x, y ) {
  875. if ( x.isVector2 ) {
  876. this.set(
  877. 1, 0, x.x,
  878. 0, 1, x.y,
  879. 0, 0, 1
  880. );
  881. } else {
  882. this.set(
  883. 1, 0, x,
  884. 0, 1, y,
  885. 0, 0, 1
  886. );
  887. }
  888. return this;
  889. }
  890. makeRotation( theta ) {
  891. // counterclockwise
  892. const c = Math.cos( theta );
  893. const s = Math.sin( theta );
  894. this.set(
  895. c, - s, 0,
  896. s, c, 0,
  897. 0, 0, 1
  898. );
  899. return this;
  900. }
  901. makeScale( x, y ) {
  902. this.set(
  903. x, 0, 0,
  904. 0, y, 0,
  905. 0, 0, 1
  906. );
  907. return this;
  908. }
  909. //
  910. equals( matrix ) {
  911. const te = this.elements;
  912. const me = matrix.elements;
  913. for ( let i = 0; i < 9; i ++ ) {
  914. if ( te[ i ] !== me[ i ] ) return false;
  915. }
  916. return true;
  917. }
  918. fromArray( array, offset = 0 ) {
  919. for ( let i = 0; i < 9; i ++ ) {
  920. this.elements[ i ] = array[ i + offset ];
  921. }
  922. return this;
  923. }
  924. toArray( array = [], offset = 0 ) {
  925. const te = this.elements;
  926. array[ offset ] = te[ 0 ];
  927. array[ offset + 1 ] = te[ 1 ];
  928. array[ offset + 2 ] = te[ 2 ];
  929. array[ offset + 3 ] = te[ 3 ];
  930. array[ offset + 4 ] = te[ 4 ];
  931. array[ offset + 5 ] = te[ 5 ];
  932. array[ offset + 6 ] = te[ 6 ];
  933. array[ offset + 7 ] = te[ 7 ];
  934. array[ offset + 8 ] = te[ 8 ];
  935. return array;
  936. }
  937. clone() {
  938. return new this.constructor().fromArray( this.elements );
  939. }
  940. }
  941. const _m3 = /*@__PURE__*/ new Matrix3();
  942. function arrayNeedsUint32$1( array ) {
  943. // assumes larger values usually on last
  944. for ( let i = array.length - 1; i >= 0; -- i ) {
  945. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  946. }
  947. return false;
  948. }
  949. const TYPED_ARRAYS = {
  950. Int8Array: Int8Array,
  951. Uint8Array: Uint8Array,
  952. Uint8ClampedArray: Uint8ClampedArray,
  953. Int16Array: Int16Array,
  954. Uint16Array: Uint16Array,
  955. Int32Array: Int32Array,
  956. Uint32Array: Uint32Array,
  957. Float32Array: Float32Array,
  958. Float64Array: Float64Array
  959. };
  960. function getTypedArray( type, buffer ) {
  961. return new TYPED_ARRAYS[ type ]( buffer );
  962. }
  963. function createElementNS( name ) {
  964. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  965. }
  966. function createCanvasElement() {
  967. const canvas = createElementNS( 'canvas' );
  968. canvas.style.display = 'block';
  969. return canvas;
  970. }
  971. const _cache$1 = {};
  972. function warnOnce( message ) {
  973. if ( message in _cache$1 ) return;
  974. _cache$1[ message ] = true;
  975. console.warn( message );
  976. }
  977. /**
  978. * Matrices converting P3 <-> Rec. 709 primaries, without gamut mapping
  979. * or clipping. Based on W3C specifications for sRGB and Display P3,
  980. * and ICC specifications for the D50 connection space. Values in/out
  981. * are _linear_ sRGB and _linear_ Display P3.
  982. *
  983. * Note that both sRGB and Display P3 use the sRGB transfer functions.
  984. *
  985. * Reference:
  986. * - http://www.russellcottrell.com/photo/matrixCalculator.htm
  987. */
  988. const LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = /*@__PURE__*/ new Matrix3().set(
  989. 0.8224621, 0.177538, 0.0,
  990. 0.0331941, 0.9668058, 0.0,
  991. 0.0170827, 0.0723974, 0.9105199,
  992. );
  993. const LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = /*@__PURE__*/ new Matrix3().set(
  994. 1.2249401, - 0.2249404, 0.0,
  995. - 0.0420569, 1.0420571, 0.0,
  996. - 0.0196376, - 0.0786361, 1.0982735
  997. );
  998. /**
  999. * Defines supported color spaces by transfer function and primaries,
  1000. * and provides conversions to/from the Linear-sRGB reference space.
  1001. */
  1002. const COLOR_SPACES = {
  1003. [ LinearSRGBColorSpace ]: {
  1004. transfer: LinearTransfer,
  1005. primaries: Rec709Primaries,
  1006. toReference: ( color ) => color,
  1007. fromReference: ( color ) => color,
  1008. },
  1009. [ SRGBColorSpace ]: {
  1010. transfer: SRGBTransfer,
  1011. primaries: Rec709Primaries,
  1012. toReference: ( color ) => color.convertSRGBToLinear(),
  1013. fromReference: ( color ) => color.convertLinearToSRGB(),
  1014. },
  1015. [ LinearDisplayP3ColorSpace ]: {
  1016. transfer: LinearTransfer,
  1017. primaries: P3Primaries,
  1018. toReference: ( color ) => color.applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1019. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ),
  1020. },
  1021. [ DisplayP3ColorSpace ]: {
  1022. transfer: SRGBTransfer,
  1023. primaries: P3Primaries,
  1024. toReference: ( color ) => color.convertSRGBToLinear().applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1025. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ).convertLinearToSRGB(),
  1026. },
  1027. };
  1028. const SUPPORTED_WORKING_COLOR_SPACES = new Set( [ LinearSRGBColorSpace, LinearDisplayP3ColorSpace ] );
  1029. const ColorManagement = {
  1030. enabled: true,
  1031. _workingColorSpace: LinearSRGBColorSpace,
  1032. get workingColorSpace() {
  1033. return this._workingColorSpace;
  1034. },
  1035. set workingColorSpace( colorSpace ) {
  1036. if ( ! SUPPORTED_WORKING_COLOR_SPACES.has( colorSpace ) ) {
  1037. throw new Error( `Unsupported working color space, "${ colorSpace }".` );
  1038. }
  1039. this._workingColorSpace = colorSpace;
  1040. },
  1041. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1042. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1043. return color;
  1044. }
  1045. const sourceToReference = COLOR_SPACES[ sourceColorSpace ].toReference;
  1046. const targetFromReference = COLOR_SPACES[ targetColorSpace ].fromReference;
  1047. return targetFromReference( sourceToReference( color ) );
  1048. },
  1049. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1050. return this.convert( color, this._workingColorSpace, targetColorSpace );
  1051. },
  1052. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1053. return this.convert( color, sourceColorSpace, this._workingColorSpace );
  1054. },
  1055. getPrimaries: function ( colorSpace ) {
  1056. return COLOR_SPACES[ colorSpace ].primaries;
  1057. },
  1058. getTransfer: function ( colorSpace ) {
  1059. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  1060. return COLOR_SPACES[ colorSpace ].transfer;
  1061. },
  1062. };
  1063. function SRGBToLinear( c ) {
  1064. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1065. }
  1066. function LinearToSRGB( c ) {
  1067. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1068. }
  1069. let _canvas;
  1070. class ImageUtils {
  1071. static getDataURL( image ) {
  1072. if ( /^data:/i.test( image.src ) ) {
  1073. return image.src;
  1074. }
  1075. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1076. return image.src;
  1077. }
  1078. let canvas;
  1079. if ( image instanceof HTMLCanvasElement ) {
  1080. canvas = image;
  1081. } else {
  1082. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1083. _canvas.width = image.width;
  1084. _canvas.height = image.height;
  1085. const context = _canvas.getContext( '2d' );
  1086. if ( image instanceof ImageData ) {
  1087. context.putImageData( image, 0, 0 );
  1088. } else {
  1089. context.drawImage( image, 0, 0, image.width, image.height );
  1090. }
  1091. canvas = _canvas;
  1092. }
  1093. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1094. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1095. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1096. } else {
  1097. return canvas.toDataURL( 'image/png' );
  1098. }
  1099. }
  1100. static sRGBToLinear( image ) {
  1101. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1102. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1103. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1104. const canvas = createElementNS( 'canvas' );
  1105. canvas.width = image.width;
  1106. canvas.height = image.height;
  1107. const context = canvas.getContext( '2d' );
  1108. context.drawImage( image, 0, 0, image.width, image.height );
  1109. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1110. const data = imageData.data;
  1111. for ( let i = 0; i < data.length; i ++ ) {
  1112. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1113. }
  1114. context.putImageData( imageData, 0, 0 );
  1115. return canvas;
  1116. } else if ( image.data ) {
  1117. const data = image.data.slice( 0 );
  1118. for ( let i = 0; i < data.length; i ++ ) {
  1119. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1120. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1121. } else {
  1122. // assuming float
  1123. data[ i ] = SRGBToLinear( data[ i ] );
  1124. }
  1125. }
  1126. return {
  1127. data: data,
  1128. width: image.width,
  1129. height: image.height
  1130. };
  1131. } else {
  1132. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1133. return image;
  1134. }
  1135. }
  1136. }
  1137. let _sourceId = 0;
  1138. class Source {
  1139. constructor( data = null ) {
  1140. this.isSource = true;
  1141. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  1142. this.uuid = generateUUID();
  1143. this.data = data;
  1144. this.dataReady = true;
  1145. this.version = 0;
  1146. }
  1147. set needsUpdate( value ) {
  1148. if ( value === true ) this.version ++;
  1149. }
  1150. toJSON( meta ) {
  1151. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1152. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1153. return meta.images[ this.uuid ];
  1154. }
  1155. const output = {
  1156. uuid: this.uuid,
  1157. url: ''
  1158. };
  1159. const data = this.data;
  1160. if ( data !== null ) {
  1161. let url;
  1162. if ( Array.isArray( data ) ) {
  1163. // cube texture
  1164. url = [];
  1165. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1166. if ( data[ i ].isDataTexture ) {
  1167. url.push( serializeImage( data[ i ].image ) );
  1168. } else {
  1169. url.push( serializeImage( data[ i ] ) );
  1170. }
  1171. }
  1172. } else {
  1173. // texture
  1174. url = serializeImage( data );
  1175. }
  1176. output.url = url;
  1177. }
  1178. if ( ! isRootObject ) {
  1179. meta.images[ this.uuid ] = output;
  1180. }
  1181. return output;
  1182. }
  1183. }
  1184. function serializeImage( image ) {
  1185. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1186. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1187. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1188. // default images
  1189. return ImageUtils.getDataURL( image );
  1190. } else {
  1191. if ( image.data ) {
  1192. // images of DataTexture
  1193. return {
  1194. data: Array.from( image.data ),
  1195. width: image.width,
  1196. height: image.height,
  1197. type: image.data.constructor.name
  1198. };
  1199. } else {
  1200. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1201. return {};
  1202. }
  1203. }
  1204. }
  1205. let _textureId = 0;
  1206. class Texture extends EventDispatcher {
  1207. constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace ) {
  1208. super();
  1209. this.isTexture = true;
  1210. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  1211. this.uuid = generateUUID();
  1212. this.name = '';
  1213. this.source = new Source( image );
  1214. this.mipmaps = [];
  1215. this.mapping = mapping;
  1216. this.channel = 0;
  1217. this.wrapS = wrapS;
  1218. this.wrapT = wrapT;
  1219. this.magFilter = magFilter;
  1220. this.minFilter = minFilter;
  1221. this.anisotropy = anisotropy;
  1222. this.format = format;
  1223. this.internalFormat = null;
  1224. this.type = type;
  1225. this.offset = new Vector2( 0, 0 );
  1226. this.repeat = new Vector2( 1, 1 );
  1227. this.center = new Vector2( 0, 0 );
  1228. this.rotation = 0;
  1229. this.matrixAutoUpdate = true;
  1230. this.matrix = new Matrix3();
  1231. this.generateMipmaps = true;
  1232. this.premultiplyAlpha = false;
  1233. this.flipY = true;
  1234. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1235. this.colorSpace = colorSpace;
  1236. this.userData = {};
  1237. this.version = 0;
  1238. this.onUpdate = null;
  1239. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1240. this.pmremVersion = 0; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1241. }
  1242. get image() {
  1243. return this.source.data;
  1244. }
  1245. set image( value = null ) {
  1246. this.source.data = value;
  1247. }
  1248. updateMatrix() {
  1249. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1250. }
  1251. clone() {
  1252. return new this.constructor().copy( this );
  1253. }
  1254. copy( source ) {
  1255. this.name = source.name;
  1256. this.source = source.source;
  1257. this.mipmaps = source.mipmaps.slice( 0 );
  1258. this.mapping = source.mapping;
  1259. this.channel = source.channel;
  1260. this.wrapS = source.wrapS;
  1261. this.wrapT = source.wrapT;
  1262. this.magFilter = source.magFilter;
  1263. this.minFilter = source.minFilter;
  1264. this.anisotropy = source.anisotropy;
  1265. this.format = source.format;
  1266. this.internalFormat = source.internalFormat;
  1267. this.type = source.type;
  1268. this.offset.copy( source.offset );
  1269. this.repeat.copy( source.repeat );
  1270. this.center.copy( source.center );
  1271. this.rotation = source.rotation;
  1272. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1273. this.matrix.copy( source.matrix );
  1274. this.generateMipmaps = source.generateMipmaps;
  1275. this.premultiplyAlpha = source.premultiplyAlpha;
  1276. this.flipY = source.flipY;
  1277. this.unpackAlignment = source.unpackAlignment;
  1278. this.colorSpace = source.colorSpace;
  1279. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1280. this.needsUpdate = true;
  1281. return this;
  1282. }
  1283. toJSON( meta ) {
  1284. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1285. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1286. return meta.textures[ this.uuid ];
  1287. }
  1288. const output = {
  1289. metadata: {
  1290. version: 4.6,
  1291. type: 'Texture',
  1292. generator: 'Texture.toJSON'
  1293. },
  1294. uuid: this.uuid,
  1295. name: this.name,
  1296. image: this.source.toJSON( meta ).uuid,
  1297. mapping: this.mapping,
  1298. channel: this.channel,
  1299. repeat: [ this.repeat.x, this.repeat.y ],
  1300. offset: [ this.offset.x, this.offset.y ],
  1301. center: [ this.center.x, this.center.y ],
  1302. rotation: this.rotation,
  1303. wrap: [ this.wrapS, this.wrapT ],
  1304. format: this.format,
  1305. internalFormat: this.internalFormat,
  1306. type: this.type,
  1307. colorSpace: this.colorSpace,
  1308. minFilter: this.minFilter,
  1309. magFilter: this.magFilter,
  1310. anisotropy: this.anisotropy,
  1311. flipY: this.flipY,
  1312. generateMipmaps: this.generateMipmaps,
  1313. premultiplyAlpha: this.premultiplyAlpha,
  1314. unpackAlignment: this.unpackAlignment
  1315. };
  1316. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1317. if ( ! isRootObject ) {
  1318. meta.textures[ this.uuid ] = output;
  1319. }
  1320. return output;
  1321. }
  1322. dispose() {
  1323. this.dispatchEvent( { type: 'dispose' } );
  1324. }
  1325. transformUv( uv ) {
  1326. if ( this.mapping !== UVMapping ) return uv;
  1327. uv.applyMatrix3( this.matrix );
  1328. if ( uv.x < 0 || uv.x > 1 ) {
  1329. switch ( this.wrapS ) {
  1330. case RepeatWrapping:
  1331. uv.x = uv.x - Math.floor( uv.x );
  1332. break;
  1333. case ClampToEdgeWrapping:
  1334. uv.x = uv.x < 0 ? 0 : 1;
  1335. break;
  1336. case MirroredRepeatWrapping:
  1337. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1338. uv.x = Math.ceil( uv.x ) - uv.x;
  1339. } else {
  1340. uv.x = uv.x - Math.floor( uv.x );
  1341. }
  1342. break;
  1343. }
  1344. }
  1345. if ( uv.y < 0 || uv.y > 1 ) {
  1346. switch ( this.wrapT ) {
  1347. case RepeatWrapping:
  1348. uv.y = uv.y - Math.floor( uv.y );
  1349. break;
  1350. case ClampToEdgeWrapping:
  1351. uv.y = uv.y < 0 ? 0 : 1;
  1352. break;
  1353. case MirroredRepeatWrapping:
  1354. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1355. uv.y = Math.ceil( uv.y ) - uv.y;
  1356. } else {
  1357. uv.y = uv.y - Math.floor( uv.y );
  1358. }
  1359. break;
  1360. }
  1361. }
  1362. if ( this.flipY ) {
  1363. uv.y = 1 - uv.y;
  1364. }
  1365. return uv;
  1366. }
  1367. set needsUpdate( value ) {
  1368. if ( value === true ) {
  1369. this.version ++;
  1370. this.source.needsUpdate = true;
  1371. }
  1372. }
  1373. set needsPMREMUpdate( value ) {
  1374. if ( value === true ) {
  1375. this.pmremVersion ++;
  1376. }
  1377. }
  1378. }
  1379. Texture.DEFAULT_IMAGE = null;
  1380. Texture.DEFAULT_MAPPING = UVMapping;
  1381. Texture.DEFAULT_ANISOTROPY = 1;
  1382. class Vector4 {
  1383. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1384. Vector4.prototype.isVector4 = true;
  1385. this.x = x;
  1386. this.y = y;
  1387. this.z = z;
  1388. this.w = w;
  1389. }
  1390. get width() {
  1391. return this.z;
  1392. }
  1393. set width( value ) {
  1394. this.z = value;
  1395. }
  1396. get height() {
  1397. return this.w;
  1398. }
  1399. set height( value ) {
  1400. this.w = value;
  1401. }
  1402. set( x, y, z, w ) {
  1403. this.x = x;
  1404. this.y = y;
  1405. this.z = z;
  1406. this.w = w;
  1407. return this;
  1408. }
  1409. setScalar( scalar ) {
  1410. this.x = scalar;
  1411. this.y = scalar;
  1412. this.z = scalar;
  1413. this.w = scalar;
  1414. return this;
  1415. }
  1416. setX( x ) {
  1417. this.x = x;
  1418. return this;
  1419. }
  1420. setY( y ) {
  1421. this.y = y;
  1422. return this;
  1423. }
  1424. setZ( z ) {
  1425. this.z = z;
  1426. return this;
  1427. }
  1428. setW( w ) {
  1429. this.w = w;
  1430. return this;
  1431. }
  1432. setComponent( index, value ) {
  1433. switch ( index ) {
  1434. case 0: this.x = value; break;
  1435. case 1: this.y = value; break;
  1436. case 2: this.z = value; break;
  1437. case 3: this.w = value; break;
  1438. default: throw new Error( 'index is out of range: ' + index );
  1439. }
  1440. return this;
  1441. }
  1442. getComponent( index ) {
  1443. switch ( index ) {
  1444. case 0: return this.x;
  1445. case 1: return this.y;
  1446. case 2: return this.z;
  1447. case 3: return this.w;
  1448. default: throw new Error( 'index is out of range: ' + index );
  1449. }
  1450. }
  1451. clone() {
  1452. return new this.constructor( this.x, this.y, this.z, this.w );
  1453. }
  1454. copy( v ) {
  1455. this.x = v.x;
  1456. this.y = v.y;
  1457. this.z = v.z;
  1458. this.w = ( v.w !== undefined ) ? v.w : 1;
  1459. return this;
  1460. }
  1461. add( v ) {
  1462. this.x += v.x;
  1463. this.y += v.y;
  1464. this.z += v.z;
  1465. this.w += v.w;
  1466. return this;
  1467. }
  1468. addScalar( s ) {
  1469. this.x += s;
  1470. this.y += s;
  1471. this.z += s;
  1472. this.w += s;
  1473. return this;
  1474. }
  1475. addVectors( a, b ) {
  1476. this.x = a.x + b.x;
  1477. this.y = a.y + b.y;
  1478. this.z = a.z + b.z;
  1479. this.w = a.w + b.w;
  1480. return this;
  1481. }
  1482. addScaledVector( v, s ) {
  1483. this.x += v.x * s;
  1484. this.y += v.y * s;
  1485. this.z += v.z * s;
  1486. this.w += v.w * s;
  1487. return this;
  1488. }
  1489. sub( v ) {
  1490. this.x -= v.x;
  1491. this.y -= v.y;
  1492. this.z -= v.z;
  1493. this.w -= v.w;
  1494. return this;
  1495. }
  1496. subScalar( s ) {
  1497. this.x -= s;
  1498. this.y -= s;
  1499. this.z -= s;
  1500. this.w -= s;
  1501. return this;
  1502. }
  1503. subVectors( a, b ) {
  1504. this.x = a.x - b.x;
  1505. this.y = a.y - b.y;
  1506. this.z = a.z - b.z;
  1507. this.w = a.w - b.w;
  1508. return this;
  1509. }
  1510. multiply( v ) {
  1511. this.x *= v.x;
  1512. this.y *= v.y;
  1513. this.z *= v.z;
  1514. this.w *= v.w;
  1515. return this;
  1516. }
  1517. multiplyScalar( scalar ) {
  1518. this.x *= scalar;
  1519. this.y *= scalar;
  1520. this.z *= scalar;
  1521. this.w *= scalar;
  1522. return this;
  1523. }
  1524. applyMatrix4( m ) {
  1525. const x = this.x, y = this.y, z = this.z, w = this.w;
  1526. const e = m.elements;
  1527. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1528. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1529. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1530. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1531. return this;
  1532. }
  1533. divideScalar( scalar ) {
  1534. return this.multiplyScalar( 1 / scalar );
  1535. }
  1536. setAxisAngleFromQuaternion( q ) {
  1537. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1538. // q is assumed to be normalized
  1539. this.w = 2 * Math.acos( q.w );
  1540. const s = Math.sqrt( 1 - q.w * q.w );
  1541. if ( s < 0.0001 ) {
  1542. this.x = 1;
  1543. this.y = 0;
  1544. this.z = 0;
  1545. } else {
  1546. this.x = q.x / s;
  1547. this.y = q.y / s;
  1548. this.z = q.z / s;
  1549. }
  1550. return this;
  1551. }
  1552. setAxisAngleFromRotationMatrix( m ) {
  1553. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1554. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1555. let angle, x, y, z; // variables for result
  1556. const epsilon = 0.01, // margin to allow for rounding errors
  1557. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1558. te = m.elements,
  1559. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1560. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1561. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1562. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1563. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1564. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1565. // singularity found
  1566. // first check for identity matrix which must have +1 for all terms
  1567. // in leading diagonal and zero in other terms
  1568. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1569. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1570. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1571. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1572. // this singularity is identity matrix so angle = 0
  1573. this.set( 1, 0, 0, 0 );
  1574. return this; // zero angle, arbitrary axis
  1575. }
  1576. // otherwise this singularity is angle = 180
  1577. angle = Math.PI;
  1578. const xx = ( m11 + 1 ) / 2;
  1579. const yy = ( m22 + 1 ) / 2;
  1580. const zz = ( m33 + 1 ) / 2;
  1581. const xy = ( m12 + m21 ) / 4;
  1582. const xz = ( m13 + m31 ) / 4;
  1583. const yz = ( m23 + m32 ) / 4;
  1584. if ( ( xx > yy ) && ( xx > zz ) ) {
  1585. // m11 is the largest diagonal term
  1586. if ( xx < epsilon ) {
  1587. x = 0;
  1588. y = 0.707106781;
  1589. z = 0.707106781;
  1590. } else {
  1591. x = Math.sqrt( xx );
  1592. y = xy / x;
  1593. z = xz / x;
  1594. }
  1595. } else if ( yy > zz ) {
  1596. // m22 is the largest diagonal term
  1597. if ( yy < epsilon ) {
  1598. x = 0.707106781;
  1599. y = 0;
  1600. z = 0.707106781;
  1601. } else {
  1602. y = Math.sqrt( yy );
  1603. x = xy / y;
  1604. z = yz / y;
  1605. }
  1606. } else {
  1607. // m33 is the largest diagonal term so base result on this
  1608. if ( zz < epsilon ) {
  1609. x = 0.707106781;
  1610. y = 0.707106781;
  1611. z = 0;
  1612. } else {
  1613. z = Math.sqrt( zz );
  1614. x = xz / z;
  1615. y = yz / z;
  1616. }
  1617. }
  1618. this.set( x, y, z, angle );
  1619. return this; // return 180 deg rotation
  1620. }
  1621. // as we have reached here there are no singularities so we can handle normally
  1622. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1623. ( m13 - m31 ) * ( m13 - m31 ) +
  1624. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1625. if ( Math.abs( s ) < 0.001 ) s = 1;
  1626. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1627. // caught by singularity test above, but I've left it in just in case
  1628. this.x = ( m32 - m23 ) / s;
  1629. this.y = ( m13 - m31 ) / s;
  1630. this.z = ( m21 - m12 ) / s;
  1631. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1632. return this;
  1633. }
  1634. setFromMatrixPosition( m ) {
  1635. const e = m.elements;
  1636. this.x = e[ 12 ];
  1637. this.y = e[ 13 ];
  1638. this.z = e[ 14 ];
  1639. this.w = e[ 15 ];
  1640. return this;
  1641. }
  1642. min( v ) {
  1643. this.x = Math.min( this.x, v.x );
  1644. this.y = Math.min( this.y, v.y );
  1645. this.z = Math.min( this.z, v.z );
  1646. this.w = Math.min( this.w, v.w );
  1647. return this;
  1648. }
  1649. max( v ) {
  1650. this.x = Math.max( this.x, v.x );
  1651. this.y = Math.max( this.y, v.y );
  1652. this.z = Math.max( this.z, v.z );
  1653. this.w = Math.max( this.w, v.w );
  1654. return this;
  1655. }
  1656. clamp( min, max ) {
  1657. // assumes min < max, componentwise
  1658. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1659. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1660. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1661. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1662. return this;
  1663. }
  1664. clampScalar( minVal, maxVal ) {
  1665. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1666. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1667. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1668. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1669. return this;
  1670. }
  1671. clampLength( min, max ) {
  1672. const length = this.length();
  1673. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1674. }
  1675. floor() {
  1676. this.x = Math.floor( this.x );
  1677. this.y = Math.floor( this.y );
  1678. this.z = Math.floor( this.z );
  1679. this.w = Math.floor( this.w );
  1680. return this;
  1681. }
  1682. ceil() {
  1683. this.x = Math.ceil( this.x );
  1684. this.y = Math.ceil( this.y );
  1685. this.z = Math.ceil( this.z );
  1686. this.w = Math.ceil( this.w );
  1687. return this;
  1688. }
  1689. round() {
  1690. this.x = Math.round( this.x );
  1691. this.y = Math.round( this.y );
  1692. this.z = Math.round( this.z );
  1693. this.w = Math.round( this.w );
  1694. return this;
  1695. }
  1696. roundToZero() {
  1697. this.x = Math.trunc( this.x );
  1698. this.y = Math.trunc( this.y );
  1699. this.z = Math.trunc( this.z );
  1700. this.w = Math.trunc( this.w );
  1701. return this;
  1702. }
  1703. negate() {
  1704. this.x = - this.x;
  1705. this.y = - this.y;
  1706. this.z = - this.z;
  1707. this.w = - this.w;
  1708. return this;
  1709. }
  1710. dot( v ) {
  1711. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1712. }
  1713. lengthSq() {
  1714. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1715. }
  1716. length() {
  1717. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1718. }
  1719. manhattanLength() {
  1720. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1721. }
  1722. normalize() {
  1723. return this.divideScalar( this.length() || 1 );
  1724. }
  1725. setLength( length ) {
  1726. return this.normalize().multiplyScalar( length );
  1727. }
  1728. lerp( v, alpha ) {
  1729. this.x += ( v.x - this.x ) * alpha;
  1730. this.y += ( v.y - this.y ) * alpha;
  1731. this.z += ( v.z - this.z ) * alpha;
  1732. this.w += ( v.w - this.w ) * alpha;
  1733. return this;
  1734. }
  1735. lerpVectors( v1, v2, alpha ) {
  1736. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1737. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1738. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1739. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1740. return this;
  1741. }
  1742. equals( v ) {
  1743. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1744. }
  1745. fromArray( array, offset = 0 ) {
  1746. this.x = array[ offset ];
  1747. this.y = array[ offset + 1 ];
  1748. this.z = array[ offset + 2 ];
  1749. this.w = array[ offset + 3 ];
  1750. return this;
  1751. }
  1752. toArray( array = [], offset = 0 ) {
  1753. array[ offset ] = this.x;
  1754. array[ offset + 1 ] = this.y;
  1755. array[ offset + 2 ] = this.z;
  1756. array[ offset + 3 ] = this.w;
  1757. return array;
  1758. }
  1759. fromBufferAttribute( attribute, index ) {
  1760. this.x = attribute.getX( index );
  1761. this.y = attribute.getY( index );
  1762. this.z = attribute.getZ( index );
  1763. this.w = attribute.getW( index );
  1764. return this;
  1765. }
  1766. random() {
  1767. this.x = Math.random();
  1768. this.y = Math.random();
  1769. this.z = Math.random();
  1770. this.w = Math.random();
  1771. return this;
  1772. }
  1773. *[ Symbol.iterator ]() {
  1774. yield this.x;
  1775. yield this.y;
  1776. yield this.z;
  1777. yield this.w;
  1778. }
  1779. }
  1780. /*
  1781. In options, we can specify:
  1782. * Texture parameters for an auto-generated target texture
  1783. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1784. */
  1785. class RenderTarget extends EventDispatcher {
  1786. constructor( width = 1, height = 1, options = {} ) {
  1787. super();
  1788. this.isRenderTarget = true;
  1789. this.width = width;
  1790. this.height = height;
  1791. this.depth = 1;
  1792. this.scissor = new Vector4( 0, 0, width, height );
  1793. this.scissorTest = false;
  1794. this.viewport = new Vector4( 0, 0, width, height );
  1795. const image = { width: width, height: height, depth: 1 };
  1796. options = Object.assign( {
  1797. generateMipmaps: false,
  1798. internalFormat: null,
  1799. minFilter: LinearFilter,
  1800. depthBuffer: true,
  1801. stencilBuffer: false,
  1802. resolveDepthBuffer: true,
  1803. resolveStencilBuffer: true,
  1804. depthTexture: null,
  1805. samples: 0,
  1806. count: 1
  1807. }, options );
  1808. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  1809. texture.flipY = false;
  1810. texture.generateMipmaps = options.generateMipmaps;
  1811. texture.internalFormat = options.internalFormat;
  1812. this.textures = [];
  1813. const count = options.count;
  1814. for ( let i = 0; i < count; i ++ ) {
  1815. this.textures[ i ] = texture.clone();
  1816. this.textures[ i ].isRenderTargetTexture = true;
  1817. }
  1818. this.depthBuffer = options.depthBuffer;
  1819. this.stencilBuffer = options.stencilBuffer;
  1820. this.resolveDepthBuffer = options.resolveDepthBuffer;
  1821. this.resolveStencilBuffer = options.resolveStencilBuffer;
  1822. this.depthTexture = options.depthTexture;
  1823. this.samples = options.samples;
  1824. }
  1825. get texture() {
  1826. return this.textures[ 0 ];
  1827. }
  1828. set texture( value ) {
  1829. this.textures[ 0 ] = value;
  1830. }
  1831. setSize( width, height, depth = 1 ) {
  1832. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1833. this.width = width;
  1834. this.height = height;
  1835. this.depth = depth;
  1836. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  1837. this.textures[ i ].image.width = width;
  1838. this.textures[ i ].image.height = height;
  1839. this.textures[ i ].image.depth = depth;
  1840. }
  1841. this.dispose();
  1842. }
  1843. this.viewport.set( 0, 0, width, height );
  1844. this.scissor.set( 0, 0, width, height );
  1845. }
  1846. clone() {
  1847. return new this.constructor().copy( this );
  1848. }
  1849. copy( source ) {
  1850. this.width = source.width;
  1851. this.height = source.height;
  1852. this.depth = source.depth;
  1853. this.scissor.copy( source.scissor );
  1854. this.scissorTest = source.scissorTest;
  1855. this.viewport.copy( source.viewport );
  1856. this.textures.length = 0;
  1857. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  1858. this.textures[ i ] = source.textures[ i ].clone();
  1859. this.textures[ i ].isRenderTargetTexture = true;
  1860. }
  1861. // ensure image object is not shared, see #20328
  1862. const image = Object.assign( {}, source.texture.image );
  1863. this.texture.source = new Source( image );
  1864. this.depthBuffer = source.depthBuffer;
  1865. this.stencilBuffer = source.stencilBuffer;
  1866. this.resolveDepthBuffer = source.resolveDepthBuffer;
  1867. this.resolveStencilBuffer = source.resolveStencilBuffer;
  1868. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1869. this.samples = source.samples;
  1870. return this;
  1871. }
  1872. dispose() {
  1873. this.dispatchEvent( { type: 'dispose' } );
  1874. }
  1875. }
  1876. class WebGLRenderTarget extends RenderTarget {
  1877. constructor( width = 1, height = 1, options = {} ) {
  1878. super( width, height, options );
  1879. this.isWebGLRenderTarget = true;
  1880. }
  1881. }
  1882. class DataArrayTexture extends Texture {
  1883. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1884. super( null );
  1885. this.isDataArrayTexture = true;
  1886. this.image = { data, width, height, depth };
  1887. this.magFilter = NearestFilter;
  1888. this.minFilter = NearestFilter;
  1889. this.wrapR = ClampToEdgeWrapping;
  1890. this.generateMipmaps = false;
  1891. this.flipY = false;
  1892. this.unpackAlignment = 1;
  1893. this.layerUpdates = new Set();
  1894. }
  1895. addLayerUpdate( layerIndex ) {
  1896. this.layerUpdates.add( layerIndex );
  1897. }
  1898. clearLayerUpdates() {
  1899. this.layerUpdates.clear();
  1900. }
  1901. }
  1902. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  1903. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1904. super( width, height, options );
  1905. this.isWebGLArrayRenderTarget = true;
  1906. this.depth = depth;
  1907. this.texture = new DataArrayTexture( null, width, height, depth );
  1908. this.texture.isRenderTargetTexture = true;
  1909. }
  1910. }
  1911. class Data3DTexture extends Texture {
  1912. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1913. // We're going to add .setXXX() methods for setting properties later.
  1914. // Users can still set in DataTexture3D directly.
  1915. //
  1916. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  1917. // texture.anisotropy = 16;
  1918. //
  1919. // See #14839
  1920. super( null );
  1921. this.isData3DTexture = true;
  1922. this.image = { data, width, height, depth };
  1923. this.magFilter = NearestFilter;
  1924. this.minFilter = NearestFilter;
  1925. this.wrapR = ClampToEdgeWrapping;
  1926. this.generateMipmaps = false;
  1927. this.flipY = false;
  1928. this.unpackAlignment = 1;
  1929. }
  1930. }
  1931. class WebGL3DRenderTarget extends WebGLRenderTarget {
  1932. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1933. super( width, height, options );
  1934. this.isWebGL3DRenderTarget = true;
  1935. this.depth = depth;
  1936. this.texture = new Data3DTexture( null, width, height, depth );
  1937. this.texture.isRenderTargetTexture = true;
  1938. }
  1939. }
  1940. class Quaternion {
  1941. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1942. this.isQuaternion = true;
  1943. this._x = x;
  1944. this._y = y;
  1945. this._z = z;
  1946. this._w = w;
  1947. }
  1948. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1949. // fuzz-free, array-based Quaternion SLERP operation
  1950. let x0 = src0[ srcOffset0 + 0 ],
  1951. y0 = src0[ srcOffset0 + 1 ],
  1952. z0 = src0[ srcOffset0 + 2 ],
  1953. w0 = src0[ srcOffset0 + 3 ];
  1954. const x1 = src1[ srcOffset1 + 0 ],
  1955. y1 = src1[ srcOffset1 + 1 ],
  1956. z1 = src1[ srcOffset1 + 2 ],
  1957. w1 = src1[ srcOffset1 + 3 ];
  1958. if ( t === 0 ) {
  1959. dst[ dstOffset + 0 ] = x0;
  1960. dst[ dstOffset + 1 ] = y0;
  1961. dst[ dstOffset + 2 ] = z0;
  1962. dst[ dstOffset + 3 ] = w0;
  1963. return;
  1964. }
  1965. if ( t === 1 ) {
  1966. dst[ dstOffset + 0 ] = x1;
  1967. dst[ dstOffset + 1 ] = y1;
  1968. dst[ dstOffset + 2 ] = z1;
  1969. dst[ dstOffset + 3 ] = w1;
  1970. return;
  1971. }
  1972. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1973. let s = 1 - t;
  1974. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1975. dir = ( cos >= 0 ? 1 : - 1 ),
  1976. sqrSin = 1 - cos * cos;
  1977. // Skip the Slerp for tiny steps to avoid numeric problems:
  1978. if ( sqrSin > Number.EPSILON ) {
  1979. const sin = Math.sqrt( sqrSin ),
  1980. len = Math.atan2( sin, cos * dir );
  1981. s = Math.sin( s * len ) / sin;
  1982. t = Math.sin( t * len ) / sin;
  1983. }
  1984. const tDir = t * dir;
  1985. x0 = x0 * s + x1 * tDir;
  1986. y0 = y0 * s + y1 * tDir;
  1987. z0 = z0 * s + z1 * tDir;
  1988. w0 = w0 * s + w1 * tDir;
  1989. // Normalize in case we just did a lerp:
  1990. if ( s === 1 - t ) {
  1991. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1992. x0 *= f;
  1993. y0 *= f;
  1994. z0 *= f;
  1995. w0 *= f;
  1996. }
  1997. }
  1998. dst[ dstOffset ] = x0;
  1999. dst[ dstOffset + 1 ] = y0;
  2000. dst[ dstOffset + 2 ] = z0;
  2001. dst[ dstOffset + 3 ] = w0;
  2002. }
  2003. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2004. const x0 = src0[ srcOffset0 ];
  2005. const y0 = src0[ srcOffset0 + 1 ];
  2006. const z0 = src0[ srcOffset0 + 2 ];
  2007. const w0 = src0[ srcOffset0 + 3 ];
  2008. const x1 = src1[ srcOffset1 ];
  2009. const y1 = src1[ srcOffset1 + 1 ];
  2010. const z1 = src1[ srcOffset1 + 2 ];
  2011. const w1 = src1[ srcOffset1 + 3 ];
  2012. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2013. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2014. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2015. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2016. return dst;
  2017. }
  2018. get x() {
  2019. return this._x;
  2020. }
  2021. set x( value ) {
  2022. this._x = value;
  2023. this._onChangeCallback();
  2024. }
  2025. get y() {
  2026. return this._y;
  2027. }
  2028. set y( value ) {
  2029. this._y = value;
  2030. this._onChangeCallback();
  2031. }
  2032. get z() {
  2033. return this._z;
  2034. }
  2035. set z( value ) {
  2036. this._z = value;
  2037. this._onChangeCallback();
  2038. }
  2039. get w() {
  2040. return this._w;
  2041. }
  2042. set w( value ) {
  2043. this._w = value;
  2044. this._onChangeCallback();
  2045. }
  2046. set( x, y, z, w ) {
  2047. this._x = x;
  2048. this._y = y;
  2049. this._z = z;
  2050. this._w = w;
  2051. this._onChangeCallback();
  2052. return this;
  2053. }
  2054. clone() {
  2055. return new this.constructor( this._x, this._y, this._z, this._w );
  2056. }
  2057. copy( quaternion ) {
  2058. this._x = quaternion.x;
  2059. this._y = quaternion.y;
  2060. this._z = quaternion.z;
  2061. this._w = quaternion.w;
  2062. this._onChangeCallback();
  2063. return this;
  2064. }
  2065. setFromEuler( euler, update = true ) {
  2066. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2067. // http://www.mathworks.com/matlabcentral/fileexchange/
  2068. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2069. // content/SpinCalc.m
  2070. const cos = Math.cos;
  2071. const sin = Math.sin;
  2072. const c1 = cos( x / 2 );
  2073. const c2 = cos( y / 2 );
  2074. const c3 = cos( z / 2 );
  2075. const s1 = sin( x / 2 );
  2076. const s2 = sin( y / 2 );
  2077. const s3 = sin( z / 2 );
  2078. switch ( order ) {
  2079. case 'XYZ':
  2080. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2081. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2082. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2083. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2084. break;
  2085. case 'YXZ':
  2086. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2087. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2088. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2089. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2090. break;
  2091. case 'ZXY':
  2092. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2093. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2094. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2095. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2096. break;
  2097. case 'ZYX':
  2098. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2099. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2100. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2101. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2102. break;
  2103. case 'YZX':
  2104. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2105. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2106. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2107. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2108. break;
  2109. case 'XZY':
  2110. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2111. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2112. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2113. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2114. break;
  2115. default:
  2116. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2117. }
  2118. if ( update === true ) this._onChangeCallback();
  2119. return this;
  2120. }
  2121. setFromAxisAngle( axis, angle ) {
  2122. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2123. // assumes axis is normalized
  2124. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2125. this._x = axis.x * s;
  2126. this._y = axis.y * s;
  2127. this._z = axis.z * s;
  2128. this._w = Math.cos( halfAngle );
  2129. this._onChangeCallback();
  2130. return this;
  2131. }
  2132. setFromRotationMatrix( m ) {
  2133. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2134. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2135. const te = m.elements,
  2136. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2137. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2138. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2139. trace = m11 + m22 + m33;
  2140. if ( trace > 0 ) {
  2141. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2142. this._w = 0.25 / s;
  2143. this._x = ( m32 - m23 ) * s;
  2144. this._y = ( m13 - m31 ) * s;
  2145. this._z = ( m21 - m12 ) * s;
  2146. } else if ( m11 > m22 && m11 > m33 ) {
  2147. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2148. this._w = ( m32 - m23 ) / s;
  2149. this._x = 0.25 * s;
  2150. this._y = ( m12 + m21 ) / s;
  2151. this._z = ( m13 + m31 ) / s;
  2152. } else if ( m22 > m33 ) {
  2153. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2154. this._w = ( m13 - m31 ) / s;
  2155. this._x = ( m12 + m21 ) / s;
  2156. this._y = 0.25 * s;
  2157. this._z = ( m23 + m32 ) / s;
  2158. } else {
  2159. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2160. this._w = ( m21 - m12 ) / s;
  2161. this._x = ( m13 + m31 ) / s;
  2162. this._y = ( m23 + m32 ) / s;
  2163. this._z = 0.25 * s;
  2164. }
  2165. this._onChangeCallback();
  2166. return this;
  2167. }
  2168. setFromUnitVectors( vFrom, vTo ) {
  2169. // assumes direction vectors vFrom and vTo are normalized
  2170. let r = vFrom.dot( vTo ) + 1;
  2171. if ( r < Number.EPSILON ) {
  2172. // vFrom and vTo point in opposite directions
  2173. r = 0;
  2174. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2175. this._x = - vFrom.y;
  2176. this._y = vFrom.x;
  2177. this._z = 0;
  2178. this._w = r;
  2179. } else {
  2180. this._x = 0;
  2181. this._y = - vFrom.z;
  2182. this._z = vFrom.y;
  2183. this._w = r;
  2184. }
  2185. } else {
  2186. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2187. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2188. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2189. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2190. this._w = r;
  2191. }
  2192. return this.normalize();
  2193. }
  2194. angleTo( q ) {
  2195. return 2 * Math.acos( Math.abs( clamp$1( this.dot( q ), - 1, 1 ) ) );
  2196. }
  2197. rotateTowards( q, step ) {
  2198. const angle = this.angleTo( q );
  2199. if ( angle === 0 ) return this;
  2200. const t = Math.min( 1, step / angle );
  2201. this.slerp( q, t );
  2202. return this;
  2203. }
  2204. identity() {
  2205. return this.set( 0, 0, 0, 1 );
  2206. }
  2207. invert() {
  2208. // quaternion is assumed to have unit length
  2209. return this.conjugate();
  2210. }
  2211. conjugate() {
  2212. this._x *= - 1;
  2213. this._y *= - 1;
  2214. this._z *= - 1;
  2215. this._onChangeCallback();
  2216. return this;
  2217. }
  2218. dot( v ) {
  2219. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2220. }
  2221. lengthSq() {
  2222. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2223. }
  2224. length() {
  2225. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2226. }
  2227. normalize() {
  2228. let l = this.length();
  2229. if ( l === 0 ) {
  2230. this._x = 0;
  2231. this._y = 0;
  2232. this._z = 0;
  2233. this._w = 1;
  2234. } else {
  2235. l = 1 / l;
  2236. this._x = this._x * l;
  2237. this._y = this._y * l;
  2238. this._z = this._z * l;
  2239. this._w = this._w * l;
  2240. }
  2241. this._onChangeCallback();
  2242. return this;
  2243. }
  2244. multiply( q ) {
  2245. return this.multiplyQuaternions( this, q );
  2246. }
  2247. premultiply( q ) {
  2248. return this.multiplyQuaternions( q, this );
  2249. }
  2250. multiplyQuaternions( a, b ) {
  2251. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2252. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2253. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2254. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2255. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2256. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2257. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2258. this._onChangeCallback();
  2259. return this;
  2260. }
  2261. slerp( qb, t ) {
  2262. if ( t === 0 ) return this;
  2263. if ( t === 1 ) return this.copy( qb );
  2264. const x = this._x, y = this._y, z = this._z, w = this._w;
  2265. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2266. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2267. if ( cosHalfTheta < 0 ) {
  2268. this._w = - qb._w;
  2269. this._x = - qb._x;
  2270. this._y = - qb._y;
  2271. this._z = - qb._z;
  2272. cosHalfTheta = - cosHalfTheta;
  2273. } else {
  2274. this.copy( qb );
  2275. }
  2276. if ( cosHalfTheta >= 1.0 ) {
  2277. this._w = w;
  2278. this._x = x;
  2279. this._y = y;
  2280. this._z = z;
  2281. return this;
  2282. }
  2283. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2284. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2285. const s = 1 - t;
  2286. this._w = s * w + t * this._w;
  2287. this._x = s * x + t * this._x;
  2288. this._y = s * y + t * this._y;
  2289. this._z = s * z + t * this._z;
  2290. this.normalize(); // normalize calls _onChangeCallback()
  2291. return this;
  2292. }
  2293. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2294. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2295. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2296. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2297. this._w = ( w * ratioA + this._w * ratioB );
  2298. this._x = ( x * ratioA + this._x * ratioB );
  2299. this._y = ( y * ratioA + this._y * ratioB );
  2300. this._z = ( z * ratioA + this._z * ratioB );
  2301. this._onChangeCallback();
  2302. return this;
  2303. }
  2304. slerpQuaternions( qa, qb, t ) {
  2305. return this.copy( qa ).slerp( qb, t );
  2306. }
  2307. random() {
  2308. // sets this quaternion to a uniform random unit quaternnion
  2309. // Ken Shoemake
  2310. // Uniform random rotations
  2311. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  2312. const theta1 = 2 * Math.PI * Math.random();
  2313. const theta2 = 2 * Math.PI * Math.random();
  2314. const x0 = Math.random();
  2315. const r1 = Math.sqrt( 1 - x0 );
  2316. const r2 = Math.sqrt( x0 );
  2317. return this.set(
  2318. r1 * Math.sin( theta1 ),
  2319. r1 * Math.cos( theta1 ),
  2320. r2 * Math.sin( theta2 ),
  2321. r2 * Math.cos( theta2 ),
  2322. );
  2323. }
  2324. equals( quaternion ) {
  2325. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2326. }
  2327. fromArray( array, offset = 0 ) {
  2328. this._x = array[ offset ];
  2329. this._y = array[ offset + 1 ];
  2330. this._z = array[ offset + 2 ];
  2331. this._w = array[ offset + 3 ];
  2332. this._onChangeCallback();
  2333. return this;
  2334. }
  2335. toArray( array = [], offset = 0 ) {
  2336. array[ offset ] = this._x;
  2337. array[ offset + 1 ] = this._y;
  2338. array[ offset + 2 ] = this._z;
  2339. array[ offset + 3 ] = this._w;
  2340. return array;
  2341. }
  2342. fromBufferAttribute( attribute, index ) {
  2343. this._x = attribute.getX( index );
  2344. this._y = attribute.getY( index );
  2345. this._z = attribute.getZ( index );
  2346. this._w = attribute.getW( index );
  2347. this._onChangeCallback();
  2348. return this;
  2349. }
  2350. toJSON() {
  2351. return this.toArray();
  2352. }
  2353. _onChange( callback ) {
  2354. this._onChangeCallback = callback;
  2355. return this;
  2356. }
  2357. _onChangeCallback() {}
  2358. *[ Symbol.iterator ]() {
  2359. yield this._x;
  2360. yield this._y;
  2361. yield this._z;
  2362. yield this._w;
  2363. }
  2364. }
  2365. class Vector3 {
  2366. constructor( x = 0, y = 0, z = 0 ) {
  2367. Vector3.prototype.isVector3 = true;
  2368. this.x = x;
  2369. this.y = y;
  2370. this.z = z;
  2371. }
  2372. set( x, y, z ) {
  2373. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2374. this.x = x;
  2375. this.y = y;
  2376. this.z = z;
  2377. return this;
  2378. }
  2379. setScalar( scalar ) {
  2380. this.x = scalar;
  2381. this.y = scalar;
  2382. this.z = scalar;
  2383. return this;
  2384. }
  2385. setX( x ) {
  2386. this.x = x;
  2387. return this;
  2388. }
  2389. setY( y ) {
  2390. this.y = y;
  2391. return this;
  2392. }
  2393. setZ( z ) {
  2394. this.z = z;
  2395. return this;
  2396. }
  2397. setComponent( index, value ) {
  2398. switch ( index ) {
  2399. case 0: this.x = value; break;
  2400. case 1: this.y = value; break;
  2401. case 2: this.z = value; break;
  2402. default: throw new Error( 'index is out of range: ' + index );
  2403. }
  2404. return this;
  2405. }
  2406. getComponent( index ) {
  2407. switch ( index ) {
  2408. case 0: return this.x;
  2409. case 1: return this.y;
  2410. case 2: return this.z;
  2411. default: throw new Error( 'index is out of range: ' + index );
  2412. }
  2413. }
  2414. clone() {
  2415. return new this.constructor( this.x, this.y, this.z );
  2416. }
  2417. copy( v ) {
  2418. this.x = v.x;
  2419. this.y = v.y;
  2420. this.z = v.z;
  2421. return this;
  2422. }
  2423. add( v ) {
  2424. this.x += v.x;
  2425. this.y += v.y;
  2426. this.z += v.z;
  2427. return this;
  2428. }
  2429. addScalar( s ) {
  2430. this.x += s;
  2431. this.y += s;
  2432. this.z += s;
  2433. return this;
  2434. }
  2435. addVectors( a, b ) {
  2436. this.x = a.x + b.x;
  2437. this.y = a.y + b.y;
  2438. this.z = a.z + b.z;
  2439. return this;
  2440. }
  2441. addScaledVector( v, s ) {
  2442. this.x += v.x * s;
  2443. this.y += v.y * s;
  2444. this.z += v.z * s;
  2445. return this;
  2446. }
  2447. sub( v ) {
  2448. this.x -= v.x;
  2449. this.y -= v.y;
  2450. this.z -= v.z;
  2451. return this;
  2452. }
  2453. subScalar( s ) {
  2454. this.x -= s;
  2455. this.y -= s;
  2456. this.z -= s;
  2457. return this;
  2458. }
  2459. subVectors( a, b ) {
  2460. this.x = a.x - b.x;
  2461. this.y = a.y - b.y;
  2462. this.z = a.z - b.z;
  2463. return this;
  2464. }
  2465. multiply( v ) {
  2466. this.x *= v.x;
  2467. this.y *= v.y;
  2468. this.z *= v.z;
  2469. return this;
  2470. }
  2471. multiplyScalar( scalar ) {
  2472. this.x *= scalar;
  2473. this.y *= scalar;
  2474. this.z *= scalar;
  2475. return this;
  2476. }
  2477. multiplyVectors( a, b ) {
  2478. this.x = a.x * b.x;
  2479. this.y = a.y * b.y;
  2480. this.z = a.z * b.z;
  2481. return this;
  2482. }
  2483. applyEuler( euler ) {
  2484. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2485. }
  2486. applyAxisAngle( axis, angle ) {
  2487. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2488. }
  2489. applyMatrix3( m ) {
  2490. const x = this.x, y = this.y, z = this.z;
  2491. const e = m.elements;
  2492. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2493. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2494. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2495. return this;
  2496. }
  2497. applyNormalMatrix( m ) {
  2498. return this.applyMatrix3( m ).normalize();
  2499. }
  2500. applyMatrix4( m ) {
  2501. const x = this.x, y = this.y, z = this.z;
  2502. const e = m.elements;
  2503. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2504. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2505. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2506. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2507. return this;
  2508. }
  2509. applyQuaternion( q ) {
  2510. // quaternion q is assumed to have unit length
  2511. const vx = this.x, vy = this.y, vz = this.z;
  2512. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2513. // t = 2 * cross( q.xyz, v );
  2514. const tx = 2 * ( qy * vz - qz * vy );
  2515. const ty = 2 * ( qz * vx - qx * vz );
  2516. const tz = 2 * ( qx * vy - qy * vx );
  2517. // v + q.w * t + cross( q.xyz, t );
  2518. this.x = vx + qw * tx + qy * tz - qz * ty;
  2519. this.y = vy + qw * ty + qz * tx - qx * tz;
  2520. this.z = vz + qw * tz + qx * ty - qy * tx;
  2521. return this;
  2522. }
  2523. project( camera ) {
  2524. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2525. }
  2526. unproject( camera ) {
  2527. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2528. }
  2529. transformDirection( m ) {
  2530. // input: THREE.Matrix4 affine matrix
  2531. // vector interpreted as a direction
  2532. const x = this.x, y = this.y, z = this.z;
  2533. const e = m.elements;
  2534. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2535. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2536. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2537. return this.normalize();
  2538. }
  2539. divide( v ) {
  2540. this.x /= v.x;
  2541. this.y /= v.y;
  2542. this.z /= v.z;
  2543. return this;
  2544. }
  2545. divideScalar( scalar ) {
  2546. return this.multiplyScalar( 1 / scalar );
  2547. }
  2548. min( v ) {
  2549. this.x = Math.min( this.x, v.x );
  2550. this.y = Math.min( this.y, v.y );
  2551. this.z = Math.min( this.z, v.z );
  2552. return this;
  2553. }
  2554. max( v ) {
  2555. this.x = Math.max( this.x, v.x );
  2556. this.y = Math.max( this.y, v.y );
  2557. this.z = Math.max( this.z, v.z );
  2558. return this;
  2559. }
  2560. clamp( min, max ) {
  2561. // assumes min < max, componentwise
  2562. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2563. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2564. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2565. return this;
  2566. }
  2567. clampScalar( minVal, maxVal ) {
  2568. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2569. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2570. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2571. return this;
  2572. }
  2573. clampLength( min, max ) {
  2574. const length = this.length();
  2575. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2576. }
  2577. floor() {
  2578. this.x = Math.floor( this.x );
  2579. this.y = Math.floor( this.y );
  2580. this.z = Math.floor( this.z );
  2581. return this;
  2582. }
  2583. ceil() {
  2584. this.x = Math.ceil( this.x );
  2585. this.y = Math.ceil( this.y );
  2586. this.z = Math.ceil( this.z );
  2587. return this;
  2588. }
  2589. round() {
  2590. this.x = Math.round( this.x );
  2591. this.y = Math.round( this.y );
  2592. this.z = Math.round( this.z );
  2593. return this;
  2594. }
  2595. roundToZero() {
  2596. this.x = Math.trunc( this.x );
  2597. this.y = Math.trunc( this.y );
  2598. this.z = Math.trunc( this.z );
  2599. return this;
  2600. }
  2601. negate() {
  2602. this.x = - this.x;
  2603. this.y = - this.y;
  2604. this.z = - this.z;
  2605. return this;
  2606. }
  2607. dot( v ) {
  2608. return this.x * v.x + this.y * v.y + this.z * v.z;
  2609. }
  2610. // TODO lengthSquared?
  2611. lengthSq() {
  2612. return this.x * this.x + this.y * this.y + this.z * this.z;
  2613. }
  2614. length() {
  2615. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2616. }
  2617. manhattanLength() {
  2618. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2619. }
  2620. normalize() {
  2621. return this.divideScalar( this.length() || 1 );
  2622. }
  2623. setLength( length ) {
  2624. return this.normalize().multiplyScalar( length );
  2625. }
  2626. lerp( v, alpha ) {
  2627. this.x += ( v.x - this.x ) * alpha;
  2628. this.y += ( v.y - this.y ) * alpha;
  2629. this.z += ( v.z - this.z ) * alpha;
  2630. return this;
  2631. }
  2632. lerpVectors( v1, v2, alpha ) {
  2633. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2634. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2635. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2636. return this;
  2637. }
  2638. cross( v ) {
  2639. return this.crossVectors( this, v );
  2640. }
  2641. crossVectors( a, b ) {
  2642. const ax = a.x, ay = a.y, az = a.z;
  2643. const bx = b.x, by = b.y, bz = b.z;
  2644. this.x = ay * bz - az * by;
  2645. this.y = az * bx - ax * bz;
  2646. this.z = ax * by - ay * bx;
  2647. return this;
  2648. }
  2649. projectOnVector( v ) {
  2650. const denominator = v.lengthSq();
  2651. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2652. const scalar = v.dot( this ) / denominator;
  2653. return this.copy( v ).multiplyScalar( scalar );
  2654. }
  2655. projectOnPlane( planeNormal ) {
  2656. _vector$c.copy( this ).projectOnVector( planeNormal );
  2657. return this.sub( _vector$c );
  2658. }
  2659. reflect( normal ) {
  2660. // reflect incident vector off plane orthogonal to normal
  2661. // normal is assumed to have unit length
  2662. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2663. }
  2664. angleTo( v ) {
  2665. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2666. if ( denominator === 0 ) return Math.PI / 2;
  2667. const theta = this.dot( v ) / denominator;
  2668. // clamp, to handle numerical problems
  2669. return Math.acos( clamp$1( theta, - 1, 1 ) );
  2670. }
  2671. distanceTo( v ) {
  2672. return Math.sqrt( this.distanceToSquared( v ) );
  2673. }
  2674. distanceToSquared( v ) {
  2675. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2676. return dx * dx + dy * dy + dz * dz;
  2677. }
  2678. manhattanDistanceTo( v ) {
  2679. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2680. }
  2681. setFromSpherical( s ) {
  2682. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2683. }
  2684. setFromSphericalCoords( radius, phi, theta ) {
  2685. const sinPhiRadius = Math.sin( phi ) * radius;
  2686. this.x = sinPhiRadius * Math.sin( theta );
  2687. this.y = Math.cos( phi ) * radius;
  2688. this.z = sinPhiRadius * Math.cos( theta );
  2689. return this;
  2690. }
  2691. setFromCylindrical( c ) {
  2692. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2693. }
  2694. setFromCylindricalCoords( radius, theta, y ) {
  2695. this.x = radius * Math.sin( theta );
  2696. this.y = y;
  2697. this.z = radius * Math.cos( theta );
  2698. return this;
  2699. }
  2700. setFromMatrixPosition( m ) {
  2701. const e = m.elements;
  2702. this.x = e[ 12 ];
  2703. this.y = e[ 13 ];
  2704. this.z = e[ 14 ];
  2705. return this;
  2706. }
  2707. setFromMatrixScale( m ) {
  2708. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2709. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2710. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2711. this.x = sx;
  2712. this.y = sy;
  2713. this.z = sz;
  2714. return this;
  2715. }
  2716. setFromMatrixColumn( m, index ) {
  2717. return this.fromArray( m.elements, index * 4 );
  2718. }
  2719. setFromMatrix3Column( m, index ) {
  2720. return this.fromArray( m.elements, index * 3 );
  2721. }
  2722. setFromEuler( e ) {
  2723. this.x = e._x;
  2724. this.y = e._y;
  2725. this.z = e._z;
  2726. return this;
  2727. }
  2728. setFromColor( c ) {
  2729. this.x = c.r;
  2730. this.y = c.g;
  2731. this.z = c.b;
  2732. return this;
  2733. }
  2734. equals( v ) {
  2735. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2736. }
  2737. fromArray( array, offset = 0 ) {
  2738. this.x = array[ offset ];
  2739. this.y = array[ offset + 1 ];
  2740. this.z = array[ offset + 2 ];
  2741. return this;
  2742. }
  2743. toArray( array = [], offset = 0 ) {
  2744. array[ offset ] = this.x;
  2745. array[ offset + 1 ] = this.y;
  2746. array[ offset + 2 ] = this.z;
  2747. return array;
  2748. }
  2749. fromBufferAttribute( attribute, index ) {
  2750. this.x = attribute.getX( index );
  2751. this.y = attribute.getY( index );
  2752. this.z = attribute.getZ( index );
  2753. return this;
  2754. }
  2755. random() {
  2756. this.x = Math.random();
  2757. this.y = Math.random();
  2758. this.z = Math.random();
  2759. return this;
  2760. }
  2761. randomDirection() {
  2762. // https://mathworld.wolfram.com/SpherePointPicking.html
  2763. const theta = Math.random() * Math.PI * 2;
  2764. const u = Math.random() * 2 - 1;
  2765. const c = Math.sqrt( 1 - u * u );
  2766. this.x = c * Math.cos( theta );
  2767. this.y = u;
  2768. this.z = c * Math.sin( theta );
  2769. return this;
  2770. }
  2771. *[ Symbol.iterator ]() {
  2772. yield this.x;
  2773. yield this.y;
  2774. yield this.z;
  2775. }
  2776. }
  2777. const _vector$c = /*@__PURE__*/ new Vector3();
  2778. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2779. class Box3 {
  2780. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2781. this.isBox3 = true;
  2782. this.min = min;
  2783. this.max = max;
  2784. }
  2785. set( min, max ) {
  2786. this.min.copy( min );
  2787. this.max.copy( max );
  2788. return this;
  2789. }
  2790. setFromArray( array ) {
  2791. this.makeEmpty();
  2792. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2793. this.expandByPoint( _vector$b.fromArray( array, i ) );
  2794. }
  2795. return this;
  2796. }
  2797. setFromBufferAttribute( attribute ) {
  2798. this.makeEmpty();
  2799. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2800. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  2801. }
  2802. return this;
  2803. }
  2804. setFromPoints( points ) {
  2805. this.makeEmpty();
  2806. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2807. this.expandByPoint( points[ i ] );
  2808. }
  2809. return this;
  2810. }
  2811. setFromCenterAndSize( center, size ) {
  2812. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2813. this.min.copy( center ).sub( halfSize );
  2814. this.max.copy( center ).add( halfSize );
  2815. return this;
  2816. }
  2817. setFromObject( object, precise = false ) {
  2818. this.makeEmpty();
  2819. return this.expandByObject( object, precise );
  2820. }
  2821. clone() {
  2822. return new this.constructor().copy( this );
  2823. }
  2824. copy( box ) {
  2825. this.min.copy( box.min );
  2826. this.max.copy( box.max );
  2827. return this;
  2828. }
  2829. makeEmpty() {
  2830. this.min.x = this.min.y = this.min.z = + Infinity;
  2831. this.max.x = this.max.y = this.max.z = - Infinity;
  2832. return this;
  2833. }
  2834. isEmpty() {
  2835. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2836. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2837. }
  2838. getCenter( target ) {
  2839. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2840. }
  2841. getSize( target ) {
  2842. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2843. }
  2844. expandByPoint( point ) {
  2845. this.min.min( point );
  2846. this.max.max( point );
  2847. return this;
  2848. }
  2849. expandByVector( vector ) {
  2850. this.min.sub( vector );
  2851. this.max.add( vector );
  2852. return this;
  2853. }
  2854. expandByScalar( scalar ) {
  2855. this.min.addScalar( - scalar );
  2856. this.max.addScalar( scalar );
  2857. return this;
  2858. }
  2859. expandByObject( object, precise = false ) {
  2860. // Computes the world-axis-aligned bounding box of an object (including its children),
  2861. // accounting for both the object's, and children's, world transforms
  2862. object.updateWorldMatrix( false, false );
  2863. const geometry = object.geometry;
  2864. if ( geometry !== undefined ) {
  2865. const positionAttribute = geometry.getAttribute( 'position' );
  2866. // precise AABB computation based on vertex data requires at least a position attribute.
  2867. // instancing isn't supported so far and uses the normal (conservative) code path.
  2868. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  2869. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  2870. if ( object.isMesh === true ) {
  2871. object.getVertexPosition( i, _vector$b );
  2872. } else {
  2873. _vector$b.fromBufferAttribute( positionAttribute, i );
  2874. }
  2875. _vector$b.applyMatrix4( object.matrixWorld );
  2876. this.expandByPoint( _vector$b );
  2877. }
  2878. } else {
  2879. if ( object.boundingBox !== undefined ) {
  2880. // object-level bounding box
  2881. if ( object.boundingBox === null ) {
  2882. object.computeBoundingBox();
  2883. }
  2884. _box$4.copy( object.boundingBox );
  2885. } else {
  2886. // geometry-level bounding box
  2887. if ( geometry.boundingBox === null ) {
  2888. geometry.computeBoundingBox();
  2889. }
  2890. _box$4.copy( geometry.boundingBox );
  2891. }
  2892. _box$4.applyMatrix4( object.matrixWorld );
  2893. this.union( _box$4 );
  2894. }
  2895. }
  2896. const children = object.children;
  2897. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2898. this.expandByObject( children[ i ], precise );
  2899. }
  2900. return this;
  2901. }
  2902. containsPoint( point ) {
  2903. return point.x < this.min.x || point.x > this.max.x ||
  2904. point.y < this.min.y || point.y > this.max.y ||
  2905. point.z < this.min.z || point.z > this.max.z ? false : true;
  2906. }
  2907. containsBox( box ) {
  2908. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2909. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2910. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2911. }
  2912. getParameter( point, target ) {
  2913. // This can potentially have a divide by zero if the box
  2914. // has a size dimension of 0.
  2915. return target.set(
  2916. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2917. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2918. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2919. );
  2920. }
  2921. intersectsBox( box ) {
  2922. // using 6 splitting planes to rule out intersections.
  2923. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2924. box.max.y < this.min.y || box.min.y > this.max.y ||
  2925. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2926. }
  2927. intersectsSphere( sphere ) {
  2928. // Find the point on the AABB closest to the sphere center.
  2929. this.clampPoint( sphere.center, _vector$b );
  2930. // If that point is inside the sphere, the AABB and sphere intersect.
  2931. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2932. }
  2933. intersectsPlane( plane ) {
  2934. // We compute the minimum and maximum dot product values. If those values
  2935. // are on the same side (back or front) of the plane, then there is no intersection.
  2936. let min, max;
  2937. if ( plane.normal.x > 0 ) {
  2938. min = plane.normal.x * this.min.x;
  2939. max = plane.normal.x * this.max.x;
  2940. } else {
  2941. min = plane.normal.x * this.max.x;
  2942. max = plane.normal.x * this.min.x;
  2943. }
  2944. if ( plane.normal.y > 0 ) {
  2945. min += plane.normal.y * this.min.y;
  2946. max += plane.normal.y * this.max.y;
  2947. } else {
  2948. min += plane.normal.y * this.max.y;
  2949. max += plane.normal.y * this.min.y;
  2950. }
  2951. if ( plane.normal.z > 0 ) {
  2952. min += plane.normal.z * this.min.z;
  2953. max += plane.normal.z * this.max.z;
  2954. } else {
  2955. min += plane.normal.z * this.max.z;
  2956. max += plane.normal.z * this.min.z;
  2957. }
  2958. return ( min <= - plane.constant && max >= - plane.constant );
  2959. }
  2960. intersectsTriangle( triangle ) {
  2961. if ( this.isEmpty() ) {
  2962. return false;
  2963. }
  2964. // compute box center and extents
  2965. this.getCenter( _center );
  2966. _extents.subVectors( this.max, _center );
  2967. // translate triangle to aabb origin
  2968. _v0$2.subVectors( triangle.a, _center );
  2969. _v1$7.subVectors( triangle.b, _center );
  2970. _v2$4.subVectors( triangle.c, _center );
  2971. // compute edge vectors for triangle
  2972. _f0.subVectors( _v1$7, _v0$2 );
  2973. _f1.subVectors( _v2$4, _v1$7 );
  2974. _f2.subVectors( _v0$2, _v2$4 );
  2975. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2976. // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation
  2977. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2978. let axes = [
  2979. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2980. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2981. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2982. ];
  2983. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2984. return false;
  2985. }
  2986. // test 3 face normals from the aabb
  2987. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2988. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2989. return false;
  2990. }
  2991. // finally testing the face normal of the triangle
  2992. // use already existing triangle edge vectors here
  2993. _triangleNormal.crossVectors( _f0, _f1 );
  2994. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  2995. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  2996. }
  2997. clampPoint( point, target ) {
  2998. return target.copy( point ).clamp( this.min, this.max );
  2999. }
  3000. distanceToPoint( point ) {
  3001. return this.clampPoint( point, _vector$b ).distanceTo( point );
  3002. }
  3003. getBoundingSphere( target ) {
  3004. if ( this.isEmpty() ) {
  3005. target.makeEmpty();
  3006. } else {
  3007. this.getCenter( target.center );
  3008. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3009. }
  3010. return target;
  3011. }
  3012. intersect( box ) {
  3013. this.min.max( box.min );
  3014. this.max.min( box.max );
  3015. // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.
  3016. if ( this.isEmpty() ) this.makeEmpty();
  3017. return this;
  3018. }
  3019. union( box ) {
  3020. this.min.min( box.min );
  3021. this.max.max( box.max );
  3022. return this;
  3023. }
  3024. applyMatrix4( matrix ) {
  3025. // transform of empty box is an empty box.
  3026. if ( this.isEmpty() ) return this;
  3027. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3028. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3029. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3030. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3031. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3032. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3033. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3034. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3035. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3036. this.setFromPoints( _points );
  3037. return this;
  3038. }
  3039. translate( offset ) {
  3040. this.min.add( offset );
  3041. this.max.add( offset );
  3042. return this;
  3043. }
  3044. equals( box ) {
  3045. return box.min.equals( this.min ) && box.max.equals( this.max );
  3046. }
  3047. }
  3048. const _points = [
  3049. /*@__PURE__*/ new Vector3(),
  3050. /*@__PURE__*/ new Vector3(),
  3051. /*@__PURE__*/ new Vector3(),
  3052. /*@__PURE__*/ new Vector3(),
  3053. /*@__PURE__*/ new Vector3(),
  3054. /*@__PURE__*/ new Vector3(),
  3055. /*@__PURE__*/ new Vector3(),
  3056. /*@__PURE__*/ new Vector3()
  3057. ];
  3058. const _vector$b = /*@__PURE__*/ new Vector3();
  3059. const _box$4 = /*@__PURE__*/ new Box3();
  3060. // triangle centered vertices
  3061. const _v0$2 = /*@__PURE__*/ new Vector3();
  3062. const _v1$7 = /*@__PURE__*/ new Vector3();
  3063. const _v2$4 = /*@__PURE__*/ new Vector3();
  3064. // triangle edge vectors
  3065. const _f0 = /*@__PURE__*/ new Vector3();
  3066. const _f1 = /*@__PURE__*/ new Vector3();
  3067. const _f2 = /*@__PURE__*/ new Vector3();
  3068. const _center = /*@__PURE__*/ new Vector3();
  3069. const _extents = /*@__PURE__*/ new Vector3();
  3070. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3071. const _testAxis = /*@__PURE__*/ new Vector3();
  3072. function satForAxes( axes, v0, v1, v2, extents ) {
  3073. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3074. _testAxis.fromArray( axes, i );
  3075. // project the aabb onto the separating axis
  3076. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3077. // project all 3 vertices of the triangle onto the separating axis
  3078. const p0 = v0.dot( _testAxis );
  3079. const p1 = v1.dot( _testAxis );
  3080. const p2 = v2.dot( _testAxis );
  3081. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3082. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3083. // points of the projected triangle are outside the projected half-length of the aabb
  3084. // the axis is separating and we can exit
  3085. return false;
  3086. }
  3087. }
  3088. return true;
  3089. }
  3090. const _box$3 = /*@__PURE__*/ new Box3();
  3091. const _v1$6 = /*@__PURE__*/ new Vector3();
  3092. const _v2$3 = /*@__PURE__*/ new Vector3();
  3093. class Sphere {
  3094. constructor( center = new Vector3(), radius = - 1 ) {
  3095. this.isSphere = true;
  3096. this.center = center;
  3097. this.radius = radius;
  3098. }
  3099. set( center, radius ) {
  3100. this.center.copy( center );
  3101. this.radius = radius;
  3102. return this;
  3103. }
  3104. setFromPoints( points, optionalCenter ) {
  3105. const center = this.center;
  3106. if ( optionalCenter !== undefined ) {
  3107. center.copy( optionalCenter );
  3108. } else {
  3109. _box$3.setFromPoints( points ).getCenter( center );
  3110. }
  3111. let maxRadiusSq = 0;
  3112. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3113. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3114. }
  3115. this.radius = Math.sqrt( maxRadiusSq );
  3116. return this;
  3117. }
  3118. copy( sphere ) {
  3119. this.center.copy( sphere.center );
  3120. this.radius = sphere.radius;
  3121. return this;
  3122. }
  3123. isEmpty() {
  3124. return ( this.radius < 0 );
  3125. }
  3126. makeEmpty() {
  3127. this.center.set( 0, 0, 0 );
  3128. this.radius = - 1;
  3129. return this;
  3130. }
  3131. containsPoint( point ) {
  3132. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3133. }
  3134. distanceToPoint( point ) {
  3135. return ( point.distanceTo( this.center ) - this.radius );
  3136. }
  3137. intersectsSphere( sphere ) {
  3138. const radiusSum = this.radius + sphere.radius;
  3139. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3140. }
  3141. intersectsBox( box ) {
  3142. return box.intersectsSphere( this );
  3143. }
  3144. intersectsPlane( plane ) {
  3145. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3146. }
  3147. clampPoint( point, target ) {
  3148. const deltaLengthSq = this.center.distanceToSquared( point );
  3149. target.copy( point );
  3150. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3151. target.sub( this.center ).normalize();
  3152. target.multiplyScalar( this.radius ).add( this.center );
  3153. }
  3154. return target;
  3155. }
  3156. getBoundingBox( target ) {
  3157. if ( this.isEmpty() ) {
  3158. // Empty sphere produces empty bounding box
  3159. target.makeEmpty();
  3160. return target;
  3161. }
  3162. target.set( this.center, this.center );
  3163. target.expandByScalar( this.radius );
  3164. return target;
  3165. }
  3166. applyMatrix4( matrix ) {
  3167. this.center.applyMatrix4( matrix );
  3168. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3169. return this;
  3170. }
  3171. translate( offset ) {
  3172. this.center.add( offset );
  3173. return this;
  3174. }
  3175. expandByPoint( point ) {
  3176. if ( this.isEmpty() ) {
  3177. this.center.copy( point );
  3178. this.radius = 0;
  3179. return this;
  3180. }
  3181. _v1$6.subVectors( point, this.center );
  3182. const lengthSq = _v1$6.lengthSq();
  3183. if ( lengthSq > ( this.radius * this.radius ) ) {
  3184. // calculate the minimal sphere
  3185. const length = Math.sqrt( lengthSq );
  3186. const delta = ( length - this.radius ) * 0.5;
  3187. this.center.addScaledVector( _v1$6, delta / length );
  3188. this.radius += delta;
  3189. }
  3190. return this;
  3191. }
  3192. union( sphere ) {
  3193. if ( sphere.isEmpty() ) {
  3194. return this;
  3195. }
  3196. if ( this.isEmpty() ) {
  3197. this.copy( sphere );
  3198. return this;
  3199. }
  3200. if ( this.center.equals( sphere.center ) === true ) {
  3201. this.radius = Math.max( this.radius, sphere.radius );
  3202. } else {
  3203. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3204. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3205. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3206. }
  3207. return this;
  3208. }
  3209. equals( sphere ) {
  3210. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3211. }
  3212. clone() {
  3213. return new this.constructor().copy( this );
  3214. }
  3215. }
  3216. const _vector$a = /*@__PURE__*/ new Vector3();
  3217. const _segCenter = /*@__PURE__*/ new Vector3();
  3218. const _segDir = /*@__PURE__*/ new Vector3();
  3219. const _diff = /*@__PURE__*/ new Vector3();
  3220. const _edge1 = /*@__PURE__*/ new Vector3();
  3221. const _edge2 = /*@__PURE__*/ new Vector3();
  3222. const _normal$2 = /*@__PURE__*/ new Vector3();
  3223. class Ray {
  3224. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3225. this.origin = origin;
  3226. this.direction = direction;
  3227. }
  3228. set( origin, direction ) {
  3229. this.origin.copy( origin );
  3230. this.direction.copy( direction );
  3231. return this;
  3232. }
  3233. copy( ray ) {
  3234. this.origin.copy( ray.origin );
  3235. this.direction.copy( ray.direction );
  3236. return this;
  3237. }
  3238. at( t, target ) {
  3239. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3240. }
  3241. lookAt( v ) {
  3242. this.direction.copy( v ).sub( this.origin ).normalize();
  3243. return this;
  3244. }
  3245. recast( t ) {
  3246. this.origin.copy( this.at( t, _vector$a ) );
  3247. return this;
  3248. }
  3249. closestPointToPoint( point, target ) {
  3250. target.subVectors( point, this.origin );
  3251. const directionDistance = target.dot( this.direction );
  3252. if ( directionDistance < 0 ) {
  3253. return target.copy( this.origin );
  3254. }
  3255. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3256. }
  3257. distanceToPoint( point ) {
  3258. return Math.sqrt( this.distanceSqToPoint( point ) );
  3259. }
  3260. distanceSqToPoint( point ) {
  3261. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3262. // point behind the ray
  3263. if ( directionDistance < 0 ) {
  3264. return this.origin.distanceToSquared( point );
  3265. }
  3266. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3267. return _vector$a.distanceToSquared( point );
  3268. }
  3269. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3270. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3271. // It returns the min distance between the ray and the segment
  3272. // defined by v0 and v1
  3273. // It can also set two optional targets :
  3274. // - The closest point on the ray
  3275. // - The closest point on the segment
  3276. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3277. _segDir.copy( v1 ).sub( v0 ).normalize();
  3278. _diff.copy( this.origin ).sub( _segCenter );
  3279. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3280. const a01 = - this.direction.dot( _segDir );
  3281. const b0 = _diff.dot( this.direction );
  3282. const b1 = - _diff.dot( _segDir );
  3283. const c = _diff.lengthSq();
  3284. const det = Math.abs( 1 - a01 * a01 );
  3285. let s0, s1, sqrDist, extDet;
  3286. if ( det > 0 ) {
  3287. // The ray and segment are not parallel.
  3288. s0 = a01 * b1 - b0;
  3289. s1 = a01 * b0 - b1;
  3290. extDet = segExtent * det;
  3291. if ( s0 >= 0 ) {
  3292. if ( s1 >= - extDet ) {
  3293. if ( s1 <= extDet ) {
  3294. // region 0
  3295. // Minimum at interior points of ray and segment.
  3296. const invDet = 1 / det;
  3297. s0 *= invDet;
  3298. s1 *= invDet;
  3299. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3300. } else {
  3301. // region 1
  3302. s1 = segExtent;
  3303. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3304. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3305. }
  3306. } else {
  3307. // region 5
  3308. s1 = - segExtent;
  3309. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3310. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3311. }
  3312. } else {
  3313. if ( s1 <= - extDet ) {
  3314. // region 4
  3315. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3316. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3317. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3318. } else if ( s1 <= extDet ) {
  3319. // region 3
  3320. s0 = 0;
  3321. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3322. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3323. } else {
  3324. // region 2
  3325. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3326. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3327. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3328. }
  3329. }
  3330. } else {
  3331. // Ray and segment are parallel.
  3332. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3333. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3334. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3335. }
  3336. if ( optionalPointOnRay ) {
  3337. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3338. }
  3339. if ( optionalPointOnSegment ) {
  3340. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3341. }
  3342. return sqrDist;
  3343. }
  3344. intersectSphere( sphere, target ) {
  3345. _vector$a.subVectors( sphere.center, this.origin );
  3346. const tca = _vector$a.dot( this.direction );
  3347. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3348. const radius2 = sphere.radius * sphere.radius;
  3349. if ( d2 > radius2 ) return null;
  3350. const thc = Math.sqrt( radius2 - d2 );
  3351. // t0 = first intersect point - entrance on front of sphere
  3352. const t0 = tca - thc;
  3353. // t1 = second intersect point - exit point on back of sphere
  3354. const t1 = tca + thc;
  3355. // test to see if t1 is behind the ray - if so, return null
  3356. if ( t1 < 0 ) return null;
  3357. // test to see if t0 is behind the ray:
  3358. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3359. // in order to always return an intersect point that is in front of the ray.
  3360. if ( t0 < 0 ) return this.at( t1, target );
  3361. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3362. return this.at( t0, target );
  3363. }
  3364. intersectsSphere( sphere ) {
  3365. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3366. }
  3367. distanceToPlane( plane ) {
  3368. const denominator = plane.normal.dot( this.direction );
  3369. if ( denominator === 0 ) {
  3370. // line is coplanar, return origin
  3371. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3372. return 0;
  3373. }
  3374. // Null is preferable to undefined since undefined means.... it is undefined
  3375. return null;
  3376. }
  3377. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3378. // Return if the ray never intersects the plane
  3379. return t >= 0 ? t : null;
  3380. }
  3381. intersectPlane( plane, target ) {
  3382. const t = this.distanceToPlane( plane );
  3383. if ( t === null ) {
  3384. return null;
  3385. }
  3386. return this.at( t, target );
  3387. }
  3388. intersectsPlane( plane ) {
  3389. // check if the ray lies on the plane first
  3390. const distToPoint = plane.distanceToPoint( this.origin );
  3391. if ( distToPoint === 0 ) {
  3392. return true;
  3393. }
  3394. const denominator = plane.normal.dot( this.direction );
  3395. if ( denominator * distToPoint < 0 ) {
  3396. return true;
  3397. }
  3398. // ray origin is behind the plane (and is pointing behind it)
  3399. return false;
  3400. }
  3401. intersectBox( box, target ) {
  3402. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3403. const invdirx = 1 / this.direction.x,
  3404. invdiry = 1 / this.direction.y,
  3405. invdirz = 1 / this.direction.z;
  3406. const origin = this.origin;
  3407. if ( invdirx >= 0 ) {
  3408. tmin = ( box.min.x - origin.x ) * invdirx;
  3409. tmax = ( box.max.x - origin.x ) * invdirx;
  3410. } else {
  3411. tmin = ( box.max.x - origin.x ) * invdirx;
  3412. tmax = ( box.min.x - origin.x ) * invdirx;
  3413. }
  3414. if ( invdiry >= 0 ) {
  3415. tymin = ( box.min.y - origin.y ) * invdiry;
  3416. tymax = ( box.max.y - origin.y ) * invdiry;
  3417. } else {
  3418. tymin = ( box.max.y - origin.y ) * invdiry;
  3419. tymax = ( box.min.y - origin.y ) * invdiry;
  3420. }
  3421. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3422. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3423. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3424. if ( invdirz >= 0 ) {
  3425. tzmin = ( box.min.z - origin.z ) * invdirz;
  3426. tzmax = ( box.max.z - origin.z ) * invdirz;
  3427. } else {
  3428. tzmin = ( box.max.z - origin.z ) * invdirz;
  3429. tzmax = ( box.min.z - origin.z ) * invdirz;
  3430. }
  3431. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3432. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3433. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3434. //return point closest to the ray (positive side)
  3435. if ( tmax < 0 ) return null;
  3436. return this.at( tmin >= 0 ? tmin : tmax, target );
  3437. }
  3438. intersectsBox( box ) {
  3439. return this.intersectBox( box, _vector$a ) !== null;
  3440. }
  3441. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3442. // Compute the offset origin, edges, and normal.
  3443. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3444. _edge1.subVectors( b, a );
  3445. _edge2.subVectors( c, a );
  3446. _normal$2.crossVectors( _edge1, _edge2 );
  3447. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3448. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3449. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3450. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3451. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3452. let DdN = this.direction.dot( _normal$2 );
  3453. let sign;
  3454. if ( DdN > 0 ) {
  3455. if ( backfaceCulling ) return null;
  3456. sign = 1;
  3457. } else if ( DdN < 0 ) {
  3458. sign = - 1;
  3459. DdN = - DdN;
  3460. } else {
  3461. return null;
  3462. }
  3463. _diff.subVectors( this.origin, a );
  3464. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3465. // b1 < 0, no intersection
  3466. if ( DdQxE2 < 0 ) {
  3467. return null;
  3468. }
  3469. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3470. // b2 < 0, no intersection
  3471. if ( DdE1xQ < 0 ) {
  3472. return null;
  3473. }
  3474. // b1+b2 > 1, no intersection
  3475. if ( DdQxE2 + DdE1xQ > DdN ) {
  3476. return null;
  3477. }
  3478. // Line intersects triangle, check if ray does.
  3479. const QdN = - sign * _diff.dot( _normal$2 );
  3480. // t < 0, no intersection
  3481. if ( QdN < 0 ) {
  3482. return null;
  3483. }
  3484. // Ray intersects triangle.
  3485. return this.at( QdN / DdN, target );
  3486. }
  3487. applyMatrix4( matrix4 ) {
  3488. this.origin.applyMatrix4( matrix4 );
  3489. this.direction.transformDirection( matrix4 );
  3490. return this;
  3491. }
  3492. equals( ray ) {
  3493. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3494. }
  3495. clone() {
  3496. return new this.constructor().copy( this );
  3497. }
  3498. }
  3499. class Matrix4 {
  3500. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3501. Matrix4.prototype.isMatrix4 = true;
  3502. this.elements = [
  3503. 1, 0, 0, 0,
  3504. 0, 1, 0, 0,
  3505. 0, 0, 1, 0,
  3506. 0, 0, 0, 1
  3507. ];
  3508. if ( n11 !== undefined ) {
  3509. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  3510. }
  3511. }
  3512. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3513. const te = this.elements;
  3514. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3515. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3516. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3517. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3518. return this;
  3519. }
  3520. identity() {
  3521. this.set(
  3522. 1, 0, 0, 0,
  3523. 0, 1, 0, 0,
  3524. 0, 0, 1, 0,
  3525. 0, 0, 0, 1
  3526. );
  3527. return this;
  3528. }
  3529. clone() {
  3530. return new Matrix4().fromArray( this.elements );
  3531. }
  3532. copy( m ) {
  3533. const te = this.elements;
  3534. const me = m.elements;
  3535. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3536. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3537. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3538. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3539. return this;
  3540. }
  3541. copyPosition( m ) {
  3542. const te = this.elements, me = m.elements;
  3543. te[ 12 ] = me[ 12 ];
  3544. te[ 13 ] = me[ 13 ];
  3545. te[ 14 ] = me[ 14 ];
  3546. return this;
  3547. }
  3548. setFromMatrix3( m ) {
  3549. const me = m.elements;
  3550. this.set(
  3551. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3552. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3553. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3554. 0, 0, 0, 1
  3555. );
  3556. return this;
  3557. }
  3558. extractBasis( xAxis, yAxis, zAxis ) {
  3559. xAxis.setFromMatrixColumn( this, 0 );
  3560. yAxis.setFromMatrixColumn( this, 1 );
  3561. zAxis.setFromMatrixColumn( this, 2 );
  3562. return this;
  3563. }
  3564. makeBasis( xAxis, yAxis, zAxis ) {
  3565. this.set(
  3566. xAxis.x, yAxis.x, zAxis.x, 0,
  3567. xAxis.y, yAxis.y, zAxis.y, 0,
  3568. xAxis.z, yAxis.z, zAxis.z, 0,
  3569. 0, 0, 0, 1
  3570. );
  3571. return this;
  3572. }
  3573. extractRotation( m ) {
  3574. // this method does not support reflection matrices
  3575. const te = this.elements;
  3576. const me = m.elements;
  3577. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3578. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3579. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3580. te[ 0 ] = me[ 0 ] * scaleX;
  3581. te[ 1 ] = me[ 1 ] * scaleX;
  3582. te[ 2 ] = me[ 2 ] * scaleX;
  3583. te[ 3 ] = 0;
  3584. te[ 4 ] = me[ 4 ] * scaleY;
  3585. te[ 5 ] = me[ 5 ] * scaleY;
  3586. te[ 6 ] = me[ 6 ] * scaleY;
  3587. te[ 7 ] = 0;
  3588. te[ 8 ] = me[ 8 ] * scaleZ;
  3589. te[ 9 ] = me[ 9 ] * scaleZ;
  3590. te[ 10 ] = me[ 10 ] * scaleZ;
  3591. te[ 11 ] = 0;
  3592. te[ 12 ] = 0;
  3593. te[ 13 ] = 0;
  3594. te[ 14 ] = 0;
  3595. te[ 15 ] = 1;
  3596. return this;
  3597. }
  3598. makeRotationFromEuler( euler ) {
  3599. const te = this.elements;
  3600. const x = euler.x, y = euler.y, z = euler.z;
  3601. const a = Math.cos( x ), b = Math.sin( x );
  3602. const c = Math.cos( y ), d = Math.sin( y );
  3603. const e = Math.cos( z ), f = Math.sin( z );
  3604. if ( euler.order === 'XYZ' ) {
  3605. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3606. te[ 0 ] = c * e;
  3607. te[ 4 ] = - c * f;
  3608. te[ 8 ] = d;
  3609. te[ 1 ] = af + be * d;
  3610. te[ 5 ] = ae - bf * d;
  3611. te[ 9 ] = - b * c;
  3612. te[ 2 ] = bf - ae * d;
  3613. te[ 6 ] = be + af * d;
  3614. te[ 10 ] = a * c;
  3615. } else if ( euler.order === 'YXZ' ) {
  3616. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3617. te[ 0 ] = ce + df * b;
  3618. te[ 4 ] = de * b - cf;
  3619. te[ 8 ] = a * d;
  3620. te[ 1 ] = a * f;
  3621. te[ 5 ] = a * e;
  3622. te[ 9 ] = - b;
  3623. te[ 2 ] = cf * b - de;
  3624. te[ 6 ] = df + ce * b;
  3625. te[ 10 ] = a * c;
  3626. } else if ( euler.order === 'ZXY' ) {
  3627. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3628. te[ 0 ] = ce - df * b;
  3629. te[ 4 ] = - a * f;
  3630. te[ 8 ] = de + cf * b;
  3631. te[ 1 ] = cf + de * b;
  3632. te[ 5 ] = a * e;
  3633. te[ 9 ] = df - ce * b;
  3634. te[ 2 ] = - a * d;
  3635. te[ 6 ] = b;
  3636. te[ 10 ] = a * c;
  3637. } else if ( euler.order === 'ZYX' ) {
  3638. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3639. te[ 0 ] = c * e;
  3640. te[ 4 ] = be * d - af;
  3641. te[ 8 ] = ae * d + bf;
  3642. te[ 1 ] = c * f;
  3643. te[ 5 ] = bf * d + ae;
  3644. te[ 9 ] = af * d - be;
  3645. te[ 2 ] = - d;
  3646. te[ 6 ] = b * c;
  3647. te[ 10 ] = a * c;
  3648. } else if ( euler.order === 'YZX' ) {
  3649. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3650. te[ 0 ] = c * e;
  3651. te[ 4 ] = bd - ac * f;
  3652. te[ 8 ] = bc * f + ad;
  3653. te[ 1 ] = f;
  3654. te[ 5 ] = a * e;
  3655. te[ 9 ] = - b * e;
  3656. te[ 2 ] = - d * e;
  3657. te[ 6 ] = ad * f + bc;
  3658. te[ 10 ] = ac - bd * f;
  3659. } else if ( euler.order === 'XZY' ) {
  3660. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3661. te[ 0 ] = c * e;
  3662. te[ 4 ] = - f;
  3663. te[ 8 ] = d * e;
  3664. te[ 1 ] = ac * f + bd;
  3665. te[ 5 ] = a * e;
  3666. te[ 9 ] = ad * f - bc;
  3667. te[ 2 ] = bc * f - ad;
  3668. te[ 6 ] = b * e;
  3669. te[ 10 ] = bd * f + ac;
  3670. }
  3671. // bottom row
  3672. te[ 3 ] = 0;
  3673. te[ 7 ] = 0;
  3674. te[ 11 ] = 0;
  3675. // last column
  3676. te[ 12 ] = 0;
  3677. te[ 13 ] = 0;
  3678. te[ 14 ] = 0;
  3679. te[ 15 ] = 1;
  3680. return this;
  3681. }
  3682. makeRotationFromQuaternion( q ) {
  3683. return this.compose( _zero, q, _one );
  3684. }
  3685. lookAt( eye, target, up ) {
  3686. const te = this.elements;
  3687. _z.subVectors( eye, target );
  3688. if ( _z.lengthSq() === 0 ) {
  3689. // eye and target are in the same position
  3690. _z.z = 1;
  3691. }
  3692. _z.normalize();
  3693. _x.crossVectors( up, _z );
  3694. if ( _x.lengthSq() === 0 ) {
  3695. // up and z are parallel
  3696. if ( Math.abs( up.z ) === 1 ) {
  3697. _z.x += 0.0001;
  3698. } else {
  3699. _z.z += 0.0001;
  3700. }
  3701. _z.normalize();
  3702. _x.crossVectors( up, _z );
  3703. }
  3704. _x.normalize();
  3705. _y.crossVectors( _z, _x );
  3706. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3707. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3708. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3709. return this;
  3710. }
  3711. multiply( m ) {
  3712. return this.multiplyMatrices( this, m );
  3713. }
  3714. premultiply( m ) {
  3715. return this.multiplyMatrices( m, this );
  3716. }
  3717. multiplyMatrices( a, b ) {
  3718. const ae = a.elements;
  3719. const be = b.elements;
  3720. const te = this.elements;
  3721. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3722. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3723. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3724. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3725. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3726. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3727. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3728. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3729. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3730. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3731. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3732. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3733. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3734. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3735. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3736. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3737. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3738. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3739. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3740. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3741. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3742. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3743. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3744. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3745. return this;
  3746. }
  3747. multiplyScalar( s ) {
  3748. const te = this.elements;
  3749. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3750. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3751. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3752. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3753. return this;
  3754. }
  3755. determinant() {
  3756. const te = this.elements;
  3757. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3758. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3759. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3760. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3761. //TODO: make this more efficient
  3762. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3763. return (
  3764. n41 * (
  3765. + n14 * n23 * n32
  3766. - n13 * n24 * n32
  3767. - n14 * n22 * n33
  3768. + n12 * n24 * n33
  3769. + n13 * n22 * n34
  3770. - n12 * n23 * n34
  3771. ) +
  3772. n42 * (
  3773. + n11 * n23 * n34
  3774. - n11 * n24 * n33
  3775. + n14 * n21 * n33
  3776. - n13 * n21 * n34
  3777. + n13 * n24 * n31
  3778. - n14 * n23 * n31
  3779. ) +
  3780. n43 * (
  3781. + n11 * n24 * n32
  3782. - n11 * n22 * n34
  3783. - n14 * n21 * n32
  3784. + n12 * n21 * n34
  3785. + n14 * n22 * n31
  3786. - n12 * n24 * n31
  3787. ) +
  3788. n44 * (
  3789. - n13 * n22 * n31
  3790. - n11 * n23 * n32
  3791. + n11 * n22 * n33
  3792. + n13 * n21 * n32
  3793. - n12 * n21 * n33
  3794. + n12 * n23 * n31
  3795. )
  3796. );
  3797. }
  3798. transpose() {
  3799. const te = this.elements;
  3800. let tmp;
  3801. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3802. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3803. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3804. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3805. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3806. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3807. return this;
  3808. }
  3809. setPosition( x, y, z ) {
  3810. const te = this.elements;
  3811. if ( x.isVector3 ) {
  3812. te[ 12 ] = x.x;
  3813. te[ 13 ] = x.y;
  3814. te[ 14 ] = x.z;
  3815. } else {
  3816. te[ 12 ] = x;
  3817. te[ 13 ] = y;
  3818. te[ 14 ] = z;
  3819. }
  3820. return this;
  3821. }
  3822. invert() {
  3823. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3824. const te = this.elements,
  3825. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3826. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3827. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3828. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3829. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3830. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3831. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3832. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3833. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3834. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3835. const detInv = 1 / det;
  3836. te[ 0 ] = t11 * detInv;
  3837. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3838. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3839. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3840. te[ 4 ] = t12 * detInv;
  3841. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3842. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3843. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3844. te[ 8 ] = t13 * detInv;
  3845. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3846. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3847. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3848. te[ 12 ] = t14 * detInv;
  3849. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3850. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3851. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3852. return this;
  3853. }
  3854. scale( v ) {
  3855. const te = this.elements;
  3856. const x = v.x, y = v.y, z = v.z;
  3857. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3858. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3859. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3860. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3861. return this;
  3862. }
  3863. getMaxScaleOnAxis() {
  3864. const te = this.elements;
  3865. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3866. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3867. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3868. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3869. }
  3870. makeTranslation( x, y, z ) {
  3871. if ( x.isVector3 ) {
  3872. this.set(
  3873. 1, 0, 0, x.x,
  3874. 0, 1, 0, x.y,
  3875. 0, 0, 1, x.z,
  3876. 0, 0, 0, 1
  3877. );
  3878. } else {
  3879. this.set(
  3880. 1, 0, 0, x,
  3881. 0, 1, 0, y,
  3882. 0, 0, 1, z,
  3883. 0, 0, 0, 1
  3884. );
  3885. }
  3886. return this;
  3887. }
  3888. makeRotationX( theta ) {
  3889. const c = Math.cos( theta ), s = Math.sin( theta );
  3890. this.set(
  3891. 1, 0, 0, 0,
  3892. 0, c, - s, 0,
  3893. 0, s, c, 0,
  3894. 0, 0, 0, 1
  3895. );
  3896. return this;
  3897. }
  3898. makeRotationY( theta ) {
  3899. const c = Math.cos( theta ), s = Math.sin( theta );
  3900. this.set(
  3901. c, 0, s, 0,
  3902. 0, 1, 0, 0,
  3903. - s, 0, c, 0,
  3904. 0, 0, 0, 1
  3905. );
  3906. return this;
  3907. }
  3908. makeRotationZ( theta ) {
  3909. const c = Math.cos( theta ), s = Math.sin( theta );
  3910. this.set(
  3911. c, - s, 0, 0,
  3912. s, c, 0, 0,
  3913. 0, 0, 1, 0,
  3914. 0, 0, 0, 1
  3915. );
  3916. return this;
  3917. }
  3918. makeRotationAxis( axis, angle ) {
  3919. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3920. const c = Math.cos( angle );
  3921. const s = Math.sin( angle );
  3922. const t = 1 - c;
  3923. const x = axis.x, y = axis.y, z = axis.z;
  3924. const tx = t * x, ty = t * y;
  3925. this.set(
  3926. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3927. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3928. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3929. 0, 0, 0, 1
  3930. );
  3931. return this;
  3932. }
  3933. makeScale( x, y, z ) {
  3934. this.set(
  3935. x, 0, 0, 0,
  3936. 0, y, 0, 0,
  3937. 0, 0, z, 0,
  3938. 0, 0, 0, 1
  3939. );
  3940. return this;
  3941. }
  3942. makeShear( xy, xz, yx, yz, zx, zy ) {
  3943. this.set(
  3944. 1, yx, zx, 0,
  3945. xy, 1, zy, 0,
  3946. xz, yz, 1, 0,
  3947. 0, 0, 0, 1
  3948. );
  3949. return this;
  3950. }
  3951. compose( position, quaternion, scale ) {
  3952. const te = this.elements;
  3953. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3954. const x2 = x + x, y2 = y + y, z2 = z + z;
  3955. const xx = x * x2, xy = x * y2, xz = x * z2;
  3956. const yy = y * y2, yz = y * z2, zz = z * z2;
  3957. const wx = w * x2, wy = w * y2, wz = w * z2;
  3958. const sx = scale.x, sy = scale.y, sz = scale.z;
  3959. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3960. te[ 1 ] = ( xy + wz ) * sx;
  3961. te[ 2 ] = ( xz - wy ) * sx;
  3962. te[ 3 ] = 0;
  3963. te[ 4 ] = ( xy - wz ) * sy;
  3964. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3965. te[ 6 ] = ( yz + wx ) * sy;
  3966. te[ 7 ] = 0;
  3967. te[ 8 ] = ( xz + wy ) * sz;
  3968. te[ 9 ] = ( yz - wx ) * sz;
  3969. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3970. te[ 11 ] = 0;
  3971. te[ 12 ] = position.x;
  3972. te[ 13 ] = position.y;
  3973. te[ 14 ] = position.z;
  3974. te[ 15 ] = 1;
  3975. return this;
  3976. }
  3977. decompose( position, quaternion, scale ) {
  3978. const te = this.elements;
  3979. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3980. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3981. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3982. // if determine is negative, we need to invert one scale
  3983. const det = this.determinant();
  3984. if ( det < 0 ) sx = - sx;
  3985. position.x = te[ 12 ];
  3986. position.y = te[ 13 ];
  3987. position.z = te[ 14 ];
  3988. // scale the rotation part
  3989. _m1$2.copy( this );
  3990. const invSX = 1 / sx;
  3991. const invSY = 1 / sy;
  3992. const invSZ = 1 / sz;
  3993. _m1$2.elements[ 0 ] *= invSX;
  3994. _m1$2.elements[ 1 ] *= invSX;
  3995. _m1$2.elements[ 2 ] *= invSX;
  3996. _m1$2.elements[ 4 ] *= invSY;
  3997. _m1$2.elements[ 5 ] *= invSY;
  3998. _m1$2.elements[ 6 ] *= invSY;
  3999. _m1$2.elements[ 8 ] *= invSZ;
  4000. _m1$2.elements[ 9 ] *= invSZ;
  4001. _m1$2.elements[ 10 ] *= invSZ;
  4002. quaternion.setFromRotationMatrix( _m1$2 );
  4003. scale.x = sx;
  4004. scale.y = sy;
  4005. scale.z = sz;
  4006. return this;
  4007. }
  4008. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4009. const te = this.elements;
  4010. const x = 2 * near / ( right - left );
  4011. const y = 2 * near / ( top - bottom );
  4012. const a = ( right + left ) / ( right - left );
  4013. const b = ( top + bottom ) / ( top - bottom );
  4014. let c, d;
  4015. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4016. c = - ( far + near ) / ( far - near );
  4017. d = ( - 2 * far * near ) / ( far - near );
  4018. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4019. c = - far / ( far - near );
  4020. d = ( - far * near ) / ( far - near );
  4021. } else {
  4022. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  4023. }
  4024. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4025. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4026. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4027. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4028. return this;
  4029. }
  4030. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4031. const te = this.elements;
  4032. const w = 1.0 / ( right - left );
  4033. const h = 1.0 / ( top - bottom );
  4034. const p = 1.0 / ( far - near );
  4035. const x = ( right + left ) * w;
  4036. const y = ( top + bottom ) * h;
  4037. let z, zInv;
  4038. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4039. z = ( far + near ) * p;
  4040. zInv = - 2 * p;
  4041. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4042. z = near * p;
  4043. zInv = - 1 * p;
  4044. } else {
  4045. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  4046. }
  4047. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4048. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4049. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  4050. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4051. return this;
  4052. }
  4053. equals( matrix ) {
  4054. const te = this.elements;
  4055. const me = matrix.elements;
  4056. for ( let i = 0; i < 16; i ++ ) {
  4057. if ( te[ i ] !== me[ i ] ) return false;
  4058. }
  4059. return true;
  4060. }
  4061. fromArray( array, offset = 0 ) {
  4062. for ( let i = 0; i < 16; i ++ ) {
  4063. this.elements[ i ] = array[ i + offset ];
  4064. }
  4065. return this;
  4066. }
  4067. toArray( array = [], offset = 0 ) {
  4068. const te = this.elements;
  4069. array[ offset ] = te[ 0 ];
  4070. array[ offset + 1 ] = te[ 1 ];
  4071. array[ offset + 2 ] = te[ 2 ];
  4072. array[ offset + 3 ] = te[ 3 ];
  4073. array[ offset + 4 ] = te[ 4 ];
  4074. array[ offset + 5 ] = te[ 5 ];
  4075. array[ offset + 6 ] = te[ 6 ];
  4076. array[ offset + 7 ] = te[ 7 ];
  4077. array[ offset + 8 ] = te[ 8 ];
  4078. array[ offset + 9 ] = te[ 9 ];
  4079. array[ offset + 10 ] = te[ 10 ];
  4080. array[ offset + 11 ] = te[ 11 ];
  4081. array[ offset + 12 ] = te[ 12 ];
  4082. array[ offset + 13 ] = te[ 13 ];
  4083. array[ offset + 14 ] = te[ 14 ];
  4084. array[ offset + 15 ] = te[ 15 ];
  4085. return array;
  4086. }
  4087. }
  4088. const _v1$5 = /*@__PURE__*/ new Vector3();
  4089. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4090. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4091. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4092. const _x = /*@__PURE__*/ new Vector3();
  4093. const _y = /*@__PURE__*/ new Vector3();
  4094. const _z = /*@__PURE__*/ new Vector3();
  4095. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  4096. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4097. class Euler {
  4098. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4099. this.isEuler = true;
  4100. this._x = x;
  4101. this._y = y;
  4102. this._z = z;
  4103. this._order = order;
  4104. }
  4105. get x() {
  4106. return this._x;
  4107. }
  4108. set x( value ) {
  4109. this._x = value;
  4110. this._onChangeCallback();
  4111. }
  4112. get y() {
  4113. return this._y;
  4114. }
  4115. set y( value ) {
  4116. this._y = value;
  4117. this._onChangeCallback();
  4118. }
  4119. get z() {
  4120. return this._z;
  4121. }
  4122. set z( value ) {
  4123. this._z = value;
  4124. this._onChangeCallback();
  4125. }
  4126. get order() {
  4127. return this._order;
  4128. }
  4129. set order( value ) {
  4130. this._order = value;
  4131. this._onChangeCallback();
  4132. }
  4133. set( x, y, z, order = this._order ) {
  4134. this._x = x;
  4135. this._y = y;
  4136. this._z = z;
  4137. this._order = order;
  4138. this._onChangeCallback();
  4139. return this;
  4140. }
  4141. clone() {
  4142. return new this.constructor( this._x, this._y, this._z, this._order );
  4143. }
  4144. copy( euler ) {
  4145. this._x = euler._x;
  4146. this._y = euler._y;
  4147. this._z = euler._z;
  4148. this._order = euler._order;
  4149. this._onChangeCallback();
  4150. return this;
  4151. }
  4152. setFromRotationMatrix( m, order = this._order, update = true ) {
  4153. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4154. const te = m.elements;
  4155. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4156. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4157. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4158. switch ( order ) {
  4159. case 'XYZ':
  4160. this._y = Math.asin( clamp$1( m13, - 1, 1 ) );
  4161. if ( Math.abs( m13 ) < 0.9999999 ) {
  4162. this._x = Math.atan2( - m23, m33 );
  4163. this._z = Math.atan2( - m12, m11 );
  4164. } else {
  4165. this._x = Math.atan2( m32, m22 );
  4166. this._z = 0;
  4167. }
  4168. break;
  4169. case 'YXZ':
  4170. this._x = Math.asin( - clamp$1( m23, - 1, 1 ) );
  4171. if ( Math.abs( m23 ) < 0.9999999 ) {
  4172. this._y = Math.atan2( m13, m33 );
  4173. this._z = Math.atan2( m21, m22 );
  4174. } else {
  4175. this._y = Math.atan2( - m31, m11 );
  4176. this._z = 0;
  4177. }
  4178. break;
  4179. case 'ZXY':
  4180. this._x = Math.asin( clamp$1( m32, - 1, 1 ) );
  4181. if ( Math.abs( m32 ) < 0.9999999 ) {
  4182. this._y = Math.atan2( - m31, m33 );
  4183. this._z = Math.atan2( - m12, m22 );
  4184. } else {
  4185. this._y = 0;
  4186. this._z = Math.atan2( m21, m11 );
  4187. }
  4188. break;
  4189. case 'ZYX':
  4190. this._y = Math.asin( - clamp$1( m31, - 1, 1 ) );
  4191. if ( Math.abs( m31 ) < 0.9999999 ) {
  4192. this._x = Math.atan2( m32, m33 );
  4193. this._z = Math.atan2( m21, m11 );
  4194. } else {
  4195. this._x = 0;
  4196. this._z = Math.atan2( - m12, m22 );
  4197. }
  4198. break;
  4199. case 'YZX':
  4200. this._z = Math.asin( clamp$1( m21, - 1, 1 ) );
  4201. if ( Math.abs( m21 ) < 0.9999999 ) {
  4202. this._x = Math.atan2( - m23, m22 );
  4203. this._y = Math.atan2( - m31, m11 );
  4204. } else {
  4205. this._x = 0;
  4206. this._y = Math.atan2( m13, m33 );
  4207. }
  4208. break;
  4209. case 'XZY':
  4210. this._z = Math.asin( - clamp$1( m12, - 1, 1 ) );
  4211. if ( Math.abs( m12 ) < 0.9999999 ) {
  4212. this._x = Math.atan2( m32, m22 );
  4213. this._y = Math.atan2( m13, m11 );
  4214. } else {
  4215. this._x = Math.atan2( - m23, m33 );
  4216. this._y = 0;
  4217. }
  4218. break;
  4219. default:
  4220. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4221. }
  4222. this._order = order;
  4223. if ( update === true ) this._onChangeCallback();
  4224. return this;
  4225. }
  4226. setFromQuaternion( q, order, update ) {
  4227. _matrix$2.makeRotationFromQuaternion( q );
  4228. return this.setFromRotationMatrix( _matrix$2, order, update );
  4229. }
  4230. setFromVector3( v, order = this._order ) {
  4231. return this.set( v.x, v.y, v.z, order );
  4232. }
  4233. reorder( newOrder ) {
  4234. // WARNING: this discards revolution information -bhouston
  4235. _quaternion$3.setFromEuler( this );
  4236. return this.setFromQuaternion( _quaternion$3, newOrder );
  4237. }
  4238. equals( euler ) {
  4239. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4240. }
  4241. fromArray( array ) {
  4242. this._x = array[ 0 ];
  4243. this._y = array[ 1 ];
  4244. this._z = array[ 2 ];
  4245. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4246. this._onChangeCallback();
  4247. return this;
  4248. }
  4249. toArray( array = [], offset = 0 ) {
  4250. array[ offset ] = this._x;
  4251. array[ offset + 1 ] = this._y;
  4252. array[ offset + 2 ] = this._z;
  4253. array[ offset + 3 ] = this._order;
  4254. return array;
  4255. }
  4256. _onChange( callback ) {
  4257. this._onChangeCallback = callback;
  4258. return this;
  4259. }
  4260. _onChangeCallback() {}
  4261. *[ Symbol.iterator ]() {
  4262. yield this._x;
  4263. yield this._y;
  4264. yield this._z;
  4265. yield this._order;
  4266. }
  4267. }
  4268. Euler.DEFAULT_ORDER = 'XYZ';
  4269. class Layers {
  4270. constructor() {
  4271. this.mask = 1 | 0;
  4272. }
  4273. set( channel ) {
  4274. this.mask = ( 1 << channel | 0 ) >>> 0;
  4275. }
  4276. enable( channel ) {
  4277. this.mask |= 1 << channel | 0;
  4278. }
  4279. enableAll() {
  4280. this.mask = 0xffffffff | 0;
  4281. }
  4282. toggle( channel ) {
  4283. this.mask ^= 1 << channel | 0;
  4284. }
  4285. disable( channel ) {
  4286. this.mask &= ~ ( 1 << channel | 0 );
  4287. }
  4288. disableAll() {
  4289. this.mask = 0;
  4290. }
  4291. test( layers ) {
  4292. return ( this.mask & layers.mask ) !== 0;
  4293. }
  4294. isEnabled( channel ) {
  4295. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4296. }
  4297. }
  4298. let _object3DId = 0;
  4299. const _v1$4 = /*@__PURE__*/ new Vector3();
  4300. const _q1 = /*@__PURE__*/ new Quaternion();
  4301. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4302. const _target$1 = /*@__PURE__*/ new Vector3();
  4303. const _position$3 = /*@__PURE__*/ new Vector3();
  4304. const _scale$2 = /*@__PURE__*/ new Vector3();
  4305. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4306. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4307. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4308. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4309. const _addedEvent = { type: 'added' };
  4310. const _removedEvent = { type: 'removed' };
  4311. const _childaddedEvent = { type: 'childadded', child: null };
  4312. const _childremovedEvent = { type: 'childremoved', child: null };
  4313. class Object3D extends EventDispatcher {
  4314. constructor() {
  4315. super();
  4316. this.isObject3D = true;
  4317. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4318. this.uuid = generateUUID();
  4319. this.name = '';
  4320. this.type = 'Object3D';
  4321. this.parent = null;
  4322. this.children = [];
  4323. this.up = Object3D.DEFAULT_UP.clone();
  4324. const position = new Vector3();
  4325. const rotation = new Euler();
  4326. const quaternion = new Quaternion();
  4327. const scale = new Vector3( 1, 1, 1 );
  4328. function onRotationChange() {
  4329. quaternion.setFromEuler( rotation, false );
  4330. }
  4331. function onQuaternionChange() {
  4332. rotation.setFromQuaternion( quaternion, undefined, false );
  4333. }
  4334. rotation._onChange( onRotationChange );
  4335. quaternion._onChange( onQuaternionChange );
  4336. Object.defineProperties( this, {
  4337. position: {
  4338. configurable: true,
  4339. enumerable: true,
  4340. value: position
  4341. },
  4342. rotation: {
  4343. configurable: true,
  4344. enumerable: true,
  4345. value: rotation
  4346. },
  4347. quaternion: {
  4348. configurable: true,
  4349. enumerable: true,
  4350. value: quaternion
  4351. },
  4352. scale: {
  4353. configurable: true,
  4354. enumerable: true,
  4355. value: scale
  4356. },
  4357. modelViewMatrix: {
  4358. value: new Matrix4()
  4359. },
  4360. normalMatrix: {
  4361. value: new Matrix3()
  4362. }
  4363. } );
  4364. this.matrix = new Matrix4();
  4365. this.matrixWorld = new Matrix4();
  4366. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4367. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4368. this.matrixWorldNeedsUpdate = false;
  4369. this.layers = new Layers();
  4370. this.visible = true;
  4371. this.castShadow = false;
  4372. this.receiveShadow = false;
  4373. this.frustumCulled = true;
  4374. this.renderOrder = 0;
  4375. this.animations = [];
  4376. this.userData = {};
  4377. }
  4378. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4379. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4380. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4381. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4382. applyMatrix4( matrix ) {
  4383. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4384. this.matrix.premultiply( matrix );
  4385. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4386. }
  4387. applyQuaternion( q ) {
  4388. this.quaternion.premultiply( q );
  4389. return this;
  4390. }
  4391. setRotationFromAxisAngle( axis, angle ) {
  4392. // assumes axis is normalized
  4393. this.quaternion.setFromAxisAngle( axis, angle );
  4394. }
  4395. setRotationFromEuler( euler ) {
  4396. this.quaternion.setFromEuler( euler, true );
  4397. }
  4398. setRotationFromMatrix( m ) {
  4399. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4400. this.quaternion.setFromRotationMatrix( m );
  4401. }
  4402. setRotationFromQuaternion( q ) {
  4403. // assumes q is normalized
  4404. this.quaternion.copy( q );
  4405. }
  4406. rotateOnAxis( axis, angle ) {
  4407. // rotate object on axis in object space
  4408. // axis is assumed to be normalized
  4409. _q1.setFromAxisAngle( axis, angle );
  4410. this.quaternion.multiply( _q1 );
  4411. return this;
  4412. }
  4413. rotateOnWorldAxis( axis, angle ) {
  4414. // rotate object on axis in world space
  4415. // axis is assumed to be normalized
  4416. // method assumes no rotated parent
  4417. _q1.setFromAxisAngle( axis, angle );
  4418. this.quaternion.premultiply( _q1 );
  4419. return this;
  4420. }
  4421. rotateX( angle ) {
  4422. return this.rotateOnAxis( _xAxis, angle );
  4423. }
  4424. rotateY( angle ) {
  4425. return this.rotateOnAxis( _yAxis, angle );
  4426. }
  4427. rotateZ( angle ) {
  4428. return this.rotateOnAxis( _zAxis, angle );
  4429. }
  4430. translateOnAxis( axis, distance ) {
  4431. // translate object by distance along axis in object space
  4432. // axis is assumed to be normalized
  4433. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4434. this.position.add( _v1$4.multiplyScalar( distance ) );
  4435. return this;
  4436. }
  4437. translateX( distance ) {
  4438. return this.translateOnAxis( _xAxis, distance );
  4439. }
  4440. translateY( distance ) {
  4441. return this.translateOnAxis( _yAxis, distance );
  4442. }
  4443. translateZ( distance ) {
  4444. return this.translateOnAxis( _zAxis, distance );
  4445. }
  4446. localToWorld( vector ) {
  4447. this.updateWorldMatrix( true, false );
  4448. return vector.applyMatrix4( this.matrixWorld );
  4449. }
  4450. worldToLocal( vector ) {
  4451. this.updateWorldMatrix( true, false );
  4452. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4453. }
  4454. lookAt( x, y, z ) {
  4455. // This method does not support objects having non-uniformly-scaled parent(s)
  4456. if ( x.isVector3 ) {
  4457. _target$1.copy( x );
  4458. } else {
  4459. _target$1.set( x, y, z );
  4460. }
  4461. const parent = this.parent;
  4462. this.updateWorldMatrix( true, false );
  4463. _position$3.setFromMatrixPosition( this.matrixWorld );
  4464. if ( this.isCamera || this.isLight ) {
  4465. _m1$1.lookAt( _position$3, _target$1, this.up );
  4466. } else {
  4467. _m1$1.lookAt( _target$1, _position$3, this.up );
  4468. }
  4469. this.quaternion.setFromRotationMatrix( _m1$1 );
  4470. if ( parent ) {
  4471. _m1$1.extractRotation( parent.matrixWorld );
  4472. _q1.setFromRotationMatrix( _m1$1 );
  4473. this.quaternion.premultiply( _q1.invert() );
  4474. }
  4475. }
  4476. add( object ) {
  4477. if ( arguments.length > 1 ) {
  4478. for ( let i = 0; i < arguments.length; i ++ ) {
  4479. this.add( arguments[ i ] );
  4480. }
  4481. return this;
  4482. }
  4483. if ( object === this ) {
  4484. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4485. return this;
  4486. }
  4487. if ( object && object.isObject3D ) {
  4488. object.removeFromParent();
  4489. object.parent = this;
  4490. this.children.push( object );
  4491. object.dispatchEvent( _addedEvent );
  4492. _childaddedEvent.child = object;
  4493. this.dispatchEvent( _childaddedEvent );
  4494. _childaddedEvent.child = null;
  4495. } else {
  4496. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4497. }
  4498. return this;
  4499. }
  4500. remove( object ) {
  4501. if ( arguments.length > 1 ) {
  4502. for ( let i = 0; i < arguments.length; i ++ ) {
  4503. this.remove( arguments[ i ] );
  4504. }
  4505. return this;
  4506. }
  4507. const index = this.children.indexOf( object );
  4508. if ( index !== - 1 ) {
  4509. object.parent = null;
  4510. this.children.splice( index, 1 );
  4511. object.dispatchEvent( _removedEvent );
  4512. _childremovedEvent.child = object;
  4513. this.dispatchEvent( _childremovedEvent );
  4514. _childremovedEvent.child = null;
  4515. }
  4516. return this;
  4517. }
  4518. removeFromParent() {
  4519. const parent = this.parent;
  4520. if ( parent !== null ) {
  4521. parent.remove( this );
  4522. }
  4523. return this;
  4524. }
  4525. clear() {
  4526. return this.remove( ... this.children );
  4527. }
  4528. attach( object ) {
  4529. // adds object as a child of this, while maintaining the object's world transform
  4530. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4531. this.updateWorldMatrix( true, false );
  4532. _m1$1.copy( this.matrixWorld ).invert();
  4533. if ( object.parent !== null ) {
  4534. object.parent.updateWorldMatrix( true, false );
  4535. _m1$1.multiply( object.parent.matrixWorld );
  4536. }
  4537. object.applyMatrix4( _m1$1 );
  4538. object.removeFromParent();
  4539. object.parent = this;
  4540. this.children.push( object );
  4541. object.updateWorldMatrix( false, true );
  4542. object.dispatchEvent( _addedEvent );
  4543. _childaddedEvent.child = object;
  4544. this.dispatchEvent( _childaddedEvent );
  4545. _childaddedEvent.child = null;
  4546. return this;
  4547. }
  4548. getObjectById( id ) {
  4549. return this.getObjectByProperty( 'id', id );
  4550. }
  4551. getObjectByName( name ) {
  4552. return this.getObjectByProperty( 'name', name );
  4553. }
  4554. getObjectByProperty( name, value ) {
  4555. if ( this[ name ] === value ) return this;
  4556. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4557. const child = this.children[ i ];
  4558. const object = child.getObjectByProperty( name, value );
  4559. if ( object !== undefined ) {
  4560. return object;
  4561. }
  4562. }
  4563. return undefined;
  4564. }
  4565. getObjectsByProperty( name, value, result = [] ) {
  4566. if ( this[ name ] === value ) result.push( this );
  4567. const children = this.children;
  4568. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4569. children[ i ].getObjectsByProperty( name, value, result );
  4570. }
  4571. return result;
  4572. }
  4573. getWorldPosition( target ) {
  4574. this.updateWorldMatrix( true, false );
  4575. return target.setFromMatrixPosition( this.matrixWorld );
  4576. }
  4577. getWorldQuaternion( target ) {
  4578. this.updateWorldMatrix( true, false );
  4579. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4580. return target;
  4581. }
  4582. getWorldScale( target ) {
  4583. this.updateWorldMatrix( true, false );
  4584. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4585. return target;
  4586. }
  4587. getWorldDirection( target ) {
  4588. this.updateWorldMatrix( true, false );
  4589. const e = this.matrixWorld.elements;
  4590. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4591. }
  4592. raycast( /* raycaster, intersects */ ) {}
  4593. traverse( callback ) {
  4594. callback( this );
  4595. const children = this.children;
  4596. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4597. children[ i ].traverse( callback );
  4598. }
  4599. }
  4600. traverseVisible( callback ) {
  4601. if ( this.visible === false ) return;
  4602. callback( this );
  4603. const children = this.children;
  4604. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4605. children[ i ].traverseVisible( callback );
  4606. }
  4607. }
  4608. traverseAncestors( callback ) {
  4609. const parent = this.parent;
  4610. if ( parent !== null ) {
  4611. callback( parent );
  4612. parent.traverseAncestors( callback );
  4613. }
  4614. }
  4615. updateMatrix() {
  4616. this.matrix.compose( this.position, this.quaternion, this.scale );
  4617. this.matrixWorldNeedsUpdate = true;
  4618. }
  4619. updateMatrixWorld( force ) {
  4620. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4621. if ( this.matrixWorldNeedsUpdate || force ) {
  4622. if ( this.matrixWorldAutoUpdate === true ) {
  4623. if ( this.parent === null ) {
  4624. this.matrixWorld.copy( this.matrix );
  4625. } else {
  4626. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4627. }
  4628. }
  4629. this.matrixWorldNeedsUpdate = false;
  4630. force = true;
  4631. }
  4632. // make sure descendants are updated if required
  4633. const children = this.children;
  4634. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4635. const child = children[ i ];
  4636. child.updateMatrixWorld( force );
  4637. }
  4638. }
  4639. updateWorldMatrix( updateParents, updateChildren ) {
  4640. const parent = this.parent;
  4641. if ( updateParents === true && parent !== null ) {
  4642. parent.updateWorldMatrix( true, false );
  4643. }
  4644. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4645. if ( this.matrixWorldAutoUpdate === true ) {
  4646. if ( this.parent === null ) {
  4647. this.matrixWorld.copy( this.matrix );
  4648. } else {
  4649. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4650. }
  4651. }
  4652. // make sure descendants are updated
  4653. if ( updateChildren === true ) {
  4654. const children = this.children;
  4655. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4656. const child = children[ i ];
  4657. child.updateWorldMatrix( false, true );
  4658. }
  4659. }
  4660. }
  4661. toJSON( meta ) {
  4662. // meta is a string when called from JSON.stringify
  4663. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4664. const output = {};
  4665. // meta is a hash used to collect geometries, materials.
  4666. // not providing it implies that this is the root object
  4667. // being serialized.
  4668. if ( isRootObject ) {
  4669. // initialize meta obj
  4670. meta = {
  4671. geometries: {},
  4672. materials: {},
  4673. textures: {},
  4674. images: {},
  4675. shapes: {},
  4676. skeletons: {},
  4677. animations: {},
  4678. nodes: {}
  4679. };
  4680. output.metadata = {
  4681. version: 4.6,
  4682. type: 'Object',
  4683. generator: 'Object3D.toJSON'
  4684. };
  4685. }
  4686. // standard Object3D serialization
  4687. const object = {};
  4688. object.uuid = this.uuid;
  4689. object.type = this.type;
  4690. if ( this.name !== '' ) object.name = this.name;
  4691. if ( this.castShadow === true ) object.castShadow = true;
  4692. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4693. if ( this.visible === false ) object.visible = false;
  4694. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4695. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4696. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4697. object.layers = this.layers.mask;
  4698. object.matrix = this.matrix.toArray();
  4699. object.up = this.up.toArray();
  4700. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4701. // object specific properties
  4702. if ( this.isInstancedMesh ) {
  4703. object.type = 'InstancedMesh';
  4704. object.count = this.count;
  4705. object.instanceMatrix = this.instanceMatrix.toJSON();
  4706. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4707. }
  4708. if ( this.isBatchedMesh ) {
  4709. object.type = 'BatchedMesh';
  4710. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  4711. object.sortObjects = this.sortObjects;
  4712. object.drawRanges = this._drawRanges;
  4713. object.reservedRanges = this._reservedRanges;
  4714. object.visibility = this._visibility;
  4715. object.active = this._active;
  4716. object.bounds = this._bounds.map( bound => ( {
  4717. boxInitialized: bound.boxInitialized,
  4718. boxMin: bound.box.min.toArray(),
  4719. boxMax: bound.box.max.toArray(),
  4720. sphereInitialized: bound.sphereInitialized,
  4721. sphereRadius: bound.sphere.radius,
  4722. sphereCenter: bound.sphere.center.toArray()
  4723. } ) );
  4724. object.maxInstanceCount = this._maxInstanceCount;
  4725. object.maxVertexCount = this._maxVertexCount;
  4726. object.maxIndexCount = this._maxIndexCount;
  4727. object.geometryInitialized = this._geometryInitialized;
  4728. object.geometryCount = this._geometryCount;
  4729. object.matricesTexture = this._matricesTexture.toJSON( meta );
  4730. if ( this._colorsTexture !== null ) object.colorsTexture = this._colorsTexture.toJSON( meta );
  4731. if ( this.boundingSphere !== null ) {
  4732. object.boundingSphere = {
  4733. center: object.boundingSphere.center.toArray(),
  4734. radius: object.boundingSphere.radius
  4735. };
  4736. }
  4737. if ( this.boundingBox !== null ) {
  4738. object.boundingBox = {
  4739. min: object.boundingBox.min.toArray(),
  4740. max: object.boundingBox.max.toArray()
  4741. };
  4742. }
  4743. }
  4744. //
  4745. function serialize( library, element ) {
  4746. if ( library[ element.uuid ] === undefined ) {
  4747. library[ element.uuid ] = element.toJSON( meta );
  4748. }
  4749. return element.uuid;
  4750. }
  4751. if ( this.isScene ) {
  4752. if ( this.background ) {
  4753. if ( this.background.isColor ) {
  4754. object.background = this.background.toJSON();
  4755. } else if ( this.background.isTexture ) {
  4756. object.background = this.background.toJSON( meta ).uuid;
  4757. }
  4758. }
  4759. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4760. object.environment = this.environment.toJSON( meta ).uuid;
  4761. }
  4762. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4763. object.geometry = serialize( meta.geometries, this.geometry );
  4764. const parameters = this.geometry.parameters;
  4765. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4766. const shapes = parameters.shapes;
  4767. if ( Array.isArray( shapes ) ) {
  4768. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4769. const shape = shapes[ i ];
  4770. serialize( meta.shapes, shape );
  4771. }
  4772. } else {
  4773. serialize( meta.shapes, shapes );
  4774. }
  4775. }
  4776. }
  4777. if ( this.isSkinnedMesh ) {
  4778. object.bindMode = this.bindMode;
  4779. object.bindMatrix = this.bindMatrix.toArray();
  4780. if ( this.skeleton !== undefined ) {
  4781. serialize( meta.skeletons, this.skeleton );
  4782. object.skeleton = this.skeleton.uuid;
  4783. }
  4784. }
  4785. if ( this.material !== undefined ) {
  4786. if ( Array.isArray( this.material ) ) {
  4787. const uuids = [];
  4788. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4789. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4790. }
  4791. object.material = uuids;
  4792. } else {
  4793. object.material = serialize( meta.materials, this.material );
  4794. }
  4795. }
  4796. //
  4797. if ( this.children.length > 0 ) {
  4798. object.children = [];
  4799. for ( let i = 0; i < this.children.length; i ++ ) {
  4800. object.children.push( this.children[ i ].toJSON( meta ).object );
  4801. }
  4802. }
  4803. //
  4804. if ( this.animations.length > 0 ) {
  4805. object.animations = [];
  4806. for ( let i = 0; i < this.animations.length; i ++ ) {
  4807. const animation = this.animations[ i ];
  4808. object.animations.push( serialize( meta.animations, animation ) );
  4809. }
  4810. }
  4811. if ( isRootObject ) {
  4812. const geometries = extractFromCache( meta.geometries );
  4813. const materials = extractFromCache( meta.materials );
  4814. const textures = extractFromCache( meta.textures );
  4815. const images = extractFromCache( meta.images );
  4816. const shapes = extractFromCache( meta.shapes );
  4817. const skeletons = extractFromCache( meta.skeletons );
  4818. const animations = extractFromCache( meta.animations );
  4819. const nodes = extractFromCache( meta.nodes );
  4820. if ( geometries.length > 0 ) output.geometries = geometries;
  4821. if ( materials.length > 0 ) output.materials = materials;
  4822. if ( textures.length > 0 ) output.textures = textures;
  4823. if ( images.length > 0 ) output.images = images;
  4824. if ( shapes.length > 0 ) output.shapes = shapes;
  4825. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4826. if ( animations.length > 0 ) output.animations = animations;
  4827. if ( nodes.length > 0 ) output.nodes = nodes;
  4828. }
  4829. output.object = object;
  4830. return output;
  4831. // extract data from the cache hash
  4832. // remove metadata on each item
  4833. // and return as array
  4834. function extractFromCache( cache ) {
  4835. const values = [];
  4836. for ( const key in cache ) {
  4837. const data = cache[ key ];
  4838. delete data.metadata;
  4839. values.push( data );
  4840. }
  4841. return values;
  4842. }
  4843. }
  4844. clone( recursive ) {
  4845. return new this.constructor().copy( this, recursive );
  4846. }
  4847. copy( source, recursive = true ) {
  4848. this.name = source.name;
  4849. this.up.copy( source.up );
  4850. this.position.copy( source.position );
  4851. this.rotation.order = source.rotation.order;
  4852. this.quaternion.copy( source.quaternion );
  4853. this.scale.copy( source.scale );
  4854. this.matrix.copy( source.matrix );
  4855. this.matrixWorld.copy( source.matrixWorld );
  4856. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4857. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4858. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4859. this.layers.mask = source.layers.mask;
  4860. this.visible = source.visible;
  4861. this.castShadow = source.castShadow;
  4862. this.receiveShadow = source.receiveShadow;
  4863. this.frustumCulled = source.frustumCulled;
  4864. this.renderOrder = source.renderOrder;
  4865. this.animations = source.animations.slice();
  4866. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4867. if ( recursive === true ) {
  4868. for ( let i = 0; i < source.children.length; i ++ ) {
  4869. const child = source.children[ i ];
  4870. this.add( child.clone() );
  4871. }
  4872. }
  4873. return this;
  4874. }
  4875. }
  4876. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4877. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4878. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4879. const _v0$1 = /*@__PURE__*/ new Vector3();
  4880. const _v1$3 = /*@__PURE__*/ new Vector3();
  4881. const _v2$2 = /*@__PURE__*/ new Vector3();
  4882. const _v3$2 = /*@__PURE__*/ new Vector3();
  4883. const _vab = /*@__PURE__*/ new Vector3();
  4884. const _vac = /*@__PURE__*/ new Vector3();
  4885. const _vbc = /*@__PURE__*/ new Vector3();
  4886. const _vap = /*@__PURE__*/ new Vector3();
  4887. const _vbp = /*@__PURE__*/ new Vector3();
  4888. const _vcp = /*@__PURE__*/ new Vector3();
  4889. class Triangle {
  4890. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4891. this.a = a;
  4892. this.b = b;
  4893. this.c = c;
  4894. }
  4895. static getNormal( a, b, c, target ) {
  4896. target.subVectors( c, b );
  4897. _v0$1.subVectors( a, b );
  4898. target.cross( _v0$1 );
  4899. const targetLengthSq = target.lengthSq();
  4900. if ( targetLengthSq > 0 ) {
  4901. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4902. }
  4903. return target.set( 0, 0, 0 );
  4904. }
  4905. // static/instance method to calculate barycentric coordinates
  4906. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4907. static getBarycoord( point, a, b, c, target ) {
  4908. _v0$1.subVectors( c, a );
  4909. _v1$3.subVectors( b, a );
  4910. _v2$2.subVectors( point, a );
  4911. const dot00 = _v0$1.dot( _v0$1 );
  4912. const dot01 = _v0$1.dot( _v1$3 );
  4913. const dot02 = _v0$1.dot( _v2$2 );
  4914. const dot11 = _v1$3.dot( _v1$3 );
  4915. const dot12 = _v1$3.dot( _v2$2 );
  4916. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4917. // collinear or singular triangle
  4918. if ( denom === 0 ) {
  4919. target.set( 0, 0, 0 );
  4920. return null;
  4921. }
  4922. const invDenom = 1 / denom;
  4923. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4924. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4925. // barycentric coordinates must always sum to 1
  4926. return target.set( 1 - u - v, v, u );
  4927. }
  4928. static containsPoint( point, a, b, c ) {
  4929. // if the triangle is degenerate then we can't contain a point
  4930. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  4931. return false;
  4932. }
  4933. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  4934. }
  4935. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  4936. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  4937. target.x = 0;
  4938. target.y = 0;
  4939. if ( 'z' in target ) target.z = 0;
  4940. if ( 'w' in target ) target.w = 0;
  4941. return null;
  4942. }
  4943. target.setScalar( 0 );
  4944. target.addScaledVector( v1, _v3$2.x );
  4945. target.addScaledVector( v2, _v3$2.y );
  4946. target.addScaledVector( v3, _v3$2.z );
  4947. return target;
  4948. }
  4949. static isFrontFacing( a, b, c, direction ) {
  4950. _v0$1.subVectors( c, b );
  4951. _v1$3.subVectors( a, b );
  4952. // strictly front facing
  4953. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4954. }
  4955. set( a, b, c ) {
  4956. this.a.copy( a );
  4957. this.b.copy( b );
  4958. this.c.copy( c );
  4959. return this;
  4960. }
  4961. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4962. this.a.copy( points[ i0 ] );
  4963. this.b.copy( points[ i1 ] );
  4964. this.c.copy( points[ i2 ] );
  4965. return this;
  4966. }
  4967. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4968. this.a.fromBufferAttribute( attribute, i0 );
  4969. this.b.fromBufferAttribute( attribute, i1 );
  4970. this.c.fromBufferAttribute( attribute, i2 );
  4971. return this;
  4972. }
  4973. clone() {
  4974. return new this.constructor().copy( this );
  4975. }
  4976. copy( triangle ) {
  4977. this.a.copy( triangle.a );
  4978. this.b.copy( triangle.b );
  4979. this.c.copy( triangle.c );
  4980. return this;
  4981. }
  4982. getArea() {
  4983. _v0$1.subVectors( this.c, this.b );
  4984. _v1$3.subVectors( this.a, this.b );
  4985. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4986. }
  4987. getMidpoint( target ) {
  4988. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4989. }
  4990. getNormal( target ) {
  4991. return Triangle.getNormal( this.a, this.b, this.c, target );
  4992. }
  4993. getPlane( target ) {
  4994. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  4995. }
  4996. getBarycoord( point, target ) {
  4997. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  4998. }
  4999. getInterpolation( point, v1, v2, v3, target ) {
  5000. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  5001. }
  5002. containsPoint( point ) {
  5003. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5004. }
  5005. isFrontFacing( direction ) {
  5006. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5007. }
  5008. intersectsBox( box ) {
  5009. return box.intersectsTriangle( this );
  5010. }
  5011. closestPointToPoint( p, target ) {
  5012. const a = this.a, b = this.b, c = this.c;
  5013. let v, w;
  5014. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5015. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5016. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5017. // basically, we're distinguishing which of the voronoi regions of the triangle
  5018. // the point lies in with the minimum amount of redundant computation.
  5019. _vab.subVectors( b, a );
  5020. _vac.subVectors( c, a );
  5021. _vap.subVectors( p, a );
  5022. const d1 = _vab.dot( _vap );
  5023. const d2 = _vac.dot( _vap );
  5024. if ( d1 <= 0 && d2 <= 0 ) {
  5025. // vertex region of A; barycentric coords (1, 0, 0)
  5026. return target.copy( a );
  5027. }
  5028. _vbp.subVectors( p, b );
  5029. const d3 = _vab.dot( _vbp );
  5030. const d4 = _vac.dot( _vbp );
  5031. if ( d3 >= 0 && d4 <= d3 ) {
  5032. // vertex region of B; barycentric coords (0, 1, 0)
  5033. return target.copy( b );
  5034. }
  5035. const vc = d1 * d4 - d3 * d2;
  5036. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5037. v = d1 / ( d1 - d3 );
  5038. // edge region of AB; barycentric coords (1-v, v, 0)
  5039. return target.copy( a ).addScaledVector( _vab, v );
  5040. }
  5041. _vcp.subVectors( p, c );
  5042. const d5 = _vab.dot( _vcp );
  5043. const d6 = _vac.dot( _vcp );
  5044. if ( d6 >= 0 && d5 <= d6 ) {
  5045. // vertex region of C; barycentric coords (0, 0, 1)
  5046. return target.copy( c );
  5047. }
  5048. const vb = d5 * d2 - d1 * d6;
  5049. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5050. w = d2 / ( d2 - d6 );
  5051. // edge region of AC; barycentric coords (1-w, 0, w)
  5052. return target.copy( a ).addScaledVector( _vac, w );
  5053. }
  5054. const va = d3 * d6 - d5 * d4;
  5055. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5056. _vbc.subVectors( c, b );
  5057. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5058. // edge region of BC; barycentric coords (0, 1-w, w)
  5059. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5060. }
  5061. // face region
  5062. const denom = 1 / ( va + vb + vc );
  5063. // u = va * denom
  5064. v = vb * denom;
  5065. w = vc * denom;
  5066. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5067. }
  5068. equals( triangle ) {
  5069. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5070. }
  5071. }
  5072. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5073. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5074. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5075. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5076. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5077. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5078. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5079. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5080. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5081. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5082. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5083. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5084. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5085. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5086. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5087. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5088. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5089. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5090. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5091. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5092. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5093. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5094. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5095. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5096. const _hslA = { h: 0, s: 0, l: 0 };
  5097. const _hslB = { h: 0, s: 0, l: 0 };
  5098. function hue2rgb( p, q, t ) {
  5099. if ( t < 0 ) t += 1;
  5100. if ( t > 1 ) t -= 1;
  5101. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5102. if ( t < 1 / 2 ) return q;
  5103. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5104. return p;
  5105. }
  5106. class Color {
  5107. constructor( r, g, b ) {
  5108. this.isColor = true;
  5109. this.r = 1;
  5110. this.g = 1;
  5111. this.b = 1;
  5112. return this.set( r, g, b );
  5113. }
  5114. set( r, g, b ) {
  5115. if ( g === undefined && b === undefined ) {
  5116. // r is THREE.Color, hex or string
  5117. const value = r;
  5118. if ( value && value.isColor ) {
  5119. this.copy( value );
  5120. } else if ( typeof value === 'number' ) {
  5121. this.setHex( value );
  5122. } else if ( typeof value === 'string' ) {
  5123. this.setStyle( value );
  5124. }
  5125. } else {
  5126. this.setRGB( r, g, b );
  5127. }
  5128. return this;
  5129. }
  5130. setScalar( scalar ) {
  5131. this.r = scalar;
  5132. this.g = scalar;
  5133. this.b = scalar;
  5134. return this;
  5135. }
  5136. setHex( hex, colorSpace = SRGBColorSpace ) {
  5137. hex = Math.floor( hex );
  5138. this.r = ( hex >> 16 & 255 ) / 255;
  5139. this.g = ( hex >> 8 & 255 ) / 255;
  5140. this.b = ( hex & 255 ) / 255;
  5141. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5142. return this;
  5143. }
  5144. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5145. this.r = r;
  5146. this.g = g;
  5147. this.b = b;
  5148. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5149. return this;
  5150. }
  5151. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5152. // h,s,l ranges are in 0.0 - 1.0
  5153. h = euclideanModulo( h, 1 );
  5154. s = clamp$1( s, 0, 1 );
  5155. l = clamp$1( l, 0, 1 );
  5156. if ( s === 0 ) {
  5157. this.r = this.g = this.b = l;
  5158. } else {
  5159. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5160. const q = ( 2 * l ) - p;
  5161. this.r = hue2rgb( q, p, h + 1 / 3 );
  5162. this.g = hue2rgb( q, p, h );
  5163. this.b = hue2rgb( q, p, h - 1 / 3 );
  5164. }
  5165. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5166. return this;
  5167. }
  5168. setStyle( style, colorSpace = SRGBColorSpace ) {
  5169. function handleAlpha( string ) {
  5170. if ( string === undefined ) return;
  5171. if ( parseFloat( string ) < 1 ) {
  5172. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5173. }
  5174. }
  5175. let m;
  5176. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5177. // rgb / hsl
  5178. let color;
  5179. const name = m[ 1 ];
  5180. const components = m[ 2 ];
  5181. switch ( name ) {
  5182. case 'rgb':
  5183. case 'rgba':
  5184. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5185. // rgb(255,0,0) rgba(255,0,0,0.5)
  5186. handleAlpha( color[ 4 ] );
  5187. return this.setRGB(
  5188. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  5189. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  5190. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  5191. colorSpace
  5192. );
  5193. }
  5194. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5195. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5196. handleAlpha( color[ 4 ] );
  5197. return this.setRGB(
  5198. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  5199. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  5200. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  5201. colorSpace
  5202. );
  5203. }
  5204. break;
  5205. case 'hsl':
  5206. case 'hsla':
  5207. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5208. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5209. handleAlpha( color[ 4 ] );
  5210. return this.setHSL(
  5211. parseFloat( color[ 1 ] ) / 360,
  5212. parseFloat( color[ 2 ] ) / 100,
  5213. parseFloat( color[ 3 ] ) / 100,
  5214. colorSpace
  5215. );
  5216. }
  5217. break;
  5218. default:
  5219. console.warn( 'THREE.Color: Unknown color model ' + style );
  5220. }
  5221. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5222. // hex color
  5223. const hex = m[ 1 ];
  5224. const size = hex.length;
  5225. if ( size === 3 ) {
  5226. // #ff0
  5227. return this.setRGB(
  5228. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5229. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5230. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5231. colorSpace
  5232. );
  5233. } else if ( size === 6 ) {
  5234. // #ff0000
  5235. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5236. } else {
  5237. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5238. }
  5239. } else if ( style && style.length > 0 ) {
  5240. return this.setColorName( style, colorSpace );
  5241. }
  5242. return this;
  5243. }
  5244. setColorName( style, colorSpace = SRGBColorSpace ) {
  5245. // color keywords
  5246. const hex = _colorKeywords[ style.toLowerCase() ];
  5247. if ( hex !== undefined ) {
  5248. // red
  5249. this.setHex( hex, colorSpace );
  5250. } else {
  5251. // unknown color
  5252. console.warn( 'THREE.Color: Unknown color ' + style );
  5253. }
  5254. return this;
  5255. }
  5256. clone() {
  5257. return new this.constructor( this.r, this.g, this.b );
  5258. }
  5259. copy( color ) {
  5260. this.r = color.r;
  5261. this.g = color.g;
  5262. this.b = color.b;
  5263. return this;
  5264. }
  5265. copySRGBToLinear( color ) {
  5266. this.r = SRGBToLinear( color.r );
  5267. this.g = SRGBToLinear( color.g );
  5268. this.b = SRGBToLinear( color.b );
  5269. return this;
  5270. }
  5271. copyLinearToSRGB( color ) {
  5272. this.r = LinearToSRGB( color.r );
  5273. this.g = LinearToSRGB( color.g );
  5274. this.b = LinearToSRGB( color.b );
  5275. return this;
  5276. }
  5277. convertSRGBToLinear() {
  5278. this.copySRGBToLinear( this );
  5279. return this;
  5280. }
  5281. convertLinearToSRGB() {
  5282. this.copyLinearToSRGB( this );
  5283. return this;
  5284. }
  5285. getHex( colorSpace = SRGBColorSpace ) {
  5286. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5287. return Math.round( clamp$1( _color.r * 255, 0, 255 ) ) * 65536 + Math.round( clamp$1( _color.g * 255, 0, 255 ) ) * 256 + Math.round( clamp$1( _color.b * 255, 0, 255 ) );
  5288. }
  5289. getHexString( colorSpace = SRGBColorSpace ) {
  5290. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5291. }
  5292. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5293. // h,s,l ranges are in 0.0 - 1.0
  5294. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5295. const r = _color.r, g = _color.g, b = _color.b;
  5296. const max = Math.max( r, g, b );
  5297. const min = Math.min( r, g, b );
  5298. let hue, saturation;
  5299. const lightness = ( min + max ) / 2.0;
  5300. if ( min === max ) {
  5301. hue = 0;
  5302. saturation = 0;
  5303. } else {
  5304. const delta = max - min;
  5305. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5306. switch ( max ) {
  5307. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5308. case g: hue = ( b - r ) / delta + 2; break;
  5309. case b: hue = ( r - g ) / delta + 4; break;
  5310. }
  5311. hue /= 6;
  5312. }
  5313. target.h = hue;
  5314. target.s = saturation;
  5315. target.l = lightness;
  5316. return target;
  5317. }
  5318. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5319. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5320. target.r = _color.r;
  5321. target.g = _color.g;
  5322. target.b = _color.b;
  5323. return target;
  5324. }
  5325. getStyle( colorSpace = SRGBColorSpace ) {
  5326. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5327. const r = _color.r, g = _color.g, b = _color.b;
  5328. if ( colorSpace !== SRGBColorSpace ) {
  5329. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5330. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5331. }
  5332. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  5333. }
  5334. offsetHSL( h, s, l ) {
  5335. this.getHSL( _hslA );
  5336. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  5337. }
  5338. add( color ) {
  5339. this.r += color.r;
  5340. this.g += color.g;
  5341. this.b += color.b;
  5342. return this;
  5343. }
  5344. addColors( color1, color2 ) {
  5345. this.r = color1.r + color2.r;
  5346. this.g = color1.g + color2.g;
  5347. this.b = color1.b + color2.b;
  5348. return this;
  5349. }
  5350. addScalar( s ) {
  5351. this.r += s;
  5352. this.g += s;
  5353. this.b += s;
  5354. return this;
  5355. }
  5356. sub( color ) {
  5357. this.r = Math.max( 0, this.r - color.r );
  5358. this.g = Math.max( 0, this.g - color.g );
  5359. this.b = Math.max( 0, this.b - color.b );
  5360. return this;
  5361. }
  5362. multiply( color ) {
  5363. this.r *= color.r;
  5364. this.g *= color.g;
  5365. this.b *= color.b;
  5366. return this;
  5367. }
  5368. multiplyScalar( s ) {
  5369. this.r *= s;
  5370. this.g *= s;
  5371. this.b *= s;
  5372. return this;
  5373. }
  5374. lerp( color, alpha ) {
  5375. this.r += ( color.r - this.r ) * alpha;
  5376. this.g += ( color.g - this.g ) * alpha;
  5377. this.b += ( color.b - this.b ) * alpha;
  5378. return this;
  5379. }
  5380. lerpColors( color1, color2, alpha ) {
  5381. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5382. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5383. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5384. return this;
  5385. }
  5386. lerpHSL( color, alpha ) {
  5387. this.getHSL( _hslA );
  5388. color.getHSL( _hslB );
  5389. const h = lerp( _hslA.h, _hslB.h, alpha );
  5390. const s = lerp( _hslA.s, _hslB.s, alpha );
  5391. const l = lerp( _hslA.l, _hslB.l, alpha );
  5392. this.setHSL( h, s, l );
  5393. return this;
  5394. }
  5395. setFromVector3( v ) {
  5396. this.r = v.x;
  5397. this.g = v.y;
  5398. this.b = v.z;
  5399. return this;
  5400. }
  5401. applyMatrix3( m ) {
  5402. const r = this.r, g = this.g, b = this.b;
  5403. const e = m.elements;
  5404. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5405. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5406. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5407. return this;
  5408. }
  5409. equals( c ) {
  5410. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5411. }
  5412. fromArray( array, offset = 0 ) {
  5413. this.r = array[ offset ];
  5414. this.g = array[ offset + 1 ];
  5415. this.b = array[ offset + 2 ];
  5416. return this;
  5417. }
  5418. toArray( array = [], offset = 0 ) {
  5419. array[ offset ] = this.r;
  5420. array[ offset + 1 ] = this.g;
  5421. array[ offset + 2 ] = this.b;
  5422. return array;
  5423. }
  5424. fromBufferAttribute( attribute, index ) {
  5425. this.r = attribute.getX( index );
  5426. this.g = attribute.getY( index );
  5427. this.b = attribute.getZ( index );
  5428. return this;
  5429. }
  5430. toJSON() {
  5431. return this.getHex();
  5432. }
  5433. *[ Symbol.iterator ]() {
  5434. yield this.r;
  5435. yield this.g;
  5436. yield this.b;
  5437. }
  5438. }
  5439. const _color = /*@__PURE__*/ new Color();
  5440. Color.NAMES = _colorKeywords;
  5441. let _materialId = 0;
  5442. class Material extends EventDispatcher {
  5443. constructor() {
  5444. super();
  5445. this.isMaterial = true;
  5446. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  5447. this.uuid = generateUUID();
  5448. this.name = '';
  5449. this.type = 'Material';
  5450. this.blending = NormalBlending;
  5451. this.side = FrontSide;
  5452. this.vertexColors = false;
  5453. this.opacity = 1;
  5454. this.transparent = false;
  5455. this.alphaHash = false;
  5456. this.blendSrc = SrcAlphaFactor;
  5457. this.blendDst = OneMinusSrcAlphaFactor;
  5458. this.blendEquation = AddEquation;
  5459. this.blendSrcAlpha = null;
  5460. this.blendDstAlpha = null;
  5461. this.blendEquationAlpha = null;
  5462. this.blendColor = new Color( 0, 0, 0 );
  5463. this.blendAlpha = 0;
  5464. this.depthFunc = LessEqualDepth;
  5465. this.depthTest = true;
  5466. this.depthWrite = true;
  5467. this.stencilWriteMask = 0xff;
  5468. this.stencilFunc = AlwaysStencilFunc;
  5469. this.stencilRef = 0;
  5470. this.stencilFuncMask = 0xff;
  5471. this.stencilFail = KeepStencilOp;
  5472. this.stencilZFail = KeepStencilOp;
  5473. this.stencilZPass = KeepStencilOp;
  5474. this.stencilWrite = false;
  5475. this.clippingPlanes = null;
  5476. this.clipIntersection = false;
  5477. this.clipShadows = false;
  5478. this.shadowSide = null;
  5479. this.colorWrite = true;
  5480. this.precision = null; // override the renderer's default precision for this material
  5481. this.polygonOffset = false;
  5482. this.polygonOffsetFactor = 0;
  5483. this.polygonOffsetUnits = 0;
  5484. this.dithering = false;
  5485. this.alphaToCoverage = false;
  5486. this.premultipliedAlpha = false;
  5487. this.forceSinglePass = false;
  5488. this.visible = true;
  5489. this.toneMapped = true;
  5490. this.userData = {};
  5491. this.version = 0;
  5492. this._alphaTest = 0;
  5493. }
  5494. get alphaTest() {
  5495. return this._alphaTest;
  5496. }
  5497. set alphaTest( value ) {
  5498. if ( this._alphaTest > 0 !== value > 0 ) {
  5499. this.version ++;
  5500. }
  5501. this._alphaTest = value;
  5502. }
  5503. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5504. customProgramCacheKey() {
  5505. return this.onBeforeCompile.toString();
  5506. }
  5507. setValues( values ) {
  5508. if ( values === undefined ) return;
  5509. for ( const key in values ) {
  5510. const newValue = values[ key ];
  5511. if ( newValue === undefined ) {
  5512. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5513. continue;
  5514. }
  5515. const currentValue = this[ key ];
  5516. if ( currentValue === undefined ) {
  5517. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5518. continue;
  5519. }
  5520. if ( currentValue && currentValue.isColor ) {
  5521. currentValue.set( newValue );
  5522. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5523. currentValue.copy( newValue );
  5524. } else {
  5525. this[ key ] = newValue;
  5526. }
  5527. }
  5528. }
  5529. toJSON( meta ) {
  5530. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5531. if ( isRootObject ) {
  5532. meta = {
  5533. textures: {},
  5534. images: {}
  5535. };
  5536. }
  5537. const data = {
  5538. metadata: {
  5539. version: 4.6,
  5540. type: 'Material',
  5541. generator: 'Material.toJSON'
  5542. }
  5543. };
  5544. // standard Material serialization
  5545. data.uuid = this.uuid;
  5546. data.type = this.type;
  5547. if ( this.name !== '' ) data.name = this.name;
  5548. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5549. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5550. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5551. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5552. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5553. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5554. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5555. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5556. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5557. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5558. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5559. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5560. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5561. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5562. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5563. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5564. }
  5565. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5566. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5567. }
  5568. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5569. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5570. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5571. }
  5572. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  5573. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5574. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5575. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5576. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5577. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5578. }
  5579. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5580. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5581. }
  5582. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  5583. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  5584. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  5585. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  5586. }
  5587. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5588. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5589. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5590. if ( this.lightMap && this.lightMap.isTexture ) {
  5591. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5592. data.lightMapIntensity = this.lightMapIntensity;
  5593. }
  5594. if ( this.aoMap && this.aoMap.isTexture ) {
  5595. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5596. data.aoMapIntensity = this.aoMapIntensity;
  5597. }
  5598. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5599. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5600. data.bumpScale = this.bumpScale;
  5601. }
  5602. if ( this.normalMap && this.normalMap.isTexture ) {
  5603. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5604. data.normalMapType = this.normalMapType;
  5605. data.normalScale = this.normalScale.toArray();
  5606. }
  5607. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5608. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5609. data.displacementScale = this.displacementScale;
  5610. data.displacementBias = this.displacementBias;
  5611. }
  5612. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5613. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5614. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5615. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5616. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5617. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5618. if ( this.envMap && this.envMap.isTexture ) {
  5619. data.envMap = this.envMap.toJSON( meta ).uuid;
  5620. if ( this.combine !== undefined ) data.combine = this.combine;
  5621. }
  5622. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  5623. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5624. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5625. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5626. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5627. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5628. }
  5629. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5630. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5631. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5632. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5633. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5634. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5635. if ( this.size !== undefined ) data.size = this.size;
  5636. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5637. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5638. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5639. if ( this.side !== FrontSide ) data.side = this.side;
  5640. if ( this.vertexColors === true ) data.vertexColors = true;
  5641. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5642. if ( this.transparent === true ) data.transparent = true;
  5643. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  5644. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  5645. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  5646. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  5647. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  5648. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  5649. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  5650. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  5651. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  5652. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  5653. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  5654. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  5655. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  5656. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  5657. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  5658. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  5659. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  5660. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  5661. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  5662. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  5663. // rotation (SpriteMaterial)
  5664. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5665. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5666. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5667. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5668. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5669. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5670. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5671. if ( this.scale !== undefined ) data.scale = this.scale;
  5672. if ( this.dithering === true ) data.dithering = true;
  5673. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5674. if ( this.alphaHash === true ) data.alphaHash = true;
  5675. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  5676. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  5677. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  5678. if ( this.wireframe === true ) data.wireframe = true;
  5679. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5680. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5681. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5682. if ( this.flatShading === true ) data.flatShading = true;
  5683. if ( this.visible === false ) data.visible = false;
  5684. if ( this.toneMapped === false ) data.toneMapped = false;
  5685. if ( this.fog === false ) data.fog = false;
  5686. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5687. // TODO: Copied from Object3D.toJSON
  5688. function extractFromCache( cache ) {
  5689. const values = [];
  5690. for ( const key in cache ) {
  5691. const data = cache[ key ];
  5692. delete data.metadata;
  5693. values.push( data );
  5694. }
  5695. return values;
  5696. }
  5697. if ( isRootObject ) {
  5698. const textures = extractFromCache( meta.textures );
  5699. const images = extractFromCache( meta.images );
  5700. if ( textures.length > 0 ) data.textures = textures;
  5701. if ( images.length > 0 ) data.images = images;
  5702. }
  5703. return data;
  5704. }
  5705. clone() {
  5706. return new this.constructor().copy( this );
  5707. }
  5708. copy( source ) {
  5709. this.name = source.name;
  5710. this.blending = source.blending;
  5711. this.side = source.side;
  5712. this.vertexColors = source.vertexColors;
  5713. this.opacity = source.opacity;
  5714. this.transparent = source.transparent;
  5715. this.blendSrc = source.blendSrc;
  5716. this.blendDst = source.blendDst;
  5717. this.blendEquation = source.blendEquation;
  5718. this.blendSrcAlpha = source.blendSrcAlpha;
  5719. this.blendDstAlpha = source.blendDstAlpha;
  5720. this.blendEquationAlpha = source.blendEquationAlpha;
  5721. this.blendColor.copy( source.blendColor );
  5722. this.blendAlpha = source.blendAlpha;
  5723. this.depthFunc = source.depthFunc;
  5724. this.depthTest = source.depthTest;
  5725. this.depthWrite = source.depthWrite;
  5726. this.stencilWriteMask = source.stencilWriteMask;
  5727. this.stencilFunc = source.stencilFunc;
  5728. this.stencilRef = source.stencilRef;
  5729. this.stencilFuncMask = source.stencilFuncMask;
  5730. this.stencilFail = source.stencilFail;
  5731. this.stencilZFail = source.stencilZFail;
  5732. this.stencilZPass = source.stencilZPass;
  5733. this.stencilWrite = source.stencilWrite;
  5734. const srcPlanes = source.clippingPlanes;
  5735. let dstPlanes = null;
  5736. if ( srcPlanes !== null ) {
  5737. const n = srcPlanes.length;
  5738. dstPlanes = new Array( n );
  5739. for ( let i = 0; i !== n; ++ i ) {
  5740. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5741. }
  5742. }
  5743. this.clippingPlanes = dstPlanes;
  5744. this.clipIntersection = source.clipIntersection;
  5745. this.clipShadows = source.clipShadows;
  5746. this.shadowSide = source.shadowSide;
  5747. this.colorWrite = source.colorWrite;
  5748. this.precision = source.precision;
  5749. this.polygonOffset = source.polygonOffset;
  5750. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5751. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5752. this.dithering = source.dithering;
  5753. this.alphaTest = source.alphaTest;
  5754. this.alphaHash = source.alphaHash;
  5755. this.alphaToCoverage = source.alphaToCoverage;
  5756. this.premultipliedAlpha = source.premultipliedAlpha;
  5757. this.forceSinglePass = source.forceSinglePass;
  5758. this.visible = source.visible;
  5759. this.toneMapped = source.toneMapped;
  5760. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5761. return this;
  5762. }
  5763. dispose() {
  5764. this.dispatchEvent( { type: 'dispose' } );
  5765. }
  5766. set needsUpdate( value ) {
  5767. if ( value === true ) this.version ++;
  5768. }
  5769. onBuild( /* shaderobject, renderer */ ) {
  5770. console.warn( 'Material: onBuild() has been removed.' ); // @deprecated, r166
  5771. }
  5772. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {
  5773. console.warn( 'Material: onBeforeRender() has been removed.' ); // @deprecated, r166
  5774. }
  5775. }
  5776. class MeshBasicMaterial extends Material {
  5777. constructor( parameters ) {
  5778. super();
  5779. this.isMeshBasicMaterial = true;
  5780. this.type = 'MeshBasicMaterial';
  5781. this.color = new Color( 0xffffff ); // emissive
  5782. this.map = null;
  5783. this.lightMap = null;
  5784. this.lightMapIntensity = 1.0;
  5785. this.aoMap = null;
  5786. this.aoMapIntensity = 1.0;
  5787. this.specularMap = null;
  5788. this.alphaMap = null;
  5789. this.envMap = null;
  5790. this.envMapRotation = new Euler();
  5791. this.combine = MultiplyOperation;
  5792. this.reflectivity = 1;
  5793. this.refractionRatio = 0.98;
  5794. this.wireframe = false;
  5795. this.wireframeLinewidth = 1;
  5796. this.wireframeLinecap = 'round';
  5797. this.wireframeLinejoin = 'round';
  5798. this.fog = true;
  5799. this.setValues( parameters );
  5800. }
  5801. copy( source ) {
  5802. super.copy( source );
  5803. this.color.copy( source.color );
  5804. this.map = source.map;
  5805. this.lightMap = source.lightMap;
  5806. this.lightMapIntensity = source.lightMapIntensity;
  5807. this.aoMap = source.aoMap;
  5808. this.aoMapIntensity = source.aoMapIntensity;
  5809. this.specularMap = source.specularMap;
  5810. this.alphaMap = source.alphaMap;
  5811. this.envMap = source.envMap;
  5812. this.envMapRotation.copy( source.envMapRotation );
  5813. this.combine = source.combine;
  5814. this.reflectivity = source.reflectivity;
  5815. this.refractionRatio = source.refractionRatio;
  5816. this.wireframe = source.wireframe;
  5817. this.wireframeLinewidth = source.wireframeLinewidth;
  5818. this.wireframeLinecap = source.wireframeLinecap;
  5819. this.wireframeLinejoin = source.wireframeLinejoin;
  5820. this.fog = source.fog;
  5821. return this;
  5822. }
  5823. }
  5824. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5825. const _tables = /*@__PURE__*/ _generateTables();
  5826. function _generateTables() {
  5827. // float32 to float16 helpers
  5828. const buffer = new ArrayBuffer( 4 );
  5829. const floatView = new Float32Array( buffer );
  5830. const uint32View = new Uint32Array( buffer );
  5831. const baseTable = new Uint32Array( 512 );
  5832. const shiftTable = new Uint32Array( 512 );
  5833. for ( let i = 0; i < 256; ++ i ) {
  5834. const e = i - 127;
  5835. // very small number (0, -0)
  5836. if ( e < - 27 ) {
  5837. baseTable[ i ] = 0x0000;
  5838. baseTable[ i | 0x100 ] = 0x8000;
  5839. shiftTable[ i ] = 24;
  5840. shiftTable[ i | 0x100 ] = 24;
  5841. // small number (denorm)
  5842. } else if ( e < - 14 ) {
  5843. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5844. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5845. shiftTable[ i ] = - e - 1;
  5846. shiftTable[ i | 0x100 ] = - e - 1;
  5847. // normal number
  5848. } else if ( e <= 15 ) {
  5849. baseTable[ i ] = ( e + 15 ) << 10;
  5850. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5851. shiftTable[ i ] = 13;
  5852. shiftTable[ i | 0x100 ] = 13;
  5853. // large number (Infinity, -Infinity)
  5854. } else if ( e < 128 ) {
  5855. baseTable[ i ] = 0x7c00;
  5856. baseTable[ i | 0x100 ] = 0xfc00;
  5857. shiftTable[ i ] = 24;
  5858. shiftTable[ i | 0x100 ] = 24;
  5859. // stay (NaN, Infinity, -Infinity)
  5860. } else {
  5861. baseTable[ i ] = 0x7c00;
  5862. baseTable[ i | 0x100 ] = 0xfc00;
  5863. shiftTable[ i ] = 13;
  5864. shiftTable[ i | 0x100 ] = 13;
  5865. }
  5866. }
  5867. // float16 to float32 helpers
  5868. const mantissaTable = new Uint32Array( 2048 );
  5869. const exponentTable = new Uint32Array( 64 );
  5870. const offsetTable = new Uint32Array( 64 );
  5871. for ( let i = 1; i < 1024; ++ i ) {
  5872. let m = i << 13; // zero pad mantissa bits
  5873. let e = 0; // zero exponent
  5874. // normalized
  5875. while ( ( m & 0x00800000 ) === 0 ) {
  5876. m <<= 1;
  5877. e -= 0x00800000; // decrement exponent
  5878. }
  5879. m &= ~ 0x00800000; // clear leading 1 bit
  5880. e += 0x38800000; // adjust bias
  5881. mantissaTable[ i ] = m | e;
  5882. }
  5883. for ( let i = 1024; i < 2048; ++ i ) {
  5884. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5885. }
  5886. for ( let i = 1; i < 31; ++ i ) {
  5887. exponentTable[ i ] = i << 23;
  5888. }
  5889. exponentTable[ 31 ] = 0x47800000;
  5890. exponentTable[ 32 ] = 0x80000000;
  5891. for ( let i = 33; i < 63; ++ i ) {
  5892. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5893. }
  5894. exponentTable[ 63 ] = 0xc7800000;
  5895. for ( let i = 1; i < 64; ++ i ) {
  5896. if ( i !== 32 ) {
  5897. offsetTable[ i ] = 1024;
  5898. }
  5899. }
  5900. return {
  5901. floatView: floatView,
  5902. uint32View: uint32View,
  5903. baseTable: baseTable,
  5904. shiftTable: shiftTable,
  5905. mantissaTable: mantissaTable,
  5906. exponentTable: exponentTable,
  5907. offsetTable: offsetTable
  5908. };
  5909. }
  5910. // float32 to float16
  5911. function toHalfFloat( val ) {
  5912. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5913. val = clamp$1( val, - 65504, 65504 );
  5914. _tables.floatView[ 0 ] = val;
  5915. const f = _tables.uint32View[ 0 ];
  5916. const e = ( f >> 23 ) & 0x1ff;
  5917. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5918. }
  5919. // float16 to float32
  5920. function fromHalfFloat( val ) {
  5921. const m = val >> 10;
  5922. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5923. return _tables.floatView[ 0 ];
  5924. }
  5925. const DataUtils = {
  5926. toHalfFloat: toHalfFloat,
  5927. fromHalfFloat: fromHalfFloat,
  5928. };
  5929. const _vector$9 = /*@__PURE__*/ new Vector3();
  5930. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5931. class BufferAttribute {
  5932. constructor( array, itemSize, normalized = false ) {
  5933. if ( Array.isArray( array ) ) {
  5934. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5935. }
  5936. this.isBufferAttribute = true;
  5937. this.name = '';
  5938. this.array = array;
  5939. this.itemSize = itemSize;
  5940. this.count = array !== undefined ? array.length / itemSize : 0;
  5941. this.normalized = normalized;
  5942. this.usage = StaticDrawUsage;
  5943. this._updateRange = { offset: 0, count: - 1 };
  5944. this.updateRanges = [];
  5945. this.gpuType = FloatType;
  5946. this.version = 0;
  5947. }
  5948. onUploadCallback() {}
  5949. set needsUpdate( value ) {
  5950. if ( value === true ) this.version ++;
  5951. }
  5952. get updateRange() {
  5953. warnOnce( 'THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159
  5954. return this._updateRange;
  5955. }
  5956. setUsage( value ) {
  5957. this.usage = value;
  5958. return this;
  5959. }
  5960. addUpdateRange( start, count ) {
  5961. this.updateRanges.push( { start, count } );
  5962. }
  5963. clearUpdateRanges() {
  5964. this.updateRanges.length = 0;
  5965. }
  5966. copy( source ) {
  5967. this.name = source.name;
  5968. this.array = new source.array.constructor( source.array );
  5969. this.itemSize = source.itemSize;
  5970. this.count = source.count;
  5971. this.normalized = source.normalized;
  5972. this.usage = source.usage;
  5973. this.gpuType = source.gpuType;
  5974. return this;
  5975. }
  5976. copyAt( index1, attribute, index2 ) {
  5977. index1 *= this.itemSize;
  5978. index2 *= attribute.itemSize;
  5979. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5980. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5981. }
  5982. return this;
  5983. }
  5984. copyArray( array ) {
  5985. this.array.set( array );
  5986. return this;
  5987. }
  5988. applyMatrix3( m ) {
  5989. if ( this.itemSize === 2 ) {
  5990. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5991. _vector2$1.fromBufferAttribute( this, i );
  5992. _vector2$1.applyMatrix3( m );
  5993. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5994. }
  5995. } else if ( this.itemSize === 3 ) {
  5996. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5997. _vector$9.fromBufferAttribute( this, i );
  5998. _vector$9.applyMatrix3( m );
  5999. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6000. }
  6001. }
  6002. return this;
  6003. }
  6004. applyMatrix4( m ) {
  6005. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6006. _vector$9.fromBufferAttribute( this, i );
  6007. _vector$9.applyMatrix4( m );
  6008. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6009. }
  6010. return this;
  6011. }
  6012. applyNormalMatrix( m ) {
  6013. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6014. _vector$9.fromBufferAttribute( this, i );
  6015. _vector$9.applyNormalMatrix( m );
  6016. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6017. }
  6018. return this;
  6019. }
  6020. transformDirection( m ) {
  6021. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6022. _vector$9.fromBufferAttribute( this, i );
  6023. _vector$9.transformDirection( m );
  6024. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6025. }
  6026. return this;
  6027. }
  6028. set( value, offset = 0 ) {
  6029. // Matching BufferAttribute constructor, do not normalize the array.
  6030. this.array.set( value, offset );
  6031. return this;
  6032. }
  6033. getComponent( index, component ) {
  6034. let value = this.array[ index * this.itemSize + component ];
  6035. if ( this.normalized ) value = denormalize( value, this.array );
  6036. return value;
  6037. }
  6038. setComponent( index, component, value ) {
  6039. if ( this.normalized ) value = normalize$1( value, this.array );
  6040. this.array[ index * this.itemSize + component ] = value;
  6041. return this;
  6042. }
  6043. getX( index ) {
  6044. let x = this.array[ index * this.itemSize ];
  6045. if ( this.normalized ) x = denormalize( x, this.array );
  6046. return x;
  6047. }
  6048. setX( index, x ) {
  6049. if ( this.normalized ) x = normalize$1( x, this.array );
  6050. this.array[ index * this.itemSize ] = x;
  6051. return this;
  6052. }
  6053. getY( index ) {
  6054. let y = this.array[ index * this.itemSize + 1 ];
  6055. if ( this.normalized ) y = denormalize( y, this.array );
  6056. return y;
  6057. }
  6058. setY( index, y ) {
  6059. if ( this.normalized ) y = normalize$1( y, this.array );
  6060. this.array[ index * this.itemSize + 1 ] = y;
  6061. return this;
  6062. }
  6063. getZ( index ) {
  6064. let z = this.array[ index * this.itemSize + 2 ];
  6065. if ( this.normalized ) z = denormalize( z, this.array );
  6066. return z;
  6067. }
  6068. setZ( index, z ) {
  6069. if ( this.normalized ) z = normalize$1( z, this.array );
  6070. this.array[ index * this.itemSize + 2 ] = z;
  6071. return this;
  6072. }
  6073. getW( index ) {
  6074. let w = this.array[ index * this.itemSize + 3 ];
  6075. if ( this.normalized ) w = denormalize( w, this.array );
  6076. return w;
  6077. }
  6078. setW( index, w ) {
  6079. if ( this.normalized ) w = normalize$1( w, this.array );
  6080. this.array[ index * this.itemSize + 3 ] = w;
  6081. return this;
  6082. }
  6083. setXY( index, x, y ) {
  6084. index *= this.itemSize;
  6085. if ( this.normalized ) {
  6086. x = normalize$1( x, this.array );
  6087. y = normalize$1( y, this.array );
  6088. }
  6089. this.array[ index + 0 ] = x;
  6090. this.array[ index + 1 ] = y;
  6091. return this;
  6092. }
  6093. setXYZ( index, x, y, z ) {
  6094. index *= this.itemSize;
  6095. if ( this.normalized ) {
  6096. x = normalize$1( x, this.array );
  6097. y = normalize$1( y, this.array );
  6098. z = normalize$1( z, this.array );
  6099. }
  6100. this.array[ index + 0 ] = x;
  6101. this.array[ index + 1 ] = y;
  6102. this.array[ index + 2 ] = z;
  6103. return this;
  6104. }
  6105. setXYZW( index, x, y, z, w ) {
  6106. index *= this.itemSize;
  6107. if ( this.normalized ) {
  6108. x = normalize$1( x, this.array );
  6109. y = normalize$1( y, this.array );
  6110. z = normalize$1( z, this.array );
  6111. w = normalize$1( w, this.array );
  6112. }
  6113. this.array[ index + 0 ] = x;
  6114. this.array[ index + 1 ] = y;
  6115. this.array[ index + 2 ] = z;
  6116. this.array[ index + 3 ] = w;
  6117. return this;
  6118. }
  6119. onUpload( callback ) {
  6120. this.onUploadCallback = callback;
  6121. return this;
  6122. }
  6123. clone() {
  6124. return new this.constructor( this.array, this.itemSize ).copy( this );
  6125. }
  6126. toJSON() {
  6127. const data = {
  6128. itemSize: this.itemSize,
  6129. type: this.array.constructor.name,
  6130. array: Array.from( this.array ),
  6131. normalized: this.normalized
  6132. };
  6133. if ( this.name !== '' ) data.name = this.name;
  6134. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6135. return data;
  6136. }
  6137. }
  6138. //
  6139. class Int8BufferAttribute extends BufferAttribute {
  6140. constructor( array, itemSize, normalized ) {
  6141. super( new Int8Array( array ), itemSize, normalized );
  6142. }
  6143. }
  6144. class Uint8BufferAttribute extends BufferAttribute {
  6145. constructor( array, itemSize, normalized ) {
  6146. super( new Uint8Array( array ), itemSize, normalized );
  6147. }
  6148. }
  6149. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6150. constructor( array, itemSize, normalized ) {
  6151. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6152. }
  6153. }
  6154. class Int16BufferAttribute extends BufferAttribute {
  6155. constructor( array, itemSize, normalized ) {
  6156. super( new Int16Array( array ), itemSize, normalized );
  6157. }
  6158. }
  6159. class Uint16BufferAttribute extends BufferAttribute {
  6160. constructor( array, itemSize, normalized ) {
  6161. super( new Uint16Array( array ), itemSize, normalized );
  6162. }
  6163. }
  6164. class Int32BufferAttribute extends BufferAttribute {
  6165. constructor( array, itemSize, normalized ) {
  6166. super( new Int32Array( array ), itemSize, normalized );
  6167. }
  6168. }
  6169. class Uint32BufferAttribute extends BufferAttribute {
  6170. constructor( array, itemSize, normalized ) {
  6171. super( new Uint32Array( array ), itemSize, normalized );
  6172. }
  6173. }
  6174. class Float16BufferAttribute extends BufferAttribute {
  6175. constructor( array, itemSize, normalized ) {
  6176. super( new Uint16Array( array ), itemSize, normalized );
  6177. this.isFloat16BufferAttribute = true;
  6178. }
  6179. getX( index ) {
  6180. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6181. if ( this.normalized ) x = denormalize( x, this.array );
  6182. return x;
  6183. }
  6184. setX( index, x ) {
  6185. if ( this.normalized ) x = normalize$1( x, this.array );
  6186. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6187. return this;
  6188. }
  6189. getY( index ) {
  6190. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6191. if ( this.normalized ) y = denormalize( y, this.array );
  6192. return y;
  6193. }
  6194. setY( index, y ) {
  6195. if ( this.normalized ) y = normalize$1( y, this.array );
  6196. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6197. return this;
  6198. }
  6199. getZ( index ) {
  6200. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6201. if ( this.normalized ) z = denormalize( z, this.array );
  6202. return z;
  6203. }
  6204. setZ( index, z ) {
  6205. if ( this.normalized ) z = normalize$1( z, this.array );
  6206. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6207. return this;
  6208. }
  6209. getW( index ) {
  6210. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6211. if ( this.normalized ) w = denormalize( w, this.array );
  6212. return w;
  6213. }
  6214. setW( index, w ) {
  6215. if ( this.normalized ) w = normalize$1( w, this.array );
  6216. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6217. return this;
  6218. }
  6219. setXY( index, x, y ) {
  6220. index *= this.itemSize;
  6221. if ( this.normalized ) {
  6222. x = normalize$1( x, this.array );
  6223. y = normalize$1( y, this.array );
  6224. }
  6225. this.array[ index + 0 ] = toHalfFloat( x );
  6226. this.array[ index + 1 ] = toHalfFloat( y );
  6227. return this;
  6228. }
  6229. setXYZ( index, x, y, z ) {
  6230. index *= this.itemSize;
  6231. if ( this.normalized ) {
  6232. x = normalize$1( x, this.array );
  6233. y = normalize$1( y, this.array );
  6234. z = normalize$1( z, this.array );
  6235. }
  6236. this.array[ index + 0 ] = toHalfFloat( x );
  6237. this.array[ index + 1 ] = toHalfFloat( y );
  6238. this.array[ index + 2 ] = toHalfFloat( z );
  6239. return this;
  6240. }
  6241. setXYZW( index, x, y, z, w ) {
  6242. index *= this.itemSize;
  6243. if ( this.normalized ) {
  6244. x = normalize$1( x, this.array );
  6245. y = normalize$1( y, this.array );
  6246. z = normalize$1( z, this.array );
  6247. w = normalize$1( w, this.array );
  6248. }
  6249. this.array[ index + 0 ] = toHalfFloat( x );
  6250. this.array[ index + 1 ] = toHalfFloat( y );
  6251. this.array[ index + 2 ] = toHalfFloat( z );
  6252. this.array[ index + 3 ] = toHalfFloat( w );
  6253. return this;
  6254. }
  6255. }
  6256. class Float32BufferAttribute extends BufferAttribute {
  6257. constructor( array, itemSize, normalized ) {
  6258. super( new Float32Array( array ), itemSize, normalized );
  6259. }
  6260. }
  6261. let _id$6 = 0;
  6262. const _m1 = /*@__PURE__*/ new Matrix4();
  6263. const _obj = /*@__PURE__*/ new Object3D();
  6264. const _offset = /*@__PURE__*/ new Vector3();
  6265. const _box$2 = /*@__PURE__*/ new Box3();
  6266. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6267. const _vector$8 = /*@__PURE__*/ new Vector3();
  6268. class BufferGeometry extends EventDispatcher {
  6269. constructor() {
  6270. super();
  6271. this.isBufferGeometry = true;
  6272. Object.defineProperty( this, 'id', { value: _id$6 ++ } );
  6273. this.uuid = generateUUID();
  6274. this.name = '';
  6275. this.type = 'BufferGeometry';
  6276. this.index = null;
  6277. this.attributes = {};
  6278. this.morphAttributes = {};
  6279. this.morphTargetsRelative = false;
  6280. this.groups = [];
  6281. this.boundingBox = null;
  6282. this.boundingSphere = null;
  6283. this.drawRange = { start: 0, count: Infinity };
  6284. this.userData = {};
  6285. }
  6286. getIndex() {
  6287. return this.index;
  6288. }
  6289. setIndex( index ) {
  6290. if ( Array.isArray( index ) ) {
  6291. this.index = new ( arrayNeedsUint32$1( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6292. } else {
  6293. this.index = index;
  6294. }
  6295. return this;
  6296. }
  6297. getAttribute( name ) {
  6298. return this.attributes[ name ];
  6299. }
  6300. setAttribute( name, attribute ) {
  6301. this.attributes[ name ] = attribute;
  6302. return this;
  6303. }
  6304. deleteAttribute( name ) {
  6305. delete this.attributes[ name ];
  6306. return this;
  6307. }
  6308. hasAttribute( name ) {
  6309. return this.attributes[ name ] !== undefined;
  6310. }
  6311. addGroup( start, count, materialIndex = 0 ) {
  6312. this.groups.push( {
  6313. start: start,
  6314. count: count,
  6315. materialIndex: materialIndex
  6316. } );
  6317. }
  6318. clearGroups() {
  6319. this.groups = [];
  6320. }
  6321. setDrawRange( start, count ) {
  6322. this.drawRange.start = start;
  6323. this.drawRange.count = count;
  6324. }
  6325. applyMatrix4( matrix ) {
  6326. const position = this.attributes.position;
  6327. if ( position !== undefined ) {
  6328. position.applyMatrix4( matrix );
  6329. position.needsUpdate = true;
  6330. }
  6331. const normal = this.attributes.normal;
  6332. if ( normal !== undefined ) {
  6333. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6334. normal.applyNormalMatrix( normalMatrix );
  6335. normal.needsUpdate = true;
  6336. }
  6337. const tangent = this.attributes.tangent;
  6338. if ( tangent !== undefined ) {
  6339. tangent.transformDirection( matrix );
  6340. tangent.needsUpdate = true;
  6341. }
  6342. if ( this.boundingBox !== null ) {
  6343. this.computeBoundingBox();
  6344. }
  6345. if ( this.boundingSphere !== null ) {
  6346. this.computeBoundingSphere();
  6347. }
  6348. return this;
  6349. }
  6350. applyQuaternion( q ) {
  6351. _m1.makeRotationFromQuaternion( q );
  6352. this.applyMatrix4( _m1 );
  6353. return this;
  6354. }
  6355. rotateX( angle ) {
  6356. // rotate geometry around world x-axis
  6357. _m1.makeRotationX( angle );
  6358. this.applyMatrix4( _m1 );
  6359. return this;
  6360. }
  6361. rotateY( angle ) {
  6362. // rotate geometry around world y-axis
  6363. _m1.makeRotationY( angle );
  6364. this.applyMatrix4( _m1 );
  6365. return this;
  6366. }
  6367. rotateZ( angle ) {
  6368. // rotate geometry around world z-axis
  6369. _m1.makeRotationZ( angle );
  6370. this.applyMatrix4( _m1 );
  6371. return this;
  6372. }
  6373. translate( x, y, z ) {
  6374. // translate geometry
  6375. _m1.makeTranslation( x, y, z );
  6376. this.applyMatrix4( _m1 );
  6377. return this;
  6378. }
  6379. scale( x, y, z ) {
  6380. // scale geometry
  6381. _m1.makeScale( x, y, z );
  6382. this.applyMatrix4( _m1 );
  6383. return this;
  6384. }
  6385. lookAt( vector ) {
  6386. _obj.lookAt( vector );
  6387. _obj.updateMatrix();
  6388. this.applyMatrix4( _obj.matrix );
  6389. return this;
  6390. }
  6391. center() {
  6392. this.computeBoundingBox();
  6393. this.boundingBox.getCenter( _offset ).negate();
  6394. this.translate( _offset.x, _offset.y, _offset.z );
  6395. return this;
  6396. }
  6397. setFromPoints( points ) {
  6398. const position = [];
  6399. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6400. const point = points[ i ];
  6401. position.push( point.x, point.y, point.z || 0 );
  6402. }
  6403. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6404. return this;
  6405. }
  6406. computeBoundingBox() {
  6407. if ( this.boundingBox === null ) {
  6408. this.boundingBox = new Box3();
  6409. }
  6410. const position = this.attributes.position;
  6411. const morphAttributesPosition = this.morphAttributes.position;
  6412. if ( position && position.isGLBufferAttribute ) {
  6413. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  6414. this.boundingBox.set(
  6415. new Vector3( - Infinity, - Infinity, - Infinity ),
  6416. new Vector3( + Infinity, + Infinity, + Infinity )
  6417. );
  6418. return;
  6419. }
  6420. if ( position !== undefined ) {
  6421. this.boundingBox.setFromBufferAttribute( position );
  6422. // process morph attributes if present
  6423. if ( morphAttributesPosition ) {
  6424. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6425. const morphAttribute = morphAttributesPosition[ i ];
  6426. _box$2.setFromBufferAttribute( morphAttribute );
  6427. if ( this.morphTargetsRelative ) {
  6428. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  6429. this.boundingBox.expandByPoint( _vector$8 );
  6430. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  6431. this.boundingBox.expandByPoint( _vector$8 );
  6432. } else {
  6433. this.boundingBox.expandByPoint( _box$2.min );
  6434. this.boundingBox.expandByPoint( _box$2.max );
  6435. }
  6436. }
  6437. }
  6438. } else {
  6439. this.boundingBox.makeEmpty();
  6440. }
  6441. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6442. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6443. }
  6444. }
  6445. computeBoundingSphere() {
  6446. if ( this.boundingSphere === null ) {
  6447. this.boundingSphere = new Sphere();
  6448. }
  6449. const position = this.attributes.position;
  6450. const morphAttributesPosition = this.morphAttributes.position;
  6451. if ( position && position.isGLBufferAttribute ) {
  6452. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  6453. this.boundingSphere.set( new Vector3(), Infinity );
  6454. return;
  6455. }
  6456. if ( position ) {
  6457. // first, find the center of the bounding sphere
  6458. const center = this.boundingSphere.center;
  6459. _box$2.setFromBufferAttribute( position );
  6460. // process morph attributes if present
  6461. if ( morphAttributesPosition ) {
  6462. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6463. const morphAttribute = morphAttributesPosition[ i ];
  6464. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6465. if ( this.morphTargetsRelative ) {
  6466. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  6467. _box$2.expandByPoint( _vector$8 );
  6468. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  6469. _box$2.expandByPoint( _vector$8 );
  6470. } else {
  6471. _box$2.expandByPoint( _boxMorphTargets.min );
  6472. _box$2.expandByPoint( _boxMorphTargets.max );
  6473. }
  6474. }
  6475. }
  6476. _box$2.getCenter( center );
  6477. // second, try to find a boundingSphere with a radius smaller than the
  6478. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6479. let maxRadiusSq = 0;
  6480. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6481. _vector$8.fromBufferAttribute( position, i );
  6482. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6483. }
  6484. // process morph attributes if present
  6485. if ( morphAttributesPosition ) {
  6486. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6487. const morphAttribute = morphAttributesPosition[ i ];
  6488. const morphTargetsRelative = this.morphTargetsRelative;
  6489. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6490. _vector$8.fromBufferAttribute( morphAttribute, j );
  6491. if ( morphTargetsRelative ) {
  6492. _offset.fromBufferAttribute( position, j );
  6493. _vector$8.add( _offset );
  6494. }
  6495. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6496. }
  6497. }
  6498. }
  6499. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6500. if ( isNaN( this.boundingSphere.radius ) ) {
  6501. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6502. }
  6503. }
  6504. }
  6505. computeTangents() {
  6506. const index = this.index;
  6507. const attributes = this.attributes;
  6508. // based on http://www.terathon.com/code/tangent.html
  6509. // (per vertex tangents)
  6510. if ( index === null ||
  6511. attributes.position === undefined ||
  6512. attributes.normal === undefined ||
  6513. attributes.uv === undefined ) {
  6514. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6515. return;
  6516. }
  6517. const positionAttribute = attributes.position;
  6518. const normalAttribute = attributes.normal;
  6519. const uvAttribute = attributes.uv;
  6520. if ( this.hasAttribute( 'tangent' ) === false ) {
  6521. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  6522. }
  6523. const tangentAttribute = this.getAttribute( 'tangent' );
  6524. const tan1 = [], tan2 = [];
  6525. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  6526. tan1[ i ] = new Vector3();
  6527. tan2[ i ] = new Vector3();
  6528. }
  6529. const vA = new Vector3(),
  6530. vB = new Vector3(),
  6531. vC = new Vector3(),
  6532. uvA = new Vector2(),
  6533. uvB = new Vector2(),
  6534. uvC = new Vector2(),
  6535. sdir = new Vector3(),
  6536. tdir = new Vector3();
  6537. function handleTriangle( a, b, c ) {
  6538. vA.fromBufferAttribute( positionAttribute, a );
  6539. vB.fromBufferAttribute( positionAttribute, b );
  6540. vC.fromBufferAttribute( positionAttribute, c );
  6541. uvA.fromBufferAttribute( uvAttribute, a );
  6542. uvB.fromBufferAttribute( uvAttribute, b );
  6543. uvC.fromBufferAttribute( uvAttribute, c );
  6544. vB.sub( vA );
  6545. vC.sub( vA );
  6546. uvB.sub( uvA );
  6547. uvC.sub( uvA );
  6548. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6549. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6550. if ( ! isFinite( r ) ) return;
  6551. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6552. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6553. tan1[ a ].add( sdir );
  6554. tan1[ b ].add( sdir );
  6555. tan1[ c ].add( sdir );
  6556. tan2[ a ].add( tdir );
  6557. tan2[ b ].add( tdir );
  6558. tan2[ c ].add( tdir );
  6559. }
  6560. let groups = this.groups;
  6561. if ( groups.length === 0 ) {
  6562. groups = [ {
  6563. start: 0,
  6564. count: index.count
  6565. } ];
  6566. }
  6567. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6568. const group = groups[ i ];
  6569. const start = group.start;
  6570. const count = group.count;
  6571. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6572. handleTriangle(
  6573. index.getX( j + 0 ),
  6574. index.getX( j + 1 ),
  6575. index.getX( j + 2 )
  6576. );
  6577. }
  6578. }
  6579. const tmp = new Vector3(), tmp2 = new Vector3();
  6580. const n = new Vector3(), n2 = new Vector3();
  6581. function handleVertex( v ) {
  6582. n.fromBufferAttribute( normalAttribute, v );
  6583. n2.copy( n );
  6584. const t = tan1[ v ];
  6585. // Gram-Schmidt orthogonalize
  6586. tmp.copy( t );
  6587. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6588. // Calculate handedness
  6589. tmp2.crossVectors( n2, t );
  6590. const test = tmp2.dot( tan2[ v ] );
  6591. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6592. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  6593. }
  6594. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6595. const group = groups[ i ];
  6596. const start = group.start;
  6597. const count = group.count;
  6598. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6599. handleVertex( index.getX( j + 0 ) );
  6600. handleVertex( index.getX( j + 1 ) );
  6601. handleVertex( index.getX( j + 2 ) );
  6602. }
  6603. }
  6604. }
  6605. computeVertexNormals() {
  6606. const index = this.index;
  6607. const positionAttribute = this.getAttribute( 'position' );
  6608. if ( positionAttribute !== undefined ) {
  6609. let normalAttribute = this.getAttribute( 'normal' );
  6610. if ( normalAttribute === undefined ) {
  6611. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6612. this.setAttribute( 'normal', normalAttribute );
  6613. } else {
  6614. // reset existing normals to zero
  6615. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6616. normalAttribute.setXYZ( i, 0, 0, 0 );
  6617. }
  6618. }
  6619. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6620. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6621. const cb = new Vector3(), ab = new Vector3();
  6622. // indexed elements
  6623. if ( index ) {
  6624. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6625. const vA = index.getX( i + 0 );
  6626. const vB = index.getX( i + 1 );
  6627. const vC = index.getX( i + 2 );
  6628. pA.fromBufferAttribute( positionAttribute, vA );
  6629. pB.fromBufferAttribute( positionAttribute, vB );
  6630. pC.fromBufferAttribute( positionAttribute, vC );
  6631. cb.subVectors( pC, pB );
  6632. ab.subVectors( pA, pB );
  6633. cb.cross( ab );
  6634. nA.fromBufferAttribute( normalAttribute, vA );
  6635. nB.fromBufferAttribute( normalAttribute, vB );
  6636. nC.fromBufferAttribute( normalAttribute, vC );
  6637. nA.add( cb );
  6638. nB.add( cb );
  6639. nC.add( cb );
  6640. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6641. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6642. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6643. }
  6644. } else {
  6645. // non-indexed elements (unconnected triangle soup)
  6646. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6647. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6648. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6649. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6650. cb.subVectors( pC, pB );
  6651. ab.subVectors( pA, pB );
  6652. cb.cross( ab );
  6653. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6654. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6655. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6656. }
  6657. }
  6658. this.normalizeNormals();
  6659. normalAttribute.needsUpdate = true;
  6660. }
  6661. }
  6662. normalizeNormals() {
  6663. const normals = this.attributes.normal;
  6664. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6665. _vector$8.fromBufferAttribute( normals, i );
  6666. _vector$8.normalize();
  6667. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6668. }
  6669. }
  6670. toNonIndexed() {
  6671. function convertBufferAttribute( attribute, indices ) {
  6672. const array = attribute.array;
  6673. const itemSize = attribute.itemSize;
  6674. const normalized = attribute.normalized;
  6675. const array2 = new array.constructor( indices.length * itemSize );
  6676. let index = 0, index2 = 0;
  6677. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6678. if ( attribute.isInterleavedBufferAttribute ) {
  6679. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6680. } else {
  6681. index = indices[ i ] * itemSize;
  6682. }
  6683. for ( let j = 0; j < itemSize; j ++ ) {
  6684. array2[ index2 ++ ] = array[ index ++ ];
  6685. }
  6686. }
  6687. return new BufferAttribute( array2, itemSize, normalized );
  6688. }
  6689. //
  6690. if ( this.index === null ) {
  6691. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6692. return this;
  6693. }
  6694. const geometry2 = new BufferGeometry();
  6695. const indices = this.index.array;
  6696. const attributes = this.attributes;
  6697. // attributes
  6698. for ( const name in attributes ) {
  6699. const attribute = attributes[ name ];
  6700. const newAttribute = convertBufferAttribute( attribute, indices );
  6701. geometry2.setAttribute( name, newAttribute );
  6702. }
  6703. // morph attributes
  6704. const morphAttributes = this.morphAttributes;
  6705. for ( const name in morphAttributes ) {
  6706. const morphArray = [];
  6707. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6708. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6709. const attribute = morphAttribute[ i ];
  6710. const newAttribute = convertBufferAttribute( attribute, indices );
  6711. morphArray.push( newAttribute );
  6712. }
  6713. geometry2.morphAttributes[ name ] = morphArray;
  6714. }
  6715. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6716. // groups
  6717. const groups = this.groups;
  6718. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6719. const group = groups[ i ];
  6720. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6721. }
  6722. return geometry2;
  6723. }
  6724. toJSON() {
  6725. const data = {
  6726. metadata: {
  6727. version: 4.6,
  6728. type: 'BufferGeometry',
  6729. generator: 'BufferGeometry.toJSON'
  6730. }
  6731. };
  6732. // standard BufferGeometry serialization
  6733. data.uuid = this.uuid;
  6734. data.type = this.type;
  6735. if ( this.name !== '' ) data.name = this.name;
  6736. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6737. if ( this.parameters !== undefined ) {
  6738. const parameters = this.parameters;
  6739. for ( const key in parameters ) {
  6740. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6741. }
  6742. return data;
  6743. }
  6744. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6745. data.data = { attributes: {} };
  6746. const index = this.index;
  6747. if ( index !== null ) {
  6748. data.data.index = {
  6749. type: index.array.constructor.name,
  6750. array: Array.prototype.slice.call( index.array )
  6751. };
  6752. }
  6753. const attributes = this.attributes;
  6754. for ( const key in attributes ) {
  6755. const attribute = attributes[ key ];
  6756. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6757. }
  6758. const morphAttributes = {};
  6759. let hasMorphAttributes = false;
  6760. for ( const key in this.morphAttributes ) {
  6761. const attributeArray = this.morphAttributes[ key ];
  6762. const array = [];
  6763. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6764. const attribute = attributeArray[ i ];
  6765. array.push( attribute.toJSON( data.data ) );
  6766. }
  6767. if ( array.length > 0 ) {
  6768. morphAttributes[ key ] = array;
  6769. hasMorphAttributes = true;
  6770. }
  6771. }
  6772. if ( hasMorphAttributes ) {
  6773. data.data.morphAttributes = morphAttributes;
  6774. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6775. }
  6776. const groups = this.groups;
  6777. if ( groups.length > 0 ) {
  6778. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6779. }
  6780. const boundingSphere = this.boundingSphere;
  6781. if ( boundingSphere !== null ) {
  6782. data.data.boundingSphere = {
  6783. center: boundingSphere.center.toArray(),
  6784. radius: boundingSphere.radius
  6785. };
  6786. }
  6787. return data;
  6788. }
  6789. clone() {
  6790. return new this.constructor().copy( this );
  6791. }
  6792. copy( source ) {
  6793. // reset
  6794. this.index = null;
  6795. this.attributes = {};
  6796. this.morphAttributes = {};
  6797. this.groups = [];
  6798. this.boundingBox = null;
  6799. this.boundingSphere = null;
  6800. // used for storing cloned, shared data
  6801. const data = {};
  6802. // name
  6803. this.name = source.name;
  6804. // index
  6805. const index = source.index;
  6806. if ( index !== null ) {
  6807. this.setIndex( index.clone( data ) );
  6808. }
  6809. // attributes
  6810. const attributes = source.attributes;
  6811. for ( const name in attributes ) {
  6812. const attribute = attributes[ name ];
  6813. this.setAttribute( name, attribute.clone( data ) );
  6814. }
  6815. // morph attributes
  6816. const morphAttributes = source.morphAttributes;
  6817. for ( const name in morphAttributes ) {
  6818. const array = [];
  6819. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6820. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6821. array.push( morphAttribute[ i ].clone( data ) );
  6822. }
  6823. this.morphAttributes[ name ] = array;
  6824. }
  6825. this.morphTargetsRelative = source.morphTargetsRelative;
  6826. // groups
  6827. const groups = source.groups;
  6828. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6829. const group = groups[ i ];
  6830. this.addGroup( group.start, group.count, group.materialIndex );
  6831. }
  6832. // bounding box
  6833. const boundingBox = source.boundingBox;
  6834. if ( boundingBox !== null ) {
  6835. this.boundingBox = boundingBox.clone();
  6836. }
  6837. // bounding sphere
  6838. const boundingSphere = source.boundingSphere;
  6839. if ( boundingSphere !== null ) {
  6840. this.boundingSphere = boundingSphere.clone();
  6841. }
  6842. // draw range
  6843. this.drawRange.start = source.drawRange.start;
  6844. this.drawRange.count = source.drawRange.count;
  6845. // user data
  6846. this.userData = source.userData;
  6847. return this;
  6848. }
  6849. dispose() {
  6850. this.dispatchEvent( { type: 'dispose' } );
  6851. }
  6852. }
  6853. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  6854. const _ray$3 = /*@__PURE__*/ new Ray();
  6855. const _sphere$6 = /*@__PURE__*/ new Sphere();
  6856. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6857. const _vA$1 = /*@__PURE__*/ new Vector3();
  6858. const _vB$1 = /*@__PURE__*/ new Vector3();
  6859. const _vC$1 = /*@__PURE__*/ new Vector3();
  6860. const _tempA = /*@__PURE__*/ new Vector3();
  6861. const _morphA = /*@__PURE__*/ new Vector3();
  6862. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6863. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6864. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6865. const _normalA = /*@__PURE__*/ new Vector3();
  6866. const _normalB = /*@__PURE__*/ new Vector3();
  6867. const _normalC = /*@__PURE__*/ new Vector3();
  6868. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6869. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6870. class Mesh extends Object3D {
  6871. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6872. super();
  6873. this.isMesh = true;
  6874. this.type = 'Mesh';
  6875. this.geometry = geometry;
  6876. this.material = material;
  6877. this.updateMorphTargets();
  6878. }
  6879. copy( source, recursive ) {
  6880. super.copy( source, recursive );
  6881. if ( source.morphTargetInfluences !== undefined ) {
  6882. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6883. }
  6884. if ( source.morphTargetDictionary !== undefined ) {
  6885. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6886. }
  6887. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  6888. this.geometry = source.geometry;
  6889. return this;
  6890. }
  6891. updateMorphTargets() {
  6892. const geometry = this.geometry;
  6893. const morphAttributes = geometry.morphAttributes;
  6894. const keys = Object.keys( morphAttributes );
  6895. if ( keys.length > 0 ) {
  6896. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6897. if ( morphAttribute !== undefined ) {
  6898. this.morphTargetInfluences = [];
  6899. this.morphTargetDictionary = {};
  6900. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6901. const name = morphAttribute[ m ].name || String( m );
  6902. this.morphTargetInfluences.push( 0 );
  6903. this.morphTargetDictionary[ name ] = m;
  6904. }
  6905. }
  6906. }
  6907. }
  6908. getVertexPosition( index, target ) {
  6909. const geometry = this.geometry;
  6910. const position = geometry.attributes.position;
  6911. const morphPosition = geometry.morphAttributes.position;
  6912. const morphTargetsRelative = geometry.morphTargetsRelative;
  6913. target.fromBufferAttribute( position, index );
  6914. const morphInfluences = this.morphTargetInfluences;
  6915. if ( morphPosition && morphInfluences ) {
  6916. _morphA.set( 0, 0, 0 );
  6917. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6918. const influence = morphInfluences[ i ];
  6919. const morphAttribute = morphPosition[ i ];
  6920. if ( influence === 0 ) continue;
  6921. _tempA.fromBufferAttribute( morphAttribute, index );
  6922. if ( morphTargetsRelative ) {
  6923. _morphA.addScaledVector( _tempA, influence );
  6924. } else {
  6925. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6926. }
  6927. }
  6928. target.add( _morphA );
  6929. }
  6930. return target;
  6931. }
  6932. raycast( raycaster, intersects ) {
  6933. const geometry = this.geometry;
  6934. const material = this.material;
  6935. const matrixWorld = this.matrixWorld;
  6936. if ( material === undefined ) return;
  6937. // test with bounding sphere in world space
  6938. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6939. _sphere$6.copy( geometry.boundingSphere );
  6940. _sphere$6.applyMatrix4( matrixWorld );
  6941. // check distance from ray origin to bounding sphere
  6942. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  6943. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  6944. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  6945. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6946. }
  6947. // convert ray to local space of mesh
  6948. _inverseMatrix$3.copy( matrixWorld ).invert();
  6949. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  6950. // test with bounding box in local space
  6951. if ( geometry.boundingBox !== null ) {
  6952. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  6953. }
  6954. // test for intersections with geometry
  6955. this._computeIntersections( raycaster, intersects, _ray$3 );
  6956. }
  6957. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  6958. let intersection;
  6959. const geometry = this.geometry;
  6960. const material = this.material;
  6961. const index = geometry.index;
  6962. const position = geometry.attributes.position;
  6963. const uv = geometry.attributes.uv;
  6964. const uv1 = geometry.attributes.uv1;
  6965. const normal = geometry.attributes.normal;
  6966. const groups = geometry.groups;
  6967. const drawRange = geometry.drawRange;
  6968. if ( index !== null ) {
  6969. // indexed buffer geometry
  6970. if ( Array.isArray( material ) ) {
  6971. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6972. const group = groups[ i ];
  6973. const groupMaterial = material[ group.materialIndex ];
  6974. const start = Math.max( group.start, drawRange.start );
  6975. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6976. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6977. const a = index.getX( j );
  6978. const b = index.getX( j + 1 );
  6979. const c = index.getX( j + 2 );
  6980. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6981. if ( intersection ) {
  6982. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6983. intersection.face.materialIndex = group.materialIndex;
  6984. intersects.push( intersection );
  6985. }
  6986. }
  6987. }
  6988. } else {
  6989. const start = Math.max( 0, drawRange.start );
  6990. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6991. for ( let i = start, il = end; i < il; i += 3 ) {
  6992. const a = index.getX( i );
  6993. const b = index.getX( i + 1 );
  6994. const c = index.getX( i + 2 );
  6995. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6996. if ( intersection ) {
  6997. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6998. intersects.push( intersection );
  6999. }
  7000. }
  7001. }
  7002. } else if ( position !== undefined ) {
  7003. // non-indexed buffer geometry
  7004. if ( Array.isArray( material ) ) {
  7005. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7006. const group = groups[ i ];
  7007. const groupMaterial = material[ group.materialIndex ];
  7008. const start = Math.max( group.start, drawRange.start );
  7009. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7010. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7011. const a = j;
  7012. const b = j + 1;
  7013. const c = j + 2;
  7014. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7015. if ( intersection ) {
  7016. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  7017. intersection.face.materialIndex = group.materialIndex;
  7018. intersects.push( intersection );
  7019. }
  7020. }
  7021. }
  7022. } else {
  7023. const start = Math.max( 0, drawRange.start );
  7024. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  7025. for ( let i = start, il = end; i < il; i += 3 ) {
  7026. const a = i;
  7027. const b = i + 1;
  7028. const c = i + 2;
  7029. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7030. if ( intersection ) {
  7031. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7032. intersects.push( intersection );
  7033. }
  7034. }
  7035. }
  7036. }
  7037. }
  7038. }
  7039. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  7040. let intersect;
  7041. if ( material.side === BackSide ) {
  7042. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7043. } else {
  7044. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  7045. }
  7046. if ( intersect === null ) return null;
  7047. _intersectionPointWorld.copy( point );
  7048. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7049. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7050. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7051. return {
  7052. distance: distance,
  7053. point: _intersectionPointWorld.clone(),
  7054. object: object
  7055. };
  7056. }
  7057. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  7058. object.getVertexPosition( a, _vA$1 );
  7059. object.getVertexPosition( b, _vB$1 );
  7060. object.getVertexPosition( c, _vC$1 );
  7061. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  7062. if ( intersection ) {
  7063. if ( uv ) {
  7064. _uvA$1.fromBufferAttribute( uv, a );
  7065. _uvB$1.fromBufferAttribute( uv, b );
  7066. _uvC$1.fromBufferAttribute( uv, c );
  7067. intersection.uv = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7068. }
  7069. if ( uv1 ) {
  7070. _uvA$1.fromBufferAttribute( uv1, a );
  7071. _uvB$1.fromBufferAttribute( uv1, b );
  7072. _uvC$1.fromBufferAttribute( uv1, c );
  7073. intersection.uv1 = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7074. }
  7075. if ( normal ) {
  7076. _normalA.fromBufferAttribute( normal, a );
  7077. _normalB.fromBufferAttribute( normal, b );
  7078. _normalC.fromBufferAttribute( normal, c );
  7079. intersection.normal = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _normalA, _normalB, _normalC, new Vector3() );
  7080. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  7081. intersection.normal.multiplyScalar( - 1 );
  7082. }
  7083. }
  7084. const face = {
  7085. a: a,
  7086. b: b,
  7087. c: c,
  7088. normal: new Vector3(),
  7089. materialIndex: 0
  7090. };
  7091. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7092. intersection.face = face;
  7093. }
  7094. return intersection;
  7095. }
  7096. class BoxGeometry extends BufferGeometry {
  7097. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7098. super();
  7099. this.type = 'BoxGeometry';
  7100. this.parameters = {
  7101. width: width,
  7102. height: height,
  7103. depth: depth,
  7104. widthSegments: widthSegments,
  7105. heightSegments: heightSegments,
  7106. depthSegments: depthSegments
  7107. };
  7108. const scope = this;
  7109. // segments
  7110. widthSegments = Math.floor( widthSegments );
  7111. heightSegments = Math.floor( heightSegments );
  7112. depthSegments = Math.floor( depthSegments );
  7113. // buffers
  7114. const indices = [];
  7115. const vertices = [];
  7116. const normals = [];
  7117. const uvs = [];
  7118. // helper variables
  7119. let numberOfVertices = 0;
  7120. let groupStart = 0;
  7121. // build each side of the box geometry
  7122. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7123. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7124. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7125. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7126. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7127. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7128. // build geometry
  7129. this.setIndex( indices );
  7130. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7131. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7132. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7133. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7134. const segmentWidth = width / gridX;
  7135. const segmentHeight = height / gridY;
  7136. const widthHalf = width / 2;
  7137. const heightHalf = height / 2;
  7138. const depthHalf = depth / 2;
  7139. const gridX1 = gridX + 1;
  7140. const gridY1 = gridY + 1;
  7141. let vertexCounter = 0;
  7142. let groupCount = 0;
  7143. const vector = new Vector3();
  7144. // generate vertices, normals and uvs
  7145. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7146. const y = iy * segmentHeight - heightHalf;
  7147. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7148. const x = ix * segmentWidth - widthHalf;
  7149. // set values to correct vector component
  7150. vector[ u ] = x * udir;
  7151. vector[ v ] = y * vdir;
  7152. vector[ w ] = depthHalf;
  7153. // now apply vector to vertex buffer
  7154. vertices.push( vector.x, vector.y, vector.z );
  7155. // set values to correct vector component
  7156. vector[ u ] = 0;
  7157. vector[ v ] = 0;
  7158. vector[ w ] = depth > 0 ? 1 : - 1;
  7159. // now apply vector to normal buffer
  7160. normals.push( vector.x, vector.y, vector.z );
  7161. // uvs
  7162. uvs.push( ix / gridX );
  7163. uvs.push( 1 - ( iy / gridY ) );
  7164. // counters
  7165. vertexCounter += 1;
  7166. }
  7167. }
  7168. // indices
  7169. // 1. you need three indices to draw a single face
  7170. // 2. a single segment consists of two faces
  7171. // 3. so we need to generate six (2*3) indices per segment
  7172. for ( let iy = 0; iy < gridY; iy ++ ) {
  7173. for ( let ix = 0; ix < gridX; ix ++ ) {
  7174. const a = numberOfVertices + ix + gridX1 * iy;
  7175. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7176. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7177. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7178. // faces
  7179. indices.push( a, b, d );
  7180. indices.push( b, c, d );
  7181. // increase counter
  7182. groupCount += 6;
  7183. }
  7184. }
  7185. // add a group to the geometry. this will ensure multi material support
  7186. scope.addGroup( groupStart, groupCount, materialIndex );
  7187. // calculate new start value for groups
  7188. groupStart += groupCount;
  7189. // update total number of vertices
  7190. numberOfVertices += vertexCounter;
  7191. }
  7192. }
  7193. copy( source ) {
  7194. super.copy( source );
  7195. this.parameters = Object.assign( {}, source.parameters );
  7196. return this;
  7197. }
  7198. static fromJSON( data ) {
  7199. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7200. }
  7201. }
  7202. /**
  7203. * Uniform Utilities
  7204. */
  7205. function cloneUniforms( src ) {
  7206. const dst = {};
  7207. for ( const u in src ) {
  7208. dst[ u ] = {};
  7209. for ( const p in src[ u ] ) {
  7210. const property = src[ u ][ p ];
  7211. if ( property && ( property.isColor ||
  7212. property.isMatrix3 || property.isMatrix4 ||
  7213. property.isVector2 || property.isVector3 || property.isVector4 ||
  7214. property.isTexture || property.isQuaternion ) ) {
  7215. if ( property.isRenderTargetTexture ) {
  7216. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7217. dst[ u ][ p ] = null;
  7218. } else {
  7219. dst[ u ][ p ] = property.clone();
  7220. }
  7221. } else if ( Array.isArray( property ) ) {
  7222. dst[ u ][ p ] = property.slice();
  7223. } else {
  7224. dst[ u ][ p ] = property;
  7225. }
  7226. }
  7227. }
  7228. return dst;
  7229. }
  7230. function cloneUniformsGroups( src ) {
  7231. const dst = [];
  7232. for ( let u = 0; u < src.length; u ++ ) {
  7233. dst.push( src[ u ].clone() );
  7234. }
  7235. return dst;
  7236. }
  7237. var default_vertex = /* glsl */`
  7238. void main() {
  7239. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  7240. }
  7241. `;
  7242. var default_fragment = /* glsl */`
  7243. void main() {
  7244. gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
  7245. }
  7246. `;
  7247. class ShaderMaterial extends Material {
  7248. constructor( parameters ) {
  7249. super();
  7250. this.isShaderMaterial = true;
  7251. this.type = 'ShaderMaterial';
  7252. this.defines = {};
  7253. this.uniforms = {};
  7254. this.uniformsGroups = [];
  7255. this.vertexShader = default_vertex;
  7256. this.fragmentShader = default_fragment;
  7257. this.linewidth = 1;
  7258. this.wireframe = false;
  7259. this.wireframeLinewidth = 1;
  7260. this.fog = false; // set to use scene fog
  7261. this.lights = false; // set to use scene lights
  7262. this.clipping = false; // set to use user-defined clipping planes
  7263. this.forceSinglePass = true;
  7264. this.extensions = {
  7265. clipCullDistance: false, // set to use vertex shader clipping
  7266. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  7267. };
  7268. // When rendered geometry doesn't include these attributes but the material does,
  7269. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7270. this.defaultAttributeValues = {
  7271. 'color': [ 1, 1, 1 ],
  7272. 'uv': [ 0, 0 ],
  7273. 'uv1': [ 0, 0 ]
  7274. };
  7275. this.index0AttributeName = undefined;
  7276. this.uniformsNeedUpdate = false;
  7277. this.glslVersion = null;
  7278. if ( parameters !== undefined ) {
  7279. this.setValues( parameters );
  7280. }
  7281. }
  7282. copy( source ) {
  7283. super.copy( source );
  7284. this.fragmentShader = source.fragmentShader;
  7285. this.vertexShader = source.vertexShader;
  7286. this.uniforms = cloneUniforms( source.uniforms );
  7287. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7288. this.defines = Object.assign( {}, source.defines );
  7289. this.wireframe = source.wireframe;
  7290. this.wireframeLinewidth = source.wireframeLinewidth;
  7291. this.fog = source.fog;
  7292. this.lights = source.lights;
  7293. this.clipping = source.clipping;
  7294. this.extensions = Object.assign( {}, source.extensions );
  7295. this.glslVersion = source.glslVersion;
  7296. return this;
  7297. }
  7298. toJSON( meta ) {
  7299. const data = super.toJSON( meta );
  7300. data.glslVersion = this.glslVersion;
  7301. data.uniforms = {};
  7302. for ( const name in this.uniforms ) {
  7303. const uniform = this.uniforms[ name ];
  7304. const value = uniform.value;
  7305. if ( value && value.isTexture ) {
  7306. data.uniforms[ name ] = {
  7307. type: 't',
  7308. value: value.toJSON( meta ).uuid
  7309. };
  7310. } else if ( value && value.isColor ) {
  7311. data.uniforms[ name ] = {
  7312. type: 'c',
  7313. value: value.getHex()
  7314. };
  7315. } else if ( value && value.isVector2 ) {
  7316. data.uniforms[ name ] = {
  7317. type: 'v2',
  7318. value: value.toArray()
  7319. };
  7320. } else if ( value && value.isVector3 ) {
  7321. data.uniforms[ name ] = {
  7322. type: 'v3',
  7323. value: value.toArray()
  7324. };
  7325. } else if ( value && value.isVector4 ) {
  7326. data.uniforms[ name ] = {
  7327. type: 'v4',
  7328. value: value.toArray()
  7329. };
  7330. } else if ( value && value.isMatrix3 ) {
  7331. data.uniforms[ name ] = {
  7332. type: 'm3',
  7333. value: value.toArray()
  7334. };
  7335. } else if ( value && value.isMatrix4 ) {
  7336. data.uniforms[ name ] = {
  7337. type: 'm4',
  7338. value: value.toArray()
  7339. };
  7340. } else {
  7341. data.uniforms[ name ] = {
  7342. value: value
  7343. };
  7344. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7345. }
  7346. }
  7347. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7348. data.vertexShader = this.vertexShader;
  7349. data.fragmentShader = this.fragmentShader;
  7350. data.lights = this.lights;
  7351. data.clipping = this.clipping;
  7352. const extensions = {};
  7353. for ( const key in this.extensions ) {
  7354. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7355. }
  7356. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7357. return data;
  7358. }
  7359. }
  7360. class Camera extends Object3D {
  7361. constructor() {
  7362. super();
  7363. this.isCamera = true;
  7364. this.type = 'Camera';
  7365. this.matrixWorldInverse = new Matrix4();
  7366. this.projectionMatrix = new Matrix4();
  7367. this.projectionMatrixInverse = new Matrix4();
  7368. this.coordinateSystem = WebGLCoordinateSystem;
  7369. }
  7370. copy( source, recursive ) {
  7371. super.copy( source, recursive );
  7372. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7373. this.projectionMatrix.copy( source.projectionMatrix );
  7374. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7375. this.coordinateSystem = source.coordinateSystem;
  7376. return this;
  7377. }
  7378. getWorldDirection( target ) {
  7379. return super.getWorldDirection( target ).negate();
  7380. }
  7381. updateMatrixWorld( force ) {
  7382. super.updateMatrixWorld( force );
  7383. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7384. }
  7385. updateWorldMatrix( updateParents, updateChildren ) {
  7386. super.updateWorldMatrix( updateParents, updateChildren );
  7387. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7388. }
  7389. clone() {
  7390. return new this.constructor().copy( this );
  7391. }
  7392. }
  7393. const _v3$1 = /*@__PURE__*/ new Vector3();
  7394. const _minTarget = /*@__PURE__*/ new Vector2();
  7395. const _maxTarget = /*@__PURE__*/ new Vector2();
  7396. class PerspectiveCamera extends Camera {
  7397. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7398. super();
  7399. this.isPerspectiveCamera = true;
  7400. this.type = 'PerspectiveCamera';
  7401. this.fov = fov;
  7402. this.zoom = 1;
  7403. this.near = near;
  7404. this.far = far;
  7405. this.focus = 10;
  7406. this.aspect = aspect;
  7407. this.view = null;
  7408. this.filmGauge = 35; // width of the film (default in millimeters)
  7409. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7410. this.updateProjectionMatrix();
  7411. }
  7412. copy( source, recursive ) {
  7413. super.copy( source, recursive );
  7414. this.fov = source.fov;
  7415. this.zoom = source.zoom;
  7416. this.near = source.near;
  7417. this.far = source.far;
  7418. this.focus = source.focus;
  7419. this.aspect = source.aspect;
  7420. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7421. this.filmGauge = source.filmGauge;
  7422. this.filmOffset = source.filmOffset;
  7423. return this;
  7424. }
  7425. /**
  7426. * Sets the FOV by focal length in respect to the current .filmGauge.
  7427. *
  7428. * The default film gauge is 35, so that the focal length can be specified for
  7429. * a 35mm (full frame) camera.
  7430. *
  7431. * Values for focal length and film gauge must have the same unit.
  7432. */
  7433. setFocalLength( focalLength ) {
  7434. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7435. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7436. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7437. this.updateProjectionMatrix();
  7438. }
  7439. /**
  7440. * Calculates the focal length from the current .fov and .filmGauge.
  7441. */
  7442. getFocalLength() {
  7443. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7444. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7445. }
  7446. getEffectiveFOV() {
  7447. return RAD2DEG * 2 * Math.atan(
  7448. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7449. }
  7450. getFilmWidth() {
  7451. // film not completely covered in portrait format (aspect < 1)
  7452. return this.filmGauge * Math.min( this.aspect, 1 );
  7453. }
  7454. getFilmHeight() {
  7455. // film not completely covered in landscape format (aspect > 1)
  7456. return this.filmGauge / Math.max( this.aspect, 1 );
  7457. }
  7458. /**
  7459. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  7460. * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle.
  7461. */
  7462. getViewBounds( distance, minTarget, maxTarget ) {
  7463. _v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7464. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7465. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7466. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7467. }
  7468. /**
  7469. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  7470. * Copies the result into the target Vector2, where x is width and y is height.
  7471. */
  7472. getViewSize( distance, target ) {
  7473. this.getViewBounds( distance, _minTarget, _maxTarget );
  7474. return target.subVectors( _maxTarget, _minTarget );
  7475. }
  7476. /**
  7477. * Sets an offset in a larger frustum. This is useful for multi-window or
  7478. * multi-monitor/multi-machine setups.
  7479. *
  7480. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7481. * the monitors are in grid like this
  7482. *
  7483. * +---+---+---+
  7484. * | A | B | C |
  7485. * +---+---+---+
  7486. * | D | E | F |
  7487. * +---+---+---+
  7488. *
  7489. * then for each monitor you would call it like this
  7490. *
  7491. * const w = 1920;
  7492. * const h = 1080;
  7493. * const fullWidth = w * 3;
  7494. * const fullHeight = h * 2;
  7495. *
  7496. * --A--
  7497. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7498. * --B--
  7499. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7500. * --C--
  7501. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7502. * --D--
  7503. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7504. * --E--
  7505. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7506. * --F--
  7507. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7508. *
  7509. * Note there is no reason monitors have to be the same size or in a grid.
  7510. */
  7511. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7512. this.aspect = fullWidth / fullHeight;
  7513. if ( this.view === null ) {
  7514. this.view = {
  7515. enabled: true,
  7516. fullWidth: 1,
  7517. fullHeight: 1,
  7518. offsetX: 0,
  7519. offsetY: 0,
  7520. width: 1,
  7521. height: 1
  7522. };
  7523. }
  7524. this.view.enabled = true;
  7525. this.view.fullWidth = fullWidth;
  7526. this.view.fullHeight = fullHeight;
  7527. this.view.offsetX = x;
  7528. this.view.offsetY = y;
  7529. this.view.width = width;
  7530. this.view.height = height;
  7531. this.updateProjectionMatrix();
  7532. }
  7533. clearViewOffset() {
  7534. if ( this.view !== null ) {
  7535. this.view.enabled = false;
  7536. }
  7537. this.updateProjectionMatrix();
  7538. }
  7539. updateProjectionMatrix() {
  7540. const near = this.near;
  7541. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7542. let height = 2 * top;
  7543. let width = this.aspect * height;
  7544. let left = - 0.5 * width;
  7545. const view = this.view;
  7546. if ( this.view !== null && this.view.enabled ) {
  7547. const fullWidth = view.fullWidth,
  7548. fullHeight = view.fullHeight;
  7549. left += view.offsetX * width / fullWidth;
  7550. top -= view.offsetY * height / fullHeight;
  7551. width *= view.width / fullWidth;
  7552. height *= view.height / fullHeight;
  7553. }
  7554. const skew = this.filmOffset;
  7555. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7556. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  7557. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7558. }
  7559. toJSON( meta ) {
  7560. const data = super.toJSON( meta );
  7561. data.object.fov = this.fov;
  7562. data.object.zoom = this.zoom;
  7563. data.object.near = this.near;
  7564. data.object.far = this.far;
  7565. data.object.focus = this.focus;
  7566. data.object.aspect = this.aspect;
  7567. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7568. data.object.filmGauge = this.filmGauge;
  7569. data.object.filmOffset = this.filmOffset;
  7570. return data;
  7571. }
  7572. }
  7573. const fov = - 90; // negative fov is not an error
  7574. const aspect = 1;
  7575. class CubeCamera extends Object3D {
  7576. constructor( near, far, renderTarget ) {
  7577. super();
  7578. this.type = 'CubeCamera';
  7579. this.renderTarget = renderTarget;
  7580. this.coordinateSystem = null;
  7581. this.activeMipmapLevel = 0;
  7582. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7583. cameraPX.layers = this.layers;
  7584. this.add( cameraPX );
  7585. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7586. cameraNX.layers = this.layers;
  7587. this.add( cameraNX );
  7588. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7589. cameraPY.layers = this.layers;
  7590. this.add( cameraPY );
  7591. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7592. cameraNY.layers = this.layers;
  7593. this.add( cameraNY );
  7594. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7595. cameraPZ.layers = this.layers;
  7596. this.add( cameraPZ );
  7597. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7598. cameraNZ.layers = this.layers;
  7599. this.add( cameraNZ );
  7600. }
  7601. updateCoordinateSystem() {
  7602. const coordinateSystem = this.coordinateSystem;
  7603. const cameras = this.children.concat();
  7604. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  7605. for ( const camera of cameras ) this.remove( camera );
  7606. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7607. cameraPX.up.set( 0, 1, 0 );
  7608. cameraPX.lookAt( 1, 0, 0 );
  7609. cameraNX.up.set( 0, 1, 0 );
  7610. cameraNX.lookAt( - 1, 0, 0 );
  7611. cameraPY.up.set( 0, 0, - 1 );
  7612. cameraPY.lookAt( 0, 1, 0 );
  7613. cameraNY.up.set( 0, 0, 1 );
  7614. cameraNY.lookAt( 0, - 1, 0 );
  7615. cameraPZ.up.set( 0, 1, 0 );
  7616. cameraPZ.lookAt( 0, 0, 1 );
  7617. cameraNZ.up.set( 0, 1, 0 );
  7618. cameraNZ.lookAt( 0, 0, - 1 );
  7619. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7620. cameraPX.up.set( 0, - 1, 0 );
  7621. cameraPX.lookAt( - 1, 0, 0 );
  7622. cameraNX.up.set( 0, - 1, 0 );
  7623. cameraNX.lookAt( 1, 0, 0 );
  7624. cameraPY.up.set( 0, 0, 1 );
  7625. cameraPY.lookAt( 0, 1, 0 );
  7626. cameraNY.up.set( 0, 0, - 1 );
  7627. cameraNY.lookAt( 0, - 1, 0 );
  7628. cameraPZ.up.set( 0, - 1, 0 );
  7629. cameraPZ.lookAt( 0, 0, 1 );
  7630. cameraNZ.up.set( 0, - 1, 0 );
  7631. cameraNZ.lookAt( 0, 0, - 1 );
  7632. } else {
  7633. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  7634. }
  7635. for ( const camera of cameras ) {
  7636. this.add( camera );
  7637. camera.updateMatrixWorld();
  7638. }
  7639. }
  7640. update( renderer, scene ) {
  7641. if ( this.parent === null ) this.updateMatrixWorld();
  7642. const { renderTarget, activeMipmapLevel } = this;
  7643. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  7644. this.coordinateSystem = renderer.coordinateSystem;
  7645. this.updateCoordinateSystem();
  7646. }
  7647. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7648. const currentRenderTarget = renderer.getRenderTarget();
  7649. const currentActiveCubeFace = renderer.getActiveCubeFace();
  7650. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  7651. const currentXrEnabled = renderer.xr.enabled;
  7652. renderer.xr.enabled = false;
  7653. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7654. renderTarget.texture.generateMipmaps = false;
  7655. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  7656. renderer.render( scene, cameraPX );
  7657. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  7658. renderer.render( scene, cameraNX );
  7659. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  7660. renderer.render( scene, cameraPY );
  7661. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  7662. renderer.render( scene, cameraNY );
  7663. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  7664. renderer.render( scene, cameraPZ );
  7665. // mipmaps are generated during the last call of render()
  7666. // at this point, all sides of the cube render target are defined
  7667. renderTarget.texture.generateMipmaps = generateMipmaps;
  7668. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  7669. renderer.render( scene, cameraNZ );
  7670. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  7671. renderer.xr.enabled = currentXrEnabled;
  7672. renderTarget.texture.needsPMREMUpdate = true;
  7673. }
  7674. }
  7675. class CubeTexture extends Texture {
  7676. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7677. images = images !== undefined ? images : [];
  7678. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7679. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7680. this.isCubeTexture = true;
  7681. this.flipY = false;
  7682. }
  7683. get images() {
  7684. return this.image;
  7685. }
  7686. set images( value ) {
  7687. this.image = value;
  7688. }
  7689. }
  7690. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7691. constructor( size = 1, options = {} ) {
  7692. super( size, size, options );
  7693. this.isWebGLCubeRenderTarget = true;
  7694. const image = { width: size, height: size, depth: 1 };
  7695. const images = [ image, image, image, image, image, image ];
  7696. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7697. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7698. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7699. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7700. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7701. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7702. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7703. this.texture.isRenderTargetTexture = true;
  7704. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7705. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7706. }
  7707. fromEquirectangularTexture( renderer, texture ) {
  7708. this.texture.type = texture.type;
  7709. this.texture.colorSpace = texture.colorSpace;
  7710. this.texture.generateMipmaps = texture.generateMipmaps;
  7711. this.texture.minFilter = texture.minFilter;
  7712. this.texture.magFilter = texture.magFilter;
  7713. const shader = {
  7714. uniforms: {
  7715. tEquirect: { value: null },
  7716. },
  7717. vertexShader: /* glsl */`
  7718. varying vec3 vWorldDirection;
  7719. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7720. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7721. }
  7722. void main() {
  7723. vWorldDirection = transformDirection( position, modelMatrix );
  7724. #include <begin_vertex>
  7725. #include <project_vertex>
  7726. }
  7727. `,
  7728. fragmentShader: /* glsl */`
  7729. uniform sampler2D tEquirect;
  7730. varying vec3 vWorldDirection;
  7731. #include <common>
  7732. void main() {
  7733. vec3 direction = normalize( vWorldDirection );
  7734. vec2 sampleUV = equirectUv( direction );
  7735. gl_FragColor = texture2D( tEquirect, sampleUV );
  7736. }
  7737. `
  7738. };
  7739. const geometry = new BoxGeometry( 5, 5, 5 );
  7740. const material = new ShaderMaterial( {
  7741. name: 'CubemapFromEquirect',
  7742. uniforms: cloneUniforms( shader.uniforms ),
  7743. vertexShader: shader.vertexShader,
  7744. fragmentShader: shader.fragmentShader,
  7745. side: BackSide,
  7746. blending: NoBlending
  7747. } );
  7748. material.uniforms.tEquirect.value = texture;
  7749. const mesh = new Mesh( geometry, material );
  7750. const currentMinFilter = texture.minFilter;
  7751. // Avoid blurred poles
  7752. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7753. const camera = new CubeCamera( 1, 10, this );
  7754. camera.update( renderer, mesh );
  7755. texture.minFilter = currentMinFilter;
  7756. mesh.geometry.dispose();
  7757. mesh.material.dispose();
  7758. return this;
  7759. }
  7760. clear( renderer, color, depth, stencil ) {
  7761. const currentRenderTarget = renderer.getRenderTarget();
  7762. for ( let i = 0; i < 6; i ++ ) {
  7763. renderer.setRenderTarget( this, i );
  7764. renderer.clear( color, depth, stencil );
  7765. }
  7766. renderer.setRenderTarget( currentRenderTarget );
  7767. }
  7768. }
  7769. class FogExp2 {
  7770. constructor( color, density = 0.00025 ) {
  7771. this.isFogExp2 = true;
  7772. this.name = '';
  7773. this.color = new Color( color );
  7774. this.density = density;
  7775. }
  7776. clone() {
  7777. return new FogExp2( this.color, this.density );
  7778. }
  7779. toJSON( /* meta */ ) {
  7780. return {
  7781. type: 'FogExp2',
  7782. name: this.name,
  7783. color: this.color.getHex(),
  7784. density: this.density
  7785. };
  7786. }
  7787. }
  7788. class Fog {
  7789. constructor( color, near = 1, far = 1000 ) {
  7790. this.isFog = true;
  7791. this.name = '';
  7792. this.color = new Color( color );
  7793. this.near = near;
  7794. this.far = far;
  7795. }
  7796. clone() {
  7797. return new Fog( this.color, this.near, this.far );
  7798. }
  7799. toJSON( /* meta */ ) {
  7800. return {
  7801. type: 'Fog',
  7802. name: this.name,
  7803. color: this.color.getHex(),
  7804. near: this.near,
  7805. far: this.far
  7806. };
  7807. }
  7808. }
  7809. class Scene extends Object3D {
  7810. constructor() {
  7811. super();
  7812. this.isScene = true;
  7813. this.type = 'Scene';
  7814. this.background = null;
  7815. this.environment = null;
  7816. this.fog = null;
  7817. this.backgroundBlurriness = 0;
  7818. this.backgroundIntensity = 1;
  7819. this.backgroundRotation = new Euler();
  7820. this.environmentIntensity = 1;
  7821. this.environmentRotation = new Euler();
  7822. this.overrideMaterial = null;
  7823. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  7824. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  7825. }
  7826. }
  7827. copy( source, recursive ) {
  7828. super.copy( source, recursive );
  7829. if ( source.background !== null ) this.background = source.background.clone();
  7830. if ( source.environment !== null ) this.environment = source.environment.clone();
  7831. if ( source.fog !== null ) this.fog = source.fog.clone();
  7832. this.backgroundBlurriness = source.backgroundBlurriness;
  7833. this.backgroundIntensity = source.backgroundIntensity;
  7834. this.backgroundRotation.copy( source.backgroundRotation );
  7835. this.environmentIntensity = source.environmentIntensity;
  7836. this.environmentRotation.copy( source.environmentRotation );
  7837. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  7838. this.matrixAutoUpdate = source.matrixAutoUpdate;
  7839. return this;
  7840. }
  7841. toJSON( meta ) {
  7842. const data = super.toJSON( meta );
  7843. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  7844. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  7845. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  7846. data.object.backgroundRotation = this.backgroundRotation.toArray();
  7847. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  7848. data.object.environmentRotation = this.environmentRotation.toArray();
  7849. return data;
  7850. }
  7851. }
  7852. class InterleavedBuffer {
  7853. constructor( array, stride ) {
  7854. this.isInterleavedBuffer = true;
  7855. this.array = array;
  7856. this.stride = stride;
  7857. this.count = array !== undefined ? array.length / stride : 0;
  7858. this.usage = StaticDrawUsage;
  7859. this._updateRange = { offset: 0, count: - 1 };
  7860. this.updateRanges = [];
  7861. this.version = 0;
  7862. this.uuid = generateUUID();
  7863. }
  7864. onUploadCallback() {}
  7865. set needsUpdate( value ) {
  7866. if ( value === true ) this.version ++;
  7867. }
  7868. get updateRange() {
  7869. warnOnce( 'THREE.InterleavedBuffer: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159
  7870. return this._updateRange;
  7871. }
  7872. setUsage( value ) {
  7873. this.usage = value;
  7874. return this;
  7875. }
  7876. addUpdateRange( start, count ) {
  7877. this.updateRanges.push( { start, count } );
  7878. }
  7879. clearUpdateRanges() {
  7880. this.updateRanges.length = 0;
  7881. }
  7882. copy( source ) {
  7883. this.array = new source.array.constructor( source.array );
  7884. this.count = source.count;
  7885. this.stride = source.stride;
  7886. this.usage = source.usage;
  7887. return this;
  7888. }
  7889. copyAt( index1, attribute, index2 ) {
  7890. index1 *= this.stride;
  7891. index2 *= attribute.stride;
  7892. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  7893. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7894. }
  7895. return this;
  7896. }
  7897. set( value, offset = 0 ) {
  7898. this.array.set( value, offset );
  7899. return this;
  7900. }
  7901. clone( data ) {
  7902. if ( data.arrayBuffers === undefined ) {
  7903. data.arrayBuffers = {};
  7904. }
  7905. if ( this.array.buffer._uuid === undefined ) {
  7906. this.array.buffer._uuid = generateUUID();
  7907. }
  7908. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7909. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  7910. }
  7911. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  7912. const ib = new this.constructor( array, this.stride );
  7913. ib.setUsage( this.usage );
  7914. return ib;
  7915. }
  7916. onUpload( callback ) {
  7917. this.onUploadCallback = callback;
  7918. return this;
  7919. }
  7920. toJSON( data ) {
  7921. if ( data.arrayBuffers === undefined ) {
  7922. data.arrayBuffers = {};
  7923. }
  7924. // generate UUID for array buffer if necessary
  7925. if ( this.array.buffer._uuid === undefined ) {
  7926. this.array.buffer._uuid = generateUUID();
  7927. }
  7928. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7929. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  7930. }
  7931. //
  7932. return {
  7933. uuid: this.uuid,
  7934. buffer: this.array.buffer._uuid,
  7935. type: this.array.constructor.name,
  7936. stride: this.stride
  7937. };
  7938. }
  7939. }
  7940. const _vector$7 = /*@__PURE__*/ new Vector3();
  7941. class InterleavedBufferAttribute {
  7942. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  7943. this.isInterleavedBufferAttribute = true;
  7944. this.name = '';
  7945. this.data = interleavedBuffer;
  7946. this.itemSize = itemSize;
  7947. this.offset = offset;
  7948. this.normalized = normalized;
  7949. }
  7950. get count() {
  7951. return this.data.count;
  7952. }
  7953. get array() {
  7954. return this.data.array;
  7955. }
  7956. set needsUpdate( value ) {
  7957. this.data.needsUpdate = value;
  7958. }
  7959. applyMatrix4( m ) {
  7960. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  7961. _vector$7.fromBufferAttribute( this, i );
  7962. _vector$7.applyMatrix4( m );
  7963. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7964. }
  7965. return this;
  7966. }
  7967. applyNormalMatrix( m ) {
  7968. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7969. _vector$7.fromBufferAttribute( this, i );
  7970. _vector$7.applyNormalMatrix( m );
  7971. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7972. }
  7973. return this;
  7974. }
  7975. transformDirection( m ) {
  7976. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7977. _vector$7.fromBufferAttribute( this, i );
  7978. _vector$7.transformDirection( m );
  7979. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7980. }
  7981. return this;
  7982. }
  7983. getComponent( index, component ) {
  7984. let value = this.array[ index * this.data.stride + this.offset + component ];
  7985. if ( this.normalized ) value = denormalize( value, this.array );
  7986. return value;
  7987. }
  7988. setComponent( index, component, value ) {
  7989. if ( this.normalized ) value = normalize$1( value, this.array );
  7990. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  7991. return this;
  7992. }
  7993. setX( index, x ) {
  7994. if ( this.normalized ) x = normalize$1( x, this.array );
  7995. this.data.array[ index * this.data.stride + this.offset ] = x;
  7996. return this;
  7997. }
  7998. setY( index, y ) {
  7999. if ( this.normalized ) y = normalize$1( y, this.array );
  8000. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  8001. return this;
  8002. }
  8003. setZ( index, z ) {
  8004. if ( this.normalized ) z = normalize$1( z, this.array );
  8005. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  8006. return this;
  8007. }
  8008. setW( index, w ) {
  8009. if ( this.normalized ) w = normalize$1( w, this.array );
  8010. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  8011. return this;
  8012. }
  8013. getX( index ) {
  8014. let x = this.data.array[ index * this.data.stride + this.offset ];
  8015. if ( this.normalized ) x = denormalize( x, this.array );
  8016. return x;
  8017. }
  8018. getY( index ) {
  8019. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  8020. if ( this.normalized ) y = denormalize( y, this.array );
  8021. return y;
  8022. }
  8023. getZ( index ) {
  8024. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  8025. if ( this.normalized ) z = denormalize( z, this.array );
  8026. return z;
  8027. }
  8028. getW( index ) {
  8029. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  8030. if ( this.normalized ) w = denormalize( w, this.array );
  8031. return w;
  8032. }
  8033. setXY( index, x, y ) {
  8034. index = index * this.data.stride + this.offset;
  8035. if ( this.normalized ) {
  8036. x = normalize$1( x, this.array );
  8037. y = normalize$1( y, this.array );
  8038. }
  8039. this.data.array[ index + 0 ] = x;
  8040. this.data.array[ index + 1 ] = y;
  8041. return this;
  8042. }
  8043. setXYZ( index, x, y, z ) {
  8044. index = index * this.data.stride + this.offset;
  8045. if ( this.normalized ) {
  8046. x = normalize$1( x, this.array );
  8047. y = normalize$1( y, this.array );
  8048. z = normalize$1( z, this.array );
  8049. }
  8050. this.data.array[ index + 0 ] = x;
  8051. this.data.array[ index + 1 ] = y;
  8052. this.data.array[ index + 2 ] = z;
  8053. return this;
  8054. }
  8055. setXYZW( index, x, y, z, w ) {
  8056. index = index * this.data.stride + this.offset;
  8057. if ( this.normalized ) {
  8058. x = normalize$1( x, this.array );
  8059. y = normalize$1( y, this.array );
  8060. z = normalize$1( z, this.array );
  8061. w = normalize$1( w, this.array );
  8062. }
  8063. this.data.array[ index + 0 ] = x;
  8064. this.data.array[ index + 1 ] = y;
  8065. this.data.array[ index + 2 ] = z;
  8066. this.data.array[ index + 3 ] = w;
  8067. return this;
  8068. }
  8069. clone( data ) {
  8070. if ( data === undefined ) {
  8071. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  8072. const array = [];
  8073. for ( let i = 0; i < this.count; i ++ ) {
  8074. const index = i * this.data.stride + this.offset;
  8075. for ( let j = 0; j < this.itemSize; j ++ ) {
  8076. array.push( this.data.array[ index + j ] );
  8077. }
  8078. }
  8079. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  8080. } else {
  8081. if ( data.interleavedBuffers === undefined ) {
  8082. data.interleavedBuffers = {};
  8083. }
  8084. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8085. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  8086. }
  8087. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  8088. }
  8089. }
  8090. toJSON( data ) {
  8091. if ( data === undefined ) {
  8092. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  8093. const array = [];
  8094. for ( let i = 0; i < this.count; i ++ ) {
  8095. const index = i * this.data.stride + this.offset;
  8096. for ( let j = 0; j < this.itemSize; j ++ ) {
  8097. array.push( this.data.array[ index + j ] );
  8098. }
  8099. }
  8100. // de-interleave data and save it as an ordinary buffer attribute for now
  8101. return {
  8102. itemSize: this.itemSize,
  8103. type: this.array.constructor.name,
  8104. array: array,
  8105. normalized: this.normalized
  8106. };
  8107. } else {
  8108. // save as true interleaved attribute
  8109. if ( data.interleavedBuffers === undefined ) {
  8110. data.interleavedBuffers = {};
  8111. }
  8112. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8113. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  8114. }
  8115. return {
  8116. isInterleavedBufferAttribute: true,
  8117. itemSize: this.itemSize,
  8118. data: this.data.uuid,
  8119. offset: this.offset,
  8120. normalized: this.normalized
  8121. };
  8122. }
  8123. }
  8124. }
  8125. class SpriteMaterial extends Material {
  8126. constructor( parameters ) {
  8127. super();
  8128. this.isSpriteMaterial = true;
  8129. this.type = 'SpriteMaterial';
  8130. this.color = new Color( 0xffffff );
  8131. this.map = null;
  8132. this.alphaMap = null;
  8133. this.rotation = 0;
  8134. this.sizeAttenuation = true;
  8135. this.transparent = true;
  8136. this.fog = true;
  8137. this.setValues( parameters );
  8138. }
  8139. copy( source ) {
  8140. super.copy( source );
  8141. this.color.copy( source.color );
  8142. this.map = source.map;
  8143. this.alphaMap = source.alphaMap;
  8144. this.rotation = source.rotation;
  8145. this.sizeAttenuation = source.sizeAttenuation;
  8146. this.fog = source.fog;
  8147. return this;
  8148. }
  8149. }
  8150. let _geometry$1;
  8151. const _intersectPoint = /*@__PURE__*/ new Vector3();
  8152. const _worldScale = /*@__PURE__*/ new Vector3();
  8153. const _mvPosition = /*@__PURE__*/ new Vector3();
  8154. const _alignedPosition = /*@__PURE__*/ new Vector2();
  8155. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  8156. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  8157. const _vA = /*@__PURE__*/ new Vector3();
  8158. const _vB = /*@__PURE__*/ new Vector3();
  8159. const _vC = /*@__PURE__*/ new Vector3();
  8160. const _uvA = /*@__PURE__*/ new Vector2();
  8161. const _uvB = /*@__PURE__*/ new Vector2();
  8162. const _uvC = /*@__PURE__*/ new Vector2();
  8163. class Sprite extends Object3D {
  8164. constructor( material = new SpriteMaterial() ) {
  8165. super();
  8166. this.isSprite = true;
  8167. this.type = 'Sprite';
  8168. if ( _geometry$1 === undefined ) {
  8169. _geometry$1 = new BufferGeometry();
  8170. const float32Array = new Float32Array( [
  8171. - 0.5, - 0.5, 0, 0, 0,
  8172. 0.5, - 0.5, 0, 1, 0,
  8173. 0.5, 0.5, 0, 1, 1,
  8174. - 0.5, 0.5, 0, 0, 1
  8175. ] );
  8176. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  8177. _geometry$1.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  8178. _geometry$1.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  8179. _geometry$1.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  8180. }
  8181. this.geometry = _geometry$1;
  8182. this.material = material;
  8183. this.center = new Vector2( 0.5, 0.5 );
  8184. }
  8185. raycast( raycaster, intersects ) {
  8186. if ( raycaster.camera === null ) {
  8187. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  8188. }
  8189. _worldScale.setFromMatrixScale( this.matrixWorld );
  8190. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  8191. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  8192. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  8193. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  8194. _worldScale.multiplyScalar( - _mvPosition.z );
  8195. }
  8196. const rotation = this.material.rotation;
  8197. let sin, cos;
  8198. if ( rotation !== 0 ) {
  8199. cos = Math.cos( rotation );
  8200. sin = Math.sin( rotation );
  8201. }
  8202. const center = this.center;
  8203. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8204. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8205. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8206. _uvA.set( 0, 0 );
  8207. _uvB.set( 1, 0 );
  8208. _uvC.set( 1, 1 );
  8209. // check first triangle
  8210. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  8211. if ( intersect === null ) {
  8212. // check second triangle
  8213. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8214. _uvB.set( 0, 1 );
  8215. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  8216. if ( intersect === null ) {
  8217. return;
  8218. }
  8219. }
  8220. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  8221. if ( distance < raycaster.near || distance > raycaster.far ) return;
  8222. intersects.push( {
  8223. distance: distance,
  8224. point: _intersectPoint.clone(),
  8225. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  8226. face: null,
  8227. object: this
  8228. } );
  8229. }
  8230. copy( source, recursive ) {
  8231. super.copy( source, recursive );
  8232. if ( source.center !== undefined ) this.center.copy( source.center );
  8233. this.material = source.material;
  8234. return this;
  8235. }
  8236. }
  8237. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  8238. // compute position in camera space
  8239. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  8240. // to check if rotation is not zero
  8241. if ( sin !== undefined ) {
  8242. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  8243. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  8244. } else {
  8245. _rotatedPosition.copy( _alignedPosition );
  8246. }
  8247. vertexPosition.copy( mvPosition );
  8248. vertexPosition.x += _rotatedPosition.x;
  8249. vertexPosition.y += _rotatedPosition.y;
  8250. // transform to world space
  8251. vertexPosition.applyMatrix4( _viewWorldMatrix );
  8252. }
  8253. const _v1$2 = /*@__PURE__*/ new Vector3();
  8254. const _v2$1 = /*@__PURE__*/ new Vector3();
  8255. class LOD extends Object3D {
  8256. constructor() {
  8257. super();
  8258. this._currentLevel = 0;
  8259. this.type = 'LOD';
  8260. Object.defineProperties( this, {
  8261. levels: {
  8262. enumerable: true,
  8263. value: []
  8264. },
  8265. isLOD: {
  8266. value: true,
  8267. }
  8268. } );
  8269. this.autoUpdate = true;
  8270. }
  8271. copy( source ) {
  8272. super.copy( source, false );
  8273. const levels = source.levels;
  8274. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8275. const level = levels[ i ];
  8276. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  8277. }
  8278. this.autoUpdate = source.autoUpdate;
  8279. return this;
  8280. }
  8281. addLevel( object, distance = 0, hysteresis = 0 ) {
  8282. distance = Math.abs( distance );
  8283. const levels = this.levels;
  8284. let l;
  8285. for ( l = 0; l < levels.length; l ++ ) {
  8286. if ( distance < levels[ l ].distance ) {
  8287. break;
  8288. }
  8289. }
  8290. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  8291. this.add( object );
  8292. return this;
  8293. }
  8294. getCurrentLevel() {
  8295. return this._currentLevel;
  8296. }
  8297. getObjectForDistance( distance ) {
  8298. const levels = this.levels;
  8299. if ( levels.length > 0 ) {
  8300. let i, l;
  8301. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8302. let levelDistance = levels[ i ].distance;
  8303. if ( levels[ i ].object.visible ) {
  8304. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8305. }
  8306. if ( distance < levelDistance ) {
  8307. break;
  8308. }
  8309. }
  8310. return levels[ i - 1 ].object;
  8311. }
  8312. return null;
  8313. }
  8314. raycast( raycaster, intersects ) {
  8315. const levels = this.levels;
  8316. if ( levels.length > 0 ) {
  8317. _v1$2.setFromMatrixPosition( this.matrixWorld );
  8318. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  8319. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  8320. }
  8321. }
  8322. update( camera ) {
  8323. const levels = this.levels;
  8324. if ( levels.length > 1 ) {
  8325. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  8326. _v2$1.setFromMatrixPosition( this.matrixWorld );
  8327. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  8328. levels[ 0 ].object.visible = true;
  8329. let i, l;
  8330. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8331. let levelDistance = levels[ i ].distance;
  8332. if ( levels[ i ].object.visible ) {
  8333. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8334. }
  8335. if ( distance >= levelDistance ) {
  8336. levels[ i - 1 ].object.visible = false;
  8337. levels[ i ].object.visible = true;
  8338. } else {
  8339. break;
  8340. }
  8341. }
  8342. this._currentLevel = i - 1;
  8343. for ( ; i < l; i ++ ) {
  8344. levels[ i ].object.visible = false;
  8345. }
  8346. }
  8347. }
  8348. toJSON( meta ) {
  8349. const data = super.toJSON( meta );
  8350. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  8351. data.object.levels = [];
  8352. const levels = this.levels;
  8353. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8354. const level = levels[ i ];
  8355. data.object.levels.push( {
  8356. object: level.object.uuid,
  8357. distance: level.distance,
  8358. hysteresis: level.hysteresis
  8359. } );
  8360. }
  8361. return data;
  8362. }
  8363. }
  8364. const _basePosition = /*@__PURE__*/ new Vector3();
  8365. const _skinIndex = /*@__PURE__*/ new Vector4();
  8366. const _skinWeight = /*@__PURE__*/ new Vector4();
  8367. const _vector3$1 = /*@__PURE__*/ new Vector3();
  8368. const _matrix4 = /*@__PURE__*/ new Matrix4();
  8369. const _vertex = /*@__PURE__*/ new Vector3();
  8370. const _sphere$5 = /*@__PURE__*/ new Sphere();
  8371. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  8372. const _ray$2 = /*@__PURE__*/ new Ray();
  8373. class SkinnedMesh extends Mesh {
  8374. constructor( geometry, material ) {
  8375. super( geometry, material );
  8376. this.isSkinnedMesh = true;
  8377. this.type = 'SkinnedMesh';
  8378. this.bindMode = AttachedBindMode;
  8379. this.bindMatrix = new Matrix4();
  8380. this.bindMatrixInverse = new Matrix4();
  8381. this.boundingBox = null;
  8382. this.boundingSphere = null;
  8383. }
  8384. computeBoundingBox() {
  8385. const geometry = this.geometry;
  8386. if ( this.boundingBox === null ) {
  8387. this.boundingBox = new Box3();
  8388. }
  8389. this.boundingBox.makeEmpty();
  8390. const positionAttribute = geometry.getAttribute( 'position' );
  8391. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8392. this.getVertexPosition( i, _vertex );
  8393. this.boundingBox.expandByPoint( _vertex );
  8394. }
  8395. }
  8396. computeBoundingSphere() {
  8397. const geometry = this.geometry;
  8398. if ( this.boundingSphere === null ) {
  8399. this.boundingSphere = new Sphere();
  8400. }
  8401. this.boundingSphere.makeEmpty();
  8402. const positionAttribute = geometry.getAttribute( 'position' );
  8403. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8404. this.getVertexPosition( i, _vertex );
  8405. this.boundingSphere.expandByPoint( _vertex );
  8406. }
  8407. }
  8408. copy( source, recursive ) {
  8409. super.copy( source, recursive );
  8410. this.bindMode = source.bindMode;
  8411. this.bindMatrix.copy( source.bindMatrix );
  8412. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  8413. this.skeleton = source.skeleton;
  8414. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8415. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8416. return this;
  8417. }
  8418. raycast( raycaster, intersects ) {
  8419. const material = this.material;
  8420. const matrixWorld = this.matrixWorld;
  8421. if ( material === undefined ) return;
  8422. // test with bounding sphere in world space
  8423. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8424. _sphere$5.copy( this.boundingSphere );
  8425. _sphere$5.applyMatrix4( matrixWorld );
  8426. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  8427. // convert ray to local space of skinned mesh
  8428. _inverseMatrix$2.copy( matrixWorld ).invert();
  8429. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  8430. // test with bounding box in local space
  8431. if ( this.boundingBox !== null ) {
  8432. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  8433. }
  8434. // test for intersections with geometry
  8435. this._computeIntersections( raycaster, intersects, _ray$2 );
  8436. }
  8437. getVertexPosition( index, target ) {
  8438. super.getVertexPosition( index, target );
  8439. this.applyBoneTransform( index, target );
  8440. return target;
  8441. }
  8442. bind( skeleton, bindMatrix ) {
  8443. this.skeleton = skeleton;
  8444. if ( bindMatrix === undefined ) {
  8445. this.updateMatrixWorld( true );
  8446. this.skeleton.calculateInverses();
  8447. bindMatrix = this.matrixWorld;
  8448. }
  8449. this.bindMatrix.copy( bindMatrix );
  8450. this.bindMatrixInverse.copy( bindMatrix ).invert();
  8451. }
  8452. pose() {
  8453. this.skeleton.pose();
  8454. }
  8455. normalizeSkinWeights() {
  8456. const vector = new Vector4();
  8457. const skinWeight = this.geometry.attributes.skinWeight;
  8458. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  8459. vector.fromBufferAttribute( skinWeight, i );
  8460. const scale = 1.0 / vector.manhattanLength();
  8461. if ( scale !== Infinity ) {
  8462. vector.multiplyScalar( scale );
  8463. } else {
  8464. vector.set( 1, 0, 0, 0 ); // do something reasonable
  8465. }
  8466. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  8467. }
  8468. }
  8469. updateMatrixWorld( force ) {
  8470. super.updateMatrixWorld( force );
  8471. if ( this.bindMode === AttachedBindMode ) {
  8472. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  8473. } else if ( this.bindMode === DetachedBindMode ) {
  8474. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  8475. } else {
  8476. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  8477. }
  8478. }
  8479. applyBoneTransform( index, vector ) {
  8480. const skeleton = this.skeleton;
  8481. const geometry = this.geometry;
  8482. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  8483. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  8484. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  8485. vector.set( 0, 0, 0 );
  8486. for ( let i = 0; i < 4; i ++ ) {
  8487. const weight = _skinWeight.getComponent( i );
  8488. if ( weight !== 0 ) {
  8489. const boneIndex = _skinIndex.getComponent( i );
  8490. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  8491. vector.addScaledVector( _vector3$1.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  8492. }
  8493. }
  8494. return vector.applyMatrix4( this.bindMatrixInverse );
  8495. }
  8496. }
  8497. class Bone extends Object3D {
  8498. constructor() {
  8499. super();
  8500. this.isBone = true;
  8501. this.type = 'Bone';
  8502. }
  8503. }
  8504. class DataTexture extends Texture {
  8505. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  8506. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  8507. this.isDataTexture = true;
  8508. this.image = { data: data, width: width, height: height };
  8509. this.generateMipmaps = false;
  8510. this.flipY = false;
  8511. this.unpackAlignment = 1;
  8512. }
  8513. }
  8514. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  8515. const _identityMatrix$1 = /*@__PURE__*/ new Matrix4();
  8516. class Skeleton {
  8517. constructor( bones = [], boneInverses = [] ) {
  8518. this.uuid = generateUUID();
  8519. this.bones = bones.slice( 0 );
  8520. this.boneInverses = boneInverses;
  8521. this.boneMatrices = null;
  8522. this.boneTexture = null;
  8523. this.init();
  8524. }
  8525. init() {
  8526. const bones = this.bones;
  8527. const boneInverses = this.boneInverses;
  8528. this.boneMatrices = new Float32Array( bones.length * 16 );
  8529. // calculate inverse bone matrices if necessary
  8530. if ( boneInverses.length === 0 ) {
  8531. this.calculateInverses();
  8532. } else {
  8533. // handle special case
  8534. if ( bones.length !== boneInverses.length ) {
  8535. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  8536. this.boneInverses = [];
  8537. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8538. this.boneInverses.push( new Matrix4() );
  8539. }
  8540. }
  8541. }
  8542. }
  8543. calculateInverses() {
  8544. this.boneInverses.length = 0;
  8545. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8546. const inverse = new Matrix4();
  8547. if ( this.bones[ i ] ) {
  8548. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  8549. }
  8550. this.boneInverses.push( inverse );
  8551. }
  8552. }
  8553. pose() {
  8554. // recover the bind-time world matrices
  8555. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8556. const bone = this.bones[ i ];
  8557. if ( bone ) {
  8558. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  8559. }
  8560. }
  8561. // compute the local matrices, positions, rotations and scales
  8562. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8563. const bone = this.bones[ i ];
  8564. if ( bone ) {
  8565. if ( bone.parent && bone.parent.isBone ) {
  8566. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  8567. bone.matrix.multiply( bone.matrixWorld );
  8568. } else {
  8569. bone.matrix.copy( bone.matrixWorld );
  8570. }
  8571. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  8572. }
  8573. }
  8574. }
  8575. update() {
  8576. const bones = this.bones;
  8577. const boneInverses = this.boneInverses;
  8578. const boneMatrices = this.boneMatrices;
  8579. const boneTexture = this.boneTexture;
  8580. // flatten bone matrices to array
  8581. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  8582. // compute the offset between the current and the original transform
  8583. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix$1;
  8584. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  8585. _offsetMatrix.toArray( boneMatrices, i * 16 );
  8586. }
  8587. if ( boneTexture !== null ) {
  8588. boneTexture.needsUpdate = true;
  8589. }
  8590. }
  8591. clone() {
  8592. return new Skeleton( this.bones, this.boneInverses );
  8593. }
  8594. computeBoneTexture() {
  8595. // layout (1 matrix = 4 pixels)
  8596. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8597. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  8598. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  8599. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  8600. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  8601. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  8602. size = Math.ceil( size / 4 ) * 4;
  8603. size = Math.max( size, 4 );
  8604. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  8605. boneMatrices.set( this.boneMatrices ); // copy current values
  8606. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  8607. boneTexture.needsUpdate = true;
  8608. this.boneMatrices = boneMatrices;
  8609. this.boneTexture = boneTexture;
  8610. return this;
  8611. }
  8612. getBoneByName( name ) {
  8613. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8614. const bone = this.bones[ i ];
  8615. if ( bone.name === name ) {
  8616. return bone;
  8617. }
  8618. }
  8619. return undefined;
  8620. }
  8621. dispose( ) {
  8622. if ( this.boneTexture !== null ) {
  8623. this.boneTexture.dispose();
  8624. this.boneTexture = null;
  8625. }
  8626. }
  8627. fromJSON( json, bones ) {
  8628. this.uuid = json.uuid;
  8629. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  8630. const uuid = json.bones[ i ];
  8631. let bone = bones[ uuid ];
  8632. if ( bone === undefined ) {
  8633. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  8634. bone = new Bone();
  8635. }
  8636. this.bones.push( bone );
  8637. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  8638. }
  8639. this.init();
  8640. return this;
  8641. }
  8642. toJSON() {
  8643. const data = {
  8644. metadata: {
  8645. version: 4.6,
  8646. type: 'Skeleton',
  8647. generator: 'Skeleton.toJSON'
  8648. },
  8649. bones: [],
  8650. boneInverses: []
  8651. };
  8652. data.uuid = this.uuid;
  8653. const bones = this.bones;
  8654. const boneInverses = this.boneInverses;
  8655. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  8656. const bone = bones[ i ];
  8657. data.bones.push( bone.uuid );
  8658. const boneInverse = boneInverses[ i ];
  8659. data.boneInverses.push( boneInverse.toArray() );
  8660. }
  8661. return data;
  8662. }
  8663. }
  8664. class InstancedBufferAttribute extends BufferAttribute {
  8665. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  8666. super( array, itemSize, normalized );
  8667. this.isInstancedBufferAttribute = true;
  8668. this.meshPerAttribute = meshPerAttribute;
  8669. }
  8670. copy( source ) {
  8671. super.copy( source );
  8672. this.meshPerAttribute = source.meshPerAttribute;
  8673. return this;
  8674. }
  8675. toJSON() {
  8676. const data = super.toJSON();
  8677. data.meshPerAttribute = this.meshPerAttribute;
  8678. data.isInstancedBufferAttribute = true;
  8679. return data;
  8680. }
  8681. }
  8682. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  8683. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  8684. const _instanceIntersects = [];
  8685. const _box3 = /*@__PURE__*/ new Box3();
  8686. const _identity = /*@__PURE__*/ new Matrix4();
  8687. const _mesh$1 = /*@__PURE__*/ new Mesh();
  8688. const _sphere$4 = /*@__PURE__*/ new Sphere();
  8689. class InstancedMesh extends Mesh {
  8690. constructor( geometry, material, count ) {
  8691. super( geometry, material );
  8692. this.isInstancedMesh = true;
  8693. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  8694. this.instanceColor = null;
  8695. this.morphTexture = null;
  8696. this.count = count;
  8697. this.boundingBox = null;
  8698. this.boundingSphere = null;
  8699. for ( let i = 0; i < count; i ++ ) {
  8700. this.setMatrixAt( i, _identity );
  8701. }
  8702. }
  8703. computeBoundingBox() {
  8704. const geometry = this.geometry;
  8705. const count = this.count;
  8706. if ( this.boundingBox === null ) {
  8707. this.boundingBox = new Box3();
  8708. }
  8709. if ( geometry.boundingBox === null ) {
  8710. geometry.computeBoundingBox();
  8711. }
  8712. this.boundingBox.makeEmpty();
  8713. for ( let i = 0; i < count; i ++ ) {
  8714. this.getMatrixAt( i, _instanceLocalMatrix );
  8715. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  8716. this.boundingBox.union( _box3 );
  8717. }
  8718. }
  8719. computeBoundingSphere() {
  8720. const geometry = this.geometry;
  8721. const count = this.count;
  8722. if ( this.boundingSphere === null ) {
  8723. this.boundingSphere = new Sphere();
  8724. }
  8725. if ( geometry.boundingSphere === null ) {
  8726. geometry.computeBoundingSphere();
  8727. }
  8728. this.boundingSphere.makeEmpty();
  8729. for ( let i = 0; i < count; i ++ ) {
  8730. this.getMatrixAt( i, _instanceLocalMatrix );
  8731. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  8732. this.boundingSphere.union( _sphere$4 );
  8733. }
  8734. }
  8735. copy( source, recursive ) {
  8736. super.copy( source, recursive );
  8737. this.instanceMatrix.copy( source.instanceMatrix );
  8738. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  8739. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  8740. this.count = source.count;
  8741. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8742. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8743. return this;
  8744. }
  8745. getColorAt( index, color ) {
  8746. color.fromArray( this.instanceColor.array, index * 3 );
  8747. }
  8748. getMatrixAt( index, matrix ) {
  8749. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  8750. }
  8751. getMorphAt( index, object ) {
  8752. const objectInfluences = object.morphTargetInfluences;
  8753. const array = this.morphTexture.source.data.data;
  8754. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  8755. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  8756. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8757. objectInfluences[ i ] = array[ dataIndex + i ];
  8758. }
  8759. }
  8760. raycast( raycaster, intersects ) {
  8761. const matrixWorld = this.matrixWorld;
  8762. const raycastTimes = this.count;
  8763. _mesh$1.geometry = this.geometry;
  8764. _mesh$1.material = this.material;
  8765. if ( _mesh$1.material === undefined ) return;
  8766. // test with bounding sphere first
  8767. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8768. _sphere$4.copy( this.boundingSphere );
  8769. _sphere$4.applyMatrix4( matrixWorld );
  8770. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  8771. // now test each instance
  8772. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  8773. // calculate the world matrix for each instance
  8774. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  8775. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  8776. // the mesh represents this single instance
  8777. _mesh$1.matrixWorld = _instanceWorldMatrix;
  8778. _mesh$1.raycast( raycaster, _instanceIntersects );
  8779. // process the result of raycast
  8780. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  8781. const intersect = _instanceIntersects[ i ];
  8782. intersect.instanceId = instanceId;
  8783. intersect.object = this;
  8784. intersects.push( intersect );
  8785. }
  8786. _instanceIntersects.length = 0;
  8787. }
  8788. }
  8789. setColorAt( index, color ) {
  8790. if ( this.instanceColor === null ) {
  8791. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  8792. }
  8793. color.toArray( this.instanceColor.array, index * 3 );
  8794. }
  8795. setMatrixAt( index, matrix ) {
  8796. matrix.toArray( this.instanceMatrix.array, index * 16 );
  8797. }
  8798. setMorphAt( index, object ) {
  8799. const objectInfluences = object.morphTargetInfluences;
  8800. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  8801. if ( this.morphTexture === null ) {
  8802. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  8803. }
  8804. const array = this.morphTexture.source.data.data;
  8805. let morphInfluencesSum = 0;
  8806. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8807. morphInfluencesSum += objectInfluences[ i ];
  8808. }
  8809. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  8810. const dataIndex = len * index;
  8811. array[ dataIndex ] = morphBaseInfluence;
  8812. array.set( objectInfluences, dataIndex + 1 );
  8813. }
  8814. updateMorphTargets() {
  8815. }
  8816. dispose() {
  8817. this.dispatchEvent( { type: 'dispose' } );
  8818. if ( this.morphTexture !== null ) {
  8819. this.morphTexture.dispose();
  8820. this.morphTexture = null;
  8821. }
  8822. return this;
  8823. }
  8824. }
  8825. const _vector1 = /*@__PURE__*/ new Vector3();
  8826. const _vector2 = /*@__PURE__*/ new Vector3();
  8827. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  8828. class Plane {
  8829. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  8830. this.isPlane = true;
  8831. // normal is assumed to be normalized
  8832. this.normal = normal;
  8833. this.constant = constant;
  8834. }
  8835. set( normal, constant ) {
  8836. this.normal.copy( normal );
  8837. this.constant = constant;
  8838. return this;
  8839. }
  8840. setComponents( x, y, z, w ) {
  8841. this.normal.set( x, y, z );
  8842. this.constant = w;
  8843. return this;
  8844. }
  8845. setFromNormalAndCoplanarPoint( normal, point ) {
  8846. this.normal.copy( normal );
  8847. this.constant = - point.dot( this.normal );
  8848. return this;
  8849. }
  8850. setFromCoplanarPoints( a, b, c ) {
  8851. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  8852. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  8853. this.setFromNormalAndCoplanarPoint( normal, a );
  8854. return this;
  8855. }
  8856. copy( plane ) {
  8857. this.normal.copy( plane.normal );
  8858. this.constant = plane.constant;
  8859. return this;
  8860. }
  8861. normalize() {
  8862. // Note: will lead to a divide by zero if the plane is invalid.
  8863. const inverseNormalLength = 1.0 / this.normal.length();
  8864. this.normal.multiplyScalar( inverseNormalLength );
  8865. this.constant *= inverseNormalLength;
  8866. return this;
  8867. }
  8868. negate() {
  8869. this.constant *= - 1;
  8870. this.normal.negate();
  8871. return this;
  8872. }
  8873. distanceToPoint( point ) {
  8874. return this.normal.dot( point ) + this.constant;
  8875. }
  8876. distanceToSphere( sphere ) {
  8877. return this.distanceToPoint( sphere.center ) - sphere.radius;
  8878. }
  8879. projectPoint( point, target ) {
  8880. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  8881. }
  8882. intersectLine( line, target ) {
  8883. const direction = line.delta( _vector1 );
  8884. const denominator = this.normal.dot( direction );
  8885. if ( denominator === 0 ) {
  8886. // line is coplanar, return origin
  8887. if ( this.distanceToPoint( line.start ) === 0 ) {
  8888. return target.copy( line.start );
  8889. }
  8890. // Unsure if this is the correct method to handle this case.
  8891. return null;
  8892. }
  8893. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  8894. if ( t < 0 || t > 1 ) {
  8895. return null;
  8896. }
  8897. return target.copy( line.start ).addScaledVector( direction, t );
  8898. }
  8899. intersectsLine( line ) {
  8900. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  8901. const startSign = this.distanceToPoint( line.start );
  8902. const endSign = this.distanceToPoint( line.end );
  8903. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  8904. }
  8905. intersectsBox( box ) {
  8906. return box.intersectsPlane( this );
  8907. }
  8908. intersectsSphere( sphere ) {
  8909. return sphere.intersectsPlane( this );
  8910. }
  8911. coplanarPoint( target ) {
  8912. return target.copy( this.normal ).multiplyScalar( - this.constant );
  8913. }
  8914. applyMatrix4( matrix, optionalNormalMatrix ) {
  8915. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  8916. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  8917. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  8918. this.constant = - referencePoint.dot( normal );
  8919. return this;
  8920. }
  8921. translate( offset ) {
  8922. this.constant -= offset.dot( this.normal );
  8923. return this;
  8924. }
  8925. equals( plane ) {
  8926. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  8927. }
  8928. clone() {
  8929. return new this.constructor().copy( this );
  8930. }
  8931. }
  8932. const _sphere$3 = /*@__PURE__*/ new Sphere();
  8933. const _vector$6 = /*@__PURE__*/ new Vector3();
  8934. class Frustum {
  8935. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  8936. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  8937. }
  8938. set( p0, p1, p2, p3, p4, p5 ) {
  8939. const planes = this.planes;
  8940. planes[ 0 ].copy( p0 );
  8941. planes[ 1 ].copy( p1 );
  8942. planes[ 2 ].copy( p2 );
  8943. planes[ 3 ].copy( p3 );
  8944. planes[ 4 ].copy( p4 );
  8945. planes[ 5 ].copy( p5 );
  8946. return this;
  8947. }
  8948. copy( frustum ) {
  8949. const planes = this.planes;
  8950. for ( let i = 0; i < 6; i ++ ) {
  8951. planes[ i ].copy( frustum.planes[ i ] );
  8952. }
  8953. return this;
  8954. }
  8955. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  8956. const planes = this.planes;
  8957. const me = m.elements;
  8958. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  8959. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  8960. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  8961. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  8962. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  8963. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  8964. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  8965. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  8966. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  8967. if ( coordinateSystem === WebGLCoordinateSystem ) {
  8968. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  8969. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  8970. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  8971. } else {
  8972. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  8973. }
  8974. return this;
  8975. }
  8976. intersectsObject( object ) {
  8977. if ( object.boundingSphere !== undefined ) {
  8978. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  8979. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  8980. } else {
  8981. const geometry = object.geometry;
  8982. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8983. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  8984. }
  8985. return this.intersectsSphere( _sphere$3 );
  8986. }
  8987. intersectsSprite( sprite ) {
  8988. _sphere$3.center.set( 0, 0, 0 );
  8989. _sphere$3.radius = 0.7071067811865476;
  8990. _sphere$3.applyMatrix4( sprite.matrixWorld );
  8991. return this.intersectsSphere( _sphere$3 );
  8992. }
  8993. intersectsSphere( sphere ) {
  8994. const planes = this.planes;
  8995. const center = sphere.center;
  8996. const negRadius = - sphere.radius;
  8997. for ( let i = 0; i < 6; i ++ ) {
  8998. const distance = planes[ i ].distanceToPoint( center );
  8999. if ( distance < negRadius ) {
  9000. return false;
  9001. }
  9002. }
  9003. return true;
  9004. }
  9005. intersectsBox( box ) {
  9006. const planes = this.planes;
  9007. for ( let i = 0; i < 6; i ++ ) {
  9008. const plane = planes[ i ];
  9009. // corner at max distance
  9010. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  9011. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  9012. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  9013. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  9014. return false;
  9015. }
  9016. }
  9017. return true;
  9018. }
  9019. containsPoint( point ) {
  9020. const planes = this.planes;
  9021. for ( let i = 0; i < 6; i ++ ) {
  9022. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  9023. return false;
  9024. }
  9025. }
  9026. return true;
  9027. }
  9028. clone() {
  9029. return new this.constructor().copy( this );
  9030. }
  9031. }
  9032. function sortOpaque( a, b ) {
  9033. return a.z - b.z;
  9034. }
  9035. function sortTransparent( a, b ) {
  9036. return b.z - a.z;
  9037. }
  9038. class MultiDrawRenderList {
  9039. constructor() {
  9040. this.index = 0;
  9041. this.pool = [];
  9042. this.list = [];
  9043. }
  9044. push( drawRange, z, index ) {
  9045. const pool = this.pool;
  9046. const list = this.list;
  9047. if ( this.index >= pool.length ) {
  9048. pool.push( {
  9049. start: - 1,
  9050. count: - 1,
  9051. z: - 1,
  9052. index: - 1,
  9053. } );
  9054. }
  9055. const item = pool[ this.index ];
  9056. list.push( item );
  9057. this.index ++;
  9058. item.start = drawRange.start;
  9059. item.count = drawRange.count;
  9060. item.z = z;
  9061. item.index = index;
  9062. }
  9063. reset() {
  9064. this.list.length = 0;
  9065. this.index = 0;
  9066. }
  9067. }
  9068. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  9069. const _invMatrixWorld = /*@__PURE__*/ new Matrix4();
  9070. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  9071. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  9072. const _projScreenMatrix$3 = /*@__PURE__*/ new Matrix4();
  9073. const _frustum$1 = /*@__PURE__*/ new Frustum();
  9074. const _box$1 = /*@__PURE__*/ new Box3();
  9075. const _sphere$2 = /*@__PURE__*/ new Sphere();
  9076. const _vector$5 = /*@__PURE__*/ new Vector3();
  9077. const _forward = /*@__PURE__*/ new Vector3();
  9078. const _temp = /*@__PURE__*/ new Vector3();
  9079. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  9080. const _mesh = /*@__PURE__*/ new Mesh();
  9081. const _batchIntersects = [];
  9082. // @TODO: SkinnedMesh support?
  9083. // @TODO: geometry.groups support?
  9084. // @TODO: geometry.drawRange support?
  9085. // @TODO: geometry.morphAttributes support?
  9086. // @TODO: Support uniform parameter per geometry
  9087. // @TODO: Add an "optimize" function to pack geometry and remove data gaps
  9088. // copies data from attribute "src" into "target" starting at "targetOffset"
  9089. function copyAttributeData( src, target, targetOffset = 0 ) {
  9090. const itemSize = target.itemSize;
  9091. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  9092. // use the component getters and setters if the array data cannot
  9093. // be copied directly
  9094. const vertexCount = src.count;
  9095. for ( let i = 0; i < vertexCount; i ++ ) {
  9096. for ( let c = 0; c < itemSize; c ++ ) {
  9097. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  9098. }
  9099. }
  9100. } else {
  9101. // faster copy approach using typed array set function
  9102. target.array.set( src.array, targetOffset * itemSize );
  9103. }
  9104. target.needsUpdate = true;
  9105. }
  9106. class BatchedMesh extends Mesh {
  9107. get maxInstanceCount() {
  9108. return this._maxInstanceCount;
  9109. }
  9110. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  9111. super( new BufferGeometry(), material );
  9112. this.isBatchedMesh = true;
  9113. this.perObjectFrustumCulled = true;
  9114. this.sortObjects = true;
  9115. this.boundingBox = null;
  9116. this.boundingSphere = null;
  9117. this.customSort = null;
  9118. // stores visible, active, and geometry id per object
  9119. this._drawInfo = [];
  9120. // geometry information
  9121. this._drawRanges = [];
  9122. this._reservedRanges = [];
  9123. this._bounds = [];
  9124. this._maxInstanceCount = maxInstanceCount;
  9125. this._maxVertexCount = maxVertexCount;
  9126. this._maxIndexCount = maxIndexCount;
  9127. this._geometryInitialized = false;
  9128. this._geometryCount = 0;
  9129. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  9130. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  9131. this._multiDrawCount = 0;
  9132. this._multiDrawInstances = null;
  9133. this._visibilityChanged = true;
  9134. // Local matrix per geometry by using data texture
  9135. this._matricesTexture = null;
  9136. this._indirectTexture = null;
  9137. this._colorsTexture = null;
  9138. this._initMatricesTexture();
  9139. this._initIndirectTexture();
  9140. }
  9141. _initMatricesTexture() {
  9142. // layout (1 matrix = 4 pixels)
  9143. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9144. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  9145. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  9146. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  9147. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  9148. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  9149. size = Math.ceil( size / 4 ) * 4;
  9150. size = Math.max( size, 4 );
  9151. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  9152. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  9153. this._matricesTexture = matricesTexture;
  9154. }
  9155. _initIndirectTexture() {
  9156. let size = Math.sqrt( this._maxInstanceCount );
  9157. size = Math.ceil( size );
  9158. const indirectArray = new Uint32Array( size * size );
  9159. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  9160. this._indirectTexture = indirectTexture;
  9161. }
  9162. _initColorsTexture() {
  9163. let size = Math.sqrt( this._maxIndexCount );
  9164. size = Math.ceil( size );
  9165. // 4 floats per RGBA pixel initialized to white
  9166. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  9167. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  9168. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  9169. this._colorsTexture = colorsTexture;
  9170. }
  9171. _initializeGeometry( reference ) {
  9172. const geometry = this.geometry;
  9173. const maxVertexCount = this._maxVertexCount;
  9174. const maxIndexCount = this._maxIndexCount;
  9175. if ( this._geometryInitialized === false ) {
  9176. for ( const attributeName in reference.attributes ) {
  9177. const srcAttribute = reference.getAttribute( attributeName );
  9178. const { array, itemSize, normalized } = srcAttribute;
  9179. const dstArray = new array.constructor( maxVertexCount * itemSize );
  9180. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  9181. geometry.setAttribute( attributeName, dstAttribute );
  9182. }
  9183. if ( reference.getIndex() !== null ) {
  9184. // Reserve last u16 index for primitive restart.
  9185. const indexArray = maxVertexCount > 65535
  9186. ? new Uint32Array( maxIndexCount )
  9187. : new Uint16Array( maxIndexCount );
  9188. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  9189. }
  9190. this._geometryInitialized = true;
  9191. }
  9192. }
  9193. // Make sure the geometry is compatible with the existing combined geometry attributes
  9194. _validateGeometry( geometry ) {
  9195. // check to ensure the geometries are using consistent attributes and indices
  9196. const batchGeometry = this.geometry;
  9197. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  9198. throw new Error( 'BatchedMesh: All geometries must consistently have "index".' );
  9199. }
  9200. for ( const attributeName in batchGeometry.attributes ) {
  9201. if ( ! geometry.hasAttribute( attributeName ) ) {
  9202. throw new Error( `BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  9203. }
  9204. const srcAttribute = geometry.getAttribute( attributeName );
  9205. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9206. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  9207. throw new Error( 'BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  9208. }
  9209. }
  9210. }
  9211. setCustomSort( func ) {
  9212. this.customSort = func;
  9213. return this;
  9214. }
  9215. computeBoundingBox() {
  9216. if ( this.boundingBox === null ) {
  9217. this.boundingBox = new Box3();
  9218. }
  9219. const geometryCount = this._geometryCount;
  9220. const boundingBox = this.boundingBox;
  9221. const drawInfo = this._drawInfo;
  9222. boundingBox.makeEmpty();
  9223. for ( let i = 0; i < geometryCount; i ++ ) {
  9224. if ( drawInfo[ i ].active === false ) continue;
  9225. const geometryId = drawInfo[ i ].geometryIndex;
  9226. this.getMatrixAt( i, _matrix$1 );
  9227. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  9228. boundingBox.union( _box$1 );
  9229. }
  9230. }
  9231. computeBoundingSphere() {
  9232. if ( this.boundingSphere === null ) {
  9233. this.boundingSphere = new Sphere();
  9234. }
  9235. const boundingSphere = this.boundingSphere;
  9236. const drawInfo = this._drawInfo;
  9237. boundingSphere.makeEmpty();
  9238. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9239. if ( drawInfo[ i ].active === false ) continue;
  9240. const geometryId = drawInfo[ i ].geometryIndex;
  9241. this.getMatrixAt( i, _matrix$1 );
  9242. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9243. boundingSphere.union( _sphere$2 );
  9244. }
  9245. }
  9246. addInstance( geometryId ) {
  9247. // ensure we're not over geometry
  9248. if ( this._drawInfo.length >= this._maxInstanceCount ) {
  9249. throw new Error( 'BatchedMesh: Maximum item count reached.' );
  9250. }
  9251. this._drawInfo.push( {
  9252. visible: true,
  9253. active: true,
  9254. geometryIndex: geometryId,
  9255. } );
  9256. // initialize the matrix
  9257. const drawId = this._drawInfo.length - 1;
  9258. const matricesTexture = this._matricesTexture;
  9259. const matricesArray = matricesTexture.image.data;
  9260. _identityMatrix.toArray( matricesArray, drawId * 16 );
  9261. matricesTexture.needsUpdate = true;
  9262. const colorsTexture = this._colorsTexture;
  9263. if ( colorsTexture ) {
  9264. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  9265. colorsTexture.needsUpdate = true;
  9266. }
  9267. return drawId;
  9268. }
  9269. addGeometry( geometry, vertexCount = - 1, indexCount = - 1 ) {
  9270. this._initializeGeometry( geometry );
  9271. this._validateGeometry( geometry );
  9272. // ensure we're not over geometry
  9273. if ( this._drawInfo.length >= this._maxInstanceCount ) {
  9274. throw new Error( 'BatchedMesh: Maximum item count reached.' );
  9275. }
  9276. // get the necessary range fo the geometry
  9277. const reservedRange = {
  9278. vertexStart: - 1,
  9279. vertexCount: - 1,
  9280. indexStart: - 1,
  9281. indexCount: - 1,
  9282. };
  9283. let lastRange = null;
  9284. const reservedRanges = this._reservedRanges;
  9285. const drawRanges = this._drawRanges;
  9286. const bounds = this._bounds;
  9287. if ( this._geometryCount !== 0 ) {
  9288. lastRange = reservedRanges[ reservedRanges.length - 1 ];
  9289. }
  9290. if ( vertexCount === - 1 ) {
  9291. reservedRange.vertexCount = geometry.getAttribute( 'position' ).count;
  9292. } else {
  9293. reservedRange.vertexCount = vertexCount;
  9294. }
  9295. if ( lastRange === null ) {
  9296. reservedRange.vertexStart = 0;
  9297. } else {
  9298. reservedRange.vertexStart = lastRange.vertexStart + lastRange.vertexCount;
  9299. }
  9300. const index = geometry.getIndex();
  9301. const hasIndex = index !== null;
  9302. if ( hasIndex ) {
  9303. if ( indexCount === - 1 ) {
  9304. reservedRange.indexCount = index.count;
  9305. } else {
  9306. reservedRange.indexCount = indexCount;
  9307. }
  9308. if ( lastRange === null ) {
  9309. reservedRange.indexStart = 0;
  9310. } else {
  9311. reservedRange.indexStart = lastRange.indexStart + lastRange.indexCount;
  9312. }
  9313. }
  9314. if (
  9315. reservedRange.indexStart !== - 1 &&
  9316. reservedRange.indexStart + reservedRange.indexCount > this._maxIndexCount ||
  9317. reservedRange.vertexStart + reservedRange.vertexCount > this._maxVertexCount
  9318. ) {
  9319. throw new Error( 'BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  9320. }
  9321. // update id
  9322. const geometryId = this._geometryCount;
  9323. this._geometryCount ++;
  9324. // add the reserved range and draw range objects
  9325. reservedRanges.push( reservedRange );
  9326. drawRanges.push( {
  9327. start: hasIndex ? reservedRange.indexStart : reservedRange.vertexStart,
  9328. count: - 1
  9329. } );
  9330. bounds.push( {
  9331. boxInitialized: false,
  9332. box: new Box3(),
  9333. sphereInitialized: false,
  9334. sphere: new Sphere()
  9335. } );
  9336. // update the geometry
  9337. this.setGeometryAt( geometryId, geometry );
  9338. return geometryId;
  9339. }
  9340. setGeometryAt( geometryId, geometry ) {
  9341. if ( geometryId >= this._geometryCount ) {
  9342. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  9343. }
  9344. this._validateGeometry( geometry );
  9345. const batchGeometry = this.geometry;
  9346. const hasIndex = batchGeometry.getIndex() !== null;
  9347. const dstIndex = batchGeometry.getIndex();
  9348. const srcIndex = geometry.getIndex();
  9349. const reservedRange = this._reservedRanges[ geometryId ];
  9350. if (
  9351. hasIndex &&
  9352. srcIndex.count > reservedRange.indexCount ||
  9353. geometry.attributes.position.count > reservedRange.vertexCount
  9354. ) {
  9355. throw new Error( 'BatchedMesh: Reserved space not large enough for provided geometry.' );
  9356. }
  9357. // copy geometry over
  9358. const vertexStart = reservedRange.vertexStart;
  9359. const vertexCount = reservedRange.vertexCount;
  9360. for ( const attributeName in batchGeometry.attributes ) {
  9361. // copy attribute data
  9362. const srcAttribute = geometry.getAttribute( attributeName );
  9363. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9364. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  9365. // fill the rest in with zeroes
  9366. const itemSize = srcAttribute.itemSize;
  9367. for ( let i = srcAttribute.count, l = vertexCount; i < l; i ++ ) {
  9368. const index = vertexStart + i;
  9369. for ( let c = 0; c < itemSize; c ++ ) {
  9370. dstAttribute.setComponent( index, c, 0 );
  9371. }
  9372. }
  9373. dstAttribute.needsUpdate = true;
  9374. dstAttribute.addUpdateRange( vertexStart * itemSize, vertexCount * itemSize );
  9375. }
  9376. // copy index
  9377. if ( hasIndex ) {
  9378. const indexStart = reservedRange.indexStart;
  9379. // copy index data over
  9380. for ( let i = 0; i < srcIndex.count; i ++ ) {
  9381. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  9382. }
  9383. // fill the rest in with zeroes
  9384. for ( let i = srcIndex.count, l = reservedRange.indexCount; i < l; i ++ ) {
  9385. dstIndex.setX( indexStart + i, vertexStart );
  9386. }
  9387. dstIndex.needsUpdate = true;
  9388. dstIndex.addUpdateRange( indexStart, reservedRange.indexCount );
  9389. }
  9390. // store the bounding boxes
  9391. const bound = this._bounds[ geometryId ];
  9392. if ( geometry.boundingBox !== null ) {
  9393. bound.box.copy( geometry.boundingBox );
  9394. bound.boxInitialized = true;
  9395. } else {
  9396. bound.boxInitialized = false;
  9397. }
  9398. if ( geometry.boundingSphere !== null ) {
  9399. bound.sphere.copy( geometry.boundingSphere );
  9400. bound.sphereInitialized = true;
  9401. } else {
  9402. bound.sphereInitialized = false;
  9403. }
  9404. // set drawRange count
  9405. const drawRange = this._drawRanges[ geometryId ];
  9406. const posAttr = geometry.getAttribute( 'position' );
  9407. drawRange.count = hasIndex ? srcIndex.count : posAttr.count;
  9408. this._visibilityChanged = true;
  9409. return geometryId;
  9410. }
  9411. /*
  9412. deleteGeometry( geometryId ) {
  9413. // TODO: delete geometry and associated instances
  9414. }
  9415. */
  9416. /*
  9417. deleteInstance( instanceId ) {
  9418. // Note: User needs to call optimize() afterward to pack the data.
  9419. const drawInfo = this._drawInfo;
  9420. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9421. return this;
  9422. }
  9423. drawInfo[ instanceId ].active = false;
  9424. this._visibilityChanged = true;
  9425. return this;
  9426. }
  9427. */
  9428. // get bounding box and compute it if it doesn't exist
  9429. getBoundingBoxAt( geometryId, target ) {
  9430. if ( geometryId >= this._geometryCount ) {
  9431. return null;
  9432. }
  9433. // compute bounding box
  9434. const bound = this._bounds[ geometryId ];
  9435. const box = bound.box;
  9436. const geometry = this.geometry;
  9437. if ( bound.boxInitialized === false ) {
  9438. box.makeEmpty();
  9439. const index = geometry.index;
  9440. const position = geometry.attributes.position;
  9441. const drawRange = this._drawRanges[ geometryId ];
  9442. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  9443. let iv = i;
  9444. if ( index ) {
  9445. iv = index.getX( iv );
  9446. }
  9447. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  9448. }
  9449. bound.boxInitialized = true;
  9450. }
  9451. target.copy( box );
  9452. return target;
  9453. }
  9454. // get bounding sphere and compute it if it doesn't exist
  9455. getBoundingSphereAt( geometryId, target ) {
  9456. if ( geometryId >= this._geometryCount ) {
  9457. return null;
  9458. }
  9459. // compute bounding sphere
  9460. const bound = this._bounds[ geometryId ];
  9461. const sphere = bound.sphere;
  9462. const geometry = this.geometry;
  9463. if ( bound.sphereInitialized === false ) {
  9464. sphere.makeEmpty();
  9465. this.getBoundingBoxAt( geometryId, _box$1 );
  9466. _box$1.getCenter( sphere.center );
  9467. const index = geometry.index;
  9468. const position = geometry.attributes.position;
  9469. const drawRange = this._drawRanges[ geometryId ];
  9470. let maxRadiusSq = 0;
  9471. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  9472. let iv = i;
  9473. if ( index ) {
  9474. iv = index.getX( iv );
  9475. }
  9476. _vector$5.fromBufferAttribute( position, iv );
  9477. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  9478. }
  9479. sphere.radius = Math.sqrt( maxRadiusSq );
  9480. bound.sphereInitialized = true;
  9481. }
  9482. target.copy( sphere );
  9483. return target;
  9484. }
  9485. setMatrixAt( instanceId, matrix ) {
  9486. // @TODO: Map geometryId to index of the arrays because
  9487. // optimize() can make geometryId mismatch the index
  9488. const drawInfo = this._drawInfo;
  9489. const matricesTexture = this._matricesTexture;
  9490. const matricesArray = this._matricesTexture.image.data;
  9491. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9492. return this;
  9493. }
  9494. matrix.toArray( matricesArray, instanceId * 16 );
  9495. matricesTexture.needsUpdate = true;
  9496. return this;
  9497. }
  9498. getMatrixAt( instanceId, matrix ) {
  9499. const drawInfo = this._drawInfo;
  9500. const matricesArray = this._matricesTexture.image.data;
  9501. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9502. return null;
  9503. }
  9504. return matrix.fromArray( matricesArray, instanceId * 16 );
  9505. }
  9506. setColorAt( instanceId, color ) {
  9507. if ( this._colorsTexture === null ) {
  9508. this._initColorsTexture();
  9509. }
  9510. // @TODO: Map id to index of the arrays because
  9511. // optimize() can make id mismatch the index
  9512. const colorsTexture = this._colorsTexture;
  9513. const colorsArray = this._colorsTexture.image.data;
  9514. const drawInfo = this._drawInfo;
  9515. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9516. return this;
  9517. }
  9518. color.toArray( colorsArray, instanceId * 4 );
  9519. colorsTexture.needsUpdate = true;
  9520. return this;
  9521. }
  9522. getColorAt( instanceId, color ) {
  9523. const colorsArray = this._colorsTexture.image.data;
  9524. const drawInfo = this._drawInfo;
  9525. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9526. return null;
  9527. }
  9528. return color.fromArray( colorsArray, instanceId * 4 );
  9529. }
  9530. setVisibleAt( instanceId, value ) {
  9531. // if the geometry is out of range, not active, or visibility state
  9532. // does not change then return early
  9533. const drawInfo = this._drawInfo;
  9534. if (
  9535. instanceId >= drawInfo.length ||
  9536. drawInfo[ instanceId ].active === false ||
  9537. drawInfo[ instanceId ].visible === value
  9538. ) {
  9539. return this;
  9540. }
  9541. drawInfo[ instanceId ].visible = value;
  9542. this._visibilityChanged = true;
  9543. return this;
  9544. }
  9545. getVisibleAt( instanceId ) {
  9546. // return early if the geometry is out of range or not active
  9547. const drawInfo = this._drawInfo;
  9548. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9549. return false;
  9550. }
  9551. return drawInfo[ instanceId ].visible;
  9552. }
  9553. raycast( raycaster, intersects ) {
  9554. const drawInfo = this._drawInfo;
  9555. const drawRanges = this._drawRanges;
  9556. const matrixWorld = this.matrixWorld;
  9557. const batchGeometry = this.geometry;
  9558. // iterate over each geometry
  9559. _mesh.material = this.material;
  9560. _mesh.geometry.index = batchGeometry.index;
  9561. _mesh.geometry.attributes = batchGeometry.attributes;
  9562. if ( _mesh.geometry.boundingBox === null ) {
  9563. _mesh.geometry.boundingBox = new Box3();
  9564. }
  9565. if ( _mesh.geometry.boundingSphere === null ) {
  9566. _mesh.geometry.boundingSphere = new Sphere();
  9567. }
  9568. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9569. if ( ! drawInfo[ i ].visible || ! drawInfo[ i ].active ) {
  9570. continue;
  9571. }
  9572. const geometryId = drawInfo[ i ].geometryIndex;
  9573. const drawRange = drawRanges[ geometryId ];
  9574. _mesh.geometry.setDrawRange( drawRange.start, drawRange.count );
  9575. // ge the intersects
  9576. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  9577. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  9578. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  9579. _mesh.raycast( raycaster, _batchIntersects );
  9580. // add batch id to the intersects
  9581. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  9582. const intersect = _batchIntersects[ j ];
  9583. intersect.object = this;
  9584. intersect.batchId = i;
  9585. intersects.push( intersect );
  9586. }
  9587. _batchIntersects.length = 0;
  9588. }
  9589. _mesh.material = null;
  9590. _mesh.geometry.index = null;
  9591. _mesh.geometry.attributes = {};
  9592. _mesh.geometry.setDrawRange( 0, Infinity );
  9593. }
  9594. copy( source ) {
  9595. super.copy( source );
  9596. this.geometry = source.geometry.clone();
  9597. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  9598. this.sortObjects = source.sortObjects;
  9599. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  9600. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  9601. this._drawRanges = source._drawRanges.map( range => ( { ...range } ) );
  9602. this._reservedRanges = source._reservedRanges.map( range => ( { ...range } ) );
  9603. this._drawInfo = source._drawInfo.map( inf => ( { ...inf } ) );
  9604. this._bounds = source._bounds.map( bound => ( {
  9605. boxInitialized: bound.boxInitialized,
  9606. box: bound.box.clone(),
  9607. sphereInitialized: bound.sphereInitialized,
  9608. sphere: bound.sphere.clone()
  9609. } ) );
  9610. this._maxInstanceCount = source._maxInstanceCount;
  9611. this._maxVertexCount = source._maxVertexCount;
  9612. this._maxIndexCount = source._maxIndexCount;
  9613. this._geometryInitialized = source._geometryInitialized;
  9614. this._geometryCount = source._geometryCount;
  9615. this._multiDrawCounts = source._multiDrawCounts.slice();
  9616. this._multiDrawStarts = source._multiDrawStarts.slice();
  9617. this._matricesTexture = source._matricesTexture.clone();
  9618. this._matricesTexture.image.data = this._matricesTexture.image.slice();
  9619. if ( this._colorsTexture !== null ) {
  9620. this._colorsTexture = source._colorsTexture.clone();
  9621. this._colorsTexture.image.data = this._colorsTexture.image.slice();
  9622. }
  9623. return this;
  9624. }
  9625. dispose() {
  9626. // Assuming the geometry is not shared with other meshes
  9627. this.geometry.dispose();
  9628. this._matricesTexture.dispose();
  9629. this._matricesTexture = null;
  9630. this._indirectTexture.dispose();
  9631. this._indirectTexture = null;
  9632. if ( this._colorsTexture !== null ) {
  9633. this._colorsTexture.dispose();
  9634. this._colorsTexture = null;
  9635. }
  9636. return this;
  9637. }
  9638. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  9639. // if visibility has not changed and frustum culling and object sorting is not required
  9640. // then skip iterating over all items
  9641. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  9642. return;
  9643. }
  9644. // the indexed version of the multi draw function requires specifying the start
  9645. // offset in bytes.
  9646. const index = geometry.getIndex();
  9647. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  9648. const drawInfo = this._drawInfo;
  9649. const multiDrawStarts = this._multiDrawStarts;
  9650. const multiDrawCounts = this._multiDrawCounts;
  9651. const drawRanges = this._drawRanges;
  9652. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  9653. const indirectTexture = this._indirectTexture;
  9654. const indirectArray = indirectTexture.image.data;
  9655. // prepare the frustum in the local frame
  9656. if ( perObjectFrustumCulled ) {
  9657. _projScreenMatrix$3
  9658. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  9659. .multiply( this.matrixWorld );
  9660. _frustum$1.setFromProjectionMatrix(
  9661. _projScreenMatrix$3,
  9662. renderer.coordinateSystem
  9663. );
  9664. }
  9665. let count = 0;
  9666. if ( this.sortObjects ) {
  9667. // get the camera position in the local frame
  9668. _invMatrixWorld.copy( this.matrixWorld ).invert();
  9669. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _invMatrixWorld );
  9670. _forward.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ).transformDirection( _invMatrixWorld );
  9671. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9672. if ( drawInfo[ i ].visible && drawInfo[ i ].active ) {
  9673. const geometryId = drawInfo[ i ].geometryIndex;
  9674. // get the bounds in world space
  9675. this.getMatrixAt( i, _matrix$1 );
  9676. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9677. // determine whether the batched geometry is within the frustum
  9678. let culled = false;
  9679. if ( perObjectFrustumCulled ) {
  9680. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9681. }
  9682. if ( ! culled ) {
  9683. // get the distance from camera used for sorting
  9684. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  9685. _renderList.push( drawRanges[ geometryId ], z, i );
  9686. }
  9687. }
  9688. }
  9689. // Sort the draw ranges and prep for rendering
  9690. const list = _renderList.list;
  9691. const customSort = this.customSort;
  9692. if ( customSort === null ) {
  9693. list.sort( material.transparent ? sortTransparent : sortOpaque );
  9694. } else {
  9695. customSort.call( this, list, camera );
  9696. }
  9697. for ( let i = 0, l = list.length; i < l; i ++ ) {
  9698. const item = list[ i ];
  9699. multiDrawStarts[ count ] = item.start * bytesPerElement;
  9700. multiDrawCounts[ count ] = item.count;
  9701. indirectArray[ count ] = item.index;
  9702. count ++;
  9703. }
  9704. _renderList.reset();
  9705. } else {
  9706. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9707. if ( drawInfo[ i ].visible && drawInfo[ i ].active ) {
  9708. const geometryId = drawInfo[ i ].geometryIndex;
  9709. // determine whether the batched geometry is within the frustum
  9710. let culled = false;
  9711. if ( perObjectFrustumCulled ) {
  9712. // get the bounds in world space
  9713. this.getMatrixAt( i, _matrix$1 );
  9714. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9715. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9716. }
  9717. if ( ! culled ) {
  9718. const range = drawRanges[ geometryId ];
  9719. multiDrawStarts[ count ] = range.start * bytesPerElement;
  9720. multiDrawCounts[ count ] = range.count;
  9721. indirectArray[ count ] = i;
  9722. count ++;
  9723. }
  9724. }
  9725. }
  9726. }
  9727. indirectTexture.needsUpdate = true;
  9728. this._multiDrawCount = count;
  9729. this._visibilityChanged = false;
  9730. }
  9731. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  9732. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  9733. }
  9734. }
  9735. class LineBasicMaterial extends Material {
  9736. constructor( parameters ) {
  9737. super();
  9738. this.isLineBasicMaterial = true;
  9739. this.type = 'LineBasicMaterial';
  9740. this.color = new Color( 0xffffff );
  9741. this.map = null;
  9742. this.linewidth = 1;
  9743. this.linecap = 'round';
  9744. this.linejoin = 'round';
  9745. this.fog = true;
  9746. this.setValues( parameters );
  9747. }
  9748. copy( source ) {
  9749. super.copy( source );
  9750. this.color.copy( source.color );
  9751. this.map = source.map;
  9752. this.linewidth = source.linewidth;
  9753. this.linecap = source.linecap;
  9754. this.linejoin = source.linejoin;
  9755. this.fog = source.fog;
  9756. return this;
  9757. }
  9758. }
  9759. const _vStart = /*@__PURE__*/ new Vector3();
  9760. const _vEnd = /*@__PURE__*/ new Vector3();
  9761. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  9762. const _ray$1 = /*@__PURE__*/ new Ray();
  9763. const _sphere$1 = /*@__PURE__*/ new Sphere();
  9764. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  9765. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  9766. class Line extends Object3D {
  9767. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  9768. super();
  9769. this.isLine = true;
  9770. this.type = 'Line';
  9771. this.geometry = geometry;
  9772. this.material = material;
  9773. this.updateMorphTargets();
  9774. }
  9775. copy( source, recursive ) {
  9776. super.copy( source, recursive );
  9777. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  9778. this.geometry = source.geometry;
  9779. return this;
  9780. }
  9781. computeLineDistances() {
  9782. const geometry = this.geometry;
  9783. // we assume non-indexed geometry
  9784. if ( geometry.index === null ) {
  9785. const positionAttribute = geometry.attributes.position;
  9786. const lineDistances = [ 0 ];
  9787. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  9788. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  9789. _vEnd.fromBufferAttribute( positionAttribute, i );
  9790. lineDistances[ i ] = lineDistances[ i - 1 ];
  9791. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  9792. }
  9793. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  9794. } else {
  9795. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  9796. }
  9797. return this;
  9798. }
  9799. raycast( raycaster, intersects ) {
  9800. const geometry = this.geometry;
  9801. const matrixWorld = this.matrixWorld;
  9802. const threshold = raycaster.params.Line.threshold;
  9803. const drawRange = geometry.drawRange;
  9804. // Checking boundingSphere distance to ray
  9805. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9806. _sphere$1.copy( geometry.boundingSphere );
  9807. _sphere$1.applyMatrix4( matrixWorld );
  9808. _sphere$1.radius += threshold;
  9809. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  9810. //
  9811. _inverseMatrix$1.copy( matrixWorld ).invert();
  9812. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  9813. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  9814. const localThresholdSq = localThreshold * localThreshold;
  9815. const step = this.isLineSegments ? 2 : 1;
  9816. const index = geometry.index;
  9817. const attributes = geometry.attributes;
  9818. const positionAttribute = attributes.position;
  9819. if ( index !== null ) {
  9820. const start = Math.max( 0, drawRange.start );
  9821. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  9822. for ( let i = start, l = end - 1; i < l; i += step ) {
  9823. const a = index.getX( i );
  9824. const b = index.getX( i + 1 );
  9825. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  9826. if ( intersect ) {
  9827. intersects.push( intersect );
  9828. }
  9829. }
  9830. if ( this.isLineLoop ) {
  9831. const a = index.getX( end - 1 );
  9832. const b = index.getX( start );
  9833. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  9834. if ( intersect ) {
  9835. intersects.push( intersect );
  9836. }
  9837. }
  9838. } else {
  9839. const start = Math.max( 0, drawRange.start );
  9840. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  9841. for ( let i = start, l = end - 1; i < l; i += step ) {
  9842. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1 );
  9843. if ( intersect ) {
  9844. intersects.push( intersect );
  9845. }
  9846. }
  9847. if ( this.isLineLoop ) {
  9848. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start );
  9849. if ( intersect ) {
  9850. intersects.push( intersect );
  9851. }
  9852. }
  9853. }
  9854. }
  9855. updateMorphTargets() {
  9856. const geometry = this.geometry;
  9857. const morphAttributes = geometry.morphAttributes;
  9858. const keys = Object.keys( morphAttributes );
  9859. if ( keys.length > 0 ) {
  9860. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  9861. if ( morphAttribute !== undefined ) {
  9862. this.morphTargetInfluences = [];
  9863. this.morphTargetDictionary = {};
  9864. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  9865. const name = morphAttribute[ m ].name || String( m );
  9866. this.morphTargetInfluences.push( 0 );
  9867. this.morphTargetDictionary[ name ] = m;
  9868. }
  9869. }
  9870. }
  9871. }
  9872. }
  9873. function checkIntersection( object, raycaster, ray, thresholdSq, a, b ) {
  9874. const positionAttribute = object.geometry.attributes.position;
  9875. _vStart.fromBufferAttribute( positionAttribute, a );
  9876. _vEnd.fromBufferAttribute( positionAttribute, b );
  9877. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  9878. if ( distSq > thresholdSq ) return;
  9879. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  9880. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  9881. if ( distance < raycaster.near || distance > raycaster.far ) return;
  9882. return {
  9883. distance: distance,
  9884. // What do we want? intersection point on the ray or on the segment??
  9885. // point: raycaster.ray.at( distance ),
  9886. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  9887. index: a,
  9888. face: null,
  9889. faceIndex: null,
  9890. object: object
  9891. };
  9892. }
  9893. const _start = /*@__PURE__*/ new Vector3();
  9894. const _end = /*@__PURE__*/ new Vector3();
  9895. class LineSegments extends Line {
  9896. constructor( geometry, material ) {
  9897. super( geometry, material );
  9898. this.isLineSegments = true;
  9899. this.type = 'LineSegments';
  9900. }
  9901. computeLineDistances() {
  9902. const geometry = this.geometry;
  9903. // we assume non-indexed geometry
  9904. if ( geometry.index === null ) {
  9905. const positionAttribute = geometry.attributes.position;
  9906. const lineDistances = [];
  9907. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  9908. _start.fromBufferAttribute( positionAttribute, i );
  9909. _end.fromBufferAttribute( positionAttribute, i + 1 );
  9910. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  9911. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  9912. }
  9913. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  9914. } else {
  9915. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  9916. }
  9917. return this;
  9918. }
  9919. }
  9920. class LineLoop extends Line {
  9921. constructor( geometry, material ) {
  9922. super( geometry, material );
  9923. this.isLineLoop = true;
  9924. this.type = 'LineLoop';
  9925. }
  9926. }
  9927. class PointsMaterial extends Material {
  9928. constructor( parameters ) {
  9929. super();
  9930. this.isPointsMaterial = true;
  9931. this.type = 'PointsMaterial';
  9932. this.color = new Color( 0xffffff );
  9933. this.map = null;
  9934. this.alphaMap = null;
  9935. this.size = 1;
  9936. this.sizeAttenuation = true;
  9937. this.fog = true;
  9938. this.setValues( parameters );
  9939. }
  9940. copy( source ) {
  9941. super.copy( source );
  9942. this.color.copy( source.color );
  9943. this.map = source.map;
  9944. this.alphaMap = source.alphaMap;
  9945. this.size = source.size;
  9946. this.sizeAttenuation = source.sizeAttenuation;
  9947. this.fog = source.fog;
  9948. return this;
  9949. }
  9950. }
  9951. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  9952. const _ray = /*@__PURE__*/ new Ray();
  9953. const _sphere = /*@__PURE__*/ new Sphere();
  9954. const _position$2 = /*@__PURE__*/ new Vector3();
  9955. class Points extends Object3D {
  9956. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  9957. super();
  9958. this.isPoints = true;
  9959. this.type = 'Points';
  9960. this.geometry = geometry;
  9961. this.material = material;
  9962. this.updateMorphTargets();
  9963. }
  9964. copy( source, recursive ) {
  9965. super.copy( source, recursive );
  9966. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  9967. this.geometry = source.geometry;
  9968. return this;
  9969. }
  9970. raycast( raycaster, intersects ) {
  9971. const geometry = this.geometry;
  9972. const matrixWorld = this.matrixWorld;
  9973. const threshold = raycaster.params.Points.threshold;
  9974. const drawRange = geometry.drawRange;
  9975. // Checking boundingSphere distance to ray
  9976. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9977. _sphere.copy( geometry.boundingSphere );
  9978. _sphere.applyMatrix4( matrixWorld );
  9979. _sphere.radius += threshold;
  9980. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  9981. //
  9982. _inverseMatrix.copy( matrixWorld ).invert();
  9983. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  9984. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  9985. const localThresholdSq = localThreshold * localThreshold;
  9986. const index = geometry.index;
  9987. const attributes = geometry.attributes;
  9988. const positionAttribute = attributes.position;
  9989. if ( index !== null ) {
  9990. const start = Math.max( 0, drawRange.start );
  9991. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  9992. for ( let i = start, il = end; i < il; i ++ ) {
  9993. const a = index.getX( i );
  9994. _position$2.fromBufferAttribute( positionAttribute, a );
  9995. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  9996. }
  9997. } else {
  9998. const start = Math.max( 0, drawRange.start );
  9999. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  10000. for ( let i = start, l = end; i < l; i ++ ) {
  10001. _position$2.fromBufferAttribute( positionAttribute, i );
  10002. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  10003. }
  10004. }
  10005. }
  10006. updateMorphTargets() {
  10007. const geometry = this.geometry;
  10008. const morphAttributes = geometry.morphAttributes;
  10009. const keys = Object.keys( morphAttributes );
  10010. if ( keys.length > 0 ) {
  10011. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  10012. if ( morphAttribute !== undefined ) {
  10013. this.morphTargetInfluences = [];
  10014. this.morphTargetDictionary = {};
  10015. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  10016. const name = morphAttribute[ m ].name || String( m );
  10017. this.morphTargetInfluences.push( 0 );
  10018. this.morphTargetDictionary[ name ] = m;
  10019. }
  10020. }
  10021. }
  10022. }
  10023. }
  10024. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  10025. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  10026. if ( rayPointDistanceSq < localThresholdSq ) {
  10027. const intersectPoint = new Vector3();
  10028. _ray.closestPointToPoint( point, intersectPoint );
  10029. intersectPoint.applyMatrix4( matrixWorld );
  10030. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  10031. if ( distance < raycaster.near || distance > raycaster.far ) return;
  10032. intersects.push( {
  10033. distance: distance,
  10034. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  10035. point: intersectPoint,
  10036. index: index,
  10037. face: null,
  10038. object: object
  10039. } );
  10040. }
  10041. }
  10042. class Group extends Object3D {
  10043. constructor() {
  10044. super();
  10045. this.isGroup = true;
  10046. this.type = 'Group';
  10047. }
  10048. }
  10049. class VideoTexture extends Texture {
  10050. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10051. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10052. this.isVideoTexture = true;
  10053. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  10054. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  10055. this.generateMipmaps = false;
  10056. const scope = this;
  10057. function updateVideo() {
  10058. scope.needsUpdate = true;
  10059. video.requestVideoFrameCallback( updateVideo );
  10060. }
  10061. if ( 'requestVideoFrameCallback' in video ) {
  10062. video.requestVideoFrameCallback( updateVideo );
  10063. }
  10064. }
  10065. clone() {
  10066. return new this.constructor( this.image ).copy( this );
  10067. }
  10068. update() {
  10069. const video = this.image;
  10070. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  10071. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  10072. this.needsUpdate = true;
  10073. }
  10074. }
  10075. }
  10076. class FramebufferTexture extends Texture {
  10077. constructor( width, height ) {
  10078. super( { width, height } );
  10079. this.isFramebufferTexture = true;
  10080. this.magFilter = NearestFilter;
  10081. this.minFilter = NearestFilter;
  10082. this.generateMipmaps = false;
  10083. this.needsUpdate = true;
  10084. }
  10085. }
  10086. class CompressedTexture extends Texture {
  10087. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  10088. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  10089. this.isCompressedTexture = true;
  10090. this.image = { width: width, height: height };
  10091. this.mipmaps = mipmaps;
  10092. // no flipping for cube textures
  10093. // (also flipping doesn't work for compressed textures )
  10094. this.flipY = false;
  10095. // can't generate mipmaps for compressed textures
  10096. // mips must be embedded in DDS files
  10097. this.generateMipmaps = false;
  10098. }
  10099. }
  10100. class CompressedArrayTexture extends CompressedTexture {
  10101. constructor( mipmaps, width, height, depth, format, type ) {
  10102. super( mipmaps, width, height, format, type );
  10103. this.isCompressedArrayTexture = true;
  10104. this.image.depth = depth;
  10105. this.wrapR = ClampToEdgeWrapping;
  10106. this.layerUpdates = new Set();
  10107. }
  10108. addLayerUpdate( layerIndex ) {
  10109. this.layerUpdates.add( layerIndex );
  10110. }
  10111. clearLayerUpdates() {
  10112. this.layerUpdates.clear();
  10113. }
  10114. }
  10115. class CompressedCubeTexture extends CompressedTexture {
  10116. constructor( images, format, type ) {
  10117. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  10118. this.isCompressedCubeTexture = true;
  10119. this.isCubeTexture = true;
  10120. this.image = images;
  10121. }
  10122. }
  10123. class CanvasTexture extends Texture {
  10124. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10125. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10126. this.isCanvasTexture = true;
  10127. this.needsUpdate = true;
  10128. }
  10129. }
  10130. class DepthTexture extends Texture {
  10131. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat ) {
  10132. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  10133. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  10134. }
  10135. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  10136. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  10137. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10138. this.isDepthTexture = true;
  10139. this.image = { width: width, height: height };
  10140. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  10141. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  10142. this.flipY = false;
  10143. this.generateMipmaps = false;
  10144. this.compareFunction = null;
  10145. }
  10146. copy( source ) {
  10147. super.copy( source );
  10148. this.compareFunction = source.compareFunction;
  10149. return this;
  10150. }
  10151. toJSON( meta ) {
  10152. const data = super.toJSON( meta );
  10153. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  10154. return data;
  10155. }
  10156. }
  10157. /**
  10158. * Extensible curve object.
  10159. *
  10160. * Some common of curve methods:
  10161. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  10162. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  10163. * .getPoints(), .getSpacedPoints()
  10164. * .getLength()
  10165. * .updateArcLengths()
  10166. *
  10167. * This following curves inherit from THREE.Curve:
  10168. *
  10169. * -- 2D curves --
  10170. * THREE.ArcCurve
  10171. * THREE.CubicBezierCurve
  10172. * THREE.EllipseCurve
  10173. * THREE.LineCurve
  10174. * THREE.QuadraticBezierCurve
  10175. * THREE.SplineCurve
  10176. *
  10177. * -- 3D curves --
  10178. * THREE.CatmullRomCurve3
  10179. * THREE.CubicBezierCurve3
  10180. * THREE.LineCurve3
  10181. * THREE.QuadraticBezierCurve3
  10182. *
  10183. * A series of curves can be represented as a THREE.CurvePath.
  10184. *
  10185. **/
  10186. class Curve {
  10187. constructor() {
  10188. this.type = 'Curve';
  10189. this.arcLengthDivisions = 200;
  10190. }
  10191. // Virtual base class method to overwrite and implement in subclasses
  10192. // - t [0 .. 1]
  10193. getPoint( /* t, optionalTarget */ ) {
  10194. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  10195. return null;
  10196. }
  10197. // Get point at relative position in curve according to arc length
  10198. // - u [0 .. 1]
  10199. getPointAt( u, optionalTarget ) {
  10200. const t = this.getUtoTmapping( u );
  10201. return this.getPoint( t, optionalTarget );
  10202. }
  10203. // Get sequence of points using getPoint( t )
  10204. getPoints( divisions = 5 ) {
  10205. const points = [];
  10206. for ( let d = 0; d <= divisions; d ++ ) {
  10207. points.push( this.getPoint( d / divisions ) );
  10208. }
  10209. return points;
  10210. }
  10211. // Get sequence of points using getPointAt( u )
  10212. getSpacedPoints( divisions = 5 ) {
  10213. const points = [];
  10214. for ( let d = 0; d <= divisions; d ++ ) {
  10215. points.push( this.getPointAt( d / divisions ) );
  10216. }
  10217. return points;
  10218. }
  10219. // Get total curve arc length
  10220. getLength() {
  10221. const lengths = this.getLengths();
  10222. return lengths[ lengths.length - 1 ];
  10223. }
  10224. // Get list of cumulative segment lengths
  10225. getLengths( divisions = this.arcLengthDivisions ) {
  10226. if ( this.cacheArcLengths &&
  10227. ( this.cacheArcLengths.length === divisions + 1 ) &&
  10228. ! this.needsUpdate ) {
  10229. return this.cacheArcLengths;
  10230. }
  10231. this.needsUpdate = false;
  10232. const cache = [];
  10233. let current, last = this.getPoint( 0 );
  10234. let sum = 0;
  10235. cache.push( 0 );
  10236. for ( let p = 1; p <= divisions; p ++ ) {
  10237. current = this.getPoint( p / divisions );
  10238. sum += current.distanceTo( last );
  10239. cache.push( sum );
  10240. last = current;
  10241. }
  10242. this.cacheArcLengths = cache;
  10243. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  10244. }
  10245. updateArcLengths() {
  10246. this.needsUpdate = true;
  10247. this.getLengths();
  10248. }
  10249. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  10250. getUtoTmapping( u, distance ) {
  10251. const arcLengths = this.getLengths();
  10252. let i = 0;
  10253. const il = arcLengths.length;
  10254. let targetArcLength; // The targeted u distance value to get
  10255. if ( distance ) {
  10256. targetArcLength = distance;
  10257. } else {
  10258. targetArcLength = u * arcLengths[ il - 1 ];
  10259. }
  10260. // binary search for the index with largest value smaller than target u distance
  10261. let low = 0, high = il - 1, comparison;
  10262. while ( low <= high ) {
  10263. i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats
  10264. comparison = arcLengths[ i ] - targetArcLength;
  10265. if ( comparison < 0 ) {
  10266. low = i + 1;
  10267. } else if ( comparison > 0 ) {
  10268. high = i - 1;
  10269. } else {
  10270. high = i;
  10271. break;
  10272. // DONE
  10273. }
  10274. }
  10275. i = high;
  10276. if ( arcLengths[ i ] === targetArcLength ) {
  10277. return i / ( il - 1 );
  10278. }
  10279. // we could get finer grain at lengths, or use simple interpolation between two points
  10280. const lengthBefore = arcLengths[ i ];
  10281. const lengthAfter = arcLengths[ i + 1 ];
  10282. const segmentLength = lengthAfter - lengthBefore;
  10283. // determine where we are between the 'before' and 'after' points
  10284. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  10285. // add that fractional amount to t
  10286. const t = ( i + segmentFraction ) / ( il - 1 );
  10287. return t;
  10288. }
  10289. // Returns a unit vector tangent at t
  10290. // In case any sub curve does not implement its tangent derivation,
  10291. // 2 points a small delta apart will be used to find its gradient
  10292. // which seems to give a reasonable approximation
  10293. getTangent( t, optionalTarget ) {
  10294. const delta = 0.0001;
  10295. let t1 = t - delta;
  10296. let t2 = t + delta;
  10297. // Capping in case of danger
  10298. if ( t1 < 0 ) t1 = 0;
  10299. if ( t2 > 1 ) t2 = 1;
  10300. const pt1 = this.getPoint( t1 );
  10301. const pt2 = this.getPoint( t2 );
  10302. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  10303. tangent.copy( pt2 ).sub( pt1 ).normalize();
  10304. return tangent;
  10305. }
  10306. getTangentAt( u, optionalTarget ) {
  10307. const t = this.getUtoTmapping( u );
  10308. return this.getTangent( t, optionalTarget );
  10309. }
  10310. computeFrenetFrames( segments, closed ) {
  10311. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  10312. const normal = new Vector3();
  10313. const tangents = [];
  10314. const normals = [];
  10315. const binormals = [];
  10316. const vec = new Vector3();
  10317. const mat = new Matrix4();
  10318. // compute the tangent vectors for each segment on the curve
  10319. for ( let i = 0; i <= segments; i ++ ) {
  10320. const u = i / segments;
  10321. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  10322. }
  10323. // select an initial normal vector perpendicular to the first tangent vector,
  10324. // and in the direction of the minimum tangent xyz component
  10325. normals[ 0 ] = new Vector3();
  10326. binormals[ 0 ] = new Vector3();
  10327. let min = Number.MAX_VALUE;
  10328. const tx = Math.abs( tangents[ 0 ].x );
  10329. const ty = Math.abs( tangents[ 0 ].y );
  10330. const tz = Math.abs( tangents[ 0 ].z );
  10331. if ( tx <= min ) {
  10332. min = tx;
  10333. normal.set( 1, 0, 0 );
  10334. }
  10335. if ( ty <= min ) {
  10336. min = ty;
  10337. normal.set( 0, 1, 0 );
  10338. }
  10339. if ( tz <= min ) {
  10340. normal.set( 0, 0, 1 );
  10341. }
  10342. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  10343. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  10344. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  10345. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  10346. for ( let i = 1; i <= segments; i ++ ) {
  10347. normals[ i ] = normals[ i - 1 ].clone();
  10348. binormals[ i ] = binormals[ i - 1 ].clone();
  10349. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  10350. if ( vec.length() > Number.EPSILON ) {
  10351. vec.normalize();
  10352. const theta = Math.acos( clamp$1( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  10353. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  10354. }
  10355. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10356. }
  10357. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  10358. if ( closed === true ) {
  10359. let theta = Math.acos( clamp$1( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  10360. theta /= segments;
  10361. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  10362. theta = - theta;
  10363. }
  10364. for ( let i = 1; i <= segments; i ++ ) {
  10365. // twist a little...
  10366. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  10367. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10368. }
  10369. }
  10370. return {
  10371. tangents: tangents,
  10372. normals: normals,
  10373. binormals: binormals
  10374. };
  10375. }
  10376. clone() {
  10377. return new this.constructor().copy( this );
  10378. }
  10379. copy( source ) {
  10380. this.arcLengthDivisions = source.arcLengthDivisions;
  10381. return this;
  10382. }
  10383. toJSON() {
  10384. const data = {
  10385. metadata: {
  10386. version: 4.6,
  10387. type: 'Curve',
  10388. generator: 'Curve.toJSON'
  10389. }
  10390. };
  10391. data.arcLengthDivisions = this.arcLengthDivisions;
  10392. data.type = this.type;
  10393. return data;
  10394. }
  10395. fromJSON( json ) {
  10396. this.arcLengthDivisions = json.arcLengthDivisions;
  10397. return this;
  10398. }
  10399. }
  10400. class EllipseCurve extends Curve {
  10401. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  10402. super();
  10403. this.isEllipseCurve = true;
  10404. this.type = 'EllipseCurve';
  10405. this.aX = aX;
  10406. this.aY = aY;
  10407. this.xRadius = xRadius;
  10408. this.yRadius = yRadius;
  10409. this.aStartAngle = aStartAngle;
  10410. this.aEndAngle = aEndAngle;
  10411. this.aClockwise = aClockwise;
  10412. this.aRotation = aRotation;
  10413. }
  10414. getPoint( t, optionalTarget = new Vector2() ) {
  10415. const point = optionalTarget;
  10416. const twoPi = Math.PI * 2;
  10417. let deltaAngle = this.aEndAngle - this.aStartAngle;
  10418. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  10419. // ensures that deltaAngle is 0 .. 2 PI
  10420. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  10421. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  10422. if ( deltaAngle < Number.EPSILON ) {
  10423. if ( samePoints ) {
  10424. deltaAngle = 0;
  10425. } else {
  10426. deltaAngle = twoPi;
  10427. }
  10428. }
  10429. if ( this.aClockwise === true && ! samePoints ) {
  10430. if ( deltaAngle === twoPi ) {
  10431. deltaAngle = - twoPi;
  10432. } else {
  10433. deltaAngle = deltaAngle - twoPi;
  10434. }
  10435. }
  10436. const angle = this.aStartAngle + t * deltaAngle;
  10437. let x = this.aX + this.xRadius * Math.cos( angle );
  10438. let y = this.aY + this.yRadius * Math.sin( angle );
  10439. if ( this.aRotation !== 0 ) {
  10440. const cos = Math.cos( this.aRotation );
  10441. const sin = Math.sin( this.aRotation );
  10442. const tx = x - this.aX;
  10443. const ty = y - this.aY;
  10444. // Rotate the point about the center of the ellipse.
  10445. x = tx * cos - ty * sin + this.aX;
  10446. y = tx * sin + ty * cos + this.aY;
  10447. }
  10448. return point.set( x, y );
  10449. }
  10450. copy( source ) {
  10451. super.copy( source );
  10452. this.aX = source.aX;
  10453. this.aY = source.aY;
  10454. this.xRadius = source.xRadius;
  10455. this.yRadius = source.yRadius;
  10456. this.aStartAngle = source.aStartAngle;
  10457. this.aEndAngle = source.aEndAngle;
  10458. this.aClockwise = source.aClockwise;
  10459. this.aRotation = source.aRotation;
  10460. return this;
  10461. }
  10462. toJSON() {
  10463. const data = super.toJSON();
  10464. data.aX = this.aX;
  10465. data.aY = this.aY;
  10466. data.xRadius = this.xRadius;
  10467. data.yRadius = this.yRadius;
  10468. data.aStartAngle = this.aStartAngle;
  10469. data.aEndAngle = this.aEndAngle;
  10470. data.aClockwise = this.aClockwise;
  10471. data.aRotation = this.aRotation;
  10472. return data;
  10473. }
  10474. fromJSON( json ) {
  10475. super.fromJSON( json );
  10476. this.aX = json.aX;
  10477. this.aY = json.aY;
  10478. this.xRadius = json.xRadius;
  10479. this.yRadius = json.yRadius;
  10480. this.aStartAngle = json.aStartAngle;
  10481. this.aEndAngle = json.aEndAngle;
  10482. this.aClockwise = json.aClockwise;
  10483. this.aRotation = json.aRotation;
  10484. return this;
  10485. }
  10486. }
  10487. class ArcCurve extends EllipseCurve {
  10488. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  10489. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  10490. this.isArcCurve = true;
  10491. this.type = 'ArcCurve';
  10492. }
  10493. }
  10494. /**
  10495. * Centripetal CatmullRom Curve - which is useful for avoiding
  10496. * cusps and self-intersections in non-uniform catmull rom curves.
  10497. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  10498. *
  10499. * curve.type accepts centripetal(default), chordal and catmullrom
  10500. * curve.tension is used for catmullrom which defaults to 0.5
  10501. */
  10502. /*
  10503. Based on an optimized c++ solution in
  10504. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  10505. - http://ideone.com/NoEbVM
  10506. This CubicPoly class could be used for reusing some variables and calculations,
  10507. but for three.js curve use, it could be possible inlined and flatten into a single function call
  10508. which can be placed in CurveUtils.
  10509. */
  10510. function CubicPoly() {
  10511. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  10512. /*
  10513. * Compute coefficients for a cubic polynomial
  10514. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  10515. * such that
  10516. * p(0) = x0, p(1) = x1
  10517. * and
  10518. * p'(0) = t0, p'(1) = t1.
  10519. */
  10520. function init( x0, x1, t0, t1 ) {
  10521. c0 = x0;
  10522. c1 = t0;
  10523. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  10524. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  10525. }
  10526. return {
  10527. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  10528. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  10529. },
  10530. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  10531. // compute tangents when parameterized in [t1,t2]
  10532. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  10533. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  10534. // rescale tangents for parametrization in [0,1]
  10535. t1 *= dt1;
  10536. t2 *= dt1;
  10537. init( x1, x2, t1, t2 );
  10538. },
  10539. calc: function ( t ) {
  10540. const t2 = t * t;
  10541. const t3 = t2 * t;
  10542. return c0 + c1 * t + c2 * t2 + c3 * t3;
  10543. }
  10544. };
  10545. }
  10546. //
  10547. const tmp = /*@__PURE__*/ new Vector3();
  10548. const px = /*@__PURE__*/ new CubicPoly();
  10549. const py = /*@__PURE__*/ new CubicPoly();
  10550. const pz = /*@__PURE__*/ new CubicPoly();
  10551. class CatmullRomCurve3 extends Curve {
  10552. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  10553. super();
  10554. this.isCatmullRomCurve3 = true;
  10555. this.type = 'CatmullRomCurve3';
  10556. this.points = points;
  10557. this.closed = closed;
  10558. this.curveType = curveType;
  10559. this.tension = tension;
  10560. }
  10561. getPoint( t, optionalTarget = new Vector3() ) {
  10562. const point = optionalTarget;
  10563. const points = this.points;
  10564. const l = points.length;
  10565. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  10566. let intPoint = Math.floor( p );
  10567. let weight = p - intPoint;
  10568. if ( this.closed ) {
  10569. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  10570. } else if ( weight === 0 && intPoint === l - 1 ) {
  10571. intPoint = l - 2;
  10572. weight = 1;
  10573. }
  10574. let p0, p3; // 4 points (p1 & p2 defined below)
  10575. if ( this.closed || intPoint > 0 ) {
  10576. p0 = points[ ( intPoint - 1 ) % l ];
  10577. } else {
  10578. // extrapolate first point
  10579. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  10580. p0 = tmp;
  10581. }
  10582. const p1 = points[ intPoint % l ];
  10583. const p2 = points[ ( intPoint + 1 ) % l ];
  10584. if ( this.closed || intPoint + 2 < l ) {
  10585. p3 = points[ ( intPoint + 2 ) % l ];
  10586. } else {
  10587. // extrapolate last point
  10588. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  10589. p3 = tmp;
  10590. }
  10591. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  10592. // init Centripetal / Chordal Catmull-Rom
  10593. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  10594. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  10595. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  10596. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  10597. // safety check for repeated points
  10598. if ( dt1 < 1e-4 ) dt1 = 1.0;
  10599. if ( dt0 < 1e-4 ) dt0 = dt1;
  10600. if ( dt2 < 1e-4 ) dt2 = dt1;
  10601. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  10602. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  10603. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  10604. } else if ( this.curveType === 'catmullrom' ) {
  10605. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  10606. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  10607. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  10608. }
  10609. point.set(
  10610. px.calc( weight ),
  10611. py.calc( weight ),
  10612. pz.calc( weight )
  10613. );
  10614. return point;
  10615. }
  10616. copy( source ) {
  10617. super.copy( source );
  10618. this.points = [];
  10619. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  10620. const point = source.points[ i ];
  10621. this.points.push( point.clone() );
  10622. }
  10623. this.closed = source.closed;
  10624. this.curveType = source.curveType;
  10625. this.tension = source.tension;
  10626. return this;
  10627. }
  10628. toJSON() {
  10629. const data = super.toJSON();
  10630. data.points = [];
  10631. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  10632. const point = this.points[ i ];
  10633. data.points.push( point.toArray() );
  10634. }
  10635. data.closed = this.closed;
  10636. data.curveType = this.curveType;
  10637. data.tension = this.tension;
  10638. return data;
  10639. }
  10640. fromJSON( json ) {
  10641. super.fromJSON( json );
  10642. this.points = [];
  10643. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  10644. const point = json.points[ i ];
  10645. this.points.push( new Vector3().fromArray( point ) );
  10646. }
  10647. this.closed = json.closed;
  10648. this.curveType = json.curveType;
  10649. this.tension = json.tension;
  10650. return this;
  10651. }
  10652. }
  10653. /**
  10654. * Bezier Curves formulas obtained from
  10655. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  10656. */
  10657. function CatmullRom( t, p0, p1, p2, p3 ) {
  10658. const v0 = ( p2 - p0 ) * 0.5;
  10659. const v1 = ( p3 - p1 ) * 0.5;
  10660. const t2 = t * t;
  10661. const t3 = t * t2;
  10662. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  10663. }
  10664. //
  10665. function QuadraticBezierP0( t, p ) {
  10666. const k = 1 - t;
  10667. return k * k * p;
  10668. }
  10669. function QuadraticBezierP1( t, p ) {
  10670. return 2 * ( 1 - t ) * t * p;
  10671. }
  10672. function QuadraticBezierP2( t, p ) {
  10673. return t * t * p;
  10674. }
  10675. function QuadraticBezier( t, p0, p1, p2 ) {
  10676. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  10677. QuadraticBezierP2( t, p2 );
  10678. }
  10679. //
  10680. function CubicBezierP0( t, p ) {
  10681. const k = 1 - t;
  10682. return k * k * k * p;
  10683. }
  10684. function CubicBezierP1( t, p ) {
  10685. const k = 1 - t;
  10686. return 3 * k * k * t * p;
  10687. }
  10688. function CubicBezierP2( t, p ) {
  10689. return 3 * ( 1 - t ) * t * t * p;
  10690. }
  10691. function CubicBezierP3( t, p ) {
  10692. return t * t * t * p;
  10693. }
  10694. function CubicBezier( t, p0, p1, p2, p3 ) {
  10695. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  10696. CubicBezierP3( t, p3 );
  10697. }
  10698. class CubicBezierCurve extends Curve {
  10699. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  10700. super();
  10701. this.isCubicBezierCurve = true;
  10702. this.type = 'CubicBezierCurve';
  10703. this.v0 = v0;
  10704. this.v1 = v1;
  10705. this.v2 = v2;
  10706. this.v3 = v3;
  10707. }
  10708. getPoint( t, optionalTarget = new Vector2() ) {
  10709. const point = optionalTarget;
  10710. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10711. point.set(
  10712. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10713. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  10714. );
  10715. return point;
  10716. }
  10717. copy( source ) {
  10718. super.copy( source );
  10719. this.v0.copy( source.v0 );
  10720. this.v1.copy( source.v1 );
  10721. this.v2.copy( source.v2 );
  10722. this.v3.copy( source.v3 );
  10723. return this;
  10724. }
  10725. toJSON() {
  10726. const data = super.toJSON();
  10727. data.v0 = this.v0.toArray();
  10728. data.v1 = this.v1.toArray();
  10729. data.v2 = this.v2.toArray();
  10730. data.v3 = this.v3.toArray();
  10731. return data;
  10732. }
  10733. fromJSON( json ) {
  10734. super.fromJSON( json );
  10735. this.v0.fromArray( json.v0 );
  10736. this.v1.fromArray( json.v1 );
  10737. this.v2.fromArray( json.v2 );
  10738. this.v3.fromArray( json.v3 );
  10739. return this;
  10740. }
  10741. }
  10742. class CubicBezierCurve3 extends Curve {
  10743. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  10744. super();
  10745. this.isCubicBezierCurve3 = true;
  10746. this.type = 'CubicBezierCurve3';
  10747. this.v0 = v0;
  10748. this.v1 = v1;
  10749. this.v2 = v2;
  10750. this.v3 = v3;
  10751. }
  10752. getPoint( t, optionalTarget = new Vector3() ) {
  10753. const point = optionalTarget;
  10754. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10755. point.set(
  10756. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10757. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  10758. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  10759. );
  10760. return point;
  10761. }
  10762. copy( source ) {
  10763. super.copy( source );
  10764. this.v0.copy( source.v0 );
  10765. this.v1.copy( source.v1 );
  10766. this.v2.copy( source.v2 );
  10767. this.v3.copy( source.v3 );
  10768. return this;
  10769. }
  10770. toJSON() {
  10771. const data = super.toJSON();
  10772. data.v0 = this.v0.toArray();
  10773. data.v1 = this.v1.toArray();
  10774. data.v2 = this.v2.toArray();
  10775. data.v3 = this.v3.toArray();
  10776. return data;
  10777. }
  10778. fromJSON( json ) {
  10779. super.fromJSON( json );
  10780. this.v0.fromArray( json.v0 );
  10781. this.v1.fromArray( json.v1 );
  10782. this.v2.fromArray( json.v2 );
  10783. this.v3.fromArray( json.v3 );
  10784. return this;
  10785. }
  10786. }
  10787. class LineCurve extends Curve {
  10788. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  10789. super();
  10790. this.isLineCurve = true;
  10791. this.type = 'LineCurve';
  10792. this.v1 = v1;
  10793. this.v2 = v2;
  10794. }
  10795. getPoint( t, optionalTarget = new Vector2() ) {
  10796. const point = optionalTarget;
  10797. if ( t === 1 ) {
  10798. point.copy( this.v2 );
  10799. } else {
  10800. point.copy( this.v2 ).sub( this.v1 );
  10801. point.multiplyScalar( t ).add( this.v1 );
  10802. }
  10803. return point;
  10804. }
  10805. // Line curve is linear, so we can overwrite default getPointAt
  10806. getPointAt( u, optionalTarget ) {
  10807. return this.getPoint( u, optionalTarget );
  10808. }
  10809. getTangent( t, optionalTarget = new Vector2() ) {
  10810. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  10811. }
  10812. getTangentAt( u, optionalTarget ) {
  10813. return this.getTangent( u, optionalTarget );
  10814. }
  10815. copy( source ) {
  10816. super.copy( source );
  10817. this.v1.copy( source.v1 );
  10818. this.v2.copy( source.v2 );
  10819. return this;
  10820. }
  10821. toJSON() {
  10822. const data = super.toJSON();
  10823. data.v1 = this.v1.toArray();
  10824. data.v2 = this.v2.toArray();
  10825. return data;
  10826. }
  10827. fromJSON( json ) {
  10828. super.fromJSON( json );
  10829. this.v1.fromArray( json.v1 );
  10830. this.v2.fromArray( json.v2 );
  10831. return this;
  10832. }
  10833. }
  10834. class LineCurve3 extends Curve {
  10835. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  10836. super();
  10837. this.isLineCurve3 = true;
  10838. this.type = 'LineCurve3';
  10839. this.v1 = v1;
  10840. this.v2 = v2;
  10841. }
  10842. getPoint( t, optionalTarget = new Vector3() ) {
  10843. const point = optionalTarget;
  10844. if ( t === 1 ) {
  10845. point.copy( this.v2 );
  10846. } else {
  10847. point.copy( this.v2 ).sub( this.v1 );
  10848. point.multiplyScalar( t ).add( this.v1 );
  10849. }
  10850. return point;
  10851. }
  10852. // Line curve is linear, so we can overwrite default getPointAt
  10853. getPointAt( u, optionalTarget ) {
  10854. return this.getPoint( u, optionalTarget );
  10855. }
  10856. getTangent( t, optionalTarget = new Vector3() ) {
  10857. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  10858. }
  10859. getTangentAt( u, optionalTarget ) {
  10860. return this.getTangent( u, optionalTarget );
  10861. }
  10862. copy( source ) {
  10863. super.copy( source );
  10864. this.v1.copy( source.v1 );
  10865. this.v2.copy( source.v2 );
  10866. return this;
  10867. }
  10868. toJSON() {
  10869. const data = super.toJSON();
  10870. data.v1 = this.v1.toArray();
  10871. data.v2 = this.v2.toArray();
  10872. return data;
  10873. }
  10874. fromJSON( json ) {
  10875. super.fromJSON( json );
  10876. this.v1.fromArray( json.v1 );
  10877. this.v2.fromArray( json.v2 );
  10878. return this;
  10879. }
  10880. }
  10881. class QuadraticBezierCurve extends Curve {
  10882. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  10883. super();
  10884. this.isQuadraticBezierCurve = true;
  10885. this.type = 'QuadraticBezierCurve';
  10886. this.v0 = v0;
  10887. this.v1 = v1;
  10888. this.v2 = v2;
  10889. }
  10890. getPoint( t, optionalTarget = new Vector2() ) {
  10891. const point = optionalTarget;
  10892. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  10893. point.set(
  10894. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  10895. QuadraticBezier( t, v0.y, v1.y, v2.y )
  10896. );
  10897. return point;
  10898. }
  10899. copy( source ) {
  10900. super.copy( source );
  10901. this.v0.copy( source.v0 );
  10902. this.v1.copy( source.v1 );
  10903. this.v2.copy( source.v2 );
  10904. return this;
  10905. }
  10906. toJSON() {
  10907. const data = super.toJSON();
  10908. data.v0 = this.v0.toArray();
  10909. data.v1 = this.v1.toArray();
  10910. data.v2 = this.v2.toArray();
  10911. return data;
  10912. }
  10913. fromJSON( json ) {
  10914. super.fromJSON( json );
  10915. this.v0.fromArray( json.v0 );
  10916. this.v1.fromArray( json.v1 );
  10917. this.v2.fromArray( json.v2 );
  10918. return this;
  10919. }
  10920. }
  10921. class QuadraticBezierCurve3 extends Curve {
  10922. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  10923. super();
  10924. this.isQuadraticBezierCurve3 = true;
  10925. this.type = 'QuadraticBezierCurve3';
  10926. this.v0 = v0;
  10927. this.v1 = v1;
  10928. this.v2 = v2;
  10929. }
  10930. getPoint( t, optionalTarget = new Vector3() ) {
  10931. const point = optionalTarget;
  10932. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  10933. point.set(
  10934. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  10935. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  10936. QuadraticBezier( t, v0.z, v1.z, v2.z )
  10937. );
  10938. return point;
  10939. }
  10940. copy( source ) {
  10941. super.copy( source );
  10942. this.v0.copy( source.v0 );
  10943. this.v1.copy( source.v1 );
  10944. this.v2.copy( source.v2 );
  10945. return this;
  10946. }
  10947. toJSON() {
  10948. const data = super.toJSON();
  10949. data.v0 = this.v0.toArray();
  10950. data.v1 = this.v1.toArray();
  10951. data.v2 = this.v2.toArray();
  10952. return data;
  10953. }
  10954. fromJSON( json ) {
  10955. super.fromJSON( json );
  10956. this.v0.fromArray( json.v0 );
  10957. this.v1.fromArray( json.v1 );
  10958. this.v2.fromArray( json.v2 );
  10959. return this;
  10960. }
  10961. }
  10962. class SplineCurve extends Curve {
  10963. constructor( points = [] ) {
  10964. super();
  10965. this.isSplineCurve = true;
  10966. this.type = 'SplineCurve';
  10967. this.points = points;
  10968. }
  10969. getPoint( t, optionalTarget = new Vector2() ) {
  10970. const point = optionalTarget;
  10971. const points = this.points;
  10972. const p = ( points.length - 1 ) * t;
  10973. const intPoint = Math.floor( p );
  10974. const weight = p - intPoint;
  10975. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  10976. const p1 = points[ intPoint ];
  10977. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  10978. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  10979. point.set(
  10980. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  10981. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  10982. );
  10983. return point;
  10984. }
  10985. copy( source ) {
  10986. super.copy( source );
  10987. this.points = [];
  10988. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  10989. const point = source.points[ i ];
  10990. this.points.push( point.clone() );
  10991. }
  10992. return this;
  10993. }
  10994. toJSON() {
  10995. const data = super.toJSON();
  10996. data.points = [];
  10997. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  10998. const point = this.points[ i ];
  10999. data.points.push( point.toArray() );
  11000. }
  11001. return data;
  11002. }
  11003. fromJSON( json ) {
  11004. super.fromJSON( json );
  11005. this.points = [];
  11006. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  11007. const point = json.points[ i ];
  11008. this.points.push( new Vector2().fromArray( point ) );
  11009. }
  11010. return this;
  11011. }
  11012. }
  11013. var Curves = /*#__PURE__*/Object.freeze({
  11014. __proto__: null,
  11015. ArcCurve: ArcCurve,
  11016. CatmullRomCurve3: CatmullRomCurve3,
  11017. CubicBezierCurve: CubicBezierCurve,
  11018. CubicBezierCurve3: CubicBezierCurve3,
  11019. EllipseCurve: EllipseCurve,
  11020. LineCurve: LineCurve,
  11021. LineCurve3: LineCurve3,
  11022. QuadraticBezierCurve: QuadraticBezierCurve,
  11023. QuadraticBezierCurve3: QuadraticBezierCurve3,
  11024. SplineCurve: SplineCurve
  11025. });
  11026. /**************************************************************
  11027. * Curved Path - a curve path is simply a array of connected
  11028. * curves, but retains the api of a curve
  11029. **************************************************************/
  11030. class CurvePath extends Curve {
  11031. constructor() {
  11032. super();
  11033. this.type = 'CurvePath';
  11034. this.curves = [];
  11035. this.autoClose = false; // Automatically closes the path
  11036. }
  11037. add( curve ) {
  11038. this.curves.push( curve );
  11039. }
  11040. closePath() {
  11041. // Add a line curve if start and end of lines are not connected
  11042. const startPoint = this.curves[ 0 ].getPoint( 0 );
  11043. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  11044. if ( ! startPoint.equals( endPoint ) ) {
  11045. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  11046. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  11047. }
  11048. return this;
  11049. }
  11050. // To get accurate point with reference to
  11051. // entire path distance at time t,
  11052. // following has to be done:
  11053. // 1. Length of each sub path have to be known
  11054. // 2. Locate and identify type of curve
  11055. // 3. Get t for the curve
  11056. // 4. Return curve.getPointAt(t')
  11057. getPoint( t, optionalTarget ) {
  11058. const d = t * this.getLength();
  11059. const curveLengths = this.getCurveLengths();
  11060. let i = 0;
  11061. // To think about boundaries points.
  11062. while ( i < curveLengths.length ) {
  11063. if ( curveLengths[ i ] >= d ) {
  11064. const diff = curveLengths[ i ] - d;
  11065. const curve = this.curves[ i ];
  11066. const segmentLength = curve.getLength();
  11067. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  11068. return curve.getPointAt( u, optionalTarget );
  11069. }
  11070. i ++;
  11071. }
  11072. return null;
  11073. // loop where sum != 0, sum > d , sum+1 <d
  11074. }
  11075. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  11076. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  11077. // getPoint() depends on getLength
  11078. getLength() {
  11079. const lens = this.getCurveLengths();
  11080. return lens[ lens.length - 1 ];
  11081. }
  11082. // cacheLengths must be recalculated.
  11083. updateArcLengths() {
  11084. this.needsUpdate = true;
  11085. this.cacheLengths = null;
  11086. this.getCurveLengths();
  11087. }
  11088. // Compute lengths and cache them
  11089. // We cannot overwrite getLengths() because UtoT mapping uses it.
  11090. getCurveLengths() {
  11091. // We use cache values if curves and cache array are same length
  11092. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  11093. return this.cacheLengths;
  11094. }
  11095. // Get length of sub-curve
  11096. // Push sums into cached array
  11097. const lengths = [];
  11098. let sums = 0;
  11099. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11100. sums += this.curves[ i ].getLength();
  11101. lengths.push( sums );
  11102. }
  11103. this.cacheLengths = lengths;
  11104. return lengths;
  11105. }
  11106. getSpacedPoints( divisions = 40 ) {
  11107. const points = [];
  11108. for ( let i = 0; i <= divisions; i ++ ) {
  11109. points.push( this.getPoint( i / divisions ) );
  11110. }
  11111. if ( this.autoClose ) {
  11112. points.push( points[ 0 ] );
  11113. }
  11114. return points;
  11115. }
  11116. getPoints( divisions = 12 ) {
  11117. const points = [];
  11118. let last;
  11119. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  11120. const curve = curves[ i ];
  11121. const resolution = curve.isEllipseCurve ? divisions * 2
  11122. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  11123. : curve.isSplineCurve ? divisions * curve.points.length
  11124. : divisions;
  11125. const pts = curve.getPoints( resolution );
  11126. for ( let j = 0; j < pts.length; j ++ ) {
  11127. const point = pts[ j ];
  11128. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  11129. points.push( point );
  11130. last = point;
  11131. }
  11132. }
  11133. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  11134. points.push( points[ 0 ] );
  11135. }
  11136. return points;
  11137. }
  11138. copy( source ) {
  11139. super.copy( source );
  11140. this.curves = [];
  11141. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  11142. const curve = source.curves[ i ];
  11143. this.curves.push( curve.clone() );
  11144. }
  11145. this.autoClose = source.autoClose;
  11146. return this;
  11147. }
  11148. toJSON() {
  11149. const data = super.toJSON();
  11150. data.autoClose = this.autoClose;
  11151. data.curves = [];
  11152. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11153. const curve = this.curves[ i ];
  11154. data.curves.push( curve.toJSON() );
  11155. }
  11156. return data;
  11157. }
  11158. fromJSON( json ) {
  11159. super.fromJSON( json );
  11160. this.autoClose = json.autoClose;
  11161. this.curves = [];
  11162. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  11163. const curve = json.curves[ i ];
  11164. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  11165. }
  11166. return this;
  11167. }
  11168. }
  11169. class Path extends CurvePath {
  11170. constructor( points ) {
  11171. super();
  11172. this.type = 'Path';
  11173. this.currentPoint = new Vector2();
  11174. if ( points ) {
  11175. this.setFromPoints( points );
  11176. }
  11177. }
  11178. setFromPoints( points ) {
  11179. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  11180. for ( let i = 1, l = points.length; i < l; i ++ ) {
  11181. this.lineTo( points[ i ].x, points[ i ].y );
  11182. }
  11183. return this;
  11184. }
  11185. moveTo( x, y ) {
  11186. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  11187. return this;
  11188. }
  11189. lineTo( x, y ) {
  11190. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  11191. this.curves.push( curve );
  11192. this.currentPoint.set( x, y );
  11193. return this;
  11194. }
  11195. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  11196. const curve = new QuadraticBezierCurve(
  11197. this.currentPoint.clone(),
  11198. new Vector2( aCPx, aCPy ),
  11199. new Vector2( aX, aY )
  11200. );
  11201. this.curves.push( curve );
  11202. this.currentPoint.set( aX, aY );
  11203. return this;
  11204. }
  11205. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  11206. const curve = new CubicBezierCurve(
  11207. this.currentPoint.clone(),
  11208. new Vector2( aCP1x, aCP1y ),
  11209. new Vector2( aCP2x, aCP2y ),
  11210. new Vector2( aX, aY )
  11211. );
  11212. this.curves.push( curve );
  11213. this.currentPoint.set( aX, aY );
  11214. return this;
  11215. }
  11216. splineThru( pts /*Array of Vector*/ ) {
  11217. const npts = [ this.currentPoint.clone() ].concat( pts );
  11218. const curve = new SplineCurve( npts );
  11219. this.curves.push( curve );
  11220. this.currentPoint.copy( pts[ pts.length - 1 ] );
  11221. return this;
  11222. }
  11223. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11224. const x0 = this.currentPoint.x;
  11225. const y0 = this.currentPoint.y;
  11226. this.absarc( aX + x0, aY + y0, aRadius,
  11227. aStartAngle, aEndAngle, aClockwise );
  11228. return this;
  11229. }
  11230. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11231. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  11232. return this;
  11233. }
  11234. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11235. const x0 = this.currentPoint.x;
  11236. const y0 = this.currentPoint.y;
  11237. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11238. return this;
  11239. }
  11240. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11241. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11242. if ( this.curves.length > 0 ) {
  11243. // if a previous curve is present, attempt to join
  11244. const firstPoint = curve.getPoint( 0 );
  11245. if ( ! firstPoint.equals( this.currentPoint ) ) {
  11246. this.lineTo( firstPoint.x, firstPoint.y );
  11247. }
  11248. }
  11249. this.curves.push( curve );
  11250. const lastPoint = curve.getPoint( 1 );
  11251. this.currentPoint.copy( lastPoint );
  11252. return this;
  11253. }
  11254. copy( source ) {
  11255. super.copy( source );
  11256. this.currentPoint.copy( source.currentPoint );
  11257. return this;
  11258. }
  11259. toJSON() {
  11260. const data = super.toJSON();
  11261. data.currentPoint = this.currentPoint.toArray();
  11262. return data;
  11263. }
  11264. fromJSON( json ) {
  11265. super.fromJSON( json );
  11266. this.currentPoint.fromArray( json.currentPoint );
  11267. return this;
  11268. }
  11269. }
  11270. class LatheGeometry extends BufferGeometry {
  11271. constructor( points = [ new Vector2( 0, - 0.5 ), new Vector2( 0.5, 0 ), new Vector2( 0, 0.5 ) ], segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) {
  11272. super();
  11273. this.type = 'LatheGeometry';
  11274. this.parameters = {
  11275. points: points,
  11276. segments: segments,
  11277. phiStart: phiStart,
  11278. phiLength: phiLength
  11279. };
  11280. segments = Math.floor( segments );
  11281. // clamp phiLength so it's in range of [ 0, 2PI ]
  11282. phiLength = clamp$1( phiLength, 0, Math.PI * 2 );
  11283. // buffers
  11284. const indices = [];
  11285. const vertices = [];
  11286. const uvs = [];
  11287. const initNormals = [];
  11288. const normals = [];
  11289. // helper variables
  11290. const inverseSegments = 1.0 / segments;
  11291. const vertex = new Vector3();
  11292. const uv = new Vector2();
  11293. const normal = new Vector3();
  11294. const curNormal = new Vector3();
  11295. const prevNormal = new Vector3();
  11296. let dx = 0;
  11297. let dy = 0;
  11298. // pre-compute normals for initial "meridian"
  11299. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11300. switch ( j ) {
  11301. case 0: // special handling for 1st vertex on path
  11302. dx = points[ j + 1 ].x - points[ j ].x;
  11303. dy = points[ j + 1 ].y - points[ j ].y;
  11304. normal.x = dy * 1.0;
  11305. normal.y = - dx;
  11306. normal.z = dy * 0.0;
  11307. prevNormal.copy( normal );
  11308. normal.normalize();
  11309. initNormals.push( normal.x, normal.y, normal.z );
  11310. break;
  11311. case ( points.length - 1 ): // special handling for last Vertex on path
  11312. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  11313. break;
  11314. default: // default handling for all vertices in between
  11315. dx = points[ j + 1 ].x - points[ j ].x;
  11316. dy = points[ j + 1 ].y - points[ j ].y;
  11317. normal.x = dy * 1.0;
  11318. normal.y = - dx;
  11319. normal.z = dy * 0.0;
  11320. curNormal.copy( normal );
  11321. normal.x += prevNormal.x;
  11322. normal.y += prevNormal.y;
  11323. normal.z += prevNormal.z;
  11324. normal.normalize();
  11325. initNormals.push( normal.x, normal.y, normal.z );
  11326. prevNormal.copy( curNormal );
  11327. }
  11328. }
  11329. // generate vertices, uvs and normals
  11330. for ( let i = 0; i <= segments; i ++ ) {
  11331. const phi = phiStart + i * inverseSegments * phiLength;
  11332. const sin = Math.sin( phi );
  11333. const cos = Math.cos( phi );
  11334. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11335. // vertex
  11336. vertex.x = points[ j ].x * sin;
  11337. vertex.y = points[ j ].y;
  11338. vertex.z = points[ j ].x * cos;
  11339. vertices.push( vertex.x, vertex.y, vertex.z );
  11340. // uv
  11341. uv.x = i / segments;
  11342. uv.y = j / ( points.length - 1 );
  11343. uvs.push( uv.x, uv.y );
  11344. // normal
  11345. const x = initNormals[ 3 * j + 0 ] * sin;
  11346. const y = initNormals[ 3 * j + 1 ];
  11347. const z = initNormals[ 3 * j + 0 ] * cos;
  11348. normals.push( x, y, z );
  11349. }
  11350. }
  11351. // indices
  11352. for ( let i = 0; i < segments; i ++ ) {
  11353. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  11354. const base = j + i * points.length;
  11355. const a = base;
  11356. const b = base + points.length;
  11357. const c = base + points.length + 1;
  11358. const d = base + 1;
  11359. // faces
  11360. indices.push( a, b, d );
  11361. indices.push( c, d, b );
  11362. }
  11363. }
  11364. // build geometry
  11365. this.setIndex( indices );
  11366. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11367. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11368. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11369. }
  11370. copy( source ) {
  11371. super.copy( source );
  11372. this.parameters = Object.assign( {}, source.parameters );
  11373. return this;
  11374. }
  11375. static fromJSON( data ) {
  11376. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  11377. }
  11378. }
  11379. class CapsuleGeometry extends LatheGeometry {
  11380. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  11381. const path = new Path();
  11382. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  11383. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  11384. super( path.getPoints( capSegments ), radialSegments );
  11385. this.type = 'CapsuleGeometry';
  11386. this.parameters = {
  11387. radius: radius,
  11388. length: length,
  11389. capSegments: capSegments,
  11390. radialSegments: radialSegments,
  11391. };
  11392. }
  11393. static fromJSON( data ) {
  11394. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  11395. }
  11396. }
  11397. class CircleGeometry extends BufferGeometry {
  11398. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11399. super();
  11400. this.type = 'CircleGeometry';
  11401. this.parameters = {
  11402. radius: radius,
  11403. segments: segments,
  11404. thetaStart: thetaStart,
  11405. thetaLength: thetaLength
  11406. };
  11407. segments = Math.max( 3, segments );
  11408. // buffers
  11409. const indices = [];
  11410. const vertices = [];
  11411. const normals = [];
  11412. const uvs = [];
  11413. // helper variables
  11414. const vertex = new Vector3();
  11415. const uv = new Vector2();
  11416. // center point
  11417. vertices.push( 0, 0, 0 );
  11418. normals.push( 0, 0, 1 );
  11419. uvs.push( 0.5, 0.5 );
  11420. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  11421. const segment = thetaStart + s / segments * thetaLength;
  11422. // vertex
  11423. vertex.x = radius * Math.cos( segment );
  11424. vertex.y = radius * Math.sin( segment );
  11425. vertices.push( vertex.x, vertex.y, vertex.z );
  11426. // normal
  11427. normals.push( 0, 0, 1 );
  11428. // uvs
  11429. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  11430. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  11431. uvs.push( uv.x, uv.y );
  11432. }
  11433. // indices
  11434. for ( let i = 1; i <= segments; i ++ ) {
  11435. indices.push( i, i + 1, 0 );
  11436. }
  11437. // build geometry
  11438. this.setIndex( indices );
  11439. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11440. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11441. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11442. }
  11443. copy( source ) {
  11444. super.copy( source );
  11445. this.parameters = Object.assign( {}, source.parameters );
  11446. return this;
  11447. }
  11448. static fromJSON( data ) {
  11449. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  11450. }
  11451. }
  11452. class CylinderGeometry extends BufferGeometry {
  11453. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11454. super();
  11455. this.type = 'CylinderGeometry';
  11456. this.parameters = {
  11457. radiusTop: radiusTop,
  11458. radiusBottom: radiusBottom,
  11459. height: height,
  11460. radialSegments: radialSegments,
  11461. heightSegments: heightSegments,
  11462. openEnded: openEnded,
  11463. thetaStart: thetaStart,
  11464. thetaLength: thetaLength
  11465. };
  11466. const scope = this;
  11467. radialSegments = Math.floor( radialSegments );
  11468. heightSegments = Math.floor( heightSegments );
  11469. // buffers
  11470. const indices = [];
  11471. const vertices = [];
  11472. const normals = [];
  11473. const uvs = [];
  11474. // helper variables
  11475. let index = 0;
  11476. const indexArray = [];
  11477. const halfHeight = height / 2;
  11478. let groupStart = 0;
  11479. // generate geometry
  11480. generateTorso();
  11481. if ( openEnded === false ) {
  11482. if ( radiusTop > 0 ) generateCap( true );
  11483. if ( radiusBottom > 0 ) generateCap( false );
  11484. }
  11485. // build geometry
  11486. this.setIndex( indices );
  11487. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11488. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11489. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11490. function generateTorso() {
  11491. const normal = new Vector3();
  11492. const vertex = new Vector3();
  11493. let groupCount = 0;
  11494. // this will be used to calculate the normal
  11495. const slope = ( radiusBottom - radiusTop ) / height;
  11496. // generate vertices, normals and uvs
  11497. for ( let y = 0; y <= heightSegments; y ++ ) {
  11498. const indexRow = [];
  11499. const v = y / heightSegments;
  11500. // calculate the radius of the current row
  11501. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  11502. for ( let x = 0; x <= radialSegments; x ++ ) {
  11503. const u = x / radialSegments;
  11504. const theta = u * thetaLength + thetaStart;
  11505. const sinTheta = Math.sin( theta );
  11506. const cosTheta = Math.cos( theta );
  11507. // vertex
  11508. vertex.x = radius * sinTheta;
  11509. vertex.y = - v * height + halfHeight;
  11510. vertex.z = radius * cosTheta;
  11511. vertices.push( vertex.x, vertex.y, vertex.z );
  11512. // normal
  11513. normal.set( sinTheta, slope, cosTheta ).normalize();
  11514. normals.push( normal.x, normal.y, normal.z );
  11515. // uv
  11516. uvs.push( u, 1 - v );
  11517. // save index of vertex in respective row
  11518. indexRow.push( index ++ );
  11519. }
  11520. // now save vertices of the row in our index array
  11521. indexArray.push( indexRow );
  11522. }
  11523. // generate indices
  11524. for ( let x = 0; x < radialSegments; x ++ ) {
  11525. for ( let y = 0; y < heightSegments; y ++ ) {
  11526. // we use the index array to access the correct indices
  11527. const a = indexArray[ y ][ x ];
  11528. const b = indexArray[ y + 1 ][ x ];
  11529. const c = indexArray[ y + 1 ][ x + 1 ];
  11530. const d = indexArray[ y ][ x + 1 ];
  11531. // faces
  11532. indices.push( a, b, d );
  11533. indices.push( b, c, d );
  11534. // update group counter
  11535. groupCount += 6;
  11536. }
  11537. }
  11538. // add a group to the geometry. this will ensure multi material support
  11539. scope.addGroup( groupStart, groupCount, 0 );
  11540. // calculate new start value for groups
  11541. groupStart += groupCount;
  11542. }
  11543. function generateCap( top ) {
  11544. // save the index of the first center vertex
  11545. const centerIndexStart = index;
  11546. const uv = new Vector2();
  11547. const vertex = new Vector3();
  11548. let groupCount = 0;
  11549. const radius = ( top === true ) ? radiusTop : radiusBottom;
  11550. const sign = ( top === true ) ? 1 : - 1;
  11551. // first we generate the center vertex data of the cap.
  11552. // because the geometry needs one set of uvs per face,
  11553. // we must generate a center vertex per face/segment
  11554. for ( let x = 1; x <= radialSegments; x ++ ) {
  11555. // vertex
  11556. vertices.push( 0, halfHeight * sign, 0 );
  11557. // normal
  11558. normals.push( 0, sign, 0 );
  11559. // uv
  11560. uvs.push( 0.5, 0.5 );
  11561. // increase index
  11562. index ++;
  11563. }
  11564. // save the index of the last center vertex
  11565. const centerIndexEnd = index;
  11566. // now we generate the surrounding vertices, normals and uvs
  11567. for ( let x = 0; x <= radialSegments; x ++ ) {
  11568. const u = x / radialSegments;
  11569. const theta = u * thetaLength + thetaStart;
  11570. const cosTheta = Math.cos( theta );
  11571. const sinTheta = Math.sin( theta );
  11572. // vertex
  11573. vertex.x = radius * sinTheta;
  11574. vertex.y = halfHeight * sign;
  11575. vertex.z = radius * cosTheta;
  11576. vertices.push( vertex.x, vertex.y, vertex.z );
  11577. // normal
  11578. normals.push( 0, sign, 0 );
  11579. // uv
  11580. uv.x = ( cosTheta * 0.5 ) + 0.5;
  11581. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  11582. uvs.push( uv.x, uv.y );
  11583. // increase index
  11584. index ++;
  11585. }
  11586. // generate indices
  11587. for ( let x = 0; x < radialSegments; x ++ ) {
  11588. const c = centerIndexStart + x;
  11589. const i = centerIndexEnd + x;
  11590. if ( top === true ) {
  11591. // face top
  11592. indices.push( i, i + 1, c );
  11593. } else {
  11594. // face bottom
  11595. indices.push( i + 1, i, c );
  11596. }
  11597. groupCount += 3;
  11598. }
  11599. // add a group to the geometry. this will ensure multi material support
  11600. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  11601. // calculate new start value for groups
  11602. groupStart += groupCount;
  11603. }
  11604. }
  11605. copy( source ) {
  11606. super.copy( source );
  11607. this.parameters = Object.assign( {}, source.parameters );
  11608. return this;
  11609. }
  11610. static fromJSON( data ) {
  11611. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11612. }
  11613. }
  11614. class ConeGeometry extends CylinderGeometry {
  11615. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11616. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  11617. this.type = 'ConeGeometry';
  11618. this.parameters = {
  11619. radius: radius,
  11620. height: height,
  11621. radialSegments: radialSegments,
  11622. heightSegments: heightSegments,
  11623. openEnded: openEnded,
  11624. thetaStart: thetaStart,
  11625. thetaLength: thetaLength
  11626. };
  11627. }
  11628. static fromJSON( data ) {
  11629. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11630. }
  11631. }
  11632. class PolyhedronGeometry extends BufferGeometry {
  11633. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  11634. super();
  11635. this.type = 'PolyhedronGeometry';
  11636. this.parameters = {
  11637. vertices: vertices,
  11638. indices: indices,
  11639. radius: radius,
  11640. detail: detail
  11641. };
  11642. // default buffer data
  11643. const vertexBuffer = [];
  11644. const uvBuffer = [];
  11645. // the subdivision creates the vertex buffer data
  11646. subdivide( detail );
  11647. // all vertices should lie on a conceptual sphere with a given radius
  11648. applyRadius( radius );
  11649. // finally, create the uv data
  11650. generateUVs();
  11651. // build non-indexed geometry
  11652. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  11653. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  11654. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  11655. if ( detail === 0 ) {
  11656. this.computeVertexNormals(); // flat normals
  11657. } else {
  11658. this.normalizeNormals(); // smooth normals
  11659. }
  11660. // helper functions
  11661. function subdivide( detail ) {
  11662. const a = new Vector3();
  11663. const b = new Vector3();
  11664. const c = new Vector3();
  11665. // iterate over all faces and apply a subdivision with the given detail value
  11666. for ( let i = 0; i < indices.length; i += 3 ) {
  11667. // get the vertices of the face
  11668. getVertexByIndex( indices[ i + 0 ], a );
  11669. getVertexByIndex( indices[ i + 1 ], b );
  11670. getVertexByIndex( indices[ i + 2 ], c );
  11671. // perform subdivision
  11672. subdivideFace( a, b, c, detail );
  11673. }
  11674. }
  11675. function subdivideFace( a, b, c, detail ) {
  11676. const cols = detail + 1;
  11677. // we use this multidimensional array as a data structure for creating the subdivision
  11678. const v = [];
  11679. // construct all of the vertices for this subdivision
  11680. for ( let i = 0; i <= cols; i ++ ) {
  11681. v[ i ] = [];
  11682. const aj = a.clone().lerp( c, i / cols );
  11683. const bj = b.clone().lerp( c, i / cols );
  11684. const rows = cols - i;
  11685. for ( let j = 0; j <= rows; j ++ ) {
  11686. if ( j === 0 && i === cols ) {
  11687. v[ i ][ j ] = aj;
  11688. } else {
  11689. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  11690. }
  11691. }
  11692. }
  11693. // construct all of the faces
  11694. for ( let i = 0; i < cols; i ++ ) {
  11695. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  11696. const k = Math.floor( j / 2 );
  11697. if ( j % 2 === 0 ) {
  11698. pushVertex( v[ i ][ k + 1 ] );
  11699. pushVertex( v[ i + 1 ][ k ] );
  11700. pushVertex( v[ i ][ k ] );
  11701. } else {
  11702. pushVertex( v[ i ][ k + 1 ] );
  11703. pushVertex( v[ i + 1 ][ k + 1 ] );
  11704. pushVertex( v[ i + 1 ][ k ] );
  11705. }
  11706. }
  11707. }
  11708. }
  11709. function applyRadius( radius ) {
  11710. const vertex = new Vector3();
  11711. // iterate over the entire buffer and apply the radius to each vertex
  11712. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11713. vertex.x = vertexBuffer[ i + 0 ];
  11714. vertex.y = vertexBuffer[ i + 1 ];
  11715. vertex.z = vertexBuffer[ i + 2 ];
  11716. vertex.normalize().multiplyScalar( radius );
  11717. vertexBuffer[ i + 0 ] = vertex.x;
  11718. vertexBuffer[ i + 1 ] = vertex.y;
  11719. vertexBuffer[ i + 2 ] = vertex.z;
  11720. }
  11721. }
  11722. function generateUVs() {
  11723. const vertex = new Vector3();
  11724. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11725. vertex.x = vertexBuffer[ i + 0 ];
  11726. vertex.y = vertexBuffer[ i + 1 ];
  11727. vertex.z = vertexBuffer[ i + 2 ];
  11728. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  11729. const v = inclination( vertex ) / Math.PI + 0.5;
  11730. uvBuffer.push( u, 1 - v );
  11731. }
  11732. correctUVs();
  11733. correctSeam();
  11734. }
  11735. function correctSeam() {
  11736. // handle case when face straddles the seam, see #3269
  11737. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  11738. // uv data of a single face
  11739. const x0 = uvBuffer[ i + 0 ];
  11740. const x1 = uvBuffer[ i + 2 ];
  11741. const x2 = uvBuffer[ i + 4 ];
  11742. const max = Math.max( x0, x1, x2 );
  11743. const min = Math.min( x0, x1, x2 );
  11744. // 0.9 is somewhat arbitrary
  11745. if ( max > 0.9 && min < 0.1 ) {
  11746. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  11747. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  11748. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  11749. }
  11750. }
  11751. }
  11752. function pushVertex( vertex ) {
  11753. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  11754. }
  11755. function getVertexByIndex( index, vertex ) {
  11756. const stride = index * 3;
  11757. vertex.x = vertices[ stride + 0 ];
  11758. vertex.y = vertices[ stride + 1 ];
  11759. vertex.z = vertices[ stride + 2 ];
  11760. }
  11761. function correctUVs() {
  11762. const a = new Vector3();
  11763. const b = new Vector3();
  11764. const c = new Vector3();
  11765. const centroid = new Vector3();
  11766. const uvA = new Vector2();
  11767. const uvB = new Vector2();
  11768. const uvC = new Vector2();
  11769. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  11770. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  11771. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  11772. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  11773. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  11774. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  11775. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  11776. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  11777. const azi = azimuth( centroid );
  11778. correctUV( uvA, j + 0, a, azi );
  11779. correctUV( uvB, j + 2, b, azi );
  11780. correctUV( uvC, j + 4, c, azi );
  11781. }
  11782. }
  11783. function correctUV( uv, stride, vector, azimuth ) {
  11784. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  11785. uvBuffer[ stride ] = uv.x - 1;
  11786. }
  11787. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  11788. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  11789. }
  11790. }
  11791. // Angle around the Y axis, counter-clockwise when looking from above.
  11792. function azimuth( vector ) {
  11793. return Math.atan2( vector.z, - vector.x );
  11794. }
  11795. // Angle above the XZ plane.
  11796. function inclination( vector ) {
  11797. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  11798. }
  11799. }
  11800. copy( source ) {
  11801. super.copy( source );
  11802. this.parameters = Object.assign( {}, source.parameters );
  11803. return this;
  11804. }
  11805. static fromJSON( data ) {
  11806. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  11807. }
  11808. }
  11809. class DodecahedronGeometry extends PolyhedronGeometry {
  11810. constructor( radius = 1, detail = 0 ) {
  11811. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  11812. const r = 1 / t;
  11813. const vertices = [
  11814. // (±1, ±1, ±1)
  11815. - 1, - 1, - 1, - 1, - 1, 1,
  11816. - 1, 1, - 1, - 1, 1, 1,
  11817. 1, - 1, - 1, 1, - 1, 1,
  11818. 1, 1, - 1, 1, 1, 1,
  11819. // (0, ±1/φ, ±φ)
  11820. 0, - r, - t, 0, - r, t,
  11821. 0, r, - t, 0, r, t,
  11822. // (±1/φ, ±φ, 0)
  11823. - r, - t, 0, - r, t, 0,
  11824. r, - t, 0, r, t, 0,
  11825. // (±φ, 0, ±1/φ)
  11826. - t, 0, - r, t, 0, - r,
  11827. - t, 0, r, t, 0, r
  11828. ];
  11829. const indices = [
  11830. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  11831. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  11832. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  11833. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  11834. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  11835. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  11836. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  11837. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  11838. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  11839. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  11840. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  11841. 1, 12, 14, 1, 14, 5, 1, 5, 9
  11842. ];
  11843. super( vertices, indices, radius, detail );
  11844. this.type = 'DodecahedronGeometry';
  11845. this.parameters = {
  11846. radius: radius,
  11847. detail: detail
  11848. };
  11849. }
  11850. static fromJSON( data ) {
  11851. return new DodecahedronGeometry( data.radius, data.detail );
  11852. }
  11853. }
  11854. const _v0 = /*@__PURE__*/ new Vector3();
  11855. const _v1$1 = /*@__PURE__*/ new Vector3();
  11856. const _normal$1 = /*@__PURE__*/ new Vector3();
  11857. const _triangle = /*@__PURE__*/ new Triangle();
  11858. class EdgesGeometry extends BufferGeometry {
  11859. constructor( geometry = null, thresholdAngle = 1 ) {
  11860. super();
  11861. this.type = 'EdgesGeometry';
  11862. this.parameters = {
  11863. geometry: geometry,
  11864. thresholdAngle: thresholdAngle
  11865. };
  11866. if ( geometry !== null ) {
  11867. const precisionPoints = 4;
  11868. const precision = Math.pow( 10, precisionPoints );
  11869. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  11870. const indexAttr = geometry.getIndex();
  11871. const positionAttr = geometry.getAttribute( 'position' );
  11872. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  11873. const indexArr = [ 0, 0, 0 ];
  11874. const vertKeys = [ 'a', 'b', 'c' ];
  11875. const hashes = new Array( 3 );
  11876. const edgeData = {};
  11877. const vertices = [];
  11878. for ( let i = 0; i < indexCount; i += 3 ) {
  11879. if ( indexAttr ) {
  11880. indexArr[ 0 ] = indexAttr.getX( i );
  11881. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  11882. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  11883. } else {
  11884. indexArr[ 0 ] = i;
  11885. indexArr[ 1 ] = i + 1;
  11886. indexArr[ 2 ] = i + 2;
  11887. }
  11888. const { a, b, c } = _triangle;
  11889. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  11890. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  11891. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  11892. _triangle.getNormal( _normal$1 );
  11893. // create hashes for the edge from the vertices
  11894. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  11895. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  11896. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  11897. // skip degenerate triangles
  11898. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  11899. continue;
  11900. }
  11901. // iterate over every edge
  11902. for ( let j = 0; j < 3; j ++ ) {
  11903. // get the first and next vertex making up the edge
  11904. const jNext = ( j + 1 ) % 3;
  11905. const vecHash0 = hashes[ j ];
  11906. const vecHash1 = hashes[ jNext ];
  11907. const v0 = _triangle[ vertKeys[ j ] ];
  11908. const v1 = _triangle[ vertKeys[ jNext ] ];
  11909. const hash = `${ vecHash0 }_${ vecHash1 }`;
  11910. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  11911. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  11912. // if we found a sibling edge add it into the vertex array if
  11913. // it meets the angle threshold and delete the edge from the map.
  11914. if ( _normal$1.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  11915. vertices.push( v0.x, v0.y, v0.z );
  11916. vertices.push( v1.x, v1.y, v1.z );
  11917. }
  11918. edgeData[ reverseHash ] = null;
  11919. } else if ( ! ( hash in edgeData ) ) {
  11920. // if we've already got an edge here then skip adding a new one
  11921. edgeData[ hash ] = {
  11922. index0: indexArr[ j ],
  11923. index1: indexArr[ jNext ],
  11924. normal: _normal$1.clone(),
  11925. };
  11926. }
  11927. }
  11928. }
  11929. // iterate over all remaining, unmatched edges and add them to the vertex array
  11930. for ( const key in edgeData ) {
  11931. if ( edgeData[ key ] ) {
  11932. const { index0, index1 } = edgeData[ key ];
  11933. _v0.fromBufferAttribute( positionAttr, index0 );
  11934. _v1$1.fromBufferAttribute( positionAttr, index1 );
  11935. vertices.push( _v0.x, _v0.y, _v0.z );
  11936. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  11937. }
  11938. }
  11939. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11940. }
  11941. }
  11942. copy( source ) {
  11943. super.copy( source );
  11944. this.parameters = Object.assign( {}, source.parameters );
  11945. return this;
  11946. }
  11947. }
  11948. class Shape extends Path {
  11949. constructor( points ) {
  11950. super( points );
  11951. this.uuid = generateUUID();
  11952. this.type = 'Shape';
  11953. this.holes = [];
  11954. }
  11955. getPointsHoles( divisions ) {
  11956. const holesPts = [];
  11957. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  11958. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  11959. }
  11960. return holesPts;
  11961. }
  11962. // get points of shape and holes (keypoints based on segments parameter)
  11963. extractPoints( divisions ) {
  11964. return {
  11965. shape: this.getPoints( divisions ),
  11966. holes: this.getPointsHoles( divisions )
  11967. };
  11968. }
  11969. copy( source ) {
  11970. super.copy( source );
  11971. this.holes = [];
  11972. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  11973. const hole = source.holes[ i ];
  11974. this.holes.push( hole.clone() );
  11975. }
  11976. return this;
  11977. }
  11978. toJSON() {
  11979. const data = super.toJSON();
  11980. data.uuid = this.uuid;
  11981. data.holes = [];
  11982. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  11983. const hole = this.holes[ i ];
  11984. data.holes.push( hole.toJSON() );
  11985. }
  11986. return data;
  11987. }
  11988. fromJSON( json ) {
  11989. super.fromJSON( json );
  11990. this.uuid = json.uuid;
  11991. this.holes = [];
  11992. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  11993. const hole = json.holes[ i ];
  11994. this.holes.push( new Path().fromJSON( hole ) );
  11995. }
  11996. return this;
  11997. }
  11998. }
  11999. /**
  12000. * Port from https://github.com/mapbox/earcut (v2.2.4)
  12001. */
  12002. const Earcut = {
  12003. triangulate: function ( data, holeIndices, dim = 2 ) {
  12004. const hasHoles = holeIndices && holeIndices.length;
  12005. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  12006. let outerNode = linkedList( data, 0, outerLen, dim, true );
  12007. const triangles = [];
  12008. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  12009. let minX, minY, maxX, maxY, x, y, invSize;
  12010. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  12011. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  12012. if ( data.length > 80 * dim ) {
  12013. minX = maxX = data[ 0 ];
  12014. minY = maxY = data[ 1 ];
  12015. for ( let i = dim; i < outerLen; i += dim ) {
  12016. x = data[ i ];
  12017. y = data[ i + 1 ];
  12018. if ( x < minX ) minX = x;
  12019. if ( y < minY ) minY = y;
  12020. if ( x > maxX ) maxX = x;
  12021. if ( y > maxY ) maxY = y;
  12022. }
  12023. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  12024. invSize = Math.max( maxX - minX, maxY - minY );
  12025. invSize = invSize !== 0 ? 32767 / invSize : 0;
  12026. }
  12027. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  12028. return triangles;
  12029. }
  12030. };
  12031. // create a circular doubly linked list from polygon points in the specified winding order
  12032. function linkedList( data, start, end, dim, clockwise ) {
  12033. let i, last;
  12034. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  12035. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12036. } else {
  12037. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12038. }
  12039. if ( last && equals$1( last, last.next ) ) {
  12040. removeNode( last );
  12041. last = last.next;
  12042. }
  12043. return last;
  12044. }
  12045. // eliminate colinear or duplicate points
  12046. function filterPoints( start, end ) {
  12047. if ( ! start ) return start;
  12048. if ( ! end ) end = start;
  12049. let p = start,
  12050. again;
  12051. do {
  12052. again = false;
  12053. if ( ! p.steiner && ( equals$1( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  12054. removeNode( p );
  12055. p = end = p.prev;
  12056. if ( p === p.next ) break;
  12057. again = true;
  12058. } else {
  12059. p = p.next;
  12060. }
  12061. } while ( again || p !== end );
  12062. return end;
  12063. }
  12064. // main ear slicing loop which triangulates a polygon (given as a linked list)
  12065. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  12066. if ( ! ear ) return;
  12067. // interlink polygon nodes in z-order
  12068. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  12069. let stop = ear,
  12070. prev, next;
  12071. // iterate through ears, slicing them one by one
  12072. while ( ear.prev !== ear.next ) {
  12073. prev = ear.prev;
  12074. next = ear.next;
  12075. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  12076. // cut off the triangle
  12077. triangles.push( prev.i / dim | 0 );
  12078. triangles.push( ear.i / dim | 0 );
  12079. triangles.push( next.i / dim | 0 );
  12080. removeNode( ear );
  12081. // skipping the next vertex leads to less sliver triangles
  12082. ear = next.next;
  12083. stop = next.next;
  12084. continue;
  12085. }
  12086. ear = next;
  12087. // if we looped through the whole remaining polygon and can't find any more ears
  12088. if ( ear === stop ) {
  12089. // try filtering points and slicing again
  12090. if ( ! pass ) {
  12091. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  12092. // if this didn't work, try curing all small self-intersections locally
  12093. } else if ( pass === 1 ) {
  12094. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  12095. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  12096. // as a last resort, try splitting the remaining polygon into two
  12097. } else if ( pass === 2 ) {
  12098. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  12099. }
  12100. break;
  12101. }
  12102. }
  12103. }
  12104. // check whether a polygon node forms a valid ear with adjacent nodes
  12105. function isEar( ear ) {
  12106. const a = ear.prev,
  12107. b = ear,
  12108. c = ear.next;
  12109. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12110. // now make sure we don't have other points inside the potential ear
  12111. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12112. // triangle bbox; min & max are calculated like this for speed
  12113. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12114. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12115. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12116. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12117. let p = c.next;
  12118. while ( p !== a ) {
  12119. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  12120. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  12121. area( p.prev, p, p.next ) >= 0 ) return false;
  12122. p = p.next;
  12123. }
  12124. return true;
  12125. }
  12126. function isEarHashed( ear, minX, minY, invSize ) {
  12127. const a = ear.prev,
  12128. b = ear,
  12129. c = ear.next;
  12130. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12131. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12132. // triangle bbox; min & max are calculated like this for speed
  12133. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12134. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12135. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12136. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12137. // z-order range for the current triangle bbox;
  12138. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  12139. maxZ = zOrder( x1, y1, minX, minY, invSize );
  12140. let p = ear.prevZ,
  12141. n = ear.nextZ;
  12142. // look for points inside the triangle in both directions
  12143. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  12144. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12145. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12146. p = p.prevZ;
  12147. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12148. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12149. n = n.nextZ;
  12150. }
  12151. // look for remaining points in decreasing z-order
  12152. while ( p && p.z >= minZ ) {
  12153. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12154. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12155. p = p.prevZ;
  12156. }
  12157. // look for remaining points in increasing z-order
  12158. while ( n && n.z <= maxZ ) {
  12159. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12160. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12161. n = n.nextZ;
  12162. }
  12163. return true;
  12164. }
  12165. // go through all polygon nodes and cure small local self-intersections
  12166. function cureLocalIntersections( start, triangles, dim ) {
  12167. let p = start;
  12168. do {
  12169. const a = p.prev,
  12170. b = p.next.next;
  12171. if ( ! equals$1( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  12172. triangles.push( a.i / dim | 0 );
  12173. triangles.push( p.i / dim | 0 );
  12174. triangles.push( b.i / dim | 0 );
  12175. // remove two nodes involved
  12176. removeNode( p );
  12177. removeNode( p.next );
  12178. p = start = b;
  12179. }
  12180. p = p.next;
  12181. } while ( p !== start );
  12182. return filterPoints( p );
  12183. }
  12184. // try splitting polygon into two and triangulate them independently
  12185. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  12186. // look for a valid diagonal that divides the polygon into two
  12187. let a = start;
  12188. do {
  12189. let b = a.next.next;
  12190. while ( b !== a.prev ) {
  12191. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  12192. // split the polygon in two by the diagonal
  12193. let c = splitPolygon( a, b );
  12194. // filter colinear points around the cuts
  12195. a = filterPoints( a, a.next );
  12196. c = filterPoints( c, c.next );
  12197. // run earcut on each half
  12198. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  12199. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  12200. return;
  12201. }
  12202. b = b.next;
  12203. }
  12204. a = a.next;
  12205. } while ( a !== start );
  12206. }
  12207. // link every hole into the outer loop, producing a single-ring polygon without holes
  12208. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  12209. const queue = [];
  12210. let i, len, start, end, list;
  12211. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  12212. start = holeIndices[ i ] * dim;
  12213. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  12214. list = linkedList( data, start, end, dim, false );
  12215. if ( list === list.next ) list.steiner = true;
  12216. queue.push( getLeftmost( list ) );
  12217. }
  12218. queue.sort( compareX );
  12219. // process holes from left to right
  12220. for ( i = 0; i < queue.length; i ++ ) {
  12221. outerNode = eliminateHole( queue[ i ], outerNode );
  12222. }
  12223. return outerNode;
  12224. }
  12225. function compareX( a, b ) {
  12226. return a.x - b.x;
  12227. }
  12228. // find a bridge between vertices that connects hole with an outer ring and link it
  12229. function eliminateHole( hole, outerNode ) {
  12230. const bridge = findHoleBridge( hole, outerNode );
  12231. if ( ! bridge ) {
  12232. return outerNode;
  12233. }
  12234. const bridgeReverse = splitPolygon( bridge, hole );
  12235. // filter collinear points around the cuts
  12236. filterPoints( bridgeReverse, bridgeReverse.next );
  12237. return filterPoints( bridge, bridge.next );
  12238. }
  12239. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  12240. function findHoleBridge( hole, outerNode ) {
  12241. let p = outerNode,
  12242. qx = - Infinity,
  12243. m;
  12244. const hx = hole.x, hy = hole.y;
  12245. // find a segment intersected by a ray from the hole's leftmost point to the left;
  12246. // segment's endpoint with lesser x will be potential connection point
  12247. do {
  12248. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  12249. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  12250. if ( x <= hx && x > qx ) {
  12251. qx = x;
  12252. m = p.x < p.next.x ? p : p.next;
  12253. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  12254. }
  12255. }
  12256. p = p.next;
  12257. } while ( p !== outerNode );
  12258. if ( ! m ) return null;
  12259. // look for points inside the triangle of hole point, segment intersection and endpoint;
  12260. // if there are no points found, we have a valid connection;
  12261. // otherwise choose the point of the minimum angle with the ray as connection point
  12262. const stop = m,
  12263. mx = m.x,
  12264. my = m.y;
  12265. let tanMin = Infinity, tan;
  12266. p = m;
  12267. do {
  12268. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  12269. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  12270. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  12271. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  12272. m = p;
  12273. tanMin = tan;
  12274. }
  12275. }
  12276. p = p.next;
  12277. } while ( p !== stop );
  12278. return m;
  12279. }
  12280. // whether sector in vertex m contains sector in vertex p in the same coordinates
  12281. function sectorContainsSector( m, p ) {
  12282. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  12283. }
  12284. // interlink polygon nodes in z-order
  12285. function indexCurve( start, minX, minY, invSize ) {
  12286. let p = start;
  12287. do {
  12288. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  12289. p.prevZ = p.prev;
  12290. p.nextZ = p.next;
  12291. p = p.next;
  12292. } while ( p !== start );
  12293. p.prevZ.nextZ = null;
  12294. p.prevZ = null;
  12295. sortLinked( p );
  12296. }
  12297. // Simon Tatham's linked list merge sort algorithm
  12298. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  12299. function sortLinked( list ) {
  12300. let i, p, q, e, tail, numMerges, pSize, qSize,
  12301. inSize = 1;
  12302. do {
  12303. p = list;
  12304. list = null;
  12305. tail = null;
  12306. numMerges = 0;
  12307. while ( p ) {
  12308. numMerges ++;
  12309. q = p;
  12310. pSize = 0;
  12311. for ( i = 0; i < inSize; i ++ ) {
  12312. pSize ++;
  12313. q = q.nextZ;
  12314. if ( ! q ) break;
  12315. }
  12316. qSize = inSize;
  12317. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  12318. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  12319. e = p;
  12320. p = p.nextZ;
  12321. pSize --;
  12322. } else {
  12323. e = q;
  12324. q = q.nextZ;
  12325. qSize --;
  12326. }
  12327. if ( tail ) tail.nextZ = e;
  12328. else list = e;
  12329. e.prevZ = tail;
  12330. tail = e;
  12331. }
  12332. p = q;
  12333. }
  12334. tail.nextZ = null;
  12335. inSize *= 2;
  12336. } while ( numMerges > 1 );
  12337. return list;
  12338. }
  12339. // z-order of a point given coords and inverse of the longer side of data bbox
  12340. function zOrder( x, y, minX, minY, invSize ) {
  12341. // coords are transformed into non-negative 15-bit integer range
  12342. x = ( x - minX ) * invSize | 0;
  12343. y = ( y - minY ) * invSize | 0;
  12344. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  12345. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  12346. x = ( x | ( x << 2 ) ) & 0x33333333;
  12347. x = ( x | ( x << 1 ) ) & 0x55555555;
  12348. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  12349. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  12350. y = ( y | ( y << 2 ) ) & 0x33333333;
  12351. y = ( y | ( y << 1 ) ) & 0x55555555;
  12352. return x | ( y << 1 );
  12353. }
  12354. // find the leftmost node of a polygon ring
  12355. function getLeftmost( start ) {
  12356. let p = start,
  12357. leftmost = start;
  12358. do {
  12359. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  12360. p = p.next;
  12361. } while ( p !== start );
  12362. return leftmost;
  12363. }
  12364. // check if a point lies within a convex triangle
  12365. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  12366. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  12367. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  12368. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  12369. }
  12370. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  12371. function isValidDiagonal( a, b ) {
  12372. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  12373. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  12374. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  12375. equals$1( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  12376. }
  12377. // signed area of a triangle
  12378. function area( p, q, r ) {
  12379. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  12380. }
  12381. // check if two points are equal
  12382. function equals$1( p1, p2 ) {
  12383. return p1.x === p2.x && p1.y === p2.y;
  12384. }
  12385. // check if two segments intersect
  12386. function intersects( p1, q1, p2, q2 ) {
  12387. const o1 = sign$1( area( p1, q1, p2 ) );
  12388. const o2 = sign$1( area( p1, q1, q2 ) );
  12389. const o3 = sign$1( area( p2, q2, p1 ) );
  12390. const o4 = sign$1( area( p2, q2, q1 ) );
  12391. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  12392. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  12393. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  12394. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  12395. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  12396. return false;
  12397. }
  12398. // for collinear points p, q, r, check if point q lies on segment pr
  12399. function onSegment( p, q, r ) {
  12400. return q.x <= Math.max( p.x, r.x ) && q.x >= Math.min( p.x, r.x ) && q.y <= Math.max( p.y, r.y ) && q.y >= Math.min( p.y, r.y );
  12401. }
  12402. function sign$1( num ) {
  12403. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  12404. }
  12405. // check if a polygon diagonal intersects any polygon segments
  12406. function intersectsPolygon( a, b ) {
  12407. let p = a;
  12408. do {
  12409. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  12410. intersects( p, p.next, a, b ) ) return true;
  12411. p = p.next;
  12412. } while ( p !== a );
  12413. return false;
  12414. }
  12415. // check if a polygon diagonal is locally inside the polygon
  12416. function locallyInside( a, b ) {
  12417. return area( a.prev, a, a.next ) < 0 ?
  12418. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  12419. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  12420. }
  12421. // check if the middle point of a polygon diagonal is inside the polygon
  12422. function middleInside( a, b ) {
  12423. let p = a,
  12424. inside = false;
  12425. const px = ( a.x + b.x ) / 2,
  12426. py = ( a.y + b.y ) / 2;
  12427. do {
  12428. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  12429. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  12430. inside = ! inside;
  12431. p = p.next;
  12432. } while ( p !== a );
  12433. return inside;
  12434. }
  12435. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  12436. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  12437. function splitPolygon( a, b ) {
  12438. const a2 = new Node$1( a.i, a.x, a.y ),
  12439. b2 = new Node$1( b.i, b.x, b.y ),
  12440. an = a.next,
  12441. bp = b.prev;
  12442. a.next = b;
  12443. b.prev = a;
  12444. a2.next = an;
  12445. an.prev = a2;
  12446. b2.next = a2;
  12447. a2.prev = b2;
  12448. bp.next = b2;
  12449. b2.prev = bp;
  12450. return b2;
  12451. }
  12452. // create a node and optionally link it with previous one (in a circular doubly linked list)
  12453. function insertNode( i, x, y, last ) {
  12454. const p = new Node$1( i, x, y );
  12455. if ( ! last ) {
  12456. p.prev = p;
  12457. p.next = p;
  12458. } else {
  12459. p.next = last.next;
  12460. p.prev = last;
  12461. last.next.prev = p;
  12462. last.next = p;
  12463. }
  12464. return p;
  12465. }
  12466. function removeNode( p ) {
  12467. p.next.prev = p.prev;
  12468. p.prev.next = p.next;
  12469. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  12470. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  12471. }
  12472. function Node$1( i, x, y ) {
  12473. // vertex index in coordinates array
  12474. this.i = i;
  12475. // vertex coordinates
  12476. this.x = x;
  12477. this.y = y;
  12478. // previous and next vertex nodes in a polygon ring
  12479. this.prev = null;
  12480. this.next = null;
  12481. // z-order curve value
  12482. this.z = 0;
  12483. // previous and next nodes in z-order
  12484. this.prevZ = null;
  12485. this.nextZ = null;
  12486. // indicates whether this is a steiner point
  12487. this.steiner = false;
  12488. }
  12489. function signedArea( data, start, end, dim ) {
  12490. let sum = 0;
  12491. for ( let i = start, j = end - dim; i < end; i += dim ) {
  12492. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  12493. j = i;
  12494. }
  12495. return sum;
  12496. }
  12497. class ShapeUtils {
  12498. // calculate area of the contour polygon
  12499. static area( contour ) {
  12500. const n = contour.length;
  12501. let a = 0.0;
  12502. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  12503. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  12504. }
  12505. return a * 0.5;
  12506. }
  12507. static isClockWise( pts ) {
  12508. return ShapeUtils.area( pts ) < 0;
  12509. }
  12510. static triangulateShape( contour, holes ) {
  12511. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  12512. const holeIndices = []; // array of hole indices
  12513. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  12514. removeDupEndPts( contour );
  12515. addContour( vertices, contour );
  12516. //
  12517. let holeIndex = contour.length;
  12518. holes.forEach( removeDupEndPts );
  12519. for ( let i = 0; i < holes.length; i ++ ) {
  12520. holeIndices.push( holeIndex );
  12521. holeIndex += holes[ i ].length;
  12522. addContour( vertices, holes[ i ] );
  12523. }
  12524. //
  12525. const triangles = Earcut.triangulate( vertices, holeIndices );
  12526. //
  12527. for ( let i = 0; i < triangles.length; i += 3 ) {
  12528. faces.push( triangles.slice( i, i + 3 ) );
  12529. }
  12530. return faces;
  12531. }
  12532. }
  12533. function removeDupEndPts( points ) {
  12534. const l = points.length;
  12535. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  12536. points.pop();
  12537. }
  12538. }
  12539. function addContour( vertices, contour ) {
  12540. for ( let i = 0; i < contour.length; i ++ ) {
  12541. vertices.push( contour[ i ].x );
  12542. vertices.push( contour[ i ].y );
  12543. }
  12544. }
  12545. /**
  12546. * Creates extruded geometry from a path shape.
  12547. *
  12548. * parameters = {
  12549. *
  12550. * curveSegments: <int>, // number of points on the curves
  12551. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  12552. * depth: <float>, // Depth to extrude the shape
  12553. *
  12554. * bevelEnabled: <bool>, // turn on bevel
  12555. * bevelThickness: <float>, // how deep into the original shape bevel goes
  12556. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  12557. * bevelOffset: <float>, // how far from shape outline does bevel start
  12558. * bevelSegments: <int>, // number of bevel layers
  12559. *
  12560. * extrudePath: <THREE.Curve> // curve to extrude shape along
  12561. *
  12562. * UVGenerator: <Object> // object that provides UV generator functions
  12563. *
  12564. * }
  12565. */
  12566. class ExtrudeGeometry extends BufferGeometry {
  12567. constructor( shapes = new Shape( [ new Vector2( 0.5, 0.5 ), new Vector2( - 0.5, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), options = {} ) {
  12568. super();
  12569. this.type = 'ExtrudeGeometry';
  12570. this.parameters = {
  12571. shapes: shapes,
  12572. options: options
  12573. };
  12574. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  12575. const scope = this;
  12576. const verticesArray = [];
  12577. const uvArray = [];
  12578. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  12579. const shape = shapes[ i ];
  12580. addShape( shape );
  12581. }
  12582. // build geometry
  12583. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  12584. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  12585. this.computeVertexNormals();
  12586. // functions
  12587. function addShape( shape ) {
  12588. const placeholder = [];
  12589. // options
  12590. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  12591. const steps = options.steps !== undefined ? options.steps : 1;
  12592. const depth = options.depth !== undefined ? options.depth : 1;
  12593. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  12594. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  12595. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  12596. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  12597. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  12598. const extrudePath = options.extrudePath;
  12599. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  12600. //
  12601. let extrudePts, extrudeByPath = false;
  12602. let splineTube, binormal, normal, position2;
  12603. if ( extrudePath ) {
  12604. extrudePts = extrudePath.getSpacedPoints( steps );
  12605. extrudeByPath = true;
  12606. bevelEnabled = false; // bevels not supported for path extrusion
  12607. // SETUP TNB variables
  12608. // TODO1 - have a .isClosed in spline?
  12609. splineTube = extrudePath.computeFrenetFrames( steps, false );
  12610. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  12611. binormal = new Vector3();
  12612. normal = new Vector3();
  12613. position2 = new Vector3();
  12614. }
  12615. // Safeguards if bevels are not enabled
  12616. if ( ! bevelEnabled ) {
  12617. bevelSegments = 0;
  12618. bevelThickness = 0;
  12619. bevelSize = 0;
  12620. bevelOffset = 0;
  12621. }
  12622. // Variables initialization
  12623. const shapePoints = shape.extractPoints( curveSegments );
  12624. let vertices = shapePoints.shape;
  12625. const holes = shapePoints.holes;
  12626. const reverse = ! ShapeUtils.isClockWise( vertices );
  12627. if ( reverse ) {
  12628. vertices = vertices.reverse();
  12629. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  12630. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12631. const ahole = holes[ h ];
  12632. if ( ShapeUtils.isClockWise( ahole ) ) {
  12633. holes[ h ] = ahole.reverse();
  12634. }
  12635. }
  12636. }
  12637. const faces = ShapeUtils.triangulateShape( vertices, holes );
  12638. /* Vertices */
  12639. const contour = vertices; // vertices has all points but contour has only points of circumference
  12640. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12641. const ahole = holes[ h ];
  12642. vertices = vertices.concat( ahole );
  12643. }
  12644. function scalePt2( pt, vec, size ) {
  12645. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  12646. return pt.clone().addScaledVector( vec, size );
  12647. }
  12648. const vlen = vertices.length, flen = faces.length;
  12649. // Find directions for point movement
  12650. function getBevelVec( inPt, inPrev, inNext ) {
  12651. // computes for inPt the corresponding point inPt' on a new contour
  12652. // shifted by 1 unit (length of normalized vector) to the left
  12653. // if we walk along contour clockwise, this new contour is outside the old one
  12654. //
  12655. // inPt' is the intersection of the two lines parallel to the two
  12656. // adjacent edges of inPt at a distance of 1 unit on the left side.
  12657. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  12658. // good reading for geometry algorithms (here: line-line intersection)
  12659. // http://geomalgorithms.com/a05-_intersect-1.html
  12660. const v_prev_x = inPt.x - inPrev.x,
  12661. v_prev_y = inPt.y - inPrev.y;
  12662. const v_next_x = inNext.x - inPt.x,
  12663. v_next_y = inNext.y - inPt.y;
  12664. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  12665. // check for collinear edges
  12666. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12667. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  12668. // not collinear
  12669. // length of vectors for normalizing
  12670. const v_prev_len = Math.sqrt( v_prev_lensq );
  12671. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  12672. // shift adjacent points by unit vectors to the left
  12673. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  12674. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  12675. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  12676. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  12677. // scaling factor for v_prev to intersection point
  12678. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  12679. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  12680. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12681. // vector from inPt to intersection point
  12682. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  12683. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  12684. // Don't normalize!, otherwise sharp corners become ugly
  12685. // but prevent crazy spikes
  12686. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  12687. if ( v_trans_lensq <= 2 ) {
  12688. return new Vector2( v_trans_x, v_trans_y );
  12689. } else {
  12690. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  12691. }
  12692. } else {
  12693. // handle special case of collinear edges
  12694. let direction_eq = false; // assumes: opposite
  12695. if ( v_prev_x > Number.EPSILON ) {
  12696. if ( v_next_x > Number.EPSILON ) {
  12697. direction_eq = true;
  12698. }
  12699. } else {
  12700. if ( v_prev_x < - Number.EPSILON ) {
  12701. if ( v_next_x < - Number.EPSILON ) {
  12702. direction_eq = true;
  12703. }
  12704. } else {
  12705. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  12706. direction_eq = true;
  12707. }
  12708. }
  12709. }
  12710. if ( direction_eq ) {
  12711. // console.log("Warning: lines are a straight sequence");
  12712. v_trans_x = - v_prev_y;
  12713. v_trans_y = v_prev_x;
  12714. shrink_by = Math.sqrt( v_prev_lensq );
  12715. } else {
  12716. // console.log("Warning: lines are a straight spike");
  12717. v_trans_x = v_prev_x;
  12718. v_trans_y = v_prev_y;
  12719. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  12720. }
  12721. }
  12722. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  12723. }
  12724. const contourMovements = [];
  12725. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12726. if ( j === il ) j = 0;
  12727. if ( k === il ) k = 0;
  12728. // (j)---(i)---(k)
  12729. // console.log('i,j,k', i, j , k)
  12730. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  12731. }
  12732. const holesMovements = [];
  12733. let oneHoleMovements, verticesMovements = contourMovements.concat();
  12734. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12735. const ahole = holes[ h ];
  12736. oneHoleMovements = [];
  12737. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12738. if ( j === il ) j = 0;
  12739. if ( k === il ) k = 0;
  12740. // (j)---(i)---(k)
  12741. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  12742. }
  12743. holesMovements.push( oneHoleMovements );
  12744. verticesMovements = verticesMovements.concat( oneHoleMovements );
  12745. }
  12746. // Loop bevelSegments, 1 for the front, 1 for the back
  12747. for ( let b = 0; b < bevelSegments; b ++ ) {
  12748. //for ( b = bevelSegments; b > 0; b -- ) {
  12749. const t = b / bevelSegments;
  12750. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  12751. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  12752. // contract shape
  12753. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  12754. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  12755. v( vert.x, vert.y, - z );
  12756. }
  12757. // expand holes
  12758. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12759. const ahole = holes[ h ];
  12760. oneHoleMovements = holesMovements[ h ];
  12761. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  12762. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  12763. v( vert.x, vert.y, - z );
  12764. }
  12765. }
  12766. }
  12767. const bs = bevelSize + bevelOffset;
  12768. // Back facing vertices
  12769. for ( let i = 0; i < vlen; i ++ ) {
  12770. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  12771. if ( ! extrudeByPath ) {
  12772. v( vert.x, vert.y, 0 );
  12773. } else {
  12774. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  12775. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  12776. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  12777. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  12778. v( position2.x, position2.y, position2.z );
  12779. }
  12780. }
  12781. // Add stepped vertices...
  12782. // Including front facing vertices
  12783. for ( let s = 1; s <= steps; s ++ ) {
  12784. for ( let i = 0; i < vlen; i ++ ) {
  12785. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  12786. if ( ! extrudeByPath ) {
  12787. v( vert.x, vert.y, depth / steps * s );
  12788. } else {
  12789. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  12790. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  12791. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  12792. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  12793. v( position2.x, position2.y, position2.z );
  12794. }
  12795. }
  12796. }
  12797. // Add bevel segments planes
  12798. //for ( b = 1; b <= bevelSegments; b ++ ) {
  12799. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  12800. const t = b / bevelSegments;
  12801. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  12802. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  12803. // contract shape
  12804. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  12805. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  12806. v( vert.x, vert.y, depth + z );
  12807. }
  12808. // expand holes
  12809. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12810. const ahole = holes[ h ];
  12811. oneHoleMovements = holesMovements[ h ];
  12812. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  12813. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  12814. if ( ! extrudeByPath ) {
  12815. v( vert.x, vert.y, depth + z );
  12816. } else {
  12817. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  12818. }
  12819. }
  12820. }
  12821. }
  12822. /* Faces */
  12823. // Top and bottom faces
  12824. buildLidFaces();
  12825. // Sides faces
  12826. buildSideFaces();
  12827. ///// Internal functions
  12828. function buildLidFaces() {
  12829. const start = verticesArray.length / 3;
  12830. if ( bevelEnabled ) {
  12831. let layer = 0; // steps + 1
  12832. let offset = vlen * layer;
  12833. // Bottom faces
  12834. for ( let i = 0; i < flen; i ++ ) {
  12835. const face = faces[ i ];
  12836. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  12837. }
  12838. layer = steps + bevelSegments * 2;
  12839. offset = vlen * layer;
  12840. // Top faces
  12841. for ( let i = 0; i < flen; i ++ ) {
  12842. const face = faces[ i ];
  12843. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  12844. }
  12845. } else {
  12846. // Bottom faces
  12847. for ( let i = 0; i < flen; i ++ ) {
  12848. const face = faces[ i ];
  12849. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  12850. }
  12851. // Top faces
  12852. for ( let i = 0; i < flen; i ++ ) {
  12853. const face = faces[ i ];
  12854. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  12855. }
  12856. }
  12857. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  12858. }
  12859. // Create faces for the z-sides of the shape
  12860. function buildSideFaces() {
  12861. const start = verticesArray.length / 3;
  12862. let layeroffset = 0;
  12863. sidewalls( contour, layeroffset );
  12864. layeroffset += contour.length;
  12865. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12866. const ahole = holes[ h ];
  12867. sidewalls( ahole, layeroffset );
  12868. //, true
  12869. layeroffset += ahole.length;
  12870. }
  12871. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  12872. }
  12873. function sidewalls( contour, layeroffset ) {
  12874. let i = contour.length;
  12875. while ( -- i >= 0 ) {
  12876. const j = i;
  12877. let k = i - 1;
  12878. if ( k < 0 ) k = contour.length - 1;
  12879. //console.log('b', i,j, i-1, k,vertices.length);
  12880. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  12881. const slen1 = vlen * s;
  12882. const slen2 = vlen * ( s + 1 );
  12883. const a = layeroffset + j + slen1,
  12884. b = layeroffset + k + slen1,
  12885. c = layeroffset + k + slen2,
  12886. d = layeroffset + j + slen2;
  12887. f4( a, b, c, d );
  12888. }
  12889. }
  12890. }
  12891. function v( x, y, z ) {
  12892. placeholder.push( x );
  12893. placeholder.push( y );
  12894. placeholder.push( z );
  12895. }
  12896. function f3( a, b, c ) {
  12897. addVertex( a );
  12898. addVertex( b );
  12899. addVertex( c );
  12900. const nextIndex = verticesArray.length / 3;
  12901. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  12902. addUV( uvs[ 0 ] );
  12903. addUV( uvs[ 1 ] );
  12904. addUV( uvs[ 2 ] );
  12905. }
  12906. function f4( a, b, c, d ) {
  12907. addVertex( a );
  12908. addVertex( b );
  12909. addVertex( d );
  12910. addVertex( b );
  12911. addVertex( c );
  12912. addVertex( d );
  12913. const nextIndex = verticesArray.length / 3;
  12914. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  12915. addUV( uvs[ 0 ] );
  12916. addUV( uvs[ 1 ] );
  12917. addUV( uvs[ 3 ] );
  12918. addUV( uvs[ 1 ] );
  12919. addUV( uvs[ 2 ] );
  12920. addUV( uvs[ 3 ] );
  12921. }
  12922. function addVertex( index ) {
  12923. verticesArray.push( placeholder[ index * 3 + 0 ] );
  12924. verticesArray.push( placeholder[ index * 3 + 1 ] );
  12925. verticesArray.push( placeholder[ index * 3 + 2 ] );
  12926. }
  12927. function addUV( vector2 ) {
  12928. uvArray.push( vector2.x );
  12929. uvArray.push( vector2.y );
  12930. }
  12931. }
  12932. }
  12933. copy( source ) {
  12934. super.copy( source );
  12935. this.parameters = Object.assign( {}, source.parameters );
  12936. return this;
  12937. }
  12938. toJSON() {
  12939. const data = super.toJSON();
  12940. const shapes = this.parameters.shapes;
  12941. const options = this.parameters.options;
  12942. return toJSON$1( shapes, options, data );
  12943. }
  12944. static fromJSON( data, shapes ) {
  12945. const geometryShapes = [];
  12946. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  12947. const shape = shapes[ data.shapes[ j ] ];
  12948. geometryShapes.push( shape );
  12949. }
  12950. const extrudePath = data.options.extrudePath;
  12951. if ( extrudePath !== undefined ) {
  12952. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  12953. }
  12954. return new ExtrudeGeometry( geometryShapes, data.options );
  12955. }
  12956. }
  12957. const WorldUVGenerator = {
  12958. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  12959. const a_x = vertices[ indexA * 3 ];
  12960. const a_y = vertices[ indexA * 3 + 1 ];
  12961. const b_x = vertices[ indexB * 3 ];
  12962. const b_y = vertices[ indexB * 3 + 1 ];
  12963. const c_x = vertices[ indexC * 3 ];
  12964. const c_y = vertices[ indexC * 3 + 1 ];
  12965. return [
  12966. new Vector2( a_x, a_y ),
  12967. new Vector2( b_x, b_y ),
  12968. new Vector2( c_x, c_y )
  12969. ];
  12970. },
  12971. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  12972. const a_x = vertices[ indexA * 3 ];
  12973. const a_y = vertices[ indexA * 3 + 1 ];
  12974. const a_z = vertices[ indexA * 3 + 2 ];
  12975. const b_x = vertices[ indexB * 3 ];
  12976. const b_y = vertices[ indexB * 3 + 1 ];
  12977. const b_z = vertices[ indexB * 3 + 2 ];
  12978. const c_x = vertices[ indexC * 3 ];
  12979. const c_y = vertices[ indexC * 3 + 1 ];
  12980. const c_z = vertices[ indexC * 3 + 2 ];
  12981. const d_x = vertices[ indexD * 3 ];
  12982. const d_y = vertices[ indexD * 3 + 1 ];
  12983. const d_z = vertices[ indexD * 3 + 2 ];
  12984. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  12985. return [
  12986. new Vector2( a_x, 1 - a_z ),
  12987. new Vector2( b_x, 1 - b_z ),
  12988. new Vector2( c_x, 1 - c_z ),
  12989. new Vector2( d_x, 1 - d_z )
  12990. ];
  12991. } else {
  12992. return [
  12993. new Vector2( a_y, 1 - a_z ),
  12994. new Vector2( b_y, 1 - b_z ),
  12995. new Vector2( c_y, 1 - c_z ),
  12996. new Vector2( d_y, 1 - d_z )
  12997. ];
  12998. }
  12999. }
  13000. };
  13001. function toJSON$1( shapes, options, data ) {
  13002. data.shapes = [];
  13003. if ( Array.isArray( shapes ) ) {
  13004. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13005. const shape = shapes[ i ];
  13006. data.shapes.push( shape.uuid );
  13007. }
  13008. } else {
  13009. data.shapes.push( shapes.uuid );
  13010. }
  13011. data.options = Object.assign( {}, options );
  13012. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  13013. return data;
  13014. }
  13015. class IcosahedronGeometry extends PolyhedronGeometry {
  13016. constructor( radius = 1, detail = 0 ) {
  13017. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  13018. const vertices = [
  13019. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  13020. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  13021. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  13022. ];
  13023. const indices = [
  13024. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  13025. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  13026. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  13027. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  13028. ];
  13029. super( vertices, indices, radius, detail );
  13030. this.type = 'IcosahedronGeometry';
  13031. this.parameters = {
  13032. radius: radius,
  13033. detail: detail
  13034. };
  13035. }
  13036. static fromJSON( data ) {
  13037. return new IcosahedronGeometry( data.radius, data.detail );
  13038. }
  13039. }
  13040. class OctahedronGeometry extends PolyhedronGeometry {
  13041. constructor( radius = 1, detail = 0 ) {
  13042. const vertices = [
  13043. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  13044. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  13045. ];
  13046. const indices = [
  13047. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  13048. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  13049. 1, 3, 4, 1, 4, 2
  13050. ];
  13051. super( vertices, indices, radius, detail );
  13052. this.type = 'OctahedronGeometry';
  13053. this.parameters = {
  13054. radius: radius,
  13055. detail: detail
  13056. };
  13057. }
  13058. static fromJSON( data ) {
  13059. return new OctahedronGeometry( data.radius, data.detail );
  13060. }
  13061. }
  13062. class PlaneGeometry extends BufferGeometry {
  13063. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  13064. super();
  13065. this.type = 'PlaneGeometry';
  13066. this.parameters = {
  13067. width: width,
  13068. height: height,
  13069. widthSegments: widthSegments,
  13070. heightSegments: heightSegments
  13071. };
  13072. const width_half = width / 2;
  13073. const height_half = height / 2;
  13074. const gridX = Math.floor( widthSegments );
  13075. const gridY = Math.floor( heightSegments );
  13076. const gridX1 = gridX + 1;
  13077. const gridY1 = gridY + 1;
  13078. const segment_width = width / gridX;
  13079. const segment_height = height / gridY;
  13080. //
  13081. const indices = [];
  13082. const vertices = [];
  13083. const normals = [];
  13084. const uvs = [];
  13085. for ( let iy = 0; iy < gridY1; iy ++ ) {
  13086. const y = iy * segment_height - height_half;
  13087. for ( let ix = 0; ix < gridX1; ix ++ ) {
  13088. const x = ix * segment_width - width_half;
  13089. vertices.push( x, - y, 0 );
  13090. normals.push( 0, 0, 1 );
  13091. uvs.push( ix / gridX );
  13092. uvs.push( 1 - ( iy / gridY ) );
  13093. }
  13094. }
  13095. for ( let iy = 0; iy < gridY; iy ++ ) {
  13096. for ( let ix = 0; ix < gridX; ix ++ ) {
  13097. const a = ix + gridX1 * iy;
  13098. const b = ix + gridX1 * ( iy + 1 );
  13099. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  13100. const d = ( ix + 1 ) + gridX1 * iy;
  13101. indices.push( a, b, d );
  13102. indices.push( b, c, d );
  13103. }
  13104. }
  13105. this.setIndex( indices );
  13106. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13107. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13108. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13109. }
  13110. copy( source ) {
  13111. super.copy( source );
  13112. this.parameters = Object.assign( {}, source.parameters );
  13113. return this;
  13114. }
  13115. static fromJSON( data ) {
  13116. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  13117. }
  13118. }
  13119. class RingGeometry extends BufferGeometry {
  13120. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  13121. super();
  13122. this.type = 'RingGeometry';
  13123. this.parameters = {
  13124. innerRadius: innerRadius,
  13125. outerRadius: outerRadius,
  13126. thetaSegments: thetaSegments,
  13127. phiSegments: phiSegments,
  13128. thetaStart: thetaStart,
  13129. thetaLength: thetaLength
  13130. };
  13131. thetaSegments = Math.max( 3, thetaSegments );
  13132. phiSegments = Math.max( 1, phiSegments );
  13133. // buffers
  13134. const indices = [];
  13135. const vertices = [];
  13136. const normals = [];
  13137. const uvs = [];
  13138. // some helper variables
  13139. let radius = innerRadius;
  13140. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  13141. const vertex = new Vector3();
  13142. const uv = new Vector2();
  13143. // generate vertices, normals and uvs
  13144. for ( let j = 0; j <= phiSegments; j ++ ) {
  13145. for ( let i = 0; i <= thetaSegments; i ++ ) {
  13146. // values are generate from the inside of the ring to the outside
  13147. const segment = thetaStart + i / thetaSegments * thetaLength;
  13148. // vertex
  13149. vertex.x = radius * Math.cos( segment );
  13150. vertex.y = radius * Math.sin( segment );
  13151. vertices.push( vertex.x, vertex.y, vertex.z );
  13152. // normal
  13153. normals.push( 0, 0, 1 );
  13154. // uv
  13155. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  13156. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  13157. uvs.push( uv.x, uv.y );
  13158. }
  13159. // increase the radius for next row of vertices
  13160. radius += radiusStep;
  13161. }
  13162. // indices
  13163. for ( let j = 0; j < phiSegments; j ++ ) {
  13164. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  13165. for ( let i = 0; i < thetaSegments; i ++ ) {
  13166. const segment = i + thetaSegmentLevel;
  13167. const a = segment;
  13168. const b = segment + thetaSegments + 1;
  13169. const c = segment + thetaSegments + 2;
  13170. const d = segment + 1;
  13171. // faces
  13172. indices.push( a, b, d );
  13173. indices.push( b, c, d );
  13174. }
  13175. }
  13176. // build geometry
  13177. this.setIndex( indices );
  13178. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13179. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13180. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13181. }
  13182. copy( source ) {
  13183. super.copy( source );
  13184. this.parameters = Object.assign( {}, source.parameters );
  13185. return this;
  13186. }
  13187. static fromJSON( data ) {
  13188. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  13189. }
  13190. }
  13191. class ShapeGeometry extends BufferGeometry {
  13192. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  13193. super();
  13194. this.type = 'ShapeGeometry';
  13195. this.parameters = {
  13196. shapes: shapes,
  13197. curveSegments: curveSegments
  13198. };
  13199. // buffers
  13200. const indices = [];
  13201. const vertices = [];
  13202. const normals = [];
  13203. const uvs = [];
  13204. // helper variables
  13205. let groupStart = 0;
  13206. let groupCount = 0;
  13207. // allow single and array values for "shapes" parameter
  13208. if ( Array.isArray( shapes ) === false ) {
  13209. addShape( shapes );
  13210. } else {
  13211. for ( let i = 0; i < shapes.length; i ++ ) {
  13212. addShape( shapes[ i ] );
  13213. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  13214. groupStart += groupCount;
  13215. groupCount = 0;
  13216. }
  13217. }
  13218. // build geometry
  13219. this.setIndex( indices );
  13220. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13221. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13222. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13223. // helper functions
  13224. function addShape( shape ) {
  13225. const indexOffset = vertices.length / 3;
  13226. const points = shape.extractPoints( curveSegments );
  13227. let shapeVertices = points.shape;
  13228. const shapeHoles = points.holes;
  13229. // check direction of vertices
  13230. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  13231. shapeVertices = shapeVertices.reverse();
  13232. }
  13233. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13234. const shapeHole = shapeHoles[ i ];
  13235. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  13236. shapeHoles[ i ] = shapeHole.reverse();
  13237. }
  13238. }
  13239. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  13240. // join vertices of inner and outer paths to a single array
  13241. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13242. const shapeHole = shapeHoles[ i ];
  13243. shapeVertices = shapeVertices.concat( shapeHole );
  13244. }
  13245. // vertices, normals, uvs
  13246. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  13247. const vertex = shapeVertices[ i ];
  13248. vertices.push( vertex.x, vertex.y, 0 );
  13249. normals.push( 0, 0, 1 );
  13250. uvs.push( vertex.x, vertex.y ); // world uvs
  13251. }
  13252. // indices
  13253. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  13254. const face = faces[ i ];
  13255. const a = face[ 0 ] + indexOffset;
  13256. const b = face[ 1 ] + indexOffset;
  13257. const c = face[ 2 ] + indexOffset;
  13258. indices.push( a, b, c );
  13259. groupCount += 3;
  13260. }
  13261. }
  13262. }
  13263. copy( source ) {
  13264. super.copy( source );
  13265. this.parameters = Object.assign( {}, source.parameters );
  13266. return this;
  13267. }
  13268. toJSON() {
  13269. const data = super.toJSON();
  13270. const shapes = this.parameters.shapes;
  13271. return toJSON( shapes, data );
  13272. }
  13273. static fromJSON( data, shapes ) {
  13274. const geometryShapes = [];
  13275. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  13276. const shape = shapes[ data.shapes[ j ] ];
  13277. geometryShapes.push( shape );
  13278. }
  13279. return new ShapeGeometry( geometryShapes, data.curveSegments );
  13280. }
  13281. }
  13282. function toJSON( shapes, data ) {
  13283. data.shapes = [];
  13284. if ( Array.isArray( shapes ) ) {
  13285. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13286. const shape = shapes[ i ];
  13287. data.shapes.push( shape.uuid );
  13288. }
  13289. } else {
  13290. data.shapes.push( shapes.uuid );
  13291. }
  13292. return data;
  13293. }
  13294. class SphereGeometry extends BufferGeometry {
  13295. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  13296. super();
  13297. this.type = 'SphereGeometry';
  13298. this.parameters = {
  13299. radius: radius,
  13300. widthSegments: widthSegments,
  13301. heightSegments: heightSegments,
  13302. phiStart: phiStart,
  13303. phiLength: phiLength,
  13304. thetaStart: thetaStart,
  13305. thetaLength: thetaLength
  13306. };
  13307. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  13308. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  13309. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  13310. let index = 0;
  13311. const grid = [];
  13312. const vertex = new Vector3();
  13313. const normal = new Vector3();
  13314. // buffers
  13315. const indices = [];
  13316. const vertices = [];
  13317. const normals = [];
  13318. const uvs = [];
  13319. // generate vertices, normals and uvs
  13320. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  13321. const verticesRow = [];
  13322. const v = iy / heightSegments;
  13323. // special case for the poles
  13324. let uOffset = 0;
  13325. if ( iy === 0 && thetaStart === 0 ) {
  13326. uOffset = 0.5 / widthSegments;
  13327. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  13328. uOffset = - 0.5 / widthSegments;
  13329. }
  13330. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  13331. const u = ix / widthSegments;
  13332. // vertex
  13333. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13334. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  13335. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13336. vertices.push( vertex.x, vertex.y, vertex.z );
  13337. // normal
  13338. normal.copy( vertex ).normalize();
  13339. normals.push( normal.x, normal.y, normal.z );
  13340. // uv
  13341. uvs.push( u + uOffset, 1 - v );
  13342. verticesRow.push( index ++ );
  13343. }
  13344. grid.push( verticesRow );
  13345. }
  13346. // indices
  13347. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  13348. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  13349. const a = grid[ iy ][ ix + 1 ];
  13350. const b = grid[ iy ][ ix ];
  13351. const c = grid[ iy + 1 ][ ix ];
  13352. const d = grid[ iy + 1 ][ ix + 1 ];
  13353. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  13354. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  13355. }
  13356. }
  13357. // build geometry
  13358. this.setIndex( indices );
  13359. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13360. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13361. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13362. }
  13363. copy( source ) {
  13364. super.copy( source );
  13365. this.parameters = Object.assign( {}, source.parameters );
  13366. return this;
  13367. }
  13368. static fromJSON( data ) {
  13369. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  13370. }
  13371. }
  13372. class TetrahedronGeometry extends PolyhedronGeometry {
  13373. constructor( radius = 1, detail = 0 ) {
  13374. const vertices = [
  13375. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  13376. ];
  13377. const indices = [
  13378. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  13379. ];
  13380. super( vertices, indices, radius, detail );
  13381. this.type = 'TetrahedronGeometry';
  13382. this.parameters = {
  13383. radius: radius,
  13384. detail: detail
  13385. };
  13386. }
  13387. static fromJSON( data ) {
  13388. return new TetrahedronGeometry( data.radius, data.detail );
  13389. }
  13390. }
  13391. class TorusGeometry extends BufferGeometry {
  13392. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  13393. super();
  13394. this.type = 'TorusGeometry';
  13395. this.parameters = {
  13396. radius: radius,
  13397. tube: tube,
  13398. radialSegments: radialSegments,
  13399. tubularSegments: tubularSegments,
  13400. arc: arc
  13401. };
  13402. radialSegments = Math.floor( radialSegments );
  13403. tubularSegments = Math.floor( tubularSegments );
  13404. // buffers
  13405. const indices = [];
  13406. const vertices = [];
  13407. const normals = [];
  13408. const uvs = [];
  13409. // helper variables
  13410. const center = new Vector3();
  13411. const vertex = new Vector3();
  13412. const normal = new Vector3();
  13413. // generate vertices, normals and uvs
  13414. for ( let j = 0; j <= radialSegments; j ++ ) {
  13415. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13416. const u = i / tubularSegments * arc;
  13417. const v = j / radialSegments * Math.PI * 2;
  13418. // vertex
  13419. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  13420. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  13421. vertex.z = tube * Math.sin( v );
  13422. vertices.push( vertex.x, vertex.y, vertex.z );
  13423. // normal
  13424. center.x = radius * Math.cos( u );
  13425. center.y = radius * Math.sin( u );
  13426. normal.subVectors( vertex, center ).normalize();
  13427. normals.push( normal.x, normal.y, normal.z );
  13428. // uv
  13429. uvs.push( i / tubularSegments );
  13430. uvs.push( j / radialSegments );
  13431. }
  13432. }
  13433. // generate indices
  13434. for ( let j = 1; j <= radialSegments; j ++ ) {
  13435. for ( let i = 1; i <= tubularSegments; i ++ ) {
  13436. // indices
  13437. const a = ( tubularSegments + 1 ) * j + i - 1;
  13438. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  13439. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  13440. const d = ( tubularSegments + 1 ) * j + i;
  13441. // faces
  13442. indices.push( a, b, d );
  13443. indices.push( b, c, d );
  13444. }
  13445. }
  13446. // build geometry
  13447. this.setIndex( indices );
  13448. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13449. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13450. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13451. }
  13452. copy( source ) {
  13453. super.copy( source );
  13454. this.parameters = Object.assign( {}, source.parameters );
  13455. return this;
  13456. }
  13457. static fromJSON( data ) {
  13458. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  13459. }
  13460. }
  13461. class TorusKnotGeometry extends BufferGeometry {
  13462. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  13463. super();
  13464. this.type = 'TorusKnotGeometry';
  13465. this.parameters = {
  13466. radius: radius,
  13467. tube: tube,
  13468. tubularSegments: tubularSegments,
  13469. radialSegments: radialSegments,
  13470. p: p,
  13471. q: q
  13472. };
  13473. tubularSegments = Math.floor( tubularSegments );
  13474. radialSegments = Math.floor( radialSegments );
  13475. // buffers
  13476. const indices = [];
  13477. const vertices = [];
  13478. const normals = [];
  13479. const uvs = [];
  13480. // helper variables
  13481. const vertex = new Vector3();
  13482. const normal = new Vector3();
  13483. const P1 = new Vector3();
  13484. const P2 = new Vector3();
  13485. const B = new Vector3();
  13486. const T = new Vector3();
  13487. const N = new Vector3();
  13488. // generate vertices, normals and uvs
  13489. for ( let i = 0; i <= tubularSegments; ++ i ) {
  13490. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  13491. const u = i / tubularSegments * p * Math.PI * 2;
  13492. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  13493. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  13494. calculatePositionOnCurve( u, p, q, radius, P1 );
  13495. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  13496. // calculate orthonormal basis
  13497. T.subVectors( P2, P1 );
  13498. N.addVectors( P2, P1 );
  13499. B.crossVectors( T, N );
  13500. N.crossVectors( B, T );
  13501. // normalize B, N. T can be ignored, we don't use it
  13502. B.normalize();
  13503. N.normalize();
  13504. for ( let j = 0; j <= radialSegments; ++ j ) {
  13505. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  13506. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  13507. const v = j / radialSegments * Math.PI * 2;
  13508. const cx = - tube * Math.cos( v );
  13509. const cy = tube * Math.sin( v );
  13510. // now calculate the final vertex position.
  13511. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  13512. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  13513. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  13514. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  13515. vertices.push( vertex.x, vertex.y, vertex.z );
  13516. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  13517. normal.subVectors( vertex, P1 ).normalize();
  13518. normals.push( normal.x, normal.y, normal.z );
  13519. // uv
  13520. uvs.push( i / tubularSegments );
  13521. uvs.push( j / radialSegments );
  13522. }
  13523. }
  13524. // generate indices
  13525. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13526. for ( let i = 1; i <= radialSegments; i ++ ) {
  13527. // indices
  13528. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13529. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13530. const c = ( radialSegments + 1 ) * j + i;
  13531. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13532. // faces
  13533. indices.push( a, b, d );
  13534. indices.push( b, c, d );
  13535. }
  13536. }
  13537. // build geometry
  13538. this.setIndex( indices );
  13539. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13540. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13541. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13542. // this function calculates the current position on the torus curve
  13543. function calculatePositionOnCurve( u, p, q, radius, position ) {
  13544. const cu = Math.cos( u );
  13545. const su = Math.sin( u );
  13546. const quOverP = q / p * u;
  13547. const cs = Math.cos( quOverP );
  13548. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  13549. position.y = radius * ( 2 + cs ) * su * 0.5;
  13550. position.z = radius * Math.sin( quOverP ) * 0.5;
  13551. }
  13552. }
  13553. copy( source ) {
  13554. super.copy( source );
  13555. this.parameters = Object.assign( {}, source.parameters );
  13556. return this;
  13557. }
  13558. static fromJSON( data ) {
  13559. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  13560. }
  13561. }
  13562. class TubeGeometry extends BufferGeometry {
  13563. constructor( path = new QuadraticBezierCurve3( new Vector3( - 1, - 1, 0 ), new Vector3( - 1, 1, 0 ), new Vector3( 1, 1, 0 ) ), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) {
  13564. super();
  13565. this.type = 'TubeGeometry';
  13566. this.parameters = {
  13567. path: path,
  13568. tubularSegments: tubularSegments,
  13569. radius: radius,
  13570. radialSegments: radialSegments,
  13571. closed: closed
  13572. };
  13573. const frames = path.computeFrenetFrames( tubularSegments, closed );
  13574. // expose internals
  13575. this.tangents = frames.tangents;
  13576. this.normals = frames.normals;
  13577. this.binormals = frames.binormals;
  13578. // helper variables
  13579. const vertex = new Vector3();
  13580. const normal = new Vector3();
  13581. const uv = new Vector2();
  13582. let P = new Vector3();
  13583. // buffer
  13584. const vertices = [];
  13585. const normals = [];
  13586. const uvs = [];
  13587. const indices = [];
  13588. // create buffer data
  13589. generateBufferData();
  13590. // build geometry
  13591. this.setIndex( indices );
  13592. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13593. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13594. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13595. // functions
  13596. function generateBufferData() {
  13597. for ( let i = 0; i < tubularSegments; i ++ ) {
  13598. generateSegment( i );
  13599. }
  13600. // if the geometry is not closed, generate the last row of vertices and normals
  13601. // at the regular position on the given path
  13602. //
  13603. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  13604. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  13605. // uvs are generated in a separate function.
  13606. // this makes it easy compute correct values for closed geometries
  13607. generateUVs();
  13608. // finally create faces
  13609. generateIndices();
  13610. }
  13611. function generateSegment( i ) {
  13612. // we use getPointAt to sample evenly distributed points from the given path
  13613. P = path.getPointAt( i / tubularSegments, P );
  13614. // retrieve corresponding normal and binormal
  13615. const N = frames.normals[ i ];
  13616. const B = frames.binormals[ i ];
  13617. // generate normals and vertices for the current segment
  13618. for ( let j = 0; j <= radialSegments; j ++ ) {
  13619. const v = j / radialSegments * Math.PI * 2;
  13620. const sin = Math.sin( v );
  13621. const cos = - Math.cos( v );
  13622. // normal
  13623. normal.x = ( cos * N.x + sin * B.x );
  13624. normal.y = ( cos * N.y + sin * B.y );
  13625. normal.z = ( cos * N.z + sin * B.z );
  13626. normal.normalize();
  13627. normals.push( normal.x, normal.y, normal.z );
  13628. // vertex
  13629. vertex.x = P.x + radius * normal.x;
  13630. vertex.y = P.y + radius * normal.y;
  13631. vertex.z = P.z + radius * normal.z;
  13632. vertices.push( vertex.x, vertex.y, vertex.z );
  13633. }
  13634. }
  13635. function generateIndices() {
  13636. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13637. for ( let i = 1; i <= radialSegments; i ++ ) {
  13638. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13639. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13640. const c = ( radialSegments + 1 ) * j + i;
  13641. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13642. // faces
  13643. indices.push( a, b, d );
  13644. indices.push( b, c, d );
  13645. }
  13646. }
  13647. }
  13648. function generateUVs() {
  13649. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13650. for ( let j = 0; j <= radialSegments; j ++ ) {
  13651. uv.x = i / tubularSegments;
  13652. uv.y = j / radialSegments;
  13653. uvs.push( uv.x, uv.y );
  13654. }
  13655. }
  13656. }
  13657. }
  13658. copy( source ) {
  13659. super.copy( source );
  13660. this.parameters = Object.assign( {}, source.parameters );
  13661. return this;
  13662. }
  13663. toJSON() {
  13664. const data = super.toJSON();
  13665. data.path = this.parameters.path.toJSON();
  13666. return data;
  13667. }
  13668. static fromJSON( data ) {
  13669. // This only works for built-in curves (e.g. CatmullRomCurve3).
  13670. // User defined curves or instances of CurvePath will not be deserialized.
  13671. return new TubeGeometry(
  13672. new Curves[ data.path.type ]().fromJSON( data.path ),
  13673. data.tubularSegments,
  13674. data.radius,
  13675. data.radialSegments,
  13676. data.closed
  13677. );
  13678. }
  13679. }
  13680. class WireframeGeometry extends BufferGeometry {
  13681. constructor( geometry = null ) {
  13682. super();
  13683. this.type = 'WireframeGeometry';
  13684. this.parameters = {
  13685. geometry: geometry
  13686. };
  13687. if ( geometry !== null ) {
  13688. // buffer
  13689. const vertices = [];
  13690. const edges = new Set();
  13691. // helper variables
  13692. const start = new Vector3();
  13693. const end = new Vector3();
  13694. if ( geometry.index !== null ) {
  13695. // indexed BufferGeometry
  13696. const position = geometry.attributes.position;
  13697. const indices = geometry.index;
  13698. let groups = geometry.groups;
  13699. if ( groups.length === 0 ) {
  13700. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  13701. }
  13702. // create a data structure that contains all edges without duplicates
  13703. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  13704. const group = groups[ o ];
  13705. const groupStart = group.start;
  13706. const groupCount = group.count;
  13707. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  13708. for ( let j = 0; j < 3; j ++ ) {
  13709. const index1 = indices.getX( i + j );
  13710. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  13711. start.fromBufferAttribute( position, index1 );
  13712. end.fromBufferAttribute( position, index2 );
  13713. if ( isUniqueEdge( start, end, edges ) === true ) {
  13714. vertices.push( start.x, start.y, start.z );
  13715. vertices.push( end.x, end.y, end.z );
  13716. }
  13717. }
  13718. }
  13719. }
  13720. } else {
  13721. // non-indexed BufferGeometry
  13722. const position = geometry.attributes.position;
  13723. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  13724. for ( let j = 0; j < 3; j ++ ) {
  13725. // three edges per triangle, an edge is represented as (index1, index2)
  13726. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  13727. const index1 = 3 * i + j;
  13728. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  13729. start.fromBufferAttribute( position, index1 );
  13730. end.fromBufferAttribute( position, index2 );
  13731. if ( isUniqueEdge( start, end, edges ) === true ) {
  13732. vertices.push( start.x, start.y, start.z );
  13733. vertices.push( end.x, end.y, end.z );
  13734. }
  13735. }
  13736. }
  13737. }
  13738. // build geometry
  13739. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13740. }
  13741. }
  13742. copy( source ) {
  13743. super.copy( source );
  13744. this.parameters = Object.assign( {}, source.parameters );
  13745. return this;
  13746. }
  13747. }
  13748. function isUniqueEdge( start, end, edges ) {
  13749. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  13750. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  13751. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  13752. return false;
  13753. } else {
  13754. edges.add( hash1 );
  13755. edges.add( hash2 );
  13756. return true;
  13757. }
  13758. }
  13759. var Geometries$1 = /*#__PURE__*/Object.freeze({
  13760. __proto__: null,
  13761. BoxGeometry: BoxGeometry,
  13762. CapsuleGeometry: CapsuleGeometry,
  13763. CircleGeometry: CircleGeometry,
  13764. ConeGeometry: ConeGeometry,
  13765. CylinderGeometry: CylinderGeometry,
  13766. DodecahedronGeometry: DodecahedronGeometry,
  13767. EdgesGeometry: EdgesGeometry,
  13768. ExtrudeGeometry: ExtrudeGeometry,
  13769. IcosahedronGeometry: IcosahedronGeometry,
  13770. LatheGeometry: LatheGeometry,
  13771. OctahedronGeometry: OctahedronGeometry,
  13772. PlaneGeometry: PlaneGeometry,
  13773. PolyhedronGeometry: PolyhedronGeometry,
  13774. RingGeometry: RingGeometry,
  13775. ShapeGeometry: ShapeGeometry,
  13776. SphereGeometry: SphereGeometry,
  13777. TetrahedronGeometry: TetrahedronGeometry,
  13778. TorusGeometry: TorusGeometry,
  13779. TorusKnotGeometry: TorusKnotGeometry,
  13780. TubeGeometry: TubeGeometry,
  13781. WireframeGeometry: WireframeGeometry
  13782. });
  13783. class ShadowMaterial extends Material {
  13784. constructor( parameters ) {
  13785. super();
  13786. this.isShadowMaterial = true;
  13787. this.type = 'ShadowMaterial';
  13788. this.color = new Color( 0x000000 );
  13789. this.transparent = true;
  13790. this.fog = true;
  13791. this.setValues( parameters );
  13792. }
  13793. copy( source ) {
  13794. super.copy( source );
  13795. this.color.copy( source.color );
  13796. this.fog = source.fog;
  13797. return this;
  13798. }
  13799. }
  13800. class RawShaderMaterial extends ShaderMaterial {
  13801. constructor( parameters ) {
  13802. super( parameters );
  13803. this.isRawShaderMaterial = true;
  13804. this.type = 'RawShaderMaterial';
  13805. }
  13806. }
  13807. class MeshStandardMaterial extends Material {
  13808. constructor( parameters ) {
  13809. super();
  13810. this.isMeshStandardMaterial = true;
  13811. this.defines = { 'STANDARD': '' };
  13812. this.type = 'MeshStandardMaterial';
  13813. this.color = new Color( 0xffffff ); // diffuse
  13814. this.roughness = 1.0;
  13815. this.metalness = 0.0;
  13816. this.map = null;
  13817. this.lightMap = null;
  13818. this.lightMapIntensity = 1.0;
  13819. this.aoMap = null;
  13820. this.aoMapIntensity = 1.0;
  13821. this.emissive = new Color( 0x000000 );
  13822. this.emissiveIntensity = 1.0;
  13823. this.emissiveMap = null;
  13824. this.bumpMap = null;
  13825. this.bumpScale = 1;
  13826. this.normalMap = null;
  13827. this.normalMapType = TangentSpaceNormalMap;
  13828. this.normalScale = new Vector2( 1, 1 );
  13829. this.displacementMap = null;
  13830. this.displacementScale = 1;
  13831. this.displacementBias = 0;
  13832. this.roughnessMap = null;
  13833. this.metalnessMap = null;
  13834. this.alphaMap = null;
  13835. this.envMap = null;
  13836. this.envMapRotation = new Euler();
  13837. this.envMapIntensity = 1.0;
  13838. this.wireframe = false;
  13839. this.wireframeLinewidth = 1;
  13840. this.wireframeLinecap = 'round';
  13841. this.wireframeLinejoin = 'round';
  13842. this.flatShading = false;
  13843. this.fog = true;
  13844. this.setValues( parameters );
  13845. }
  13846. copy( source ) {
  13847. super.copy( source );
  13848. this.defines = { 'STANDARD': '' };
  13849. this.color.copy( source.color );
  13850. this.roughness = source.roughness;
  13851. this.metalness = source.metalness;
  13852. this.map = source.map;
  13853. this.lightMap = source.lightMap;
  13854. this.lightMapIntensity = source.lightMapIntensity;
  13855. this.aoMap = source.aoMap;
  13856. this.aoMapIntensity = source.aoMapIntensity;
  13857. this.emissive.copy( source.emissive );
  13858. this.emissiveMap = source.emissiveMap;
  13859. this.emissiveIntensity = source.emissiveIntensity;
  13860. this.bumpMap = source.bumpMap;
  13861. this.bumpScale = source.bumpScale;
  13862. this.normalMap = source.normalMap;
  13863. this.normalMapType = source.normalMapType;
  13864. this.normalScale.copy( source.normalScale );
  13865. this.displacementMap = source.displacementMap;
  13866. this.displacementScale = source.displacementScale;
  13867. this.displacementBias = source.displacementBias;
  13868. this.roughnessMap = source.roughnessMap;
  13869. this.metalnessMap = source.metalnessMap;
  13870. this.alphaMap = source.alphaMap;
  13871. this.envMap = source.envMap;
  13872. this.envMapRotation.copy( source.envMapRotation );
  13873. this.envMapIntensity = source.envMapIntensity;
  13874. this.wireframe = source.wireframe;
  13875. this.wireframeLinewidth = source.wireframeLinewidth;
  13876. this.wireframeLinecap = source.wireframeLinecap;
  13877. this.wireframeLinejoin = source.wireframeLinejoin;
  13878. this.flatShading = source.flatShading;
  13879. this.fog = source.fog;
  13880. return this;
  13881. }
  13882. }
  13883. class MeshPhysicalMaterial extends MeshStandardMaterial {
  13884. constructor( parameters ) {
  13885. super();
  13886. this.isMeshPhysicalMaterial = true;
  13887. this.defines = {
  13888. 'STANDARD': '',
  13889. 'PHYSICAL': ''
  13890. };
  13891. this.type = 'MeshPhysicalMaterial';
  13892. this.anisotropyRotation = 0;
  13893. this.anisotropyMap = null;
  13894. this.clearcoatMap = null;
  13895. this.clearcoatRoughness = 0.0;
  13896. this.clearcoatRoughnessMap = null;
  13897. this.clearcoatNormalScale = new Vector2( 1, 1 );
  13898. this.clearcoatNormalMap = null;
  13899. this.ior = 1.5;
  13900. Object.defineProperty( this, 'reflectivity', {
  13901. get: function () {
  13902. return ( clamp$1( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  13903. },
  13904. set: function ( reflectivity ) {
  13905. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  13906. }
  13907. } );
  13908. this.iridescenceMap = null;
  13909. this.iridescenceIOR = 1.3;
  13910. this.iridescenceThicknessRange = [ 100, 400 ];
  13911. this.iridescenceThicknessMap = null;
  13912. this.sheenColor = new Color( 0x000000 );
  13913. this.sheenColorMap = null;
  13914. this.sheenRoughness = 1.0;
  13915. this.sheenRoughnessMap = null;
  13916. this.transmissionMap = null;
  13917. this.thickness = 0;
  13918. this.thicknessMap = null;
  13919. this.attenuationDistance = Infinity;
  13920. this.attenuationColor = new Color( 1, 1, 1 );
  13921. this.specularIntensity = 1.0;
  13922. this.specularIntensityMap = null;
  13923. this.specularColor = new Color( 1, 1, 1 );
  13924. this.specularColorMap = null;
  13925. this._anisotropy = 0;
  13926. this._clearcoat = 0;
  13927. this._dispersion = 0;
  13928. this._iridescence = 0;
  13929. this._sheen = 0.0;
  13930. this._transmission = 0;
  13931. this.setValues( parameters );
  13932. }
  13933. get anisotropy() {
  13934. return this._anisotropy;
  13935. }
  13936. set anisotropy( value ) {
  13937. if ( this._anisotropy > 0 !== value > 0 ) {
  13938. this.version ++;
  13939. }
  13940. this._anisotropy = value;
  13941. }
  13942. get clearcoat() {
  13943. return this._clearcoat;
  13944. }
  13945. set clearcoat( value ) {
  13946. if ( this._clearcoat > 0 !== value > 0 ) {
  13947. this.version ++;
  13948. }
  13949. this._clearcoat = value;
  13950. }
  13951. get iridescence() {
  13952. return this._iridescence;
  13953. }
  13954. set iridescence( value ) {
  13955. if ( this._iridescence > 0 !== value > 0 ) {
  13956. this.version ++;
  13957. }
  13958. this._iridescence = value;
  13959. }
  13960. get dispersion() {
  13961. return this._dispersion;
  13962. }
  13963. set dispersion( value ) {
  13964. if ( this._dispersion > 0 !== value > 0 ) {
  13965. this.version ++;
  13966. }
  13967. this._dispersion = value;
  13968. }
  13969. get sheen() {
  13970. return this._sheen;
  13971. }
  13972. set sheen( value ) {
  13973. if ( this._sheen > 0 !== value > 0 ) {
  13974. this.version ++;
  13975. }
  13976. this._sheen = value;
  13977. }
  13978. get transmission() {
  13979. return this._transmission;
  13980. }
  13981. set transmission( value ) {
  13982. if ( this._transmission > 0 !== value > 0 ) {
  13983. this.version ++;
  13984. }
  13985. this._transmission = value;
  13986. }
  13987. copy( source ) {
  13988. super.copy( source );
  13989. this.defines = {
  13990. 'STANDARD': '',
  13991. 'PHYSICAL': ''
  13992. };
  13993. this.anisotropy = source.anisotropy;
  13994. this.anisotropyRotation = source.anisotropyRotation;
  13995. this.anisotropyMap = source.anisotropyMap;
  13996. this.clearcoat = source.clearcoat;
  13997. this.clearcoatMap = source.clearcoatMap;
  13998. this.clearcoatRoughness = source.clearcoatRoughness;
  13999. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  14000. this.clearcoatNormalMap = source.clearcoatNormalMap;
  14001. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  14002. this.dispersion = source.dispersion;
  14003. this.ior = source.ior;
  14004. this.iridescence = source.iridescence;
  14005. this.iridescenceMap = source.iridescenceMap;
  14006. this.iridescenceIOR = source.iridescenceIOR;
  14007. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  14008. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  14009. this.sheen = source.sheen;
  14010. this.sheenColor.copy( source.sheenColor );
  14011. this.sheenColorMap = source.sheenColorMap;
  14012. this.sheenRoughness = source.sheenRoughness;
  14013. this.sheenRoughnessMap = source.sheenRoughnessMap;
  14014. this.transmission = source.transmission;
  14015. this.transmissionMap = source.transmissionMap;
  14016. this.thickness = source.thickness;
  14017. this.thicknessMap = source.thicknessMap;
  14018. this.attenuationDistance = source.attenuationDistance;
  14019. this.attenuationColor.copy( source.attenuationColor );
  14020. this.specularIntensity = source.specularIntensity;
  14021. this.specularIntensityMap = source.specularIntensityMap;
  14022. this.specularColor.copy( source.specularColor );
  14023. this.specularColorMap = source.specularColorMap;
  14024. return this;
  14025. }
  14026. }
  14027. class MeshPhongMaterial extends Material {
  14028. constructor( parameters ) {
  14029. super();
  14030. this.isMeshPhongMaterial = true;
  14031. this.type = 'MeshPhongMaterial';
  14032. this.color = new Color( 0xffffff ); // diffuse
  14033. this.specular = new Color( 0x111111 );
  14034. this.shininess = 30;
  14035. this.map = null;
  14036. this.lightMap = null;
  14037. this.lightMapIntensity = 1.0;
  14038. this.aoMap = null;
  14039. this.aoMapIntensity = 1.0;
  14040. this.emissive = new Color( 0x000000 );
  14041. this.emissiveIntensity = 1.0;
  14042. this.emissiveMap = null;
  14043. this.bumpMap = null;
  14044. this.bumpScale = 1;
  14045. this.normalMap = null;
  14046. this.normalMapType = TangentSpaceNormalMap;
  14047. this.normalScale = new Vector2( 1, 1 );
  14048. this.displacementMap = null;
  14049. this.displacementScale = 1;
  14050. this.displacementBias = 0;
  14051. this.specularMap = null;
  14052. this.alphaMap = null;
  14053. this.envMap = null;
  14054. this.envMapRotation = new Euler();
  14055. this.combine = MultiplyOperation;
  14056. this.reflectivity = 1;
  14057. this.refractionRatio = 0.98;
  14058. this.wireframe = false;
  14059. this.wireframeLinewidth = 1;
  14060. this.wireframeLinecap = 'round';
  14061. this.wireframeLinejoin = 'round';
  14062. this.flatShading = false;
  14063. this.fog = true;
  14064. this.setValues( parameters );
  14065. }
  14066. copy( source ) {
  14067. super.copy( source );
  14068. this.color.copy( source.color );
  14069. this.specular.copy( source.specular );
  14070. this.shininess = source.shininess;
  14071. this.map = source.map;
  14072. this.lightMap = source.lightMap;
  14073. this.lightMapIntensity = source.lightMapIntensity;
  14074. this.aoMap = source.aoMap;
  14075. this.aoMapIntensity = source.aoMapIntensity;
  14076. this.emissive.copy( source.emissive );
  14077. this.emissiveMap = source.emissiveMap;
  14078. this.emissiveIntensity = source.emissiveIntensity;
  14079. this.bumpMap = source.bumpMap;
  14080. this.bumpScale = source.bumpScale;
  14081. this.normalMap = source.normalMap;
  14082. this.normalMapType = source.normalMapType;
  14083. this.normalScale.copy( source.normalScale );
  14084. this.displacementMap = source.displacementMap;
  14085. this.displacementScale = source.displacementScale;
  14086. this.displacementBias = source.displacementBias;
  14087. this.specularMap = source.specularMap;
  14088. this.alphaMap = source.alphaMap;
  14089. this.envMap = source.envMap;
  14090. this.envMapRotation.copy( source.envMapRotation );
  14091. this.combine = source.combine;
  14092. this.reflectivity = source.reflectivity;
  14093. this.refractionRatio = source.refractionRatio;
  14094. this.wireframe = source.wireframe;
  14095. this.wireframeLinewidth = source.wireframeLinewidth;
  14096. this.wireframeLinecap = source.wireframeLinecap;
  14097. this.wireframeLinejoin = source.wireframeLinejoin;
  14098. this.flatShading = source.flatShading;
  14099. this.fog = source.fog;
  14100. return this;
  14101. }
  14102. }
  14103. class MeshToonMaterial extends Material {
  14104. constructor( parameters ) {
  14105. super();
  14106. this.isMeshToonMaterial = true;
  14107. this.defines = { 'TOON': '' };
  14108. this.type = 'MeshToonMaterial';
  14109. this.color = new Color( 0xffffff );
  14110. this.map = null;
  14111. this.gradientMap = null;
  14112. this.lightMap = null;
  14113. this.lightMapIntensity = 1.0;
  14114. this.aoMap = null;
  14115. this.aoMapIntensity = 1.0;
  14116. this.emissive = new Color( 0x000000 );
  14117. this.emissiveIntensity = 1.0;
  14118. this.emissiveMap = null;
  14119. this.bumpMap = null;
  14120. this.bumpScale = 1;
  14121. this.normalMap = null;
  14122. this.normalMapType = TangentSpaceNormalMap;
  14123. this.normalScale = new Vector2( 1, 1 );
  14124. this.displacementMap = null;
  14125. this.displacementScale = 1;
  14126. this.displacementBias = 0;
  14127. this.alphaMap = null;
  14128. this.wireframe = false;
  14129. this.wireframeLinewidth = 1;
  14130. this.wireframeLinecap = 'round';
  14131. this.wireframeLinejoin = 'round';
  14132. this.fog = true;
  14133. this.setValues( parameters );
  14134. }
  14135. copy( source ) {
  14136. super.copy( source );
  14137. this.color.copy( source.color );
  14138. this.map = source.map;
  14139. this.gradientMap = source.gradientMap;
  14140. this.lightMap = source.lightMap;
  14141. this.lightMapIntensity = source.lightMapIntensity;
  14142. this.aoMap = source.aoMap;
  14143. this.aoMapIntensity = source.aoMapIntensity;
  14144. this.emissive.copy( source.emissive );
  14145. this.emissiveMap = source.emissiveMap;
  14146. this.emissiveIntensity = source.emissiveIntensity;
  14147. this.bumpMap = source.bumpMap;
  14148. this.bumpScale = source.bumpScale;
  14149. this.normalMap = source.normalMap;
  14150. this.normalMapType = source.normalMapType;
  14151. this.normalScale.copy( source.normalScale );
  14152. this.displacementMap = source.displacementMap;
  14153. this.displacementScale = source.displacementScale;
  14154. this.displacementBias = source.displacementBias;
  14155. this.alphaMap = source.alphaMap;
  14156. this.wireframe = source.wireframe;
  14157. this.wireframeLinewidth = source.wireframeLinewidth;
  14158. this.wireframeLinecap = source.wireframeLinecap;
  14159. this.wireframeLinejoin = source.wireframeLinejoin;
  14160. this.fog = source.fog;
  14161. return this;
  14162. }
  14163. }
  14164. class MeshNormalMaterial extends Material {
  14165. constructor( parameters ) {
  14166. super();
  14167. this.isMeshNormalMaterial = true;
  14168. this.type = 'MeshNormalMaterial';
  14169. this.bumpMap = null;
  14170. this.bumpScale = 1;
  14171. this.normalMap = null;
  14172. this.normalMapType = TangentSpaceNormalMap;
  14173. this.normalScale = new Vector2( 1, 1 );
  14174. this.displacementMap = null;
  14175. this.displacementScale = 1;
  14176. this.displacementBias = 0;
  14177. this.wireframe = false;
  14178. this.wireframeLinewidth = 1;
  14179. this.flatShading = false;
  14180. this.setValues( parameters );
  14181. }
  14182. copy( source ) {
  14183. super.copy( source );
  14184. this.bumpMap = source.bumpMap;
  14185. this.bumpScale = source.bumpScale;
  14186. this.normalMap = source.normalMap;
  14187. this.normalMapType = source.normalMapType;
  14188. this.normalScale.copy( source.normalScale );
  14189. this.displacementMap = source.displacementMap;
  14190. this.displacementScale = source.displacementScale;
  14191. this.displacementBias = source.displacementBias;
  14192. this.wireframe = source.wireframe;
  14193. this.wireframeLinewidth = source.wireframeLinewidth;
  14194. this.flatShading = source.flatShading;
  14195. return this;
  14196. }
  14197. }
  14198. class MeshLambertMaterial extends Material {
  14199. constructor( parameters ) {
  14200. super();
  14201. this.isMeshLambertMaterial = true;
  14202. this.type = 'MeshLambertMaterial';
  14203. this.color = new Color( 0xffffff ); // diffuse
  14204. this.map = null;
  14205. this.lightMap = null;
  14206. this.lightMapIntensity = 1.0;
  14207. this.aoMap = null;
  14208. this.aoMapIntensity = 1.0;
  14209. this.emissive = new Color( 0x000000 );
  14210. this.emissiveIntensity = 1.0;
  14211. this.emissiveMap = null;
  14212. this.bumpMap = null;
  14213. this.bumpScale = 1;
  14214. this.normalMap = null;
  14215. this.normalMapType = TangentSpaceNormalMap;
  14216. this.normalScale = new Vector2( 1, 1 );
  14217. this.displacementMap = null;
  14218. this.displacementScale = 1;
  14219. this.displacementBias = 0;
  14220. this.specularMap = null;
  14221. this.alphaMap = null;
  14222. this.envMap = null;
  14223. this.envMapRotation = new Euler();
  14224. this.combine = MultiplyOperation;
  14225. this.reflectivity = 1;
  14226. this.refractionRatio = 0.98;
  14227. this.wireframe = false;
  14228. this.wireframeLinewidth = 1;
  14229. this.wireframeLinecap = 'round';
  14230. this.wireframeLinejoin = 'round';
  14231. this.flatShading = false;
  14232. this.fog = true;
  14233. this.setValues( parameters );
  14234. }
  14235. copy( source ) {
  14236. super.copy( source );
  14237. this.color.copy( source.color );
  14238. this.map = source.map;
  14239. this.lightMap = source.lightMap;
  14240. this.lightMapIntensity = source.lightMapIntensity;
  14241. this.aoMap = source.aoMap;
  14242. this.aoMapIntensity = source.aoMapIntensity;
  14243. this.emissive.copy( source.emissive );
  14244. this.emissiveMap = source.emissiveMap;
  14245. this.emissiveIntensity = source.emissiveIntensity;
  14246. this.bumpMap = source.bumpMap;
  14247. this.bumpScale = source.bumpScale;
  14248. this.normalMap = source.normalMap;
  14249. this.normalMapType = source.normalMapType;
  14250. this.normalScale.copy( source.normalScale );
  14251. this.displacementMap = source.displacementMap;
  14252. this.displacementScale = source.displacementScale;
  14253. this.displacementBias = source.displacementBias;
  14254. this.specularMap = source.specularMap;
  14255. this.alphaMap = source.alphaMap;
  14256. this.envMap = source.envMap;
  14257. this.envMapRotation.copy( source.envMapRotation );
  14258. this.combine = source.combine;
  14259. this.reflectivity = source.reflectivity;
  14260. this.refractionRatio = source.refractionRatio;
  14261. this.wireframe = source.wireframe;
  14262. this.wireframeLinewidth = source.wireframeLinewidth;
  14263. this.wireframeLinecap = source.wireframeLinecap;
  14264. this.wireframeLinejoin = source.wireframeLinejoin;
  14265. this.flatShading = source.flatShading;
  14266. this.fog = source.fog;
  14267. return this;
  14268. }
  14269. }
  14270. class MeshDepthMaterial extends Material {
  14271. constructor( parameters ) {
  14272. super();
  14273. this.isMeshDepthMaterial = true;
  14274. this.type = 'MeshDepthMaterial';
  14275. this.depthPacking = BasicDepthPacking;
  14276. this.map = null;
  14277. this.alphaMap = null;
  14278. this.displacementMap = null;
  14279. this.displacementScale = 1;
  14280. this.displacementBias = 0;
  14281. this.wireframe = false;
  14282. this.wireframeLinewidth = 1;
  14283. this.setValues( parameters );
  14284. }
  14285. copy( source ) {
  14286. super.copy( source );
  14287. this.depthPacking = source.depthPacking;
  14288. this.map = source.map;
  14289. this.alphaMap = source.alphaMap;
  14290. this.displacementMap = source.displacementMap;
  14291. this.displacementScale = source.displacementScale;
  14292. this.displacementBias = source.displacementBias;
  14293. this.wireframe = source.wireframe;
  14294. this.wireframeLinewidth = source.wireframeLinewidth;
  14295. return this;
  14296. }
  14297. }
  14298. class MeshDistanceMaterial extends Material {
  14299. constructor( parameters ) {
  14300. super();
  14301. this.isMeshDistanceMaterial = true;
  14302. this.type = 'MeshDistanceMaterial';
  14303. this.map = null;
  14304. this.alphaMap = null;
  14305. this.displacementMap = null;
  14306. this.displacementScale = 1;
  14307. this.displacementBias = 0;
  14308. this.setValues( parameters );
  14309. }
  14310. copy( source ) {
  14311. super.copy( source );
  14312. this.map = source.map;
  14313. this.alphaMap = source.alphaMap;
  14314. this.displacementMap = source.displacementMap;
  14315. this.displacementScale = source.displacementScale;
  14316. this.displacementBias = source.displacementBias;
  14317. return this;
  14318. }
  14319. }
  14320. class MeshMatcapMaterial extends Material {
  14321. constructor( parameters ) {
  14322. super();
  14323. this.isMeshMatcapMaterial = true;
  14324. this.defines = { 'MATCAP': '' };
  14325. this.type = 'MeshMatcapMaterial';
  14326. this.color = new Color( 0xffffff ); // diffuse
  14327. this.matcap = null;
  14328. this.map = null;
  14329. this.bumpMap = null;
  14330. this.bumpScale = 1;
  14331. this.normalMap = null;
  14332. this.normalMapType = TangentSpaceNormalMap;
  14333. this.normalScale = new Vector2( 1, 1 );
  14334. this.displacementMap = null;
  14335. this.displacementScale = 1;
  14336. this.displacementBias = 0;
  14337. this.alphaMap = null;
  14338. this.flatShading = false;
  14339. this.fog = true;
  14340. this.setValues( parameters );
  14341. }
  14342. copy( source ) {
  14343. super.copy( source );
  14344. this.defines = { 'MATCAP': '' };
  14345. this.color.copy( source.color );
  14346. this.matcap = source.matcap;
  14347. this.map = source.map;
  14348. this.bumpMap = source.bumpMap;
  14349. this.bumpScale = source.bumpScale;
  14350. this.normalMap = source.normalMap;
  14351. this.normalMapType = source.normalMapType;
  14352. this.normalScale.copy( source.normalScale );
  14353. this.displacementMap = source.displacementMap;
  14354. this.displacementScale = source.displacementScale;
  14355. this.displacementBias = source.displacementBias;
  14356. this.alphaMap = source.alphaMap;
  14357. this.flatShading = source.flatShading;
  14358. this.fog = source.fog;
  14359. return this;
  14360. }
  14361. }
  14362. class LineDashedMaterial extends LineBasicMaterial {
  14363. constructor( parameters ) {
  14364. super();
  14365. this.isLineDashedMaterial = true;
  14366. this.type = 'LineDashedMaterial';
  14367. this.scale = 1;
  14368. this.dashSize = 3;
  14369. this.gapSize = 1;
  14370. this.setValues( parameters );
  14371. }
  14372. copy( source ) {
  14373. super.copy( source );
  14374. this.scale = source.scale;
  14375. this.dashSize = source.dashSize;
  14376. this.gapSize = source.gapSize;
  14377. return this;
  14378. }
  14379. }
  14380. // converts an array to a specific type
  14381. function convertArray( array, type, forceClone ) {
  14382. if ( ! array || // let 'undefined' and 'null' pass
  14383. ! forceClone && array.constructor === type ) return array;
  14384. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  14385. return new type( array ); // create typed array
  14386. }
  14387. return Array.prototype.slice.call( array ); // create Array
  14388. }
  14389. function isTypedArray( object ) {
  14390. return ArrayBuffer.isView( object ) &&
  14391. ! ( object instanceof DataView );
  14392. }
  14393. // returns an array by which times and values can be sorted
  14394. function getKeyframeOrder( times ) {
  14395. function compareTime( i, j ) {
  14396. return times[ i ] - times[ j ];
  14397. }
  14398. const n = times.length;
  14399. const result = new Array( n );
  14400. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  14401. result.sort( compareTime );
  14402. return result;
  14403. }
  14404. // uses the array previously returned by 'getKeyframeOrder' to sort data
  14405. function sortedArray( values, stride, order ) {
  14406. const nValues = values.length;
  14407. const result = new values.constructor( nValues );
  14408. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  14409. const srcOffset = order[ i ] * stride;
  14410. for ( let j = 0; j !== stride; ++ j ) {
  14411. result[ dstOffset ++ ] = values[ srcOffset + j ];
  14412. }
  14413. }
  14414. return result;
  14415. }
  14416. // function for parsing AOS keyframe formats
  14417. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  14418. let i = 1, key = jsonKeys[ 0 ];
  14419. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  14420. key = jsonKeys[ i ++ ];
  14421. }
  14422. if ( key === undefined ) return; // no data
  14423. let value = key[ valuePropertyName ];
  14424. if ( value === undefined ) return; // no data
  14425. if ( Array.isArray( value ) ) {
  14426. do {
  14427. value = key[ valuePropertyName ];
  14428. if ( value !== undefined ) {
  14429. times.push( key.time );
  14430. values.push.apply( values, value ); // push all elements
  14431. }
  14432. key = jsonKeys[ i ++ ];
  14433. } while ( key !== undefined );
  14434. } else if ( value.toArray !== undefined ) {
  14435. // ...assume THREE.Math-ish
  14436. do {
  14437. value = key[ valuePropertyName ];
  14438. if ( value !== undefined ) {
  14439. times.push( key.time );
  14440. value.toArray( values, values.length );
  14441. }
  14442. key = jsonKeys[ i ++ ];
  14443. } while ( key !== undefined );
  14444. } else {
  14445. // otherwise push as-is
  14446. do {
  14447. value = key[ valuePropertyName ];
  14448. if ( value !== undefined ) {
  14449. times.push( key.time );
  14450. values.push( value );
  14451. }
  14452. key = jsonKeys[ i ++ ];
  14453. } while ( key !== undefined );
  14454. }
  14455. }
  14456. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  14457. const clip = sourceClip.clone();
  14458. clip.name = name;
  14459. const tracks = [];
  14460. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14461. const track = clip.tracks[ i ];
  14462. const valueSize = track.getValueSize();
  14463. const times = [];
  14464. const values = [];
  14465. for ( let j = 0; j < track.times.length; ++ j ) {
  14466. const frame = track.times[ j ] * fps;
  14467. if ( frame < startFrame || frame >= endFrame ) continue;
  14468. times.push( track.times[ j ] );
  14469. for ( let k = 0; k < valueSize; ++ k ) {
  14470. values.push( track.values[ j * valueSize + k ] );
  14471. }
  14472. }
  14473. if ( times.length === 0 ) continue;
  14474. track.times = convertArray( times, track.times.constructor );
  14475. track.values = convertArray( values, track.values.constructor );
  14476. tracks.push( track );
  14477. }
  14478. clip.tracks = tracks;
  14479. // find minimum .times value across all tracks in the trimmed clip
  14480. let minStartTime = Infinity;
  14481. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14482. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  14483. minStartTime = clip.tracks[ i ].times[ 0 ];
  14484. }
  14485. }
  14486. // shift all tracks such that clip begins at t=0
  14487. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14488. clip.tracks[ i ].shift( - 1 * minStartTime );
  14489. }
  14490. clip.resetDuration();
  14491. return clip;
  14492. }
  14493. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  14494. if ( fps <= 0 ) fps = 30;
  14495. const numTracks = referenceClip.tracks.length;
  14496. const referenceTime = referenceFrame / fps;
  14497. // Make each track's values relative to the values at the reference frame
  14498. for ( let i = 0; i < numTracks; ++ i ) {
  14499. const referenceTrack = referenceClip.tracks[ i ];
  14500. const referenceTrackType = referenceTrack.ValueTypeName;
  14501. // Skip this track if it's non-numeric
  14502. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  14503. // Find the track in the target clip whose name and type matches the reference track
  14504. const targetTrack = targetClip.tracks.find( function ( track ) {
  14505. return track.name === referenceTrack.name
  14506. && track.ValueTypeName === referenceTrackType;
  14507. } );
  14508. if ( targetTrack === undefined ) continue;
  14509. let referenceOffset = 0;
  14510. const referenceValueSize = referenceTrack.getValueSize();
  14511. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14512. referenceOffset = referenceValueSize / 3;
  14513. }
  14514. let targetOffset = 0;
  14515. const targetValueSize = targetTrack.getValueSize();
  14516. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14517. targetOffset = targetValueSize / 3;
  14518. }
  14519. const lastIndex = referenceTrack.times.length - 1;
  14520. let referenceValue;
  14521. // Find the value to subtract out of the track
  14522. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  14523. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  14524. const startIndex = referenceOffset;
  14525. const endIndex = referenceValueSize - referenceOffset;
  14526. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14527. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  14528. // Reference frame is after the last keyframe, so just use the last keyframe
  14529. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  14530. const endIndex = startIndex + referenceValueSize - referenceOffset;
  14531. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14532. } else {
  14533. // Interpolate to the reference value
  14534. const interpolant = referenceTrack.createInterpolant();
  14535. const startIndex = referenceOffset;
  14536. const endIndex = referenceValueSize - referenceOffset;
  14537. interpolant.evaluate( referenceTime );
  14538. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  14539. }
  14540. // Conjugate the quaternion
  14541. if ( referenceTrackType === 'quaternion' ) {
  14542. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  14543. referenceQuat.toArray( referenceValue );
  14544. }
  14545. // Subtract the reference value from all of the track values
  14546. const numTimes = targetTrack.times.length;
  14547. for ( let j = 0; j < numTimes; ++ j ) {
  14548. const valueStart = j * targetValueSize + targetOffset;
  14549. if ( referenceTrackType === 'quaternion' ) {
  14550. // Multiply the conjugate for quaternion track types
  14551. Quaternion.multiplyQuaternionsFlat(
  14552. targetTrack.values,
  14553. valueStart,
  14554. referenceValue,
  14555. 0,
  14556. targetTrack.values,
  14557. valueStart
  14558. );
  14559. } else {
  14560. const valueEnd = targetValueSize - targetOffset * 2;
  14561. // Subtract each value for all other numeric track types
  14562. for ( let k = 0; k < valueEnd; ++ k ) {
  14563. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  14564. }
  14565. }
  14566. }
  14567. }
  14568. targetClip.blendMode = AdditiveAnimationBlendMode;
  14569. return targetClip;
  14570. }
  14571. const AnimationUtils = {
  14572. convertArray: convertArray,
  14573. isTypedArray: isTypedArray,
  14574. getKeyframeOrder: getKeyframeOrder,
  14575. sortedArray: sortedArray,
  14576. flattenJSON: flattenJSON,
  14577. subclip: subclip,
  14578. makeClipAdditive: makeClipAdditive
  14579. };
  14580. /**
  14581. * Abstract base class of interpolants over parametric samples.
  14582. *
  14583. * The parameter domain is one dimensional, typically the time or a path
  14584. * along a curve defined by the data.
  14585. *
  14586. * The sample values can have any dimensionality and derived classes may
  14587. * apply special interpretations to the data.
  14588. *
  14589. * This class provides the interval seek in a Template Method, deferring
  14590. * the actual interpolation to derived classes.
  14591. *
  14592. * Time complexity is O(1) for linear access crossing at most two points
  14593. * and O(log N) for random access, where N is the number of positions.
  14594. *
  14595. * References:
  14596. *
  14597. * http://www.oodesign.com/template-method-pattern.html
  14598. *
  14599. */
  14600. class Interpolant {
  14601. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14602. this.parameterPositions = parameterPositions;
  14603. this._cachedIndex = 0;
  14604. this.resultBuffer = resultBuffer !== undefined ?
  14605. resultBuffer : new sampleValues.constructor( sampleSize );
  14606. this.sampleValues = sampleValues;
  14607. this.valueSize = sampleSize;
  14608. this.settings = null;
  14609. this.DefaultSettings_ = {};
  14610. }
  14611. evaluate( t ) {
  14612. const pp = this.parameterPositions;
  14613. let i1 = this._cachedIndex,
  14614. t1 = pp[ i1 ],
  14615. t0 = pp[ i1 - 1 ];
  14616. validate_interval: {
  14617. seek: {
  14618. let right;
  14619. linear_scan: {
  14620. //- See http://jsperf.com/comparison-to-undefined/3
  14621. //- slower code:
  14622. //-
  14623. //- if ( t >= t1 || t1 === undefined ) {
  14624. forward_scan: if ( ! ( t < t1 ) ) {
  14625. for ( let giveUpAt = i1 + 2; ; ) {
  14626. if ( t1 === undefined ) {
  14627. if ( t < t0 ) break forward_scan;
  14628. // after end
  14629. i1 = pp.length;
  14630. this._cachedIndex = i1;
  14631. return this.copySampleValue_( i1 - 1 );
  14632. }
  14633. if ( i1 === giveUpAt ) break; // this loop
  14634. t0 = t1;
  14635. t1 = pp[ ++ i1 ];
  14636. if ( t < t1 ) {
  14637. // we have arrived at the sought interval
  14638. break seek;
  14639. }
  14640. }
  14641. // prepare binary search on the right side of the index
  14642. right = pp.length;
  14643. break linear_scan;
  14644. }
  14645. //- slower code:
  14646. //- if ( t < t0 || t0 === undefined ) {
  14647. if ( ! ( t >= t0 ) ) {
  14648. // looping?
  14649. const t1global = pp[ 1 ];
  14650. if ( t < t1global ) {
  14651. i1 = 2; // + 1, using the scan for the details
  14652. t0 = t1global;
  14653. }
  14654. // linear reverse scan
  14655. for ( let giveUpAt = i1 - 2; ; ) {
  14656. if ( t0 === undefined ) {
  14657. // before start
  14658. this._cachedIndex = 0;
  14659. return this.copySampleValue_( 0 );
  14660. }
  14661. if ( i1 === giveUpAt ) break; // this loop
  14662. t1 = t0;
  14663. t0 = pp[ -- i1 - 1 ];
  14664. if ( t >= t0 ) {
  14665. // we have arrived at the sought interval
  14666. break seek;
  14667. }
  14668. }
  14669. // prepare binary search on the left side of the index
  14670. right = i1;
  14671. i1 = 0;
  14672. break linear_scan;
  14673. }
  14674. // the interval is valid
  14675. break validate_interval;
  14676. } // linear scan
  14677. // binary search
  14678. while ( i1 < right ) {
  14679. const mid = ( i1 + right ) >>> 1;
  14680. if ( t < pp[ mid ] ) {
  14681. right = mid;
  14682. } else {
  14683. i1 = mid + 1;
  14684. }
  14685. }
  14686. t1 = pp[ i1 ];
  14687. t0 = pp[ i1 - 1 ];
  14688. // check boundary cases, again
  14689. if ( t0 === undefined ) {
  14690. this._cachedIndex = 0;
  14691. return this.copySampleValue_( 0 );
  14692. }
  14693. if ( t1 === undefined ) {
  14694. i1 = pp.length;
  14695. this._cachedIndex = i1;
  14696. return this.copySampleValue_( i1 - 1 );
  14697. }
  14698. } // seek
  14699. this._cachedIndex = i1;
  14700. this.intervalChanged_( i1, t0, t1 );
  14701. } // validate_interval
  14702. return this.interpolate_( i1, t0, t, t1 );
  14703. }
  14704. getSettings_() {
  14705. return this.settings || this.DefaultSettings_;
  14706. }
  14707. copySampleValue_( index ) {
  14708. // copies a sample value to the result buffer
  14709. const result = this.resultBuffer,
  14710. values = this.sampleValues,
  14711. stride = this.valueSize,
  14712. offset = index * stride;
  14713. for ( let i = 0; i !== stride; ++ i ) {
  14714. result[ i ] = values[ offset + i ];
  14715. }
  14716. return result;
  14717. }
  14718. // Template methods for derived classes:
  14719. interpolate_( /* i1, t0, t, t1 */ ) {
  14720. throw new Error( 'call to abstract method' );
  14721. // implementations shall return this.resultBuffer
  14722. }
  14723. intervalChanged_( /* i1, t0, t1 */ ) {
  14724. // empty
  14725. }
  14726. }
  14727. /**
  14728. * Fast and simple cubic spline interpolant.
  14729. *
  14730. * It was derived from a Hermitian construction setting the first derivative
  14731. * at each sample position to the linear slope between neighboring positions
  14732. * over their parameter interval.
  14733. */
  14734. class CubicInterpolant extends Interpolant {
  14735. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14736. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14737. this._weightPrev = - 0;
  14738. this._offsetPrev = - 0;
  14739. this._weightNext = - 0;
  14740. this._offsetNext = - 0;
  14741. this.DefaultSettings_ = {
  14742. endingStart: ZeroCurvatureEnding,
  14743. endingEnd: ZeroCurvatureEnding
  14744. };
  14745. }
  14746. intervalChanged_( i1, t0, t1 ) {
  14747. const pp = this.parameterPositions;
  14748. let iPrev = i1 - 2,
  14749. iNext = i1 + 1,
  14750. tPrev = pp[ iPrev ],
  14751. tNext = pp[ iNext ];
  14752. if ( tPrev === undefined ) {
  14753. switch ( this.getSettings_().endingStart ) {
  14754. case ZeroSlopeEnding:
  14755. // f'(t0) = 0
  14756. iPrev = i1;
  14757. tPrev = 2 * t0 - t1;
  14758. break;
  14759. case WrapAroundEnding:
  14760. // use the other end of the curve
  14761. iPrev = pp.length - 2;
  14762. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  14763. break;
  14764. default: // ZeroCurvatureEnding
  14765. // f''(t0) = 0 a.k.a. Natural Spline
  14766. iPrev = i1;
  14767. tPrev = t1;
  14768. }
  14769. }
  14770. if ( tNext === undefined ) {
  14771. switch ( this.getSettings_().endingEnd ) {
  14772. case ZeroSlopeEnding:
  14773. // f'(tN) = 0
  14774. iNext = i1;
  14775. tNext = 2 * t1 - t0;
  14776. break;
  14777. case WrapAroundEnding:
  14778. // use the other end of the curve
  14779. iNext = 1;
  14780. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  14781. break;
  14782. default: // ZeroCurvatureEnding
  14783. // f''(tN) = 0, a.k.a. Natural Spline
  14784. iNext = i1 - 1;
  14785. tNext = t0;
  14786. }
  14787. }
  14788. const halfDt = ( t1 - t0 ) * 0.5,
  14789. stride = this.valueSize;
  14790. this._weightPrev = halfDt / ( t0 - tPrev );
  14791. this._weightNext = halfDt / ( tNext - t1 );
  14792. this._offsetPrev = iPrev * stride;
  14793. this._offsetNext = iNext * stride;
  14794. }
  14795. interpolate_( i1, t0, t, t1 ) {
  14796. const result = this.resultBuffer,
  14797. values = this.sampleValues,
  14798. stride = this.valueSize,
  14799. o1 = i1 * stride, o0 = o1 - stride,
  14800. oP = this._offsetPrev, oN = this._offsetNext,
  14801. wP = this._weightPrev, wN = this._weightNext,
  14802. p = ( t - t0 ) / ( t1 - t0 ),
  14803. pp = p * p,
  14804. ppp = pp * p;
  14805. // evaluate polynomials
  14806. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  14807. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  14808. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  14809. const sN = wN * ppp - wN * pp;
  14810. // combine data linearly
  14811. for ( let i = 0; i !== stride; ++ i ) {
  14812. result[ i ] =
  14813. sP * values[ oP + i ] +
  14814. s0 * values[ o0 + i ] +
  14815. s1 * values[ o1 + i ] +
  14816. sN * values[ oN + i ];
  14817. }
  14818. return result;
  14819. }
  14820. }
  14821. class LinearInterpolant extends Interpolant {
  14822. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14823. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14824. }
  14825. interpolate_( i1, t0, t, t1 ) {
  14826. const result = this.resultBuffer,
  14827. values = this.sampleValues,
  14828. stride = this.valueSize,
  14829. offset1 = i1 * stride,
  14830. offset0 = offset1 - stride,
  14831. weight1 = ( t - t0 ) / ( t1 - t0 ),
  14832. weight0 = 1 - weight1;
  14833. for ( let i = 0; i !== stride; ++ i ) {
  14834. result[ i ] =
  14835. values[ offset0 + i ] * weight0 +
  14836. values[ offset1 + i ] * weight1;
  14837. }
  14838. return result;
  14839. }
  14840. }
  14841. /**
  14842. *
  14843. * Interpolant that evaluates to the sample value at the position preceding
  14844. * the parameter.
  14845. */
  14846. class DiscreteInterpolant extends Interpolant {
  14847. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14848. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14849. }
  14850. interpolate_( i1 /*, t0, t, t1 */ ) {
  14851. return this.copySampleValue_( i1 - 1 );
  14852. }
  14853. }
  14854. class KeyframeTrack {
  14855. constructor( name, times, values, interpolation ) {
  14856. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  14857. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  14858. this.name = name;
  14859. this.times = convertArray( times, this.TimeBufferType );
  14860. this.values = convertArray( values, this.ValueBufferType );
  14861. this.setInterpolation( interpolation || this.DefaultInterpolation );
  14862. }
  14863. // Serialization (in static context, because of constructor invocation
  14864. // and automatic invocation of .toJSON):
  14865. static toJSON( track ) {
  14866. const trackType = track.constructor;
  14867. let json;
  14868. // derived classes can define a static toJSON method
  14869. if ( trackType.toJSON !== this.toJSON ) {
  14870. json = trackType.toJSON( track );
  14871. } else {
  14872. // by default, we assume the data can be serialized as-is
  14873. json = {
  14874. 'name': track.name,
  14875. 'times': convertArray( track.times, Array ),
  14876. 'values': convertArray( track.values, Array )
  14877. };
  14878. const interpolation = track.getInterpolation();
  14879. if ( interpolation !== track.DefaultInterpolation ) {
  14880. json.interpolation = interpolation;
  14881. }
  14882. }
  14883. json.type = track.ValueTypeName; // mandatory
  14884. return json;
  14885. }
  14886. InterpolantFactoryMethodDiscrete( result ) {
  14887. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  14888. }
  14889. InterpolantFactoryMethodLinear( result ) {
  14890. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  14891. }
  14892. InterpolantFactoryMethodSmooth( result ) {
  14893. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  14894. }
  14895. setInterpolation( interpolation ) {
  14896. let factoryMethod;
  14897. switch ( interpolation ) {
  14898. case InterpolateDiscrete:
  14899. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  14900. break;
  14901. case InterpolateLinear:
  14902. factoryMethod = this.InterpolantFactoryMethodLinear;
  14903. break;
  14904. case InterpolateSmooth:
  14905. factoryMethod = this.InterpolantFactoryMethodSmooth;
  14906. break;
  14907. }
  14908. if ( factoryMethod === undefined ) {
  14909. const message = 'unsupported interpolation for ' +
  14910. this.ValueTypeName + ' keyframe track named ' + this.name;
  14911. if ( this.createInterpolant === undefined ) {
  14912. // fall back to default, unless the default itself is messed up
  14913. if ( interpolation !== this.DefaultInterpolation ) {
  14914. this.setInterpolation( this.DefaultInterpolation );
  14915. } else {
  14916. throw new Error( message ); // fatal, in this case
  14917. }
  14918. }
  14919. console.warn( 'THREE.KeyframeTrack:', message );
  14920. return this;
  14921. }
  14922. this.createInterpolant = factoryMethod;
  14923. return this;
  14924. }
  14925. getInterpolation() {
  14926. switch ( this.createInterpolant ) {
  14927. case this.InterpolantFactoryMethodDiscrete:
  14928. return InterpolateDiscrete;
  14929. case this.InterpolantFactoryMethodLinear:
  14930. return InterpolateLinear;
  14931. case this.InterpolantFactoryMethodSmooth:
  14932. return InterpolateSmooth;
  14933. }
  14934. }
  14935. getValueSize() {
  14936. return this.values.length / this.times.length;
  14937. }
  14938. // move all keyframes either forwards or backwards in time
  14939. shift( timeOffset ) {
  14940. if ( timeOffset !== 0.0 ) {
  14941. const times = this.times;
  14942. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  14943. times[ i ] += timeOffset;
  14944. }
  14945. }
  14946. return this;
  14947. }
  14948. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  14949. scale( timeScale ) {
  14950. if ( timeScale !== 1.0 ) {
  14951. const times = this.times;
  14952. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  14953. times[ i ] *= timeScale;
  14954. }
  14955. }
  14956. return this;
  14957. }
  14958. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  14959. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  14960. trim( startTime, endTime ) {
  14961. const times = this.times,
  14962. nKeys = times.length;
  14963. let from = 0,
  14964. to = nKeys - 1;
  14965. while ( from !== nKeys && times[ from ] < startTime ) {
  14966. ++ from;
  14967. }
  14968. while ( to !== - 1 && times[ to ] > endTime ) {
  14969. -- to;
  14970. }
  14971. ++ to; // inclusive -> exclusive bound
  14972. if ( from !== 0 || to !== nKeys ) {
  14973. // empty tracks are forbidden, so keep at least one keyframe
  14974. if ( from >= to ) {
  14975. to = Math.max( to, 1 );
  14976. from = to - 1;
  14977. }
  14978. const stride = this.getValueSize();
  14979. this.times = times.slice( from, to );
  14980. this.values = this.values.slice( from * stride, to * stride );
  14981. }
  14982. return this;
  14983. }
  14984. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  14985. validate() {
  14986. let valid = true;
  14987. const valueSize = this.getValueSize();
  14988. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  14989. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  14990. valid = false;
  14991. }
  14992. const times = this.times,
  14993. values = this.values,
  14994. nKeys = times.length;
  14995. if ( nKeys === 0 ) {
  14996. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  14997. valid = false;
  14998. }
  14999. let prevTime = null;
  15000. for ( let i = 0; i !== nKeys; i ++ ) {
  15001. const currTime = times[ i ];
  15002. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  15003. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  15004. valid = false;
  15005. break;
  15006. }
  15007. if ( prevTime !== null && prevTime > currTime ) {
  15008. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  15009. valid = false;
  15010. break;
  15011. }
  15012. prevTime = currTime;
  15013. }
  15014. if ( values !== undefined ) {
  15015. if ( isTypedArray( values ) ) {
  15016. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  15017. const value = values[ i ];
  15018. if ( isNaN( value ) ) {
  15019. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  15020. valid = false;
  15021. break;
  15022. }
  15023. }
  15024. }
  15025. }
  15026. return valid;
  15027. }
  15028. // removes equivalent sequential keys as common in morph target sequences
  15029. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  15030. optimize() {
  15031. // times or values may be shared with other tracks, so overwriting is unsafe
  15032. const times = this.times.slice(),
  15033. values = this.values.slice(),
  15034. stride = this.getValueSize(),
  15035. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  15036. lastIndex = times.length - 1;
  15037. let writeIndex = 1;
  15038. for ( let i = 1; i < lastIndex; ++ i ) {
  15039. let keep = false;
  15040. const time = times[ i ];
  15041. const timeNext = times[ i + 1 ];
  15042. // remove adjacent keyframes scheduled at the same time
  15043. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  15044. if ( ! smoothInterpolation ) {
  15045. // remove unnecessary keyframes same as their neighbors
  15046. const offset = i * stride,
  15047. offsetP = offset - stride,
  15048. offsetN = offset + stride;
  15049. for ( let j = 0; j !== stride; ++ j ) {
  15050. const value = values[ offset + j ];
  15051. if ( value !== values[ offsetP + j ] ||
  15052. value !== values[ offsetN + j ] ) {
  15053. keep = true;
  15054. break;
  15055. }
  15056. }
  15057. } else {
  15058. keep = true;
  15059. }
  15060. }
  15061. // in-place compaction
  15062. if ( keep ) {
  15063. if ( i !== writeIndex ) {
  15064. times[ writeIndex ] = times[ i ];
  15065. const readOffset = i * stride,
  15066. writeOffset = writeIndex * stride;
  15067. for ( let j = 0; j !== stride; ++ j ) {
  15068. values[ writeOffset + j ] = values[ readOffset + j ];
  15069. }
  15070. }
  15071. ++ writeIndex;
  15072. }
  15073. }
  15074. // flush last keyframe (compaction looks ahead)
  15075. if ( lastIndex > 0 ) {
  15076. times[ writeIndex ] = times[ lastIndex ];
  15077. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  15078. values[ writeOffset + j ] = values[ readOffset + j ];
  15079. }
  15080. ++ writeIndex;
  15081. }
  15082. if ( writeIndex !== times.length ) {
  15083. this.times = times.slice( 0, writeIndex );
  15084. this.values = values.slice( 0, writeIndex * stride );
  15085. } else {
  15086. this.times = times;
  15087. this.values = values;
  15088. }
  15089. return this;
  15090. }
  15091. clone() {
  15092. const times = this.times.slice();
  15093. const values = this.values.slice();
  15094. const TypedKeyframeTrack = this.constructor;
  15095. const track = new TypedKeyframeTrack( this.name, times, values );
  15096. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  15097. track.createInterpolant = this.createInterpolant;
  15098. return track;
  15099. }
  15100. }
  15101. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  15102. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  15103. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  15104. /**
  15105. * A Track of Boolean keyframe values.
  15106. */
  15107. class BooleanKeyframeTrack extends KeyframeTrack {
  15108. // No interpolation parameter because only InterpolateDiscrete is valid.
  15109. constructor( name, times, values ) {
  15110. super( name, times, values );
  15111. }
  15112. }
  15113. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  15114. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  15115. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15116. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15117. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15118. /**
  15119. * A Track of keyframe values that represent color.
  15120. */
  15121. class ColorKeyframeTrack extends KeyframeTrack {}
  15122. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  15123. /**
  15124. * A Track of numeric keyframe values.
  15125. */
  15126. class NumberKeyframeTrack extends KeyframeTrack {}
  15127. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  15128. /**
  15129. * Spherical linear unit quaternion interpolant.
  15130. */
  15131. class QuaternionLinearInterpolant extends Interpolant {
  15132. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15133. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15134. }
  15135. interpolate_( i1, t0, t, t1 ) {
  15136. const result = this.resultBuffer,
  15137. values = this.sampleValues,
  15138. stride = this.valueSize,
  15139. alpha = ( t - t0 ) / ( t1 - t0 );
  15140. let offset = i1 * stride;
  15141. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  15142. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  15143. }
  15144. return result;
  15145. }
  15146. }
  15147. /**
  15148. * A Track of quaternion keyframe values.
  15149. */
  15150. class QuaternionKeyframeTrack extends KeyframeTrack {
  15151. InterpolantFactoryMethodLinear( result ) {
  15152. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  15153. }
  15154. }
  15155. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  15156. // ValueBufferType is inherited
  15157. // DefaultInterpolation is inherited;
  15158. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15159. /**
  15160. * A Track that interpolates Strings
  15161. */
  15162. class StringKeyframeTrack extends KeyframeTrack {
  15163. // No interpolation parameter because only InterpolateDiscrete is valid.
  15164. constructor( name, times, values ) {
  15165. super( name, times, values );
  15166. }
  15167. }
  15168. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  15169. StringKeyframeTrack.prototype.ValueBufferType = Array;
  15170. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15171. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15172. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15173. /**
  15174. * A Track of vectored keyframe values.
  15175. */
  15176. class VectorKeyframeTrack extends KeyframeTrack {}
  15177. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  15178. class AnimationClip {
  15179. constructor( name = '', duration = - 1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  15180. this.name = name;
  15181. this.tracks = tracks;
  15182. this.duration = duration;
  15183. this.blendMode = blendMode;
  15184. this.uuid = generateUUID();
  15185. // this means it should figure out its duration by scanning the tracks
  15186. if ( this.duration < 0 ) {
  15187. this.resetDuration();
  15188. }
  15189. }
  15190. static parse( json ) {
  15191. const tracks = [],
  15192. jsonTracks = json.tracks,
  15193. frameTime = 1.0 / ( json.fps || 1.0 );
  15194. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  15195. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  15196. }
  15197. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  15198. clip.uuid = json.uuid;
  15199. return clip;
  15200. }
  15201. static toJSON( clip ) {
  15202. const tracks = [],
  15203. clipTracks = clip.tracks;
  15204. const json = {
  15205. 'name': clip.name,
  15206. 'duration': clip.duration,
  15207. 'tracks': tracks,
  15208. 'uuid': clip.uuid,
  15209. 'blendMode': clip.blendMode
  15210. };
  15211. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  15212. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  15213. }
  15214. return json;
  15215. }
  15216. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  15217. const numMorphTargets = morphTargetSequence.length;
  15218. const tracks = [];
  15219. for ( let i = 0; i < numMorphTargets; i ++ ) {
  15220. let times = [];
  15221. let values = [];
  15222. times.push(
  15223. ( i + numMorphTargets - 1 ) % numMorphTargets,
  15224. i,
  15225. ( i + 1 ) % numMorphTargets );
  15226. values.push( 0, 1, 0 );
  15227. const order = getKeyframeOrder( times );
  15228. times = sortedArray( times, 1, order );
  15229. values = sortedArray( values, 1, order );
  15230. // if there is a key at the first frame, duplicate it as the
  15231. // last frame as well for perfect loop.
  15232. if ( ! noLoop && times[ 0 ] === 0 ) {
  15233. times.push( numMorphTargets );
  15234. values.push( values[ 0 ] );
  15235. }
  15236. tracks.push(
  15237. new NumberKeyframeTrack(
  15238. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  15239. times, values
  15240. ).scale( 1.0 / fps ) );
  15241. }
  15242. return new this( name, - 1, tracks );
  15243. }
  15244. static findByName( objectOrClipArray, name ) {
  15245. let clipArray = objectOrClipArray;
  15246. if ( ! Array.isArray( objectOrClipArray ) ) {
  15247. const o = objectOrClipArray;
  15248. clipArray = o.geometry && o.geometry.animations || o.animations;
  15249. }
  15250. for ( let i = 0; i < clipArray.length; i ++ ) {
  15251. if ( clipArray[ i ].name === name ) {
  15252. return clipArray[ i ];
  15253. }
  15254. }
  15255. return null;
  15256. }
  15257. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  15258. const animationToMorphTargets = {};
  15259. // tested with https://regex101.com/ on trick sequences
  15260. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  15261. const pattern = /^([\w-]*?)([\d]+)$/;
  15262. // sort morph target names into animation groups based
  15263. // patterns like Walk_001, Walk_002, Run_001, Run_002
  15264. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  15265. const morphTarget = morphTargets[ i ];
  15266. const parts = morphTarget.name.match( pattern );
  15267. if ( parts && parts.length > 1 ) {
  15268. const name = parts[ 1 ];
  15269. let animationMorphTargets = animationToMorphTargets[ name ];
  15270. if ( ! animationMorphTargets ) {
  15271. animationToMorphTargets[ name ] = animationMorphTargets = [];
  15272. }
  15273. animationMorphTargets.push( morphTarget );
  15274. }
  15275. }
  15276. const clips = [];
  15277. for ( const name in animationToMorphTargets ) {
  15278. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  15279. }
  15280. return clips;
  15281. }
  15282. // parse the animation.hierarchy format
  15283. static parseAnimation( animation, bones ) {
  15284. if ( ! animation ) {
  15285. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  15286. return null;
  15287. }
  15288. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  15289. // only return track if there are actually keys.
  15290. if ( animationKeys.length !== 0 ) {
  15291. const times = [];
  15292. const values = [];
  15293. flattenJSON( animationKeys, times, values, propertyName );
  15294. // empty keys are filtered out, so check again
  15295. if ( times.length !== 0 ) {
  15296. destTracks.push( new trackType( trackName, times, values ) );
  15297. }
  15298. }
  15299. };
  15300. const tracks = [];
  15301. const clipName = animation.name || 'default';
  15302. const fps = animation.fps || 30;
  15303. const blendMode = animation.blendMode;
  15304. // automatic length determination in AnimationClip.
  15305. let duration = animation.length || - 1;
  15306. const hierarchyTracks = animation.hierarchy || [];
  15307. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  15308. const animationKeys = hierarchyTracks[ h ].keys;
  15309. // skip empty tracks
  15310. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  15311. // process morph targets
  15312. if ( animationKeys[ 0 ].morphTargets ) {
  15313. // figure out all morph targets used in this track
  15314. const morphTargetNames = {};
  15315. let k;
  15316. for ( k = 0; k < animationKeys.length; k ++ ) {
  15317. if ( animationKeys[ k ].morphTargets ) {
  15318. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  15319. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  15320. }
  15321. }
  15322. }
  15323. // create a track for each morph target with all zero
  15324. // morphTargetInfluences except for the keys in which
  15325. // the morphTarget is named.
  15326. for ( const morphTargetName in morphTargetNames ) {
  15327. const times = [];
  15328. const values = [];
  15329. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  15330. const animationKey = animationKeys[ k ];
  15331. times.push( animationKey.time );
  15332. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  15333. }
  15334. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  15335. }
  15336. duration = morphTargetNames.length * fps;
  15337. } else {
  15338. // ...assume skeletal animation
  15339. const boneName = '.bones[' + bones[ h ].name + ']';
  15340. addNonemptyTrack(
  15341. VectorKeyframeTrack, boneName + '.position',
  15342. animationKeys, 'pos', tracks );
  15343. addNonemptyTrack(
  15344. QuaternionKeyframeTrack, boneName + '.quaternion',
  15345. animationKeys, 'rot', tracks );
  15346. addNonemptyTrack(
  15347. VectorKeyframeTrack, boneName + '.scale',
  15348. animationKeys, 'scl', tracks );
  15349. }
  15350. }
  15351. if ( tracks.length === 0 ) {
  15352. return null;
  15353. }
  15354. const clip = new this( clipName, duration, tracks, blendMode );
  15355. return clip;
  15356. }
  15357. resetDuration() {
  15358. const tracks = this.tracks;
  15359. let duration = 0;
  15360. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  15361. const track = this.tracks[ i ];
  15362. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  15363. }
  15364. this.duration = duration;
  15365. return this;
  15366. }
  15367. trim() {
  15368. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15369. this.tracks[ i ].trim( 0, this.duration );
  15370. }
  15371. return this;
  15372. }
  15373. validate() {
  15374. let valid = true;
  15375. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15376. valid = valid && this.tracks[ i ].validate();
  15377. }
  15378. return valid;
  15379. }
  15380. optimize() {
  15381. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15382. this.tracks[ i ].optimize();
  15383. }
  15384. return this;
  15385. }
  15386. clone() {
  15387. const tracks = [];
  15388. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15389. tracks.push( this.tracks[ i ].clone() );
  15390. }
  15391. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  15392. }
  15393. toJSON() {
  15394. return this.constructor.toJSON( this );
  15395. }
  15396. }
  15397. function getTrackTypeForValueTypeName( typeName ) {
  15398. switch ( typeName.toLowerCase() ) {
  15399. case 'scalar':
  15400. case 'double':
  15401. case 'float':
  15402. case 'number':
  15403. case 'integer':
  15404. return NumberKeyframeTrack;
  15405. case 'vector':
  15406. case 'vector2':
  15407. case 'vector3':
  15408. case 'vector4':
  15409. return VectorKeyframeTrack;
  15410. case 'color':
  15411. return ColorKeyframeTrack;
  15412. case 'quaternion':
  15413. return QuaternionKeyframeTrack;
  15414. case 'bool':
  15415. case 'boolean':
  15416. return BooleanKeyframeTrack;
  15417. case 'string':
  15418. return StringKeyframeTrack;
  15419. }
  15420. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  15421. }
  15422. function parseKeyframeTrack( json ) {
  15423. if ( json.type === undefined ) {
  15424. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  15425. }
  15426. const trackType = getTrackTypeForValueTypeName( json.type );
  15427. if ( json.times === undefined ) {
  15428. const times = [], values = [];
  15429. flattenJSON( json.keys, times, values, 'value' );
  15430. json.times = times;
  15431. json.values = values;
  15432. }
  15433. // derived classes can define a static parse method
  15434. if ( trackType.parse !== undefined ) {
  15435. return trackType.parse( json );
  15436. } else {
  15437. // by default, we assume a constructor compatible with the base
  15438. return new trackType( json.name, json.times, json.values, json.interpolation );
  15439. }
  15440. }
  15441. const Cache = {
  15442. enabled: false,
  15443. files: {},
  15444. add: function ( key, file ) {
  15445. if ( this.enabled === false ) return;
  15446. // console.log( 'THREE.Cache', 'Adding key:', key );
  15447. this.files[ key ] = file;
  15448. },
  15449. get: function ( key ) {
  15450. if ( this.enabled === false ) return;
  15451. // console.log( 'THREE.Cache', 'Checking key:', key );
  15452. return this.files[ key ];
  15453. },
  15454. remove: function ( key ) {
  15455. delete this.files[ key ];
  15456. },
  15457. clear: function () {
  15458. this.files = {};
  15459. }
  15460. };
  15461. class LoadingManager {
  15462. constructor( onLoad, onProgress, onError ) {
  15463. const scope = this;
  15464. let isLoading = false;
  15465. let itemsLoaded = 0;
  15466. let itemsTotal = 0;
  15467. let urlModifier = undefined;
  15468. const handlers = [];
  15469. // Refer to #5689 for the reason why we don't set .onStart
  15470. // in the constructor
  15471. this.onStart = undefined;
  15472. this.onLoad = onLoad;
  15473. this.onProgress = onProgress;
  15474. this.onError = onError;
  15475. this.itemStart = function ( url ) {
  15476. itemsTotal ++;
  15477. if ( isLoading === false ) {
  15478. if ( scope.onStart !== undefined ) {
  15479. scope.onStart( url, itemsLoaded, itemsTotal );
  15480. }
  15481. }
  15482. isLoading = true;
  15483. };
  15484. this.itemEnd = function ( url ) {
  15485. itemsLoaded ++;
  15486. if ( scope.onProgress !== undefined ) {
  15487. scope.onProgress( url, itemsLoaded, itemsTotal );
  15488. }
  15489. if ( itemsLoaded === itemsTotal ) {
  15490. isLoading = false;
  15491. if ( scope.onLoad !== undefined ) {
  15492. scope.onLoad();
  15493. }
  15494. }
  15495. };
  15496. this.itemError = function ( url ) {
  15497. if ( scope.onError !== undefined ) {
  15498. scope.onError( url );
  15499. }
  15500. };
  15501. this.resolveURL = function ( url ) {
  15502. if ( urlModifier ) {
  15503. return urlModifier( url );
  15504. }
  15505. return url;
  15506. };
  15507. this.setURLModifier = function ( transform ) {
  15508. urlModifier = transform;
  15509. return this;
  15510. };
  15511. this.addHandler = function ( regex, loader ) {
  15512. handlers.push( regex, loader );
  15513. return this;
  15514. };
  15515. this.removeHandler = function ( regex ) {
  15516. const index = handlers.indexOf( regex );
  15517. if ( index !== - 1 ) {
  15518. handlers.splice( index, 2 );
  15519. }
  15520. return this;
  15521. };
  15522. this.getHandler = function ( file ) {
  15523. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  15524. const regex = handlers[ i ];
  15525. const loader = handlers[ i + 1 ];
  15526. if ( regex.global ) regex.lastIndex = 0; // see #17920
  15527. if ( regex.test( file ) ) {
  15528. return loader;
  15529. }
  15530. }
  15531. return null;
  15532. };
  15533. }
  15534. }
  15535. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  15536. class Loader {
  15537. constructor( manager ) {
  15538. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  15539. this.crossOrigin = 'anonymous';
  15540. this.withCredentials = false;
  15541. this.path = '';
  15542. this.resourcePath = '';
  15543. this.requestHeader = {};
  15544. }
  15545. load( /* url, onLoad, onProgress, onError */ ) {}
  15546. loadAsync( url, onProgress ) {
  15547. const scope = this;
  15548. return new Promise( function ( resolve, reject ) {
  15549. scope.load( url, resolve, onProgress, reject );
  15550. } );
  15551. }
  15552. parse( /* data */ ) {}
  15553. setCrossOrigin( crossOrigin ) {
  15554. this.crossOrigin = crossOrigin;
  15555. return this;
  15556. }
  15557. setWithCredentials( value ) {
  15558. this.withCredentials = value;
  15559. return this;
  15560. }
  15561. setPath( path ) {
  15562. this.path = path;
  15563. return this;
  15564. }
  15565. setResourcePath( resourcePath ) {
  15566. this.resourcePath = resourcePath;
  15567. return this;
  15568. }
  15569. setRequestHeader( requestHeader ) {
  15570. this.requestHeader = requestHeader;
  15571. return this;
  15572. }
  15573. }
  15574. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  15575. const loading = {};
  15576. class HttpError extends Error {
  15577. constructor( message, response ) {
  15578. super( message );
  15579. this.response = response;
  15580. }
  15581. }
  15582. class FileLoader extends Loader {
  15583. constructor( manager ) {
  15584. super( manager );
  15585. }
  15586. load( url, onLoad, onProgress, onError ) {
  15587. if ( url === undefined ) url = '';
  15588. if ( this.path !== undefined ) url = this.path + url;
  15589. url = this.manager.resolveURL( url );
  15590. const cached = Cache.get( url );
  15591. if ( cached !== undefined ) {
  15592. this.manager.itemStart( url );
  15593. setTimeout( () => {
  15594. if ( onLoad ) onLoad( cached );
  15595. this.manager.itemEnd( url );
  15596. }, 0 );
  15597. return cached;
  15598. }
  15599. // Check if request is duplicate
  15600. if ( loading[ url ] !== undefined ) {
  15601. loading[ url ].push( {
  15602. onLoad: onLoad,
  15603. onProgress: onProgress,
  15604. onError: onError
  15605. } );
  15606. return;
  15607. }
  15608. // Initialise array for duplicate requests
  15609. loading[ url ] = [];
  15610. loading[ url ].push( {
  15611. onLoad: onLoad,
  15612. onProgress: onProgress,
  15613. onError: onError,
  15614. } );
  15615. // create request
  15616. const req = new Request( url, {
  15617. headers: new Headers( this.requestHeader ),
  15618. credentials: this.withCredentials ? 'include' : 'same-origin',
  15619. // An abort controller could be added within a future PR
  15620. } );
  15621. // record states ( avoid data race )
  15622. const mimeType = this.mimeType;
  15623. const responseType = this.responseType;
  15624. // start the fetch
  15625. fetch( req )
  15626. .then( response => {
  15627. if ( response.status === 200 || response.status === 0 ) {
  15628. // Some browsers return HTTP Status 0 when using non-http protocol
  15629. // e.g. 'file://' or 'data://'. Handle as success.
  15630. if ( response.status === 0 ) {
  15631. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  15632. }
  15633. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  15634. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  15635. return response;
  15636. }
  15637. const callbacks = loading[ url ];
  15638. const reader = response.body.getReader();
  15639. // Nginx needs X-File-Size check
  15640. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  15641. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  15642. const total = contentLength ? parseInt( contentLength ) : 0;
  15643. const lengthComputable = total !== 0;
  15644. let loaded = 0;
  15645. // periodically read data into the new stream tracking while download progress
  15646. const stream = new ReadableStream( {
  15647. start( controller ) {
  15648. readData();
  15649. function readData() {
  15650. reader.read().then( ( { done, value } ) => {
  15651. if ( done ) {
  15652. controller.close();
  15653. } else {
  15654. loaded += value.byteLength;
  15655. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  15656. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15657. const callback = callbacks[ i ];
  15658. if ( callback.onProgress ) callback.onProgress( event );
  15659. }
  15660. controller.enqueue( value );
  15661. readData();
  15662. }
  15663. }, ( e ) => {
  15664. controller.error( e );
  15665. } );
  15666. }
  15667. }
  15668. } );
  15669. return new Response( stream );
  15670. } else {
  15671. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  15672. }
  15673. } )
  15674. .then( response => {
  15675. switch ( responseType ) {
  15676. case 'arraybuffer':
  15677. return response.arrayBuffer();
  15678. case 'blob':
  15679. return response.blob();
  15680. case 'document':
  15681. return response.text()
  15682. .then( text => {
  15683. const parser = new DOMParser();
  15684. return parser.parseFromString( text, mimeType );
  15685. } );
  15686. case 'json':
  15687. return response.json();
  15688. default:
  15689. if ( mimeType === undefined ) {
  15690. return response.text();
  15691. } else {
  15692. // sniff encoding
  15693. const re = /charset="?([^;"\s]*)"?/i;
  15694. const exec = re.exec( mimeType );
  15695. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  15696. const decoder = new TextDecoder( label );
  15697. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  15698. }
  15699. }
  15700. } )
  15701. .then( data => {
  15702. // Add to cache only on HTTP success, so that we do not cache
  15703. // error response bodies as proper responses to requests.
  15704. Cache.add( url, data );
  15705. const callbacks = loading[ url ];
  15706. delete loading[ url ];
  15707. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15708. const callback = callbacks[ i ];
  15709. if ( callback.onLoad ) callback.onLoad( data );
  15710. }
  15711. } )
  15712. .catch( err => {
  15713. // Abort errors and other errors are handled the same
  15714. const callbacks = loading[ url ];
  15715. if ( callbacks === undefined ) {
  15716. // When onLoad was called and url was deleted in `loading`
  15717. this.manager.itemError( url );
  15718. throw err;
  15719. }
  15720. delete loading[ url ];
  15721. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15722. const callback = callbacks[ i ];
  15723. if ( callback.onError ) callback.onError( err );
  15724. }
  15725. this.manager.itemError( url );
  15726. } )
  15727. .finally( () => {
  15728. this.manager.itemEnd( url );
  15729. } );
  15730. this.manager.itemStart( url );
  15731. }
  15732. setResponseType( value ) {
  15733. this.responseType = value;
  15734. return this;
  15735. }
  15736. setMimeType( value ) {
  15737. this.mimeType = value;
  15738. return this;
  15739. }
  15740. }
  15741. class AnimationLoader extends Loader {
  15742. constructor( manager ) {
  15743. super( manager );
  15744. }
  15745. load( url, onLoad, onProgress, onError ) {
  15746. const scope = this;
  15747. const loader = new FileLoader( this.manager );
  15748. loader.setPath( this.path );
  15749. loader.setRequestHeader( this.requestHeader );
  15750. loader.setWithCredentials( this.withCredentials );
  15751. loader.load( url, function ( text ) {
  15752. try {
  15753. onLoad( scope.parse( JSON.parse( text ) ) );
  15754. } catch ( e ) {
  15755. if ( onError ) {
  15756. onError( e );
  15757. } else {
  15758. console.error( e );
  15759. }
  15760. scope.manager.itemError( url );
  15761. }
  15762. }, onProgress, onError );
  15763. }
  15764. parse( json ) {
  15765. const animations = [];
  15766. for ( let i = 0; i < json.length; i ++ ) {
  15767. const clip = AnimationClip.parse( json[ i ] );
  15768. animations.push( clip );
  15769. }
  15770. return animations;
  15771. }
  15772. }
  15773. /**
  15774. * Abstract Base class to block based textures loader (dds, pvr, ...)
  15775. *
  15776. * Sub classes have to implement the parse() method which will be used in load().
  15777. */
  15778. class CompressedTextureLoader extends Loader {
  15779. constructor( manager ) {
  15780. super( manager );
  15781. }
  15782. load( url, onLoad, onProgress, onError ) {
  15783. const scope = this;
  15784. const images = [];
  15785. const texture = new CompressedTexture();
  15786. const loader = new FileLoader( this.manager );
  15787. loader.setPath( this.path );
  15788. loader.setResponseType( 'arraybuffer' );
  15789. loader.setRequestHeader( this.requestHeader );
  15790. loader.setWithCredentials( scope.withCredentials );
  15791. let loaded = 0;
  15792. function loadTexture( i ) {
  15793. loader.load( url[ i ], function ( buffer ) {
  15794. const texDatas = scope.parse( buffer, true );
  15795. images[ i ] = {
  15796. width: texDatas.width,
  15797. height: texDatas.height,
  15798. format: texDatas.format,
  15799. mipmaps: texDatas.mipmaps
  15800. };
  15801. loaded += 1;
  15802. if ( loaded === 6 ) {
  15803. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  15804. texture.image = images;
  15805. texture.format = texDatas.format;
  15806. texture.needsUpdate = true;
  15807. if ( onLoad ) onLoad( texture );
  15808. }
  15809. }, onProgress, onError );
  15810. }
  15811. if ( Array.isArray( url ) ) {
  15812. for ( let i = 0, il = url.length; i < il; ++ i ) {
  15813. loadTexture( i );
  15814. }
  15815. } else {
  15816. // compressed cubemap texture stored in a single DDS file
  15817. loader.load( url, function ( buffer ) {
  15818. const texDatas = scope.parse( buffer, true );
  15819. if ( texDatas.isCubemap ) {
  15820. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  15821. for ( let f = 0; f < faces; f ++ ) {
  15822. images[ f ] = { mipmaps: [] };
  15823. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  15824. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  15825. images[ f ].format = texDatas.format;
  15826. images[ f ].width = texDatas.width;
  15827. images[ f ].height = texDatas.height;
  15828. }
  15829. }
  15830. texture.image = images;
  15831. } else {
  15832. texture.image.width = texDatas.width;
  15833. texture.image.height = texDatas.height;
  15834. texture.mipmaps = texDatas.mipmaps;
  15835. }
  15836. if ( texDatas.mipmapCount === 1 ) {
  15837. texture.minFilter = LinearFilter;
  15838. }
  15839. texture.format = texDatas.format;
  15840. texture.needsUpdate = true;
  15841. if ( onLoad ) onLoad( texture );
  15842. }, onProgress, onError );
  15843. }
  15844. return texture;
  15845. }
  15846. }
  15847. class ImageLoader extends Loader {
  15848. constructor( manager ) {
  15849. super( manager );
  15850. }
  15851. load( url, onLoad, onProgress, onError ) {
  15852. if ( this.path !== undefined ) url = this.path + url;
  15853. url = this.manager.resolveURL( url );
  15854. const scope = this;
  15855. const cached = Cache.get( url );
  15856. if ( cached !== undefined ) {
  15857. scope.manager.itemStart( url );
  15858. setTimeout( function () {
  15859. if ( onLoad ) onLoad( cached );
  15860. scope.manager.itemEnd( url );
  15861. }, 0 );
  15862. return cached;
  15863. }
  15864. const image = createElementNS( 'img' );
  15865. function onImageLoad() {
  15866. removeEventListeners();
  15867. Cache.add( url, this );
  15868. if ( onLoad ) onLoad( this );
  15869. scope.manager.itemEnd( url );
  15870. }
  15871. function onImageError( event ) {
  15872. removeEventListeners();
  15873. if ( onError ) onError( event );
  15874. scope.manager.itemError( url );
  15875. scope.manager.itemEnd( url );
  15876. }
  15877. function removeEventListeners() {
  15878. image.removeEventListener( 'load', onImageLoad, false );
  15879. image.removeEventListener( 'error', onImageError, false );
  15880. }
  15881. image.addEventListener( 'load', onImageLoad, false );
  15882. image.addEventListener( 'error', onImageError, false );
  15883. if ( url.slice( 0, 5 ) !== 'data:' ) {
  15884. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  15885. }
  15886. scope.manager.itemStart( url );
  15887. image.src = url;
  15888. return image;
  15889. }
  15890. }
  15891. class CubeTextureLoader extends Loader {
  15892. constructor( manager ) {
  15893. super( manager );
  15894. }
  15895. load( urls, onLoad, onProgress, onError ) {
  15896. const texture = new CubeTexture();
  15897. texture.colorSpace = SRGBColorSpace;
  15898. const loader = new ImageLoader( this.manager );
  15899. loader.setCrossOrigin( this.crossOrigin );
  15900. loader.setPath( this.path );
  15901. let loaded = 0;
  15902. function loadTexture( i ) {
  15903. loader.load( urls[ i ], function ( image ) {
  15904. texture.images[ i ] = image;
  15905. loaded ++;
  15906. if ( loaded === 6 ) {
  15907. texture.needsUpdate = true;
  15908. if ( onLoad ) onLoad( texture );
  15909. }
  15910. }, undefined, onError );
  15911. }
  15912. for ( let i = 0; i < urls.length; ++ i ) {
  15913. loadTexture( i );
  15914. }
  15915. return texture;
  15916. }
  15917. }
  15918. /**
  15919. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  15920. *
  15921. * Sub classes have to implement the parse() method which will be used in load().
  15922. */
  15923. class DataTextureLoader extends Loader {
  15924. constructor( manager ) {
  15925. super( manager );
  15926. }
  15927. load( url, onLoad, onProgress, onError ) {
  15928. const scope = this;
  15929. const texture = new DataTexture();
  15930. const loader = new FileLoader( this.manager );
  15931. loader.setResponseType( 'arraybuffer' );
  15932. loader.setRequestHeader( this.requestHeader );
  15933. loader.setPath( this.path );
  15934. loader.setWithCredentials( scope.withCredentials );
  15935. loader.load( url, function ( buffer ) {
  15936. let texData;
  15937. try {
  15938. texData = scope.parse( buffer );
  15939. } catch ( error ) {
  15940. if ( onError !== undefined ) {
  15941. onError( error );
  15942. } else {
  15943. console.error( error );
  15944. return;
  15945. }
  15946. }
  15947. if ( texData.image !== undefined ) {
  15948. texture.image = texData.image;
  15949. } else if ( texData.data !== undefined ) {
  15950. texture.image.width = texData.width;
  15951. texture.image.height = texData.height;
  15952. texture.image.data = texData.data;
  15953. }
  15954. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  15955. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  15956. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  15957. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  15958. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  15959. if ( texData.colorSpace !== undefined ) {
  15960. texture.colorSpace = texData.colorSpace;
  15961. }
  15962. if ( texData.flipY !== undefined ) {
  15963. texture.flipY = texData.flipY;
  15964. }
  15965. if ( texData.format !== undefined ) {
  15966. texture.format = texData.format;
  15967. }
  15968. if ( texData.type !== undefined ) {
  15969. texture.type = texData.type;
  15970. }
  15971. if ( texData.mipmaps !== undefined ) {
  15972. texture.mipmaps = texData.mipmaps;
  15973. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  15974. }
  15975. if ( texData.mipmapCount === 1 ) {
  15976. texture.minFilter = LinearFilter;
  15977. }
  15978. if ( texData.generateMipmaps !== undefined ) {
  15979. texture.generateMipmaps = texData.generateMipmaps;
  15980. }
  15981. texture.needsUpdate = true;
  15982. if ( onLoad ) onLoad( texture, texData );
  15983. }, onProgress, onError );
  15984. return texture;
  15985. }
  15986. }
  15987. class TextureLoader extends Loader {
  15988. constructor( manager ) {
  15989. super( manager );
  15990. }
  15991. load( url, onLoad, onProgress, onError ) {
  15992. const texture = new Texture();
  15993. const loader = new ImageLoader( this.manager );
  15994. loader.setCrossOrigin( this.crossOrigin );
  15995. loader.setPath( this.path );
  15996. loader.load( url, function ( image ) {
  15997. texture.image = image;
  15998. texture.needsUpdate = true;
  15999. if ( onLoad !== undefined ) {
  16000. onLoad( texture );
  16001. }
  16002. }, onProgress, onError );
  16003. return texture;
  16004. }
  16005. }
  16006. class Light extends Object3D {
  16007. constructor( color, intensity = 1 ) {
  16008. super();
  16009. this.isLight = true;
  16010. this.type = 'Light';
  16011. this.color = new Color( color );
  16012. this.intensity = intensity;
  16013. }
  16014. dispose() {
  16015. // Empty here in base class; some subclasses override.
  16016. }
  16017. copy( source, recursive ) {
  16018. super.copy( source, recursive );
  16019. this.color.copy( source.color );
  16020. this.intensity = source.intensity;
  16021. return this;
  16022. }
  16023. toJSON( meta ) {
  16024. const data = super.toJSON( meta );
  16025. data.object.color = this.color.getHex();
  16026. data.object.intensity = this.intensity;
  16027. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  16028. if ( this.distance !== undefined ) data.object.distance = this.distance;
  16029. if ( this.angle !== undefined ) data.object.angle = this.angle;
  16030. if ( this.decay !== undefined ) data.object.decay = this.decay;
  16031. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  16032. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  16033. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  16034. return data;
  16035. }
  16036. }
  16037. class HemisphereLight extends Light {
  16038. constructor( skyColor, groundColor, intensity ) {
  16039. super( skyColor, intensity );
  16040. this.isHemisphereLight = true;
  16041. this.type = 'HemisphereLight';
  16042. this.position.copy( Object3D.DEFAULT_UP );
  16043. this.updateMatrix();
  16044. this.groundColor = new Color( groundColor );
  16045. }
  16046. copy( source, recursive ) {
  16047. super.copy( source, recursive );
  16048. this.groundColor.copy( source.groundColor );
  16049. return this;
  16050. }
  16051. }
  16052. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  16053. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  16054. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  16055. class LightShadow {
  16056. constructor( camera ) {
  16057. this.camera = camera;
  16058. this.intensity = 1;
  16059. this.bias = 0;
  16060. this.normalBias = 0;
  16061. this.radius = 1;
  16062. this.blurSamples = 8;
  16063. this.mapSize = new Vector2( 512, 512 );
  16064. this.map = null;
  16065. this.mapPass = null;
  16066. this.matrix = new Matrix4();
  16067. this.autoUpdate = true;
  16068. this.needsUpdate = false;
  16069. this._frustum = new Frustum();
  16070. this._frameExtents = new Vector2( 1, 1 );
  16071. this._viewportCount = 1;
  16072. this._viewports = [
  16073. new Vector4( 0, 0, 1, 1 )
  16074. ];
  16075. }
  16076. getViewportCount() {
  16077. return this._viewportCount;
  16078. }
  16079. getFrustum() {
  16080. return this._frustum;
  16081. }
  16082. updateMatrices( light ) {
  16083. const shadowCamera = this.camera;
  16084. const shadowMatrix = this.matrix;
  16085. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  16086. shadowCamera.position.copy( _lightPositionWorld$1 );
  16087. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  16088. shadowCamera.lookAt( _lookTarget$1 );
  16089. shadowCamera.updateMatrixWorld();
  16090. _projScreenMatrix$2.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  16091. this._frustum.setFromProjectionMatrix( _projScreenMatrix$2 );
  16092. shadowMatrix.set(
  16093. 0.5, 0.0, 0.0, 0.5,
  16094. 0.0, 0.5, 0.0, 0.5,
  16095. 0.0, 0.0, 0.5, 0.5,
  16096. 0.0, 0.0, 0.0, 1.0
  16097. );
  16098. shadowMatrix.multiply( _projScreenMatrix$2 );
  16099. }
  16100. getViewport( viewportIndex ) {
  16101. return this._viewports[ viewportIndex ];
  16102. }
  16103. getFrameExtents() {
  16104. return this._frameExtents;
  16105. }
  16106. dispose() {
  16107. if ( this.map ) {
  16108. this.map.dispose();
  16109. }
  16110. if ( this.mapPass ) {
  16111. this.mapPass.dispose();
  16112. }
  16113. }
  16114. copy( source ) {
  16115. this.camera = source.camera.clone();
  16116. this.intensity = source.intensity;
  16117. this.bias = source.bias;
  16118. this.radius = source.radius;
  16119. this.mapSize.copy( source.mapSize );
  16120. return this;
  16121. }
  16122. clone() {
  16123. return new this.constructor().copy( this );
  16124. }
  16125. toJSON() {
  16126. const object = {};
  16127. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  16128. if ( this.bias !== 0 ) object.bias = this.bias;
  16129. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  16130. if ( this.radius !== 1 ) object.radius = this.radius;
  16131. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  16132. object.camera = this.camera.toJSON( false ).object;
  16133. delete object.camera.matrix;
  16134. return object;
  16135. }
  16136. }
  16137. class SpotLightShadow extends LightShadow {
  16138. constructor() {
  16139. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  16140. this.isSpotLightShadow = true;
  16141. this.focus = 1;
  16142. }
  16143. updateMatrices( light ) {
  16144. const camera = this.camera;
  16145. const fov = RAD2DEG * 2 * light.angle * this.focus;
  16146. const aspect = this.mapSize.width / this.mapSize.height;
  16147. const far = light.distance || camera.far;
  16148. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  16149. camera.fov = fov;
  16150. camera.aspect = aspect;
  16151. camera.far = far;
  16152. camera.updateProjectionMatrix();
  16153. }
  16154. super.updateMatrices( light );
  16155. }
  16156. copy( source ) {
  16157. super.copy( source );
  16158. this.focus = source.focus;
  16159. return this;
  16160. }
  16161. }
  16162. class SpotLight extends Light {
  16163. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  16164. super( color, intensity );
  16165. this.isSpotLight = true;
  16166. this.type = 'SpotLight';
  16167. this.position.copy( Object3D.DEFAULT_UP );
  16168. this.updateMatrix();
  16169. this.target = new Object3D();
  16170. this.distance = distance;
  16171. this.angle = angle;
  16172. this.penumbra = penumbra;
  16173. this.decay = decay;
  16174. this.map = null;
  16175. this.shadow = new SpotLightShadow();
  16176. }
  16177. get power() {
  16178. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16179. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  16180. return this.intensity * Math.PI;
  16181. }
  16182. set power( power ) {
  16183. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16184. this.intensity = power / Math.PI;
  16185. }
  16186. dispose() {
  16187. this.shadow.dispose();
  16188. }
  16189. copy( source, recursive ) {
  16190. super.copy( source, recursive );
  16191. this.distance = source.distance;
  16192. this.angle = source.angle;
  16193. this.penumbra = source.penumbra;
  16194. this.decay = source.decay;
  16195. this.target = source.target.clone();
  16196. this.shadow = source.shadow.clone();
  16197. return this;
  16198. }
  16199. }
  16200. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  16201. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  16202. const _lookTarget = /*@__PURE__*/ new Vector3();
  16203. class PointLightShadow extends LightShadow {
  16204. constructor() {
  16205. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  16206. this.isPointLightShadow = true;
  16207. this._frameExtents = new Vector2( 4, 2 );
  16208. this._viewportCount = 6;
  16209. this._viewports = [
  16210. // These viewports map a cube-map onto a 2D texture with the
  16211. // following orientation:
  16212. //
  16213. // xzXZ
  16214. // y Y
  16215. //
  16216. // X - Positive x direction
  16217. // x - Negative x direction
  16218. // Y - Positive y direction
  16219. // y - Negative y direction
  16220. // Z - Positive z direction
  16221. // z - Negative z direction
  16222. // positive X
  16223. new Vector4( 2, 1, 1, 1 ),
  16224. // negative X
  16225. new Vector4( 0, 1, 1, 1 ),
  16226. // positive Z
  16227. new Vector4( 3, 1, 1, 1 ),
  16228. // negative Z
  16229. new Vector4( 1, 1, 1, 1 ),
  16230. // positive Y
  16231. new Vector4( 3, 0, 1, 1 ),
  16232. // negative Y
  16233. new Vector4( 1, 0, 1, 1 )
  16234. ];
  16235. this._cubeDirections = [
  16236. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  16237. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  16238. ];
  16239. this._cubeUps = [
  16240. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  16241. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  16242. ];
  16243. }
  16244. updateMatrices( light, viewportIndex = 0 ) {
  16245. const camera = this.camera;
  16246. const shadowMatrix = this.matrix;
  16247. const far = light.distance || camera.far;
  16248. if ( far !== camera.far ) {
  16249. camera.far = far;
  16250. camera.updateProjectionMatrix();
  16251. }
  16252. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  16253. camera.position.copy( _lightPositionWorld );
  16254. _lookTarget.copy( camera.position );
  16255. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  16256. camera.up.copy( this._cubeUps[ viewportIndex ] );
  16257. camera.lookAt( _lookTarget );
  16258. camera.updateMatrixWorld();
  16259. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  16260. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16261. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  16262. }
  16263. }
  16264. class PointLight extends Light {
  16265. constructor( color, intensity, distance = 0, decay = 2 ) {
  16266. super( color, intensity );
  16267. this.isPointLight = true;
  16268. this.type = 'PointLight';
  16269. this.distance = distance;
  16270. this.decay = decay;
  16271. this.shadow = new PointLightShadow();
  16272. }
  16273. get power() {
  16274. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16275. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  16276. return this.intensity * 4 * Math.PI;
  16277. }
  16278. set power( power ) {
  16279. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16280. this.intensity = power / ( 4 * Math.PI );
  16281. }
  16282. dispose() {
  16283. this.shadow.dispose();
  16284. }
  16285. copy( source, recursive ) {
  16286. super.copy( source, recursive );
  16287. this.distance = source.distance;
  16288. this.decay = source.decay;
  16289. this.shadow = source.shadow.clone();
  16290. return this;
  16291. }
  16292. }
  16293. class OrthographicCamera extends Camera {
  16294. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  16295. super();
  16296. this.isOrthographicCamera = true;
  16297. this.type = 'OrthographicCamera';
  16298. this.zoom = 1;
  16299. this.view = null;
  16300. this.left = left;
  16301. this.right = right;
  16302. this.top = top;
  16303. this.bottom = bottom;
  16304. this.near = near;
  16305. this.far = far;
  16306. this.updateProjectionMatrix();
  16307. }
  16308. copy( source, recursive ) {
  16309. super.copy( source, recursive );
  16310. this.left = source.left;
  16311. this.right = source.right;
  16312. this.top = source.top;
  16313. this.bottom = source.bottom;
  16314. this.near = source.near;
  16315. this.far = source.far;
  16316. this.zoom = source.zoom;
  16317. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16318. return this;
  16319. }
  16320. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16321. if ( this.view === null ) {
  16322. this.view = {
  16323. enabled: true,
  16324. fullWidth: 1,
  16325. fullHeight: 1,
  16326. offsetX: 0,
  16327. offsetY: 0,
  16328. width: 1,
  16329. height: 1
  16330. };
  16331. }
  16332. this.view.enabled = true;
  16333. this.view.fullWidth = fullWidth;
  16334. this.view.fullHeight = fullHeight;
  16335. this.view.offsetX = x;
  16336. this.view.offsetY = y;
  16337. this.view.width = width;
  16338. this.view.height = height;
  16339. this.updateProjectionMatrix();
  16340. }
  16341. clearViewOffset() {
  16342. if ( this.view !== null ) {
  16343. this.view.enabled = false;
  16344. }
  16345. this.updateProjectionMatrix();
  16346. }
  16347. updateProjectionMatrix() {
  16348. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  16349. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  16350. const cx = ( this.right + this.left ) / 2;
  16351. const cy = ( this.top + this.bottom ) / 2;
  16352. let left = cx - dx;
  16353. let right = cx + dx;
  16354. let top = cy + dy;
  16355. let bottom = cy - dy;
  16356. if ( this.view !== null && this.view.enabled ) {
  16357. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  16358. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  16359. left += scaleW * this.view.offsetX;
  16360. right = left + scaleW * this.view.width;
  16361. top -= scaleH * this.view.offsetY;
  16362. bottom = top - scaleH * this.view.height;
  16363. }
  16364. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  16365. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16366. }
  16367. toJSON( meta ) {
  16368. const data = super.toJSON( meta );
  16369. data.object.zoom = this.zoom;
  16370. data.object.left = this.left;
  16371. data.object.right = this.right;
  16372. data.object.top = this.top;
  16373. data.object.bottom = this.bottom;
  16374. data.object.near = this.near;
  16375. data.object.far = this.far;
  16376. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16377. return data;
  16378. }
  16379. }
  16380. class DirectionalLightShadow extends LightShadow {
  16381. constructor() {
  16382. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  16383. this.isDirectionalLightShadow = true;
  16384. }
  16385. }
  16386. class DirectionalLight extends Light {
  16387. constructor( color, intensity ) {
  16388. super( color, intensity );
  16389. this.isDirectionalLight = true;
  16390. this.type = 'DirectionalLight';
  16391. this.position.copy( Object3D.DEFAULT_UP );
  16392. this.updateMatrix();
  16393. this.target = new Object3D();
  16394. this.shadow = new DirectionalLightShadow();
  16395. }
  16396. dispose() {
  16397. this.shadow.dispose();
  16398. }
  16399. copy( source ) {
  16400. super.copy( source );
  16401. this.target = source.target.clone();
  16402. this.shadow = source.shadow.clone();
  16403. return this;
  16404. }
  16405. }
  16406. class AmbientLight extends Light {
  16407. constructor( color, intensity ) {
  16408. super( color, intensity );
  16409. this.isAmbientLight = true;
  16410. this.type = 'AmbientLight';
  16411. }
  16412. }
  16413. class RectAreaLight extends Light {
  16414. constructor( color, intensity, width = 10, height = 10 ) {
  16415. super( color, intensity );
  16416. this.isRectAreaLight = true;
  16417. this.type = 'RectAreaLight';
  16418. this.width = width;
  16419. this.height = height;
  16420. }
  16421. get power() {
  16422. // compute the light's luminous power (in lumens) from its intensity (in nits)
  16423. return this.intensity * this.width * this.height * Math.PI;
  16424. }
  16425. set power( power ) {
  16426. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  16427. this.intensity = power / ( this.width * this.height * Math.PI );
  16428. }
  16429. copy( source ) {
  16430. super.copy( source );
  16431. this.width = source.width;
  16432. this.height = source.height;
  16433. return this;
  16434. }
  16435. toJSON( meta ) {
  16436. const data = super.toJSON( meta );
  16437. data.object.width = this.width;
  16438. data.object.height = this.height;
  16439. return data;
  16440. }
  16441. }
  16442. /**
  16443. * Primary reference:
  16444. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16445. *
  16446. * Secondary reference:
  16447. * https://www.ppsloan.org/publications/StupidSH36.pdf
  16448. */
  16449. // 3-band SH defined by 9 coefficients
  16450. class SphericalHarmonics3 {
  16451. constructor() {
  16452. this.isSphericalHarmonics3 = true;
  16453. this.coefficients = [];
  16454. for ( let i = 0; i < 9; i ++ ) {
  16455. this.coefficients.push( new Vector3() );
  16456. }
  16457. }
  16458. set( coefficients ) {
  16459. for ( let i = 0; i < 9; i ++ ) {
  16460. this.coefficients[ i ].copy( coefficients[ i ] );
  16461. }
  16462. return this;
  16463. }
  16464. zero() {
  16465. for ( let i = 0; i < 9; i ++ ) {
  16466. this.coefficients[ i ].set( 0, 0, 0 );
  16467. }
  16468. return this;
  16469. }
  16470. // get the radiance in the direction of the normal
  16471. // target is a Vector3
  16472. getAt( normal, target ) {
  16473. // normal is assumed to be unit length
  16474. const x = normal.x, y = normal.y, z = normal.z;
  16475. const coeff = this.coefficients;
  16476. // band 0
  16477. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  16478. // band 1
  16479. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  16480. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  16481. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  16482. // band 2
  16483. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  16484. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  16485. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  16486. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  16487. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  16488. return target;
  16489. }
  16490. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  16491. // target is a Vector3
  16492. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16493. getIrradianceAt( normal, target ) {
  16494. // normal is assumed to be unit length
  16495. const x = normal.x, y = normal.y, z = normal.z;
  16496. const coeff = this.coefficients;
  16497. // band 0
  16498. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  16499. // band 1
  16500. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  16501. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  16502. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  16503. // band 2
  16504. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  16505. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  16506. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  16507. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  16508. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  16509. return target;
  16510. }
  16511. add( sh ) {
  16512. for ( let i = 0; i < 9; i ++ ) {
  16513. this.coefficients[ i ].add( sh.coefficients[ i ] );
  16514. }
  16515. return this;
  16516. }
  16517. addScaledSH( sh, s ) {
  16518. for ( let i = 0; i < 9; i ++ ) {
  16519. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  16520. }
  16521. return this;
  16522. }
  16523. scale( s ) {
  16524. for ( let i = 0; i < 9; i ++ ) {
  16525. this.coefficients[ i ].multiplyScalar( s );
  16526. }
  16527. return this;
  16528. }
  16529. lerp( sh, alpha ) {
  16530. for ( let i = 0; i < 9; i ++ ) {
  16531. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  16532. }
  16533. return this;
  16534. }
  16535. equals( sh ) {
  16536. for ( let i = 0; i < 9; i ++ ) {
  16537. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  16538. return false;
  16539. }
  16540. }
  16541. return true;
  16542. }
  16543. copy( sh ) {
  16544. return this.set( sh.coefficients );
  16545. }
  16546. clone() {
  16547. return new this.constructor().copy( this );
  16548. }
  16549. fromArray( array, offset = 0 ) {
  16550. const coefficients = this.coefficients;
  16551. for ( let i = 0; i < 9; i ++ ) {
  16552. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  16553. }
  16554. return this;
  16555. }
  16556. toArray( array = [], offset = 0 ) {
  16557. const coefficients = this.coefficients;
  16558. for ( let i = 0; i < 9; i ++ ) {
  16559. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  16560. }
  16561. return array;
  16562. }
  16563. // evaluate the basis functions
  16564. // shBasis is an Array[ 9 ]
  16565. static getBasisAt( normal, shBasis ) {
  16566. // normal is assumed to be unit length
  16567. const x = normal.x, y = normal.y, z = normal.z;
  16568. // band 0
  16569. shBasis[ 0 ] = 0.282095;
  16570. // band 1
  16571. shBasis[ 1 ] = 0.488603 * y;
  16572. shBasis[ 2 ] = 0.488603 * z;
  16573. shBasis[ 3 ] = 0.488603 * x;
  16574. // band 2
  16575. shBasis[ 4 ] = 1.092548 * x * y;
  16576. shBasis[ 5 ] = 1.092548 * y * z;
  16577. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  16578. shBasis[ 7 ] = 1.092548 * x * z;
  16579. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  16580. }
  16581. }
  16582. class LightProbe extends Light {
  16583. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  16584. super( undefined, intensity );
  16585. this.isLightProbe = true;
  16586. this.sh = sh;
  16587. }
  16588. copy( source ) {
  16589. super.copy( source );
  16590. this.sh.copy( source.sh );
  16591. return this;
  16592. }
  16593. fromJSON( json ) {
  16594. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  16595. this.sh.fromArray( json.sh );
  16596. return this;
  16597. }
  16598. toJSON( meta ) {
  16599. const data = super.toJSON( meta );
  16600. data.object.sh = this.sh.toArray();
  16601. return data;
  16602. }
  16603. }
  16604. class MaterialLoader extends Loader {
  16605. constructor( manager ) {
  16606. super( manager );
  16607. this.textures = {};
  16608. }
  16609. load( url, onLoad, onProgress, onError ) {
  16610. const scope = this;
  16611. const loader = new FileLoader( scope.manager );
  16612. loader.setPath( scope.path );
  16613. loader.setRequestHeader( scope.requestHeader );
  16614. loader.setWithCredentials( scope.withCredentials );
  16615. loader.load( url, function ( text ) {
  16616. try {
  16617. onLoad( scope.parse( JSON.parse( text ) ) );
  16618. } catch ( e ) {
  16619. if ( onError ) {
  16620. onError( e );
  16621. } else {
  16622. console.error( e );
  16623. }
  16624. scope.manager.itemError( url );
  16625. }
  16626. }, onProgress, onError );
  16627. }
  16628. parse( json ) {
  16629. const textures = this.textures;
  16630. function getTexture( name ) {
  16631. if ( textures[ name ] === undefined ) {
  16632. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  16633. }
  16634. return textures[ name ];
  16635. }
  16636. const material = MaterialLoader.createMaterialFromType( json.type );
  16637. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  16638. if ( json.name !== undefined ) material.name = json.name;
  16639. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  16640. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  16641. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  16642. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  16643. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  16644. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  16645. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  16646. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  16647. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  16648. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  16649. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  16650. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  16651. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  16652. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  16653. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  16654. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  16655. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  16656. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  16657. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  16658. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  16659. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  16660. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  16661. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  16662. if ( json.fog !== undefined ) material.fog = json.fog;
  16663. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  16664. if ( json.blending !== undefined ) material.blending = json.blending;
  16665. if ( json.combine !== undefined ) material.combine = json.combine;
  16666. if ( json.side !== undefined ) material.side = json.side;
  16667. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  16668. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  16669. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  16670. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  16671. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  16672. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  16673. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  16674. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  16675. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  16676. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  16677. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  16678. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  16679. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  16680. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  16681. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  16682. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  16683. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  16684. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  16685. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  16686. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  16687. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  16688. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  16689. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  16690. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  16691. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  16692. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  16693. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  16694. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  16695. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  16696. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  16697. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  16698. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  16699. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  16700. if ( json.scale !== undefined ) material.scale = json.scale;
  16701. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  16702. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  16703. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  16704. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  16705. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  16706. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  16707. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  16708. if ( json.visible !== undefined ) material.visible = json.visible;
  16709. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  16710. if ( json.userData !== undefined ) material.userData = json.userData;
  16711. if ( json.vertexColors !== undefined ) {
  16712. if ( typeof json.vertexColors === 'number' ) {
  16713. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  16714. } else {
  16715. material.vertexColors = json.vertexColors;
  16716. }
  16717. }
  16718. // Shader Material
  16719. if ( json.uniforms !== undefined ) {
  16720. for ( const name in json.uniforms ) {
  16721. const uniform = json.uniforms[ name ];
  16722. material.uniforms[ name ] = {};
  16723. switch ( uniform.type ) {
  16724. case 't':
  16725. material.uniforms[ name ].value = getTexture( uniform.value );
  16726. break;
  16727. case 'c':
  16728. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  16729. break;
  16730. case 'v2':
  16731. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  16732. break;
  16733. case 'v3':
  16734. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  16735. break;
  16736. case 'v4':
  16737. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  16738. break;
  16739. case 'm3':
  16740. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  16741. break;
  16742. case 'm4':
  16743. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  16744. break;
  16745. default:
  16746. material.uniforms[ name ].value = uniform.value;
  16747. }
  16748. }
  16749. }
  16750. if ( json.defines !== undefined ) material.defines = json.defines;
  16751. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  16752. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  16753. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  16754. if ( json.extensions !== undefined ) {
  16755. for ( const key in json.extensions ) {
  16756. material.extensions[ key ] = json.extensions[ key ];
  16757. }
  16758. }
  16759. if ( json.lights !== undefined ) material.lights = json.lights;
  16760. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  16761. // for PointsMaterial
  16762. if ( json.size !== undefined ) material.size = json.size;
  16763. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  16764. // maps
  16765. if ( json.map !== undefined ) material.map = getTexture( json.map );
  16766. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  16767. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  16768. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  16769. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  16770. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  16771. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  16772. if ( json.normalScale !== undefined ) {
  16773. let normalScale = json.normalScale;
  16774. if ( Array.isArray( normalScale ) === false ) {
  16775. // Blender exporter used to export a scalar. See #7459
  16776. normalScale = [ normalScale, normalScale ];
  16777. }
  16778. material.normalScale = new Vector2().fromArray( normalScale );
  16779. }
  16780. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  16781. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  16782. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  16783. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  16784. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  16785. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  16786. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  16787. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  16788. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  16789. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  16790. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  16791. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  16792. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  16793. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  16794. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  16795. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  16796. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  16797. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  16798. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  16799. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  16800. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  16801. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  16802. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  16803. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  16804. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  16805. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  16806. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  16807. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  16808. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  16809. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  16810. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  16811. return material;
  16812. }
  16813. setTextures( value ) {
  16814. this.textures = value;
  16815. return this;
  16816. }
  16817. static createMaterialFromType( type ) {
  16818. const materialLib = {
  16819. ShadowMaterial,
  16820. SpriteMaterial,
  16821. RawShaderMaterial,
  16822. ShaderMaterial,
  16823. PointsMaterial,
  16824. MeshPhysicalMaterial,
  16825. MeshStandardMaterial,
  16826. MeshPhongMaterial,
  16827. MeshToonMaterial,
  16828. MeshNormalMaterial,
  16829. MeshLambertMaterial,
  16830. MeshDepthMaterial,
  16831. MeshDistanceMaterial,
  16832. MeshBasicMaterial,
  16833. MeshMatcapMaterial,
  16834. LineDashedMaterial,
  16835. LineBasicMaterial,
  16836. Material
  16837. };
  16838. return new materialLib[ type ]();
  16839. }
  16840. }
  16841. class LoaderUtils {
  16842. static decodeText( array ) { // @deprecated, r165
  16843. console.warn( 'THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.' );
  16844. if ( typeof TextDecoder !== 'undefined' ) {
  16845. return new TextDecoder().decode( array );
  16846. }
  16847. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  16848. // throws a "maximum call stack size exceeded" error for large arrays.
  16849. let s = '';
  16850. for ( let i = 0, il = array.length; i < il; i ++ ) {
  16851. // Implicitly assumes little-endian.
  16852. s += String.fromCharCode( array[ i ] );
  16853. }
  16854. try {
  16855. // merges multi-byte utf-8 characters.
  16856. return decodeURIComponent( escape( s ) );
  16857. } catch ( e ) { // see #16358
  16858. return s;
  16859. }
  16860. }
  16861. static extractUrlBase( url ) {
  16862. const index = url.lastIndexOf( '/' );
  16863. if ( index === - 1 ) return './';
  16864. return url.slice( 0, index + 1 );
  16865. }
  16866. static resolveURL( url, path ) {
  16867. // Invalid URL
  16868. if ( typeof url !== 'string' || url === '' ) return '';
  16869. // Host Relative URL
  16870. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  16871. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  16872. }
  16873. // Absolute URL http://,https://,//
  16874. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  16875. // Data URI
  16876. if ( /^data:.*,.*$/i.test( url ) ) return url;
  16877. // Blob URL
  16878. if ( /^blob:.*$/i.test( url ) ) return url;
  16879. // Relative URL
  16880. return path + url;
  16881. }
  16882. }
  16883. class InstancedBufferGeometry extends BufferGeometry {
  16884. constructor() {
  16885. super();
  16886. this.isInstancedBufferGeometry = true;
  16887. this.type = 'InstancedBufferGeometry';
  16888. this.instanceCount = Infinity;
  16889. }
  16890. copy( source ) {
  16891. super.copy( source );
  16892. this.instanceCount = source.instanceCount;
  16893. return this;
  16894. }
  16895. toJSON() {
  16896. const data = super.toJSON();
  16897. data.instanceCount = this.instanceCount;
  16898. data.isInstancedBufferGeometry = true;
  16899. return data;
  16900. }
  16901. }
  16902. class BufferGeometryLoader extends Loader {
  16903. constructor( manager ) {
  16904. super( manager );
  16905. }
  16906. load( url, onLoad, onProgress, onError ) {
  16907. const scope = this;
  16908. const loader = new FileLoader( scope.manager );
  16909. loader.setPath( scope.path );
  16910. loader.setRequestHeader( scope.requestHeader );
  16911. loader.setWithCredentials( scope.withCredentials );
  16912. loader.load( url, function ( text ) {
  16913. try {
  16914. onLoad( scope.parse( JSON.parse( text ) ) );
  16915. } catch ( e ) {
  16916. if ( onError ) {
  16917. onError( e );
  16918. } else {
  16919. console.error( e );
  16920. }
  16921. scope.manager.itemError( url );
  16922. }
  16923. }, onProgress, onError );
  16924. }
  16925. parse( json ) {
  16926. const interleavedBufferMap = {};
  16927. const arrayBufferMap = {};
  16928. function getInterleavedBuffer( json, uuid ) {
  16929. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  16930. const interleavedBuffers = json.interleavedBuffers;
  16931. const interleavedBuffer = interleavedBuffers[ uuid ];
  16932. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  16933. const array = getTypedArray( interleavedBuffer.type, buffer );
  16934. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  16935. ib.uuid = interleavedBuffer.uuid;
  16936. interleavedBufferMap[ uuid ] = ib;
  16937. return ib;
  16938. }
  16939. function getArrayBuffer( json, uuid ) {
  16940. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  16941. const arrayBuffers = json.arrayBuffers;
  16942. const arrayBuffer = arrayBuffers[ uuid ];
  16943. const ab = new Uint32Array( arrayBuffer ).buffer;
  16944. arrayBufferMap[ uuid ] = ab;
  16945. return ab;
  16946. }
  16947. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  16948. const index = json.data.index;
  16949. if ( index !== undefined ) {
  16950. const typedArray = getTypedArray( index.type, index.array );
  16951. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  16952. }
  16953. const attributes = json.data.attributes;
  16954. for ( const key in attributes ) {
  16955. const attribute = attributes[ key ];
  16956. let bufferAttribute;
  16957. if ( attribute.isInterleavedBufferAttribute ) {
  16958. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  16959. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  16960. } else {
  16961. const typedArray = getTypedArray( attribute.type, attribute.array );
  16962. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  16963. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  16964. }
  16965. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  16966. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  16967. geometry.setAttribute( key, bufferAttribute );
  16968. }
  16969. const morphAttributes = json.data.morphAttributes;
  16970. if ( morphAttributes ) {
  16971. for ( const key in morphAttributes ) {
  16972. const attributeArray = morphAttributes[ key ];
  16973. const array = [];
  16974. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  16975. const attribute = attributeArray[ i ];
  16976. let bufferAttribute;
  16977. if ( attribute.isInterleavedBufferAttribute ) {
  16978. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  16979. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  16980. } else {
  16981. const typedArray = getTypedArray( attribute.type, attribute.array );
  16982. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  16983. }
  16984. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  16985. array.push( bufferAttribute );
  16986. }
  16987. geometry.morphAttributes[ key ] = array;
  16988. }
  16989. }
  16990. const morphTargetsRelative = json.data.morphTargetsRelative;
  16991. if ( morphTargetsRelative ) {
  16992. geometry.morphTargetsRelative = true;
  16993. }
  16994. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  16995. if ( groups !== undefined ) {
  16996. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  16997. const group = groups[ i ];
  16998. geometry.addGroup( group.start, group.count, group.materialIndex );
  16999. }
  17000. }
  17001. const boundingSphere = json.data.boundingSphere;
  17002. if ( boundingSphere !== undefined ) {
  17003. const center = new Vector3();
  17004. if ( boundingSphere.center !== undefined ) {
  17005. center.fromArray( boundingSphere.center );
  17006. }
  17007. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  17008. }
  17009. if ( json.name ) geometry.name = json.name;
  17010. if ( json.userData ) geometry.userData = json.userData;
  17011. return geometry;
  17012. }
  17013. }
  17014. class ObjectLoader extends Loader {
  17015. constructor( manager ) {
  17016. super( manager );
  17017. }
  17018. load( url, onLoad, onProgress, onError ) {
  17019. const scope = this;
  17020. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17021. this.resourcePath = this.resourcePath || path;
  17022. const loader = new FileLoader( this.manager );
  17023. loader.setPath( this.path );
  17024. loader.setRequestHeader( this.requestHeader );
  17025. loader.setWithCredentials( this.withCredentials );
  17026. loader.load( url, function ( text ) {
  17027. let json = null;
  17028. try {
  17029. json = JSON.parse( text );
  17030. } catch ( error ) {
  17031. if ( onError !== undefined ) onError( error );
  17032. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  17033. return;
  17034. }
  17035. const metadata = json.metadata;
  17036. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17037. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  17038. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17039. return;
  17040. }
  17041. scope.parse( json, onLoad );
  17042. }, onProgress, onError );
  17043. }
  17044. async loadAsync( url, onProgress ) {
  17045. const scope = this;
  17046. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17047. this.resourcePath = this.resourcePath || path;
  17048. const loader = new FileLoader( this.manager );
  17049. loader.setPath( this.path );
  17050. loader.setRequestHeader( this.requestHeader );
  17051. loader.setWithCredentials( this.withCredentials );
  17052. const text = await loader.loadAsync( url, onProgress );
  17053. const json = JSON.parse( text );
  17054. const metadata = json.metadata;
  17055. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17056. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17057. }
  17058. return await scope.parseAsync( json );
  17059. }
  17060. parse( json, onLoad ) {
  17061. const animations = this.parseAnimations( json.animations );
  17062. const shapes = this.parseShapes( json.shapes );
  17063. const geometries = this.parseGeometries( json.geometries, shapes );
  17064. const images = this.parseImages( json.images, function () {
  17065. if ( onLoad !== undefined ) onLoad( object );
  17066. } );
  17067. const textures = this.parseTextures( json.textures, images );
  17068. const materials = this.parseMaterials( json.materials, textures );
  17069. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17070. const skeletons = this.parseSkeletons( json.skeletons, object );
  17071. this.bindSkeletons( object, skeletons );
  17072. this.bindLightTargets( object );
  17073. //
  17074. if ( onLoad !== undefined ) {
  17075. let hasImages = false;
  17076. for ( const uuid in images ) {
  17077. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  17078. hasImages = true;
  17079. break;
  17080. }
  17081. }
  17082. if ( hasImages === false ) onLoad( object );
  17083. }
  17084. return object;
  17085. }
  17086. async parseAsync( json ) {
  17087. const animations = this.parseAnimations( json.animations );
  17088. const shapes = this.parseShapes( json.shapes );
  17089. const geometries = this.parseGeometries( json.geometries, shapes );
  17090. const images = await this.parseImagesAsync( json.images );
  17091. const textures = this.parseTextures( json.textures, images );
  17092. const materials = this.parseMaterials( json.materials, textures );
  17093. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17094. const skeletons = this.parseSkeletons( json.skeletons, object );
  17095. this.bindSkeletons( object, skeletons );
  17096. this.bindLightTargets( object );
  17097. return object;
  17098. }
  17099. parseShapes( json ) {
  17100. const shapes = {};
  17101. if ( json !== undefined ) {
  17102. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17103. const shape = new Shape().fromJSON( json[ i ] );
  17104. shapes[ shape.uuid ] = shape;
  17105. }
  17106. }
  17107. return shapes;
  17108. }
  17109. parseSkeletons( json, object ) {
  17110. const skeletons = {};
  17111. const bones = {};
  17112. // generate bone lookup table
  17113. object.traverse( function ( child ) {
  17114. if ( child.isBone ) bones[ child.uuid ] = child;
  17115. } );
  17116. // create skeletons
  17117. if ( json !== undefined ) {
  17118. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17119. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  17120. skeletons[ skeleton.uuid ] = skeleton;
  17121. }
  17122. }
  17123. return skeletons;
  17124. }
  17125. parseGeometries( json, shapes ) {
  17126. const geometries = {};
  17127. if ( json !== undefined ) {
  17128. const bufferGeometryLoader = new BufferGeometryLoader();
  17129. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17130. let geometry;
  17131. const data = json[ i ];
  17132. switch ( data.type ) {
  17133. case 'BufferGeometry':
  17134. case 'InstancedBufferGeometry':
  17135. geometry = bufferGeometryLoader.parse( data );
  17136. break;
  17137. default:
  17138. if ( data.type in Geometries$1 ) {
  17139. geometry = Geometries$1[ data.type ].fromJSON( data, shapes );
  17140. } else {
  17141. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  17142. }
  17143. }
  17144. geometry.uuid = data.uuid;
  17145. if ( data.name !== undefined ) geometry.name = data.name;
  17146. if ( data.userData !== undefined ) geometry.userData = data.userData;
  17147. geometries[ data.uuid ] = geometry;
  17148. }
  17149. }
  17150. return geometries;
  17151. }
  17152. parseMaterials( json, textures ) {
  17153. const cache = {}; // MultiMaterial
  17154. const materials = {};
  17155. if ( json !== undefined ) {
  17156. const loader = new MaterialLoader();
  17157. loader.setTextures( textures );
  17158. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17159. const data = json[ i ];
  17160. if ( cache[ data.uuid ] === undefined ) {
  17161. cache[ data.uuid ] = loader.parse( data );
  17162. }
  17163. materials[ data.uuid ] = cache[ data.uuid ];
  17164. }
  17165. }
  17166. return materials;
  17167. }
  17168. parseAnimations( json ) {
  17169. const animations = {};
  17170. if ( json !== undefined ) {
  17171. for ( let i = 0; i < json.length; i ++ ) {
  17172. const data = json[ i ];
  17173. const clip = AnimationClip.parse( data );
  17174. animations[ clip.uuid ] = clip;
  17175. }
  17176. }
  17177. return animations;
  17178. }
  17179. parseImages( json, onLoad ) {
  17180. const scope = this;
  17181. const images = {};
  17182. let loader;
  17183. function loadImage( url ) {
  17184. scope.manager.itemStart( url );
  17185. return loader.load( url, function () {
  17186. scope.manager.itemEnd( url );
  17187. }, undefined, function () {
  17188. scope.manager.itemError( url );
  17189. scope.manager.itemEnd( url );
  17190. } );
  17191. }
  17192. function deserializeImage( image ) {
  17193. if ( typeof image === 'string' ) {
  17194. const url = image;
  17195. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17196. return loadImage( path );
  17197. } else {
  17198. if ( image.data ) {
  17199. return {
  17200. data: getTypedArray( image.type, image.data ),
  17201. width: image.width,
  17202. height: image.height
  17203. };
  17204. } else {
  17205. return null;
  17206. }
  17207. }
  17208. }
  17209. if ( json !== undefined && json.length > 0 ) {
  17210. const manager = new LoadingManager( onLoad );
  17211. loader = new ImageLoader( manager );
  17212. loader.setCrossOrigin( this.crossOrigin );
  17213. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17214. const image = json[ i ];
  17215. const url = image.url;
  17216. if ( Array.isArray( url ) ) {
  17217. // load array of images e.g CubeTexture
  17218. const imageArray = [];
  17219. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17220. const currentUrl = url[ j ];
  17221. const deserializedImage = deserializeImage( currentUrl );
  17222. if ( deserializedImage !== null ) {
  17223. if ( deserializedImage instanceof HTMLImageElement ) {
  17224. imageArray.push( deserializedImage );
  17225. } else {
  17226. // special case: handle array of data textures for cube textures
  17227. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17228. }
  17229. }
  17230. }
  17231. images[ image.uuid ] = new Source( imageArray );
  17232. } else {
  17233. // load single image
  17234. const deserializedImage = deserializeImage( image.url );
  17235. images[ image.uuid ] = new Source( deserializedImage );
  17236. }
  17237. }
  17238. }
  17239. return images;
  17240. }
  17241. async parseImagesAsync( json ) {
  17242. const scope = this;
  17243. const images = {};
  17244. let loader;
  17245. async function deserializeImage( image ) {
  17246. if ( typeof image === 'string' ) {
  17247. const url = image;
  17248. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17249. return await loader.loadAsync( path );
  17250. } else {
  17251. if ( image.data ) {
  17252. return {
  17253. data: getTypedArray( image.type, image.data ),
  17254. width: image.width,
  17255. height: image.height
  17256. };
  17257. } else {
  17258. return null;
  17259. }
  17260. }
  17261. }
  17262. if ( json !== undefined && json.length > 0 ) {
  17263. loader = new ImageLoader( this.manager );
  17264. loader.setCrossOrigin( this.crossOrigin );
  17265. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17266. const image = json[ i ];
  17267. const url = image.url;
  17268. if ( Array.isArray( url ) ) {
  17269. // load array of images e.g CubeTexture
  17270. const imageArray = [];
  17271. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17272. const currentUrl = url[ j ];
  17273. const deserializedImage = await deserializeImage( currentUrl );
  17274. if ( deserializedImage !== null ) {
  17275. if ( deserializedImage instanceof HTMLImageElement ) {
  17276. imageArray.push( deserializedImage );
  17277. } else {
  17278. // special case: handle array of data textures for cube textures
  17279. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17280. }
  17281. }
  17282. }
  17283. images[ image.uuid ] = new Source( imageArray );
  17284. } else {
  17285. // load single image
  17286. const deserializedImage = await deserializeImage( image.url );
  17287. images[ image.uuid ] = new Source( deserializedImage );
  17288. }
  17289. }
  17290. }
  17291. return images;
  17292. }
  17293. parseTextures( json, images ) {
  17294. function parseConstant( value, type ) {
  17295. if ( typeof value === 'number' ) return value;
  17296. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  17297. return type[ value ];
  17298. }
  17299. const textures = {};
  17300. if ( json !== undefined ) {
  17301. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17302. const data = json[ i ];
  17303. if ( data.image === undefined ) {
  17304. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  17305. }
  17306. if ( images[ data.image ] === undefined ) {
  17307. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  17308. }
  17309. const source = images[ data.image ];
  17310. const image = source.data;
  17311. let texture;
  17312. if ( Array.isArray( image ) ) {
  17313. texture = new CubeTexture();
  17314. if ( image.length === 6 ) texture.needsUpdate = true;
  17315. } else {
  17316. if ( image && image.data ) {
  17317. texture = new DataTexture();
  17318. } else {
  17319. texture = new Texture();
  17320. }
  17321. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  17322. }
  17323. texture.source = source;
  17324. texture.uuid = data.uuid;
  17325. if ( data.name !== undefined ) texture.name = data.name;
  17326. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  17327. if ( data.channel !== undefined ) texture.channel = data.channel;
  17328. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  17329. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  17330. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  17331. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  17332. if ( data.wrap !== undefined ) {
  17333. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  17334. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  17335. }
  17336. if ( data.format !== undefined ) texture.format = data.format;
  17337. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  17338. if ( data.type !== undefined ) texture.type = data.type;
  17339. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  17340. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  17341. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  17342. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  17343. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  17344. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  17345. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  17346. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  17347. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  17348. if ( data.userData !== undefined ) texture.userData = data.userData;
  17349. textures[ data.uuid ] = texture;
  17350. }
  17351. }
  17352. return textures;
  17353. }
  17354. parseObject( data, geometries, materials, textures, animations ) {
  17355. let object;
  17356. function getGeometry( name ) {
  17357. if ( geometries[ name ] === undefined ) {
  17358. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  17359. }
  17360. return geometries[ name ];
  17361. }
  17362. function getMaterial( name ) {
  17363. if ( name === undefined ) return undefined;
  17364. if ( Array.isArray( name ) ) {
  17365. const array = [];
  17366. for ( let i = 0, l = name.length; i < l; i ++ ) {
  17367. const uuid = name[ i ];
  17368. if ( materials[ uuid ] === undefined ) {
  17369. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  17370. }
  17371. array.push( materials[ uuid ] );
  17372. }
  17373. return array;
  17374. }
  17375. if ( materials[ name ] === undefined ) {
  17376. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  17377. }
  17378. return materials[ name ];
  17379. }
  17380. function getTexture( uuid ) {
  17381. if ( textures[ uuid ] === undefined ) {
  17382. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  17383. }
  17384. return textures[ uuid ];
  17385. }
  17386. let geometry, material;
  17387. switch ( data.type ) {
  17388. case 'Scene':
  17389. object = new Scene();
  17390. if ( data.background !== undefined ) {
  17391. if ( Number.isInteger( data.background ) ) {
  17392. object.background = new Color( data.background );
  17393. } else {
  17394. object.background = getTexture( data.background );
  17395. }
  17396. }
  17397. if ( data.environment !== undefined ) {
  17398. object.environment = getTexture( data.environment );
  17399. }
  17400. if ( data.fog !== undefined ) {
  17401. if ( data.fog.type === 'Fog' ) {
  17402. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  17403. } else if ( data.fog.type === 'FogExp2' ) {
  17404. object.fog = new FogExp2( data.fog.color, data.fog.density );
  17405. }
  17406. if ( data.fog.name !== '' ) {
  17407. object.fog.name = data.fog.name;
  17408. }
  17409. }
  17410. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  17411. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  17412. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  17413. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  17414. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  17415. break;
  17416. case 'PerspectiveCamera':
  17417. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  17418. if ( data.focus !== undefined ) object.focus = data.focus;
  17419. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17420. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  17421. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  17422. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17423. break;
  17424. case 'OrthographicCamera':
  17425. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  17426. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17427. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17428. break;
  17429. case 'AmbientLight':
  17430. object = new AmbientLight( data.color, data.intensity );
  17431. break;
  17432. case 'DirectionalLight':
  17433. object = new DirectionalLight( data.color, data.intensity );
  17434. object.target = data.target || '';
  17435. break;
  17436. case 'PointLight':
  17437. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  17438. break;
  17439. case 'RectAreaLight':
  17440. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  17441. break;
  17442. case 'SpotLight':
  17443. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  17444. object.target = data.target || '';
  17445. break;
  17446. case 'HemisphereLight':
  17447. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  17448. break;
  17449. case 'LightProbe':
  17450. object = new LightProbe().fromJSON( data );
  17451. break;
  17452. case 'SkinnedMesh':
  17453. geometry = getGeometry( data.geometry );
  17454. material = getMaterial( data.material );
  17455. object = new SkinnedMesh( geometry, material );
  17456. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  17457. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  17458. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  17459. break;
  17460. case 'Mesh':
  17461. geometry = getGeometry( data.geometry );
  17462. material = getMaterial( data.material );
  17463. object = new Mesh( geometry, material );
  17464. break;
  17465. case 'InstancedMesh':
  17466. geometry = getGeometry( data.geometry );
  17467. material = getMaterial( data.material );
  17468. const count = data.count;
  17469. const instanceMatrix = data.instanceMatrix;
  17470. const instanceColor = data.instanceColor;
  17471. object = new InstancedMesh( geometry, material, count );
  17472. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  17473. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  17474. break;
  17475. case 'BatchedMesh':
  17476. geometry = getGeometry( data.geometry );
  17477. material = getMaterial( data.material );
  17478. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  17479. object.geometry = geometry;
  17480. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  17481. object.sortObjects = data.sortObjects;
  17482. object._drawRanges = data.drawRanges;
  17483. object._reservedRanges = data.reservedRanges;
  17484. object._visibility = data.visibility;
  17485. object._active = data.active;
  17486. object._bounds = data.bounds.map( bound => {
  17487. const box = new Box3();
  17488. box.min.fromArray( bound.boxMin );
  17489. box.max.fromArray( bound.boxMax );
  17490. const sphere = new Sphere();
  17491. sphere.radius = bound.sphereRadius;
  17492. sphere.center.fromArray( bound.sphereCenter );
  17493. return {
  17494. boxInitialized: bound.boxInitialized,
  17495. box: box,
  17496. sphereInitialized: bound.sphereInitialized,
  17497. sphere: sphere
  17498. };
  17499. } );
  17500. object._maxInstanceCount = data.maxInstanceCount;
  17501. object._maxVertexCount = data.maxVertexCount;
  17502. object._maxIndexCount = data.maxIndexCount;
  17503. object._geometryInitialized = data.geometryInitialized;
  17504. object._geometryCount = data.geometryCount;
  17505. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  17506. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  17507. break;
  17508. case 'LOD':
  17509. object = new LOD();
  17510. break;
  17511. case 'Line':
  17512. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  17513. break;
  17514. case 'LineLoop':
  17515. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  17516. break;
  17517. case 'LineSegments':
  17518. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  17519. break;
  17520. case 'PointCloud':
  17521. case 'Points':
  17522. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  17523. break;
  17524. case 'Sprite':
  17525. object = new Sprite( getMaterial( data.material ) );
  17526. break;
  17527. case 'Group':
  17528. object = new Group();
  17529. break;
  17530. case 'Bone':
  17531. object = new Bone();
  17532. break;
  17533. default:
  17534. object = new Object3D();
  17535. }
  17536. object.uuid = data.uuid;
  17537. if ( data.name !== undefined ) object.name = data.name;
  17538. if ( data.matrix !== undefined ) {
  17539. object.matrix.fromArray( data.matrix );
  17540. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  17541. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  17542. } else {
  17543. if ( data.position !== undefined ) object.position.fromArray( data.position );
  17544. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  17545. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  17546. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  17547. }
  17548. if ( data.up !== undefined ) object.up.fromArray( data.up );
  17549. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  17550. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  17551. if ( data.shadow ) {
  17552. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  17553. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  17554. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  17555. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  17556. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  17557. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  17558. }
  17559. if ( data.visible !== undefined ) object.visible = data.visible;
  17560. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  17561. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  17562. if ( data.userData !== undefined ) object.userData = data.userData;
  17563. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  17564. if ( data.children !== undefined ) {
  17565. const children = data.children;
  17566. for ( let i = 0; i < children.length; i ++ ) {
  17567. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  17568. }
  17569. }
  17570. if ( data.animations !== undefined ) {
  17571. const objectAnimations = data.animations;
  17572. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  17573. const uuid = objectAnimations[ i ];
  17574. object.animations.push( animations[ uuid ] );
  17575. }
  17576. }
  17577. if ( data.type === 'LOD' ) {
  17578. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  17579. const levels = data.levels;
  17580. for ( let l = 0; l < levels.length; l ++ ) {
  17581. const level = levels[ l ];
  17582. const child = object.getObjectByProperty( 'uuid', level.object );
  17583. if ( child !== undefined ) {
  17584. object.addLevel( child, level.distance, level.hysteresis );
  17585. }
  17586. }
  17587. }
  17588. return object;
  17589. }
  17590. bindSkeletons( object, skeletons ) {
  17591. if ( Object.keys( skeletons ).length === 0 ) return;
  17592. object.traverse( function ( child ) {
  17593. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  17594. const skeleton = skeletons[ child.skeleton ];
  17595. if ( skeleton === undefined ) {
  17596. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  17597. } else {
  17598. child.bind( skeleton, child.bindMatrix );
  17599. }
  17600. }
  17601. } );
  17602. }
  17603. bindLightTargets( object ) {
  17604. object.traverse( function ( child ) {
  17605. if ( child.isDirectionalLight || child.isSpotLight ) {
  17606. const uuid = child.target;
  17607. const target = object.getObjectByProperty( 'uuid', uuid );
  17608. if ( target !== undefined ) {
  17609. child.target = target;
  17610. } else {
  17611. child.target = new Object3D();
  17612. }
  17613. }
  17614. } );
  17615. }
  17616. }
  17617. const TEXTURE_MAPPING = {
  17618. UVMapping: UVMapping,
  17619. CubeReflectionMapping: CubeReflectionMapping,
  17620. CubeRefractionMapping: CubeRefractionMapping,
  17621. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  17622. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  17623. CubeUVReflectionMapping: CubeUVReflectionMapping
  17624. };
  17625. const TEXTURE_WRAPPING = {
  17626. RepeatWrapping: RepeatWrapping,
  17627. ClampToEdgeWrapping: ClampToEdgeWrapping,
  17628. MirroredRepeatWrapping: MirroredRepeatWrapping
  17629. };
  17630. const TEXTURE_FILTER = {
  17631. NearestFilter: NearestFilter,
  17632. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  17633. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  17634. LinearFilter: LinearFilter,
  17635. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  17636. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  17637. };
  17638. class ImageBitmapLoader extends Loader {
  17639. constructor( manager ) {
  17640. super( manager );
  17641. this.isImageBitmapLoader = true;
  17642. if ( typeof createImageBitmap === 'undefined' ) {
  17643. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  17644. }
  17645. if ( typeof fetch === 'undefined' ) {
  17646. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  17647. }
  17648. this.options = { premultiplyAlpha: 'none' };
  17649. }
  17650. setOptions( options ) {
  17651. this.options = options;
  17652. return this;
  17653. }
  17654. load( url, onLoad, onProgress, onError ) {
  17655. if ( url === undefined ) url = '';
  17656. if ( this.path !== undefined ) url = this.path + url;
  17657. url = this.manager.resolveURL( url );
  17658. const scope = this;
  17659. const cached = Cache.get( url );
  17660. if ( cached !== undefined ) {
  17661. scope.manager.itemStart( url );
  17662. // If cached is a promise, wait for it to resolve
  17663. if ( cached.then ) {
  17664. cached.then( imageBitmap => {
  17665. if ( onLoad ) onLoad( imageBitmap );
  17666. scope.manager.itemEnd( url );
  17667. } ).catch( e => {
  17668. if ( onError ) onError( e );
  17669. } );
  17670. return;
  17671. }
  17672. // If cached is not a promise (i.e., it's already an imageBitmap)
  17673. setTimeout( function () {
  17674. if ( onLoad ) onLoad( cached );
  17675. scope.manager.itemEnd( url );
  17676. }, 0 );
  17677. return cached;
  17678. }
  17679. const fetchOptions = {};
  17680. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  17681. fetchOptions.headers = this.requestHeader;
  17682. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  17683. return res.blob();
  17684. } ).then( function ( blob ) {
  17685. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  17686. } ).then( function ( imageBitmap ) {
  17687. Cache.add( url, imageBitmap );
  17688. if ( onLoad ) onLoad( imageBitmap );
  17689. scope.manager.itemEnd( url );
  17690. return imageBitmap;
  17691. } ).catch( function ( e ) {
  17692. if ( onError ) onError( e );
  17693. Cache.remove( url );
  17694. scope.manager.itemError( url );
  17695. scope.manager.itemEnd( url );
  17696. } );
  17697. Cache.add( url, promise );
  17698. scope.manager.itemStart( url );
  17699. }
  17700. }
  17701. let _context;
  17702. class AudioContext {
  17703. static getContext() {
  17704. if ( _context === undefined ) {
  17705. _context = new ( window.AudioContext || window.webkitAudioContext )();
  17706. }
  17707. return _context;
  17708. }
  17709. static setContext( value ) {
  17710. _context = value;
  17711. }
  17712. }
  17713. class AudioLoader extends Loader {
  17714. constructor( manager ) {
  17715. super( manager );
  17716. }
  17717. load( url, onLoad, onProgress, onError ) {
  17718. const scope = this;
  17719. const loader = new FileLoader( this.manager );
  17720. loader.setResponseType( 'arraybuffer' );
  17721. loader.setPath( this.path );
  17722. loader.setRequestHeader( this.requestHeader );
  17723. loader.setWithCredentials( this.withCredentials );
  17724. loader.load( url, function ( buffer ) {
  17725. try {
  17726. // Create a copy of the buffer. The `decodeAudioData` method
  17727. // detaches the buffer when complete, preventing reuse.
  17728. const bufferCopy = buffer.slice( 0 );
  17729. const context = AudioContext.getContext();
  17730. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  17731. onLoad( audioBuffer );
  17732. } ).catch( handleError );
  17733. } catch ( e ) {
  17734. handleError( e );
  17735. }
  17736. }, onProgress, onError );
  17737. function handleError( e ) {
  17738. if ( onError ) {
  17739. onError( e );
  17740. } else {
  17741. console.error( e );
  17742. }
  17743. scope.manager.itemError( url );
  17744. }
  17745. }
  17746. }
  17747. const _eyeRight = /*@__PURE__*/ new Matrix4();
  17748. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  17749. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  17750. class StereoCamera {
  17751. constructor() {
  17752. this.type = 'StereoCamera';
  17753. this.aspect = 1;
  17754. this.eyeSep = 0.064;
  17755. this.cameraL = new PerspectiveCamera();
  17756. this.cameraL.layers.enable( 1 );
  17757. this.cameraL.matrixAutoUpdate = false;
  17758. this.cameraR = new PerspectiveCamera();
  17759. this.cameraR.layers.enable( 2 );
  17760. this.cameraR.matrixAutoUpdate = false;
  17761. this._cache = {
  17762. focus: null,
  17763. fov: null,
  17764. aspect: null,
  17765. near: null,
  17766. far: null,
  17767. zoom: null,
  17768. eyeSep: null
  17769. };
  17770. }
  17771. update( camera ) {
  17772. const cache = this._cache;
  17773. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  17774. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  17775. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  17776. if ( needsUpdate ) {
  17777. cache.focus = camera.focus;
  17778. cache.fov = camera.fov;
  17779. cache.aspect = camera.aspect * this.aspect;
  17780. cache.near = camera.near;
  17781. cache.far = camera.far;
  17782. cache.zoom = camera.zoom;
  17783. cache.eyeSep = this.eyeSep;
  17784. // Off-axis stereoscopic effect based on
  17785. // http://paulbourke.net/stereographics/stereorender/
  17786. _projectionMatrix.copy( camera.projectionMatrix );
  17787. const eyeSepHalf = cache.eyeSep / 2;
  17788. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  17789. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  17790. let xmin, xmax;
  17791. // translate xOffset
  17792. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  17793. _eyeRight.elements[ 12 ] = eyeSepHalf;
  17794. // for left eye
  17795. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  17796. xmax = ymax * cache.aspect + eyeSepOnProjection;
  17797. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  17798. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  17799. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  17800. // for right eye
  17801. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  17802. xmax = ymax * cache.aspect - eyeSepOnProjection;
  17803. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  17804. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  17805. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  17806. }
  17807. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  17808. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  17809. }
  17810. }
  17811. class ArrayCamera extends PerspectiveCamera {
  17812. constructor( array = [] ) {
  17813. super();
  17814. this.isArrayCamera = true;
  17815. this.cameras = array;
  17816. }
  17817. }
  17818. class Clock {
  17819. constructor( autoStart = true ) {
  17820. this.autoStart = autoStart;
  17821. this.startTime = 0;
  17822. this.oldTime = 0;
  17823. this.elapsedTime = 0;
  17824. this.running = false;
  17825. }
  17826. start() {
  17827. this.startTime = now();
  17828. this.oldTime = this.startTime;
  17829. this.elapsedTime = 0;
  17830. this.running = true;
  17831. }
  17832. stop() {
  17833. this.getElapsedTime();
  17834. this.running = false;
  17835. this.autoStart = false;
  17836. }
  17837. getElapsedTime() {
  17838. this.getDelta();
  17839. return this.elapsedTime;
  17840. }
  17841. getDelta() {
  17842. let diff = 0;
  17843. if ( this.autoStart && ! this.running ) {
  17844. this.start();
  17845. return 0;
  17846. }
  17847. if ( this.running ) {
  17848. const newTime = now();
  17849. diff = ( newTime - this.oldTime ) / 1000;
  17850. this.oldTime = newTime;
  17851. this.elapsedTime += diff;
  17852. }
  17853. return diff;
  17854. }
  17855. }
  17856. function now() {
  17857. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  17858. }
  17859. const _position$1 = /*@__PURE__*/ new Vector3();
  17860. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  17861. const _scale$1 = /*@__PURE__*/ new Vector3();
  17862. const _orientation$1 = /*@__PURE__*/ new Vector3();
  17863. class AudioListener extends Object3D {
  17864. constructor() {
  17865. super();
  17866. this.type = 'AudioListener';
  17867. this.context = AudioContext.getContext();
  17868. this.gain = this.context.createGain();
  17869. this.gain.connect( this.context.destination );
  17870. this.filter = null;
  17871. this.timeDelta = 0;
  17872. // private
  17873. this._clock = new Clock();
  17874. }
  17875. getInput() {
  17876. return this.gain;
  17877. }
  17878. removeFilter() {
  17879. if ( this.filter !== null ) {
  17880. this.gain.disconnect( this.filter );
  17881. this.filter.disconnect( this.context.destination );
  17882. this.gain.connect( this.context.destination );
  17883. this.filter = null;
  17884. }
  17885. return this;
  17886. }
  17887. getFilter() {
  17888. return this.filter;
  17889. }
  17890. setFilter( value ) {
  17891. if ( this.filter !== null ) {
  17892. this.gain.disconnect( this.filter );
  17893. this.filter.disconnect( this.context.destination );
  17894. } else {
  17895. this.gain.disconnect( this.context.destination );
  17896. }
  17897. this.filter = value;
  17898. this.gain.connect( this.filter );
  17899. this.filter.connect( this.context.destination );
  17900. return this;
  17901. }
  17902. getMasterVolume() {
  17903. return this.gain.gain.value;
  17904. }
  17905. setMasterVolume( value ) {
  17906. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  17907. return this;
  17908. }
  17909. updateMatrixWorld( force ) {
  17910. super.updateMatrixWorld( force );
  17911. const listener = this.context.listener;
  17912. const up = this.up;
  17913. this.timeDelta = this._clock.getDelta();
  17914. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  17915. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  17916. if ( listener.positionX ) {
  17917. // code path for Chrome (see #14393)
  17918. const endTime = this.context.currentTime + this.timeDelta;
  17919. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  17920. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  17921. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  17922. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  17923. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  17924. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  17925. listener.upX.linearRampToValueAtTime( up.x, endTime );
  17926. listener.upY.linearRampToValueAtTime( up.y, endTime );
  17927. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  17928. } else {
  17929. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  17930. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  17931. }
  17932. }
  17933. }
  17934. class Audio extends Object3D {
  17935. constructor( listener ) {
  17936. super();
  17937. this.type = 'Audio';
  17938. this.listener = listener;
  17939. this.context = listener.context;
  17940. this.gain = this.context.createGain();
  17941. this.gain.connect( listener.getInput() );
  17942. this.autoplay = false;
  17943. this.buffer = null;
  17944. this.detune = 0;
  17945. this.loop = false;
  17946. this.loopStart = 0;
  17947. this.loopEnd = 0;
  17948. this.offset = 0;
  17949. this.duration = undefined;
  17950. this.playbackRate = 1;
  17951. this.isPlaying = false;
  17952. this.hasPlaybackControl = true;
  17953. this.source = null;
  17954. this.sourceType = 'empty';
  17955. this._startedAt = 0;
  17956. this._progress = 0;
  17957. this._connected = false;
  17958. this.filters = [];
  17959. }
  17960. getOutput() {
  17961. return this.gain;
  17962. }
  17963. setNodeSource( audioNode ) {
  17964. this.hasPlaybackControl = false;
  17965. this.sourceType = 'audioNode';
  17966. this.source = audioNode;
  17967. this.connect();
  17968. return this;
  17969. }
  17970. setMediaElementSource( mediaElement ) {
  17971. this.hasPlaybackControl = false;
  17972. this.sourceType = 'mediaNode';
  17973. this.source = this.context.createMediaElementSource( mediaElement );
  17974. this.connect();
  17975. return this;
  17976. }
  17977. setMediaStreamSource( mediaStream ) {
  17978. this.hasPlaybackControl = false;
  17979. this.sourceType = 'mediaStreamNode';
  17980. this.source = this.context.createMediaStreamSource( mediaStream );
  17981. this.connect();
  17982. return this;
  17983. }
  17984. setBuffer( audioBuffer ) {
  17985. this.buffer = audioBuffer;
  17986. this.sourceType = 'buffer';
  17987. if ( this.autoplay ) this.play();
  17988. return this;
  17989. }
  17990. play( delay = 0 ) {
  17991. if ( this.isPlaying === true ) {
  17992. console.warn( 'THREE.Audio: Audio is already playing.' );
  17993. return;
  17994. }
  17995. if ( this.hasPlaybackControl === false ) {
  17996. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  17997. return;
  17998. }
  17999. this._startedAt = this.context.currentTime + delay;
  18000. const source = this.context.createBufferSource();
  18001. source.buffer = this.buffer;
  18002. source.loop = this.loop;
  18003. source.loopStart = this.loopStart;
  18004. source.loopEnd = this.loopEnd;
  18005. source.onended = this.onEnded.bind( this );
  18006. source.start( this._startedAt, this._progress + this.offset, this.duration );
  18007. this.isPlaying = true;
  18008. this.source = source;
  18009. this.setDetune( this.detune );
  18010. this.setPlaybackRate( this.playbackRate );
  18011. return this.connect();
  18012. }
  18013. pause() {
  18014. if ( this.hasPlaybackControl === false ) {
  18015. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18016. return;
  18017. }
  18018. if ( this.isPlaying === true ) {
  18019. // update current progress
  18020. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  18021. if ( this.loop === true ) {
  18022. // ensure _progress does not exceed duration with looped audios
  18023. this._progress = this._progress % ( this.duration || this.buffer.duration );
  18024. }
  18025. this.source.stop();
  18026. this.source.onended = null;
  18027. this.isPlaying = false;
  18028. }
  18029. return this;
  18030. }
  18031. stop() {
  18032. if ( this.hasPlaybackControl === false ) {
  18033. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18034. return;
  18035. }
  18036. this._progress = 0;
  18037. if ( this.source !== null ) {
  18038. this.source.stop();
  18039. this.source.onended = null;
  18040. }
  18041. this.isPlaying = false;
  18042. return this;
  18043. }
  18044. connect() {
  18045. if ( this.filters.length > 0 ) {
  18046. this.source.connect( this.filters[ 0 ] );
  18047. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18048. this.filters[ i - 1 ].connect( this.filters[ i ] );
  18049. }
  18050. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  18051. } else {
  18052. this.source.connect( this.getOutput() );
  18053. }
  18054. this._connected = true;
  18055. return this;
  18056. }
  18057. disconnect() {
  18058. if ( this._connected === false ) {
  18059. return;
  18060. }
  18061. if ( this.filters.length > 0 ) {
  18062. this.source.disconnect( this.filters[ 0 ] );
  18063. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18064. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  18065. }
  18066. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  18067. } else {
  18068. this.source.disconnect( this.getOutput() );
  18069. }
  18070. this._connected = false;
  18071. return this;
  18072. }
  18073. getFilters() {
  18074. return this.filters;
  18075. }
  18076. setFilters( value ) {
  18077. if ( ! value ) value = [];
  18078. if ( this._connected === true ) {
  18079. this.disconnect();
  18080. this.filters = value.slice();
  18081. this.connect();
  18082. } else {
  18083. this.filters = value.slice();
  18084. }
  18085. return this;
  18086. }
  18087. setDetune( value ) {
  18088. this.detune = value;
  18089. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  18090. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  18091. }
  18092. return this;
  18093. }
  18094. getDetune() {
  18095. return this.detune;
  18096. }
  18097. getFilter() {
  18098. return this.getFilters()[ 0 ];
  18099. }
  18100. setFilter( filter ) {
  18101. return this.setFilters( filter ? [ filter ] : [] );
  18102. }
  18103. setPlaybackRate( value ) {
  18104. if ( this.hasPlaybackControl === false ) {
  18105. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18106. return;
  18107. }
  18108. this.playbackRate = value;
  18109. if ( this.isPlaying === true ) {
  18110. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  18111. }
  18112. return this;
  18113. }
  18114. getPlaybackRate() {
  18115. return this.playbackRate;
  18116. }
  18117. onEnded() {
  18118. this.isPlaying = false;
  18119. }
  18120. getLoop() {
  18121. if ( this.hasPlaybackControl === false ) {
  18122. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18123. return false;
  18124. }
  18125. return this.loop;
  18126. }
  18127. setLoop( value ) {
  18128. if ( this.hasPlaybackControl === false ) {
  18129. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18130. return;
  18131. }
  18132. this.loop = value;
  18133. if ( this.isPlaying === true ) {
  18134. this.source.loop = this.loop;
  18135. }
  18136. return this;
  18137. }
  18138. setLoopStart( value ) {
  18139. this.loopStart = value;
  18140. return this;
  18141. }
  18142. setLoopEnd( value ) {
  18143. this.loopEnd = value;
  18144. return this;
  18145. }
  18146. getVolume() {
  18147. return this.gain.gain.value;
  18148. }
  18149. setVolume( value ) {
  18150. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  18151. return this;
  18152. }
  18153. }
  18154. const _position = /*@__PURE__*/ new Vector3();
  18155. const _quaternion = /*@__PURE__*/ new Quaternion();
  18156. const _scale = /*@__PURE__*/ new Vector3();
  18157. const _orientation = /*@__PURE__*/ new Vector3();
  18158. class PositionalAudio extends Audio {
  18159. constructor( listener ) {
  18160. super( listener );
  18161. this.panner = this.context.createPanner();
  18162. this.panner.panningModel = 'HRTF';
  18163. this.panner.connect( this.gain );
  18164. }
  18165. connect() {
  18166. super.connect();
  18167. this.panner.connect( this.gain );
  18168. }
  18169. disconnect() {
  18170. super.disconnect();
  18171. this.panner.disconnect( this.gain );
  18172. }
  18173. getOutput() {
  18174. return this.panner;
  18175. }
  18176. getRefDistance() {
  18177. return this.panner.refDistance;
  18178. }
  18179. setRefDistance( value ) {
  18180. this.panner.refDistance = value;
  18181. return this;
  18182. }
  18183. getRolloffFactor() {
  18184. return this.panner.rolloffFactor;
  18185. }
  18186. setRolloffFactor( value ) {
  18187. this.panner.rolloffFactor = value;
  18188. return this;
  18189. }
  18190. getDistanceModel() {
  18191. return this.panner.distanceModel;
  18192. }
  18193. setDistanceModel( value ) {
  18194. this.panner.distanceModel = value;
  18195. return this;
  18196. }
  18197. getMaxDistance() {
  18198. return this.panner.maxDistance;
  18199. }
  18200. setMaxDistance( value ) {
  18201. this.panner.maxDistance = value;
  18202. return this;
  18203. }
  18204. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  18205. this.panner.coneInnerAngle = coneInnerAngle;
  18206. this.panner.coneOuterAngle = coneOuterAngle;
  18207. this.panner.coneOuterGain = coneOuterGain;
  18208. return this;
  18209. }
  18210. updateMatrixWorld( force ) {
  18211. super.updateMatrixWorld( force );
  18212. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  18213. this.matrixWorld.decompose( _position, _quaternion, _scale );
  18214. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  18215. const panner = this.panner;
  18216. if ( panner.positionX ) {
  18217. // code path for Chrome and Firefox (see #14393)
  18218. const endTime = this.context.currentTime + this.listener.timeDelta;
  18219. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  18220. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  18221. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  18222. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  18223. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  18224. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  18225. } else {
  18226. panner.setPosition( _position.x, _position.y, _position.z );
  18227. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  18228. }
  18229. }
  18230. }
  18231. class AudioAnalyser {
  18232. constructor( audio, fftSize = 2048 ) {
  18233. this.analyser = audio.context.createAnalyser();
  18234. this.analyser.fftSize = fftSize;
  18235. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  18236. audio.getOutput().connect( this.analyser );
  18237. }
  18238. getFrequencyData() {
  18239. this.analyser.getByteFrequencyData( this.data );
  18240. return this.data;
  18241. }
  18242. getAverageFrequency() {
  18243. let value = 0;
  18244. const data = this.getFrequencyData();
  18245. for ( let i = 0; i < data.length; i ++ ) {
  18246. value += data[ i ];
  18247. }
  18248. return value / data.length;
  18249. }
  18250. }
  18251. class PropertyMixer {
  18252. constructor( binding, typeName, valueSize ) {
  18253. this.binding = binding;
  18254. this.valueSize = valueSize;
  18255. let mixFunction,
  18256. mixFunctionAdditive,
  18257. setIdentity;
  18258. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  18259. //
  18260. // interpolators can use .buffer as their .result
  18261. // the data then goes to 'incoming'
  18262. //
  18263. // 'accu0' and 'accu1' are used frame-interleaved for
  18264. // the cumulative result and are compared to detect
  18265. // changes
  18266. //
  18267. // 'orig' stores the original state of the property
  18268. //
  18269. // 'add' is used for additive cumulative results
  18270. //
  18271. // 'work' is optional and is only present for quaternion types. It is used
  18272. // to store intermediate quaternion multiplication results
  18273. switch ( typeName ) {
  18274. case 'quaternion':
  18275. mixFunction = this._slerp;
  18276. mixFunctionAdditive = this._slerpAdditive;
  18277. setIdentity = this._setAdditiveIdentityQuaternion;
  18278. this.buffer = new Float64Array( valueSize * 6 );
  18279. this._workIndex = 5;
  18280. break;
  18281. case 'string':
  18282. case 'bool':
  18283. mixFunction = this._select;
  18284. // Use the regular mix function and for additive on these types,
  18285. // additive is not relevant for non-numeric types
  18286. mixFunctionAdditive = this._select;
  18287. setIdentity = this._setAdditiveIdentityOther;
  18288. this.buffer = new Array( valueSize * 5 );
  18289. break;
  18290. default:
  18291. mixFunction = this._lerp;
  18292. mixFunctionAdditive = this._lerpAdditive;
  18293. setIdentity = this._setAdditiveIdentityNumeric;
  18294. this.buffer = new Float64Array( valueSize * 5 );
  18295. }
  18296. this._mixBufferRegion = mixFunction;
  18297. this._mixBufferRegionAdditive = mixFunctionAdditive;
  18298. this._setIdentity = setIdentity;
  18299. this._origIndex = 3;
  18300. this._addIndex = 4;
  18301. this.cumulativeWeight = 0;
  18302. this.cumulativeWeightAdditive = 0;
  18303. this.useCount = 0;
  18304. this.referenceCount = 0;
  18305. }
  18306. // accumulate data in the 'incoming' region into 'accu<i>'
  18307. accumulate( accuIndex, weight ) {
  18308. // note: happily accumulating nothing when weight = 0, the caller knows
  18309. // the weight and shouldn't have made the call in the first place
  18310. const buffer = this.buffer,
  18311. stride = this.valueSize,
  18312. offset = accuIndex * stride + stride;
  18313. let currentWeight = this.cumulativeWeight;
  18314. if ( currentWeight === 0 ) {
  18315. // accuN := incoming * weight
  18316. for ( let i = 0; i !== stride; ++ i ) {
  18317. buffer[ offset + i ] = buffer[ i ];
  18318. }
  18319. currentWeight = weight;
  18320. } else {
  18321. // accuN := accuN + incoming * weight
  18322. currentWeight += weight;
  18323. const mix = weight / currentWeight;
  18324. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  18325. }
  18326. this.cumulativeWeight = currentWeight;
  18327. }
  18328. // accumulate data in the 'incoming' region into 'add'
  18329. accumulateAdditive( weight ) {
  18330. const buffer = this.buffer,
  18331. stride = this.valueSize,
  18332. offset = stride * this._addIndex;
  18333. if ( this.cumulativeWeightAdditive === 0 ) {
  18334. // add = identity
  18335. this._setIdentity();
  18336. }
  18337. // add := add + incoming * weight
  18338. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  18339. this.cumulativeWeightAdditive += weight;
  18340. }
  18341. // apply the state of 'accu<i>' to the binding when accus differ
  18342. apply( accuIndex ) {
  18343. const stride = this.valueSize,
  18344. buffer = this.buffer,
  18345. offset = accuIndex * stride + stride,
  18346. weight = this.cumulativeWeight,
  18347. weightAdditive = this.cumulativeWeightAdditive,
  18348. binding = this.binding;
  18349. this.cumulativeWeight = 0;
  18350. this.cumulativeWeightAdditive = 0;
  18351. if ( weight < 1 ) {
  18352. // accuN := accuN + original * ( 1 - cumulativeWeight )
  18353. const originalValueOffset = stride * this._origIndex;
  18354. this._mixBufferRegion(
  18355. buffer, offset, originalValueOffset, 1 - weight, stride );
  18356. }
  18357. if ( weightAdditive > 0 ) {
  18358. // accuN := accuN + additive accuN
  18359. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  18360. }
  18361. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  18362. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  18363. // value has changed -> update scene graph
  18364. binding.setValue( buffer, offset );
  18365. break;
  18366. }
  18367. }
  18368. }
  18369. // remember the state of the bound property and copy it to both accus
  18370. saveOriginalState() {
  18371. const binding = this.binding;
  18372. const buffer = this.buffer,
  18373. stride = this.valueSize,
  18374. originalValueOffset = stride * this._origIndex;
  18375. binding.getValue( buffer, originalValueOffset );
  18376. // accu[0..1] := orig -- initially detect changes against the original
  18377. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  18378. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  18379. }
  18380. // Add to identity for additive
  18381. this._setIdentity();
  18382. this.cumulativeWeight = 0;
  18383. this.cumulativeWeightAdditive = 0;
  18384. }
  18385. // apply the state previously taken via 'saveOriginalState' to the binding
  18386. restoreOriginalState() {
  18387. const originalValueOffset = this.valueSize * 3;
  18388. this.binding.setValue( this.buffer, originalValueOffset );
  18389. }
  18390. _setAdditiveIdentityNumeric() {
  18391. const startIndex = this._addIndex * this.valueSize;
  18392. const endIndex = startIndex + this.valueSize;
  18393. for ( let i = startIndex; i < endIndex; i ++ ) {
  18394. this.buffer[ i ] = 0;
  18395. }
  18396. }
  18397. _setAdditiveIdentityQuaternion() {
  18398. this._setAdditiveIdentityNumeric();
  18399. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  18400. }
  18401. _setAdditiveIdentityOther() {
  18402. const startIndex = this._origIndex * this.valueSize;
  18403. const targetIndex = this._addIndex * this.valueSize;
  18404. for ( let i = 0; i < this.valueSize; i ++ ) {
  18405. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  18406. }
  18407. }
  18408. // mix functions
  18409. _select( buffer, dstOffset, srcOffset, t, stride ) {
  18410. if ( t >= 0.5 ) {
  18411. for ( let i = 0; i !== stride; ++ i ) {
  18412. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  18413. }
  18414. }
  18415. }
  18416. _slerp( buffer, dstOffset, srcOffset, t ) {
  18417. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  18418. }
  18419. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18420. const workOffset = this._workIndex * stride;
  18421. // Store result in intermediate buffer offset
  18422. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  18423. // Slerp to the intermediate result
  18424. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  18425. }
  18426. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  18427. const s = 1 - t;
  18428. for ( let i = 0; i !== stride; ++ i ) {
  18429. const j = dstOffset + i;
  18430. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  18431. }
  18432. }
  18433. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18434. for ( let i = 0; i !== stride; ++ i ) {
  18435. const j = dstOffset + i;
  18436. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  18437. }
  18438. }
  18439. }
  18440. // Characters [].:/ are reserved for track binding syntax.
  18441. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  18442. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  18443. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  18444. // only latin characters, and the unicode \p{L} is not yet supported. So
  18445. // instead, we exclude reserved characters and match everything else.
  18446. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  18447. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  18448. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  18449. // be matched to parse the rest of the track name.
  18450. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  18451. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  18452. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  18453. // Object on target node, and accessor. May not contain reserved
  18454. // characters. Accessor may contain any character except closing bracket.
  18455. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  18456. // Property and accessor. May not contain reserved characters. Accessor may
  18457. // contain any non-bracket characters.
  18458. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  18459. const _trackRe = new RegExp( ''
  18460. + '^'
  18461. + _directoryRe
  18462. + _nodeRe
  18463. + _objectRe
  18464. + _propertyRe
  18465. + '$'
  18466. );
  18467. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  18468. class Composite {
  18469. constructor( targetGroup, path, optionalParsedPath ) {
  18470. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  18471. this._targetGroup = targetGroup;
  18472. this._bindings = targetGroup.subscribe_( path, parsedPath );
  18473. }
  18474. getValue( array, offset ) {
  18475. this.bind(); // bind all binding
  18476. const firstValidIndex = this._targetGroup.nCachedObjects_,
  18477. binding = this._bindings[ firstValidIndex ];
  18478. // and only call .getValue on the first
  18479. if ( binding !== undefined ) binding.getValue( array, offset );
  18480. }
  18481. setValue( array, offset ) {
  18482. const bindings = this._bindings;
  18483. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18484. bindings[ i ].setValue( array, offset );
  18485. }
  18486. }
  18487. bind() {
  18488. const bindings = this._bindings;
  18489. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18490. bindings[ i ].bind();
  18491. }
  18492. }
  18493. unbind() {
  18494. const bindings = this._bindings;
  18495. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18496. bindings[ i ].unbind();
  18497. }
  18498. }
  18499. }
  18500. // Note: This class uses a State pattern on a per-method basis:
  18501. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  18502. // prototype version of these methods with one that represents
  18503. // the bound state. When the property is not found, the methods
  18504. // become no-ops.
  18505. class PropertyBinding {
  18506. constructor( rootNode, path, parsedPath ) {
  18507. this.path = path;
  18508. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  18509. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  18510. this.rootNode = rootNode;
  18511. // initial state of these methods that calls 'bind'
  18512. this.getValue = this._getValue_unbound;
  18513. this.setValue = this._setValue_unbound;
  18514. }
  18515. static create( root, path, parsedPath ) {
  18516. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  18517. return new PropertyBinding( root, path, parsedPath );
  18518. } else {
  18519. return new PropertyBinding.Composite( root, path, parsedPath );
  18520. }
  18521. }
  18522. /**
  18523. * Replaces spaces with underscores and removes unsupported characters from
  18524. * node names, to ensure compatibility with parseTrackName().
  18525. *
  18526. * @param {string} name Node name to be sanitized.
  18527. * @return {string}
  18528. */
  18529. static sanitizeNodeName( name ) {
  18530. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  18531. }
  18532. static parseTrackName( trackName ) {
  18533. const matches = _trackRe.exec( trackName );
  18534. if ( matches === null ) {
  18535. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  18536. }
  18537. const results = {
  18538. // directoryName: matches[ 1 ], // (tschw) currently unused
  18539. nodeName: matches[ 2 ],
  18540. objectName: matches[ 3 ],
  18541. objectIndex: matches[ 4 ],
  18542. propertyName: matches[ 5 ], // required
  18543. propertyIndex: matches[ 6 ]
  18544. };
  18545. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  18546. if ( lastDot !== undefined && lastDot !== - 1 ) {
  18547. const objectName = results.nodeName.substring( lastDot + 1 );
  18548. // Object names must be checked against an allowlist. Otherwise, there
  18549. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  18550. // 'bar' could be the objectName, or part of a nodeName (which can
  18551. // include '.' characters).
  18552. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  18553. results.nodeName = results.nodeName.substring( 0, lastDot );
  18554. results.objectName = objectName;
  18555. }
  18556. }
  18557. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  18558. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  18559. }
  18560. return results;
  18561. }
  18562. static findNode( root, nodeName ) {
  18563. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  18564. return root;
  18565. }
  18566. // search into skeleton bones.
  18567. if ( root.skeleton ) {
  18568. const bone = root.skeleton.getBoneByName( nodeName );
  18569. if ( bone !== undefined ) {
  18570. return bone;
  18571. }
  18572. }
  18573. // search into node subtree.
  18574. if ( root.children ) {
  18575. const searchNodeSubtree = function ( children ) {
  18576. for ( let i = 0; i < children.length; i ++ ) {
  18577. const childNode = children[ i ];
  18578. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  18579. return childNode;
  18580. }
  18581. const result = searchNodeSubtree( childNode.children );
  18582. if ( result ) return result;
  18583. }
  18584. return null;
  18585. };
  18586. const subTreeNode = searchNodeSubtree( root.children );
  18587. if ( subTreeNode ) {
  18588. return subTreeNode;
  18589. }
  18590. }
  18591. return null;
  18592. }
  18593. // these are used to "bind" a nonexistent property
  18594. _getValue_unavailable() {}
  18595. _setValue_unavailable() {}
  18596. // Getters
  18597. _getValue_direct( buffer, offset ) {
  18598. buffer[ offset ] = this.targetObject[ this.propertyName ];
  18599. }
  18600. _getValue_array( buffer, offset ) {
  18601. const source = this.resolvedProperty;
  18602. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  18603. buffer[ offset ++ ] = source[ i ];
  18604. }
  18605. }
  18606. _getValue_arrayElement( buffer, offset ) {
  18607. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  18608. }
  18609. _getValue_toArray( buffer, offset ) {
  18610. this.resolvedProperty.toArray( buffer, offset );
  18611. }
  18612. // Direct
  18613. _setValue_direct( buffer, offset ) {
  18614. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18615. }
  18616. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  18617. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18618. this.targetObject.needsUpdate = true;
  18619. }
  18620. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18621. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18622. this.targetObject.matrixWorldNeedsUpdate = true;
  18623. }
  18624. // EntireArray
  18625. _setValue_array( buffer, offset ) {
  18626. const dest = this.resolvedProperty;
  18627. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18628. dest[ i ] = buffer[ offset ++ ];
  18629. }
  18630. }
  18631. _setValue_array_setNeedsUpdate( buffer, offset ) {
  18632. const dest = this.resolvedProperty;
  18633. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18634. dest[ i ] = buffer[ offset ++ ];
  18635. }
  18636. this.targetObject.needsUpdate = true;
  18637. }
  18638. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18639. const dest = this.resolvedProperty;
  18640. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18641. dest[ i ] = buffer[ offset ++ ];
  18642. }
  18643. this.targetObject.matrixWorldNeedsUpdate = true;
  18644. }
  18645. // ArrayElement
  18646. _setValue_arrayElement( buffer, offset ) {
  18647. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18648. }
  18649. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  18650. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18651. this.targetObject.needsUpdate = true;
  18652. }
  18653. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18654. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18655. this.targetObject.matrixWorldNeedsUpdate = true;
  18656. }
  18657. // HasToFromArray
  18658. _setValue_fromArray( buffer, offset ) {
  18659. this.resolvedProperty.fromArray( buffer, offset );
  18660. }
  18661. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  18662. this.resolvedProperty.fromArray( buffer, offset );
  18663. this.targetObject.needsUpdate = true;
  18664. }
  18665. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18666. this.resolvedProperty.fromArray( buffer, offset );
  18667. this.targetObject.matrixWorldNeedsUpdate = true;
  18668. }
  18669. _getValue_unbound( targetArray, offset ) {
  18670. this.bind();
  18671. this.getValue( targetArray, offset );
  18672. }
  18673. _setValue_unbound( sourceArray, offset ) {
  18674. this.bind();
  18675. this.setValue( sourceArray, offset );
  18676. }
  18677. // create getter / setter pair for a property in the scene graph
  18678. bind() {
  18679. let targetObject = this.node;
  18680. const parsedPath = this.parsedPath;
  18681. const objectName = parsedPath.objectName;
  18682. const propertyName = parsedPath.propertyName;
  18683. let propertyIndex = parsedPath.propertyIndex;
  18684. if ( ! targetObject ) {
  18685. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  18686. this.node = targetObject;
  18687. }
  18688. // set fail state so we can just 'return' on error
  18689. this.getValue = this._getValue_unavailable;
  18690. this.setValue = this._setValue_unavailable;
  18691. // ensure there is a value node
  18692. if ( ! targetObject ) {
  18693. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  18694. return;
  18695. }
  18696. if ( objectName ) {
  18697. let objectIndex = parsedPath.objectIndex;
  18698. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  18699. switch ( objectName ) {
  18700. case 'materials':
  18701. if ( ! targetObject.material ) {
  18702. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  18703. return;
  18704. }
  18705. if ( ! targetObject.material.materials ) {
  18706. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  18707. return;
  18708. }
  18709. targetObject = targetObject.material.materials;
  18710. break;
  18711. case 'bones':
  18712. if ( ! targetObject.skeleton ) {
  18713. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  18714. return;
  18715. }
  18716. // potential future optimization: skip this if propertyIndex is already an integer
  18717. // and convert the integer string to a true integer.
  18718. targetObject = targetObject.skeleton.bones;
  18719. // support resolving morphTarget names into indices.
  18720. for ( let i = 0; i < targetObject.length; i ++ ) {
  18721. if ( targetObject[ i ].name === objectIndex ) {
  18722. objectIndex = i;
  18723. break;
  18724. }
  18725. }
  18726. break;
  18727. case 'map':
  18728. if ( 'map' in targetObject ) {
  18729. targetObject = targetObject.map;
  18730. break;
  18731. }
  18732. if ( ! targetObject.material ) {
  18733. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  18734. return;
  18735. }
  18736. if ( ! targetObject.material.map ) {
  18737. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  18738. return;
  18739. }
  18740. targetObject = targetObject.material.map;
  18741. break;
  18742. default:
  18743. if ( targetObject[ objectName ] === undefined ) {
  18744. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  18745. return;
  18746. }
  18747. targetObject = targetObject[ objectName ];
  18748. }
  18749. if ( objectIndex !== undefined ) {
  18750. if ( targetObject[ objectIndex ] === undefined ) {
  18751. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  18752. return;
  18753. }
  18754. targetObject = targetObject[ objectIndex ];
  18755. }
  18756. }
  18757. // resolve property
  18758. const nodeProperty = targetObject[ propertyName ];
  18759. if ( nodeProperty === undefined ) {
  18760. const nodeName = parsedPath.nodeName;
  18761. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  18762. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  18763. return;
  18764. }
  18765. // determine versioning scheme
  18766. let versioning = this.Versioning.None;
  18767. this.targetObject = targetObject;
  18768. if ( targetObject.needsUpdate !== undefined ) { // material
  18769. versioning = this.Versioning.NeedsUpdate;
  18770. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  18771. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  18772. }
  18773. // determine how the property gets bound
  18774. let bindingType = this.BindingType.Direct;
  18775. if ( propertyIndex !== undefined ) {
  18776. // access a sub element of the property array (only primitives are supported right now)
  18777. if ( propertyName === 'morphTargetInfluences' ) {
  18778. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  18779. // support resolving morphTarget names into indices.
  18780. if ( ! targetObject.geometry ) {
  18781. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  18782. return;
  18783. }
  18784. if ( ! targetObject.geometry.morphAttributes ) {
  18785. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  18786. return;
  18787. }
  18788. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  18789. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  18790. }
  18791. }
  18792. bindingType = this.BindingType.ArrayElement;
  18793. this.resolvedProperty = nodeProperty;
  18794. this.propertyIndex = propertyIndex;
  18795. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  18796. // must use copy for Object3D.Euler/Quaternion
  18797. bindingType = this.BindingType.HasFromToArray;
  18798. this.resolvedProperty = nodeProperty;
  18799. } else if ( Array.isArray( nodeProperty ) ) {
  18800. bindingType = this.BindingType.EntireArray;
  18801. this.resolvedProperty = nodeProperty;
  18802. } else {
  18803. this.propertyName = propertyName;
  18804. }
  18805. // select getter / setter
  18806. this.getValue = this.GetterByBindingType[ bindingType ];
  18807. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  18808. }
  18809. unbind() {
  18810. this.node = null;
  18811. // back to the prototype version of getValue / setValue
  18812. // note: avoiding to mutate the shape of 'this' via 'delete'
  18813. this.getValue = this._getValue_unbound;
  18814. this.setValue = this._setValue_unbound;
  18815. }
  18816. }
  18817. PropertyBinding.Composite = Composite;
  18818. PropertyBinding.prototype.BindingType = {
  18819. Direct: 0,
  18820. EntireArray: 1,
  18821. ArrayElement: 2,
  18822. HasFromToArray: 3
  18823. };
  18824. PropertyBinding.prototype.Versioning = {
  18825. None: 0,
  18826. NeedsUpdate: 1,
  18827. MatrixWorldNeedsUpdate: 2
  18828. };
  18829. PropertyBinding.prototype.GetterByBindingType = [
  18830. PropertyBinding.prototype._getValue_direct,
  18831. PropertyBinding.prototype._getValue_array,
  18832. PropertyBinding.prototype._getValue_arrayElement,
  18833. PropertyBinding.prototype._getValue_toArray,
  18834. ];
  18835. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  18836. [
  18837. // Direct
  18838. PropertyBinding.prototype._setValue_direct,
  18839. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  18840. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  18841. ], [
  18842. // EntireArray
  18843. PropertyBinding.prototype._setValue_array,
  18844. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  18845. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  18846. ], [
  18847. // ArrayElement
  18848. PropertyBinding.prototype._setValue_arrayElement,
  18849. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  18850. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  18851. ], [
  18852. // HasToFromArray
  18853. PropertyBinding.prototype._setValue_fromArray,
  18854. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  18855. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  18856. ]
  18857. ];
  18858. /**
  18859. *
  18860. * A group of objects that receives a shared animation state.
  18861. *
  18862. * Usage:
  18863. *
  18864. * - Add objects you would otherwise pass as 'root' to the
  18865. * constructor or the .clipAction method of AnimationMixer.
  18866. *
  18867. * - Instead pass this object as 'root'.
  18868. *
  18869. * - You can also add and remove objects later when the mixer
  18870. * is running.
  18871. *
  18872. * Note:
  18873. *
  18874. * Objects of this class appear as one object to the mixer,
  18875. * so cache control of the individual objects must be done
  18876. * on the group.
  18877. *
  18878. * Limitation:
  18879. *
  18880. * - The animated properties must be compatible among the
  18881. * all objects in the group.
  18882. *
  18883. * - A single property can either be controlled through a
  18884. * target group or directly, but not both.
  18885. */
  18886. class AnimationObjectGroup {
  18887. constructor() {
  18888. this.isAnimationObjectGroup = true;
  18889. this.uuid = generateUUID();
  18890. // cached objects followed by the active ones
  18891. this._objects = Array.prototype.slice.call( arguments );
  18892. this.nCachedObjects_ = 0; // threshold
  18893. // note: read by PropertyBinding.Composite
  18894. const indices = {};
  18895. this._indicesByUUID = indices; // for bookkeeping
  18896. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18897. indices[ arguments[ i ].uuid ] = i;
  18898. }
  18899. this._paths = []; // inside: string
  18900. this._parsedPaths = []; // inside: { we don't care, here }
  18901. this._bindings = []; // inside: Array< PropertyBinding >
  18902. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  18903. const scope = this;
  18904. this.stats = {
  18905. objects: {
  18906. get total() {
  18907. return scope._objects.length;
  18908. },
  18909. get inUse() {
  18910. return this.total - scope.nCachedObjects_;
  18911. }
  18912. },
  18913. get bindingsPerObject() {
  18914. return scope._bindings.length;
  18915. }
  18916. };
  18917. }
  18918. add() {
  18919. const objects = this._objects,
  18920. indicesByUUID = this._indicesByUUID,
  18921. paths = this._paths,
  18922. parsedPaths = this._parsedPaths,
  18923. bindings = this._bindings,
  18924. nBindings = bindings.length;
  18925. let knownObject = undefined,
  18926. nObjects = objects.length,
  18927. nCachedObjects = this.nCachedObjects_;
  18928. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18929. const object = arguments[ i ],
  18930. uuid = object.uuid;
  18931. let index = indicesByUUID[ uuid ];
  18932. if ( index === undefined ) {
  18933. // unknown object -> add it to the ACTIVE region
  18934. index = nObjects ++;
  18935. indicesByUUID[ uuid ] = index;
  18936. objects.push( object );
  18937. // accounting is done, now do the same for all bindings
  18938. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  18939. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  18940. }
  18941. } else if ( index < nCachedObjects ) {
  18942. knownObject = objects[ index ];
  18943. // move existing object to the ACTIVE region
  18944. const firstActiveIndex = -- nCachedObjects,
  18945. lastCachedObject = objects[ firstActiveIndex ];
  18946. indicesByUUID[ lastCachedObject.uuid ] = index;
  18947. objects[ index ] = lastCachedObject;
  18948. indicesByUUID[ uuid ] = firstActiveIndex;
  18949. objects[ firstActiveIndex ] = object;
  18950. // accounting is done, now do the same for all bindings
  18951. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  18952. const bindingsForPath = bindings[ j ],
  18953. lastCached = bindingsForPath[ firstActiveIndex ];
  18954. let binding = bindingsForPath[ index ];
  18955. bindingsForPath[ index ] = lastCached;
  18956. if ( binding === undefined ) {
  18957. // since we do not bother to create new bindings
  18958. // for objects that are cached, the binding may
  18959. // or may not exist
  18960. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  18961. }
  18962. bindingsForPath[ firstActiveIndex ] = binding;
  18963. }
  18964. } else if ( objects[ index ] !== knownObject ) {
  18965. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  18966. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  18967. } // else the object is already where we want it to be
  18968. } // for arguments
  18969. this.nCachedObjects_ = nCachedObjects;
  18970. }
  18971. remove() {
  18972. const objects = this._objects,
  18973. indicesByUUID = this._indicesByUUID,
  18974. bindings = this._bindings,
  18975. nBindings = bindings.length;
  18976. let nCachedObjects = this.nCachedObjects_;
  18977. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18978. const object = arguments[ i ],
  18979. uuid = object.uuid,
  18980. index = indicesByUUID[ uuid ];
  18981. if ( index !== undefined && index >= nCachedObjects ) {
  18982. // move existing object into the CACHED region
  18983. const lastCachedIndex = nCachedObjects ++,
  18984. firstActiveObject = objects[ lastCachedIndex ];
  18985. indicesByUUID[ firstActiveObject.uuid ] = index;
  18986. objects[ index ] = firstActiveObject;
  18987. indicesByUUID[ uuid ] = lastCachedIndex;
  18988. objects[ lastCachedIndex ] = object;
  18989. // accounting is done, now do the same for all bindings
  18990. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  18991. const bindingsForPath = bindings[ j ],
  18992. firstActive = bindingsForPath[ lastCachedIndex ],
  18993. binding = bindingsForPath[ index ];
  18994. bindingsForPath[ index ] = firstActive;
  18995. bindingsForPath[ lastCachedIndex ] = binding;
  18996. }
  18997. }
  18998. } // for arguments
  18999. this.nCachedObjects_ = nCachedObjects;
  19000. }
  19001. // remove & forget
  19002. uncache() {
  19003. const objects = this._objects,
  19004. indicesByUUID = this._indicesByUUID,
  19005. bindings = this._bindings,
  19006. nBindings = bindings.length;
  19007. let nCachedObjects = this.nCachedObjects_,
  19008. nObjects = objects.length;
  19009. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19010. const object = arguments[ i ],
  19011. uuid = object.uuid,
  19012. index = indicesByUUID[ uuid ];
  19013. if ( index !== undefined ) {
  19014. delete indicesByUUID[ uuid ];
  19015. if ( index < nCachedObjects ) {
  19016. // object is cached, shrink the CACHED region
  19017. const firstActiveIndex = -- nCachedObjects,
  19018. lastCachedObject = objects[ firstActiveIndex ],
  19019. lastIndex = -- nObjects,
  19020. lastObject = objects[ lastIndex ];
  19021. // last cached object takes this object's place
  19022. indicesByUUID[ lastCachedObject.uuid ] = index;
  19023. objects[ index ] = lastCachedObject;
  19024. // last object goes to the activated slot and pop
  19025. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  19026. objects[ firstActiveIndex ] = lastObject;
  19027. objects.pop();
  19028. // accounting is done, now do the same for all bindings
  19029. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19030. const bindingsForPath = bindings[ j ],
  19031. lastCached = bindingsForPath[ firstActiveIndex ],
  19032. last = bindingsForPath[ lastIndex ];
  19033. bindingsForPath[ index ] = lastCached;
  19034. bindingsForPath[ firstActiveIndex ] = last;
  19035. bindingsForPath.pop();
  19036. }
  19037. } else {
  19038. // object is active, just swap with the last and pop
  19039. const lastIndex = -- nObjects,
  19040. lastObject = objects[ lastIndex ];
  19041. if ( lastIndex > 0 ) {
  19042. indicesByUUID[ lastObject.uuid ] = index;
  19043. }
  19044. objects[ index ] = lastObject;
  19045. objects.pop();
  19046. // accounting is done, now do the same for all bindings
  19047. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19048. const bindingsForPath = bindings[ j ];
  19049. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  19050. bindingsForPath.pop();
  19051. }
  19052. } // cached or active
  19053. } // if object is known
  19054. } // for arguments
  19055. this.nCachedObjects_ = nCachedObjects;
  19056. }
  19057. // Internal interface used by befriended PropertyBinding.Composite:
  19058. subscribe_( path, parsedPath ) {
  19059. // returns an array of bindings for the given path that is changed
  19060. // according to the contained objects in the group
  19061. const indicesByPath = this._bindingsIndicesByPath;
  19062. let index = indicesByPath[ path ];
  19063. const bindings = this._bindings;
  19064. if ( index !== undefined ) return bindings[ index ];
  19065. const paths = this._paths,
  19066. parsedPaths = this._parsedPaths,
  19067. objects = this._objects,
  19068. nObjects = objects.length,
  19069. nCachedObjects = this.nCachedObjects_,
  19070. bindingsForPath = new Array( nObjects );
  19071. index = bindings.length;
  19072. indicesByPath[ path ] = index;
  19073. paths.push( path );
  19074. parsedPaths.push( parsedPath );
  19075. bindings.push( bindingsForPath );
  19076. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  19077. const object = objects[ i ];
  19078. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  19079. }
  19080. return bindingsForPath;
  19081. }
  19082. unsubscribe_( path ) {
  19083. // tells the group to forget about a property path and no longer
  19084. // update the array previously obtained with 'subscribe_'
  19085. const indicesByPath = this._bindingsIndicesByPath,
  19086. index = indicesByPath[ path ];
  19087. if ( index !== undefined ) {
  19088. const paths = this._paths,
  19089. parsedPaths = this._parsedPaths,
  19090. bindings = this._bindings,
  19091. lastBindingsIndex = bindings.length - 1,
  19092. lastBindings = bindings[ lastBindingsIndex ],
  19093. lastBindingsPath = path[ lastBindingsIndex ];
  19094. indicesByPath[ lastBindingsPath ] = index;
  19095. bindings[ index ] = lastBindings;
  19096. bindings.pop();
  19097. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  19098. parsedPaths.pop();
  19099. paths[ index ] = paths[ lastBindingsIndex ];
  19100. paths.pop();
  19101. }
  19102. }
  19103. }
  19104. class AnimationAction {
  19105. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  19106. this._mixer = mixer;
  19107. this._clip = clip;
  19108. this._localRoot = localRoot;
  19109. this.blendMode = blendMode;
  19110. const tracks = clip.tracks,
  19111. nTracks = tracks.length,
  19112. interpolants = new Array( nTracks );
  19113. const interpolantSettings = {
  19114. endingStart: ZeroCurvatureEnding,
  19115. endingEnd: ZeroCurvatureEnding
  19116. };
  19117. for ( let i = 0; i !== nTracks; ++ i ) {
  19118. const interpolant = tracks[ i ].createInterpolant( null );
  19119. interpolants[ i ] = interpolant;
  19120. interpolant.settings = interpolantSettings;
  19121. }
  19122. this._interpolantSettings = interpolantSettings;
  19123. this._interpolants = interpolants; // bound by the mixer
  19124. // inside: PropertyMixer (managed by the mixer)
  19125. this._propertyBindings = new Array( nTracks );
  19126. this._cacheIndex = null; // for the memory manager
  19127. this._byClipCacheIndex = null; // for the memory manager
  19128. this._timeScaleInterpolant = null;
  19129. this._weightInterpolant = null;
  19130. this.loop = LoopRepeat;
  19131. this._loopCount = - 1;
  19132. // global mixer time when the action is to be started
  19133. // it's set back to 'null' upon start of the action
  19134. this._startTime = null;
  19135. // scaled local time of the action
  19136. // gets clamped or wrapped to 0..clip.duration according to loop
  19137. this.time = 0;
  19138. this.timeScale = 1;
  19139. this._effectiveTimeScale = 1;
  19140. this.weight = 1;
  19141. this._effectiveWeight = 1;
  19142. this.repetitions = Infinity; // no. of repetitions when looping
  19143. this.paused = false; // true -> zero effective time scale
  19144. this.enabled = true; // false -> zero effective weight
  19145. this.clampWhenFinished = false;// keep feeding the last frame?
  19146. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  19147. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  19148. }
  19149. // State & Scheduling
  19150. play() {
  19151. this._mixer._activateAction( this );
  19152. return this;
  19153. }
  19154. stop() {
  19155. this._mixer._deactivateAction( this );
  19156. return this.reset();
  19157. }
  19158. reset() {
  19159. this.paused = false;
  19160. this.enabled = true;
  19161. this.time = 0; // restart clip
  19162. this._loopCount = - 1;// forget previous loops
  19163. this._startTime = null;// forget scheduling
  19164. return this.stopFading().stopWarping();
  19165. }
  19166. isRunning() {
  19167. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  19168. this._startTime === null && this._mixer._isActiveAction( this );
  19169. }
  19170. // return true when play has been called
  19171. isScheduled() {
  19172. return this._mixer._isActiveAction( this );
  19173. }
  19174. startAt( time ) {
  19175. this._startTime = time;
  19176. return this;
  19177. }
  19178. setLoop( mode, repetitions ) {
  19179. this.loop = mode;
  19180. this.repetitions = repetitions;
  19181. return this;
  19182. }
  19183. // Weight
  19184. // set the weight stopping any scheduled fading
  19185. // although .enabled = false yields an effective weight of zero, this
  19186. // method does *not* change .enabled, because it would be confusing
  19187. setEffectiveWeight( weight ) {
  19188. this.weight = weight;
  19189. // note: same logic as when updated at runtime
  19190. this._effectiveWeight = this.enabled ? weight : 0;
  19191. return this.stopFading();
  19192. }
  19193. // return the weight considering fading and .enabled
  19194. getEffectiveWeight() {
  19195. return this._effectiveWeight;
  19196. }
  19197. fadeIn( duration ) {
  19198. return this._scheduleFading( duration, 0, 1 );
  19199. }
  19200. fadeOut( duration ) {
  19201. return this._scheduleFading( duration, 1, 0 );
  19202. }
  19203. crossFadeFrom( fadeOutAction, duration, warp ) {
  19204. fadeOutAction.fadeOut( duration );
  19205. this.fadeIn( duration );
  19206. if ( warp ) {
  19207. const fadeInDuration = this._clip.duration,
  19208. fadeOutDuration = fadeOutAction._clip.duration,
  19209. startEndRatio = fadeOutDuration / fadeInDuration,
  19210. endStartRatio = fadeInDuration / fadeOutDuration;
  19211. fadeOutAction.warp( 1.0, startEndRatio, duration );
  19212. this.warp( endStartRatio, 1.0, duration );
  19213. }
  19214. return this;
  19215. }
  19216. crossFadeTo( fadeInAction, duration, warp ) {
  19217. return fadeInAction.crossFadeFrom( this, duration, warp );
  19218. }
  19219. stopFading() {
  19220. const weightInterpolant = this._weightInterpolant;
  19221. if ( weightInterpolant !== null ) {
  19222. this._weightInterpolant = null;
  19223. this._mixer._takeBackControlInterpolant( weightInterpolant );
  19224. }
  19225. return this;
  19226. }
  19227. // Time Scale Control
  19228. // set the time scale stopping any scheduled warping
  19229. // although .paused = true yields an effective time scale of zero, this
  19230. // method does *not* change .paused, because it would be confusing
  19231. setEffectiveTimeScale( timeScale ) {
  19232. this.timeScale = timeScale;
  19233. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  19234. return this.stopWarping();
  19235. }
  19236. // return the time scale considering warping and .paused
  19237. getEffectiveTimeScale() {
  19238. return this._effectiveTimeScale;
  19239. }
  19240. setDuration( duration ) {
  19241. this.timeScale = this._clip.duration / duration;
  19242. return this.stopWarping();
  19243. }
  19244. syncWith( action ) {
  19245. this.time = action.time;
  19246. this.timeScale = action.timeScale;
  19247. return this.stopWarping();
  19248. }
  19249. halt( duration ) {
  19250. return this.warp( this._effectiveTimeScale, 0, duration );
  19251. }
  19252. warp( startTimeScale, endTimeScale, duration ) {
  19253. const mixer = this._mixer,
  19254. now = mixer.time,
  19255. timeScale = this.timeScale;
  19256. let interpolant = this._timeScaleInterpolant;
  19257. if ( interpolant === null ) {
  19258. interpolant = mixer._lendControlInterpolant();
  19259. this._timeScaleInterpolant = interpolant;
  19260. }
  19261. const times = interpolant.parameterPositions,
  19262. values = interpolant.sampleValues;
  19263. times[ 0 ] = now;
  19264. times[ 1 ] = now + duration;
  19265. values[ 0 ] = startTimeScale / timeScale;
  19266. values[ 1 ] = endTimeScale / timeScale;
  19267. return this;
  19268. }
  19269. stopWarping() {
  19270. const timeScaleInterpolant = this._timeScaleInterpolant;
  19271. if ( timeScaleInterpolant !== null ) {
  19272. this._timeScaleInterpolant = null;
  19273. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  19274. }
  19275. return this;
  19276. }
  19277. // Object Accessors
  19278. getMixer() {
  19279. return this._mixer;
  19280. }
  19281. getClip() {
  19282. return this._clip;
  19283. }
  19284. getRoot() {
  19285. return this._localRoot || this._mixer._root;
  19286. }
  19287. // Interna
  19288. _update( time, deltaTime, timeDirection, accuIndex ) {
  19289. // called by the mixer
  19290. if ( ! this.enabled ) {
  19291. // call ._updateWeight() to update ._effectiveWeight
  19292. this._updateWeight( time );
  19293. return;
  19294. }
  19295. const startTime = this._startTime;
  19296. if ( startTime !== null ) {
  19297. // check for scheduled start of action
  19298. const timeRunning = ( time - startTime ) * timeDirection;
  19299. if ( timeRunning < 0 || timeDirection === 0 ) {
  19300. deltaTime = 0;
  19301. } else {
  19302. this._startTime = null; // unschedule
  19303. deltaTime = timeDirection * timeRunning;
  19304. }
  19305. }
  19306. // apply time scale and advance time
  19307. deltaTime *= this._updateTimeScale( time );
  19308. const clipTime = this._updateTime( deltaTime );
  19309. // note: _updateTime may disable the action resulting in
  19310. // an effective weight of 0
  19311. const weight = this._updateWeight( time );
  19312. if ( weight > 0 ) {
  19313. const interpolants = this._interpolants;
  19314. const propertyMixers = this._propertyBindings;
  19315. switch ( this.blendMode ) {
  19316. case AdditiveAnimationBlendMode:
  19317. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19318. interpolants[ j ].evaluate( clipTime );
  19319. propertyMixers[ j ].accumulateAdditive( weight );
  19320. }
  19321. break;
  19322. case NormalAnimationBlendMode:
  19323. default:
  19324. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19325. interpolants[ j ].evaluate( clipTime );
  19326. propertyMixers[ j ].accumulate( accuIndex, weight );
  19327. }
  19328. }
  19329. }
  19330. }
  19331. _updateWeight( time ) {
  19332. let weight = 0;
  19333. if ( this.enabled ) {
  19334. weight = this.weight;
  19335. const interpolant = this._weightInterpolant;
  19336. if ( interpolant !== null ) {
  19337. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19338. weight *= interpolantValue;
  19339. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19340. this.stopFading();
  19341. if ( interpolantValue === 0 ) {
  19342. // faded out, disable
  19343. this.enabled = false;
  19344. }
  19345. }
  19346. }
  19347. }
  19348. this._effectiveWeight = weight;
  19349. return weight;
  19350. }
  19351. _updateTimeScale( time ) {
  19352. let timeScale = 0;
  19353. if ( ! this.paused ) {
  19354. timeScale = this.timeScale;
  19355. const interpolant = this._timeScaleInterpolant;
  19356. if ( interpolant !== null ) {
  19357. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19358. timeScale *= interpolantValue;
  19359. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19360. this.stopWarping();
  19361. if ( timeScale === 0 ) {
  19362. // motion has halted, pause
  19363. this.paused = true;
  19364. } else {
  19365. // warp done - apply final time scale
  19366. this.timeScale = timeScale;
  19367. }
  19368. }
  19369. }
  19370. }
  19371. this._effectiveTimeScale = timeScale;
  19372. return timeScale;
  19373. }
  19374. _updateTime( deltaTime ) {
  19375. const duration = this._clip.duration;
  19376. const loop = this.loop;
  19377. let time = this.time + deltaTime;
  19378. let loopCount = this._loopCount;
  19379. const pingPong = ( loop === LoopPingPong );
  19380. if ( deltaTime === 0 ) {
  19381. if ( loopCount === - 1 ) return time;
  19382. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  19383. }
  19384. if ( loop === LoopOnce ) {
  19385. if ( loopCount === - 1 ) {
  19386. // just started
  19387. this._loopCount = 0;
  19388. this._setEndings( true, true, false );
  19389. }
  19390. handle_stop: {
  19391. if ( time >= duration ) {
  19392. time = duration;
  19393. } else if ( time < 0 ) {
  19394. time = 0;
  19395. } else {
  19396. this.time = time;
  19397. break handle_stop;
  19398. }
  19399. if ( this.clampWhenFinished ) this.paused = true;
  19400. else this.enabled = false;
  19401. this.time = time;
  19402. this._mixer.dispatchEvent( {
  19403. type: 'finished', action: this,
  19404. direction: deltaTime < 0 ? - 1 : 1
  19405. } );
  19406. }
  19407. } else { // repetitive Repeat or PingPong
  19408. if ( loopCount === - 1 ) {
  19409. // just started
  19410. if ( deltaTime >= 0 ) {
  19411. loopCount = 0;
  19412. this._setEndings( true, this.repetitions === 0, pingPong );
  19413. } else {
  19414. // when looping in reverse direction, the initial
  19415. // transition through zero counts as a repetition,
  19416. // so leave loopCount at -1
  19417. this._setEndings( this.repetitions === 0, true, pingPong );
  19418. }
  19419. }
  19420. if ( time >= duration || time < 0 ) {
  19421. // wrap around
  19422. const loopDelta = Math.floor( time / duration ); // signed
  19423. time -= duration * loopDelta;
  19424. loopCount += Math.abs( loopDelta );
  19425. const pending = this.repetitions - loopCount;
  19426. if ( pending <= 0 ) {
  19427. // have to stop (switch state, clamp time, fire event)
  19428. if ( this.clampWhenFinished ) this.paused = true;
  19429. else this.enabled = false;
  19430. time = deltaTime > 0 ? duration : 0;
  19431. this.time = time;
  19432. this._mixer.dispatchEvent( {
  19433. type: 'finished', action: this,
  19434. direction: deltaTime > 0 ? 1 : - 1
  19435. } );
  19436. } else {
  19437. // keep running
  19438. if ( pending === 1 ) {
  19439. // entering the last round
  19440. const atStart = deltaTime < 0;
  19441. this._setEndings( atStart, ! atStart, pingPong );
  19442. } else {
  19443. this._setEndings( false, false, pingPong );
  19444. }
  19445. this._loopCount = loopCount;
  19446. this.time = time;
  19447. this._mixer.dispatchEvent( {
  19448. type: 'loop', action: this, loopDelta: loopDelta
  19449. } );
  19450. }
  19451. } else {
  19452. this.time = time;
  19453. }
  19454. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  19455. // invert time for the "pong round"
  19456. return duration - time;
  19457. }
  19458. }
  19459. return time;
  19460. }
  19461. _setEndings( atStart, atEnd, pingPong ) {
  19462. const settings = this._interpolantSettings;
  19463. if ( pingPong ) {
  19464. settings.endingStart = ZeroSlopeEnding;
  19465. settings.endingEnd = ZeroSlopeEnding;
  19466. } else {
  19467. // assuming for LoopOnce atStart == atEnd == true
  19468. if ( atStart ) {
  19469. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19470. } else {
  19471. settings.endingStart = WrapAroundEnding;
  19472. }
  19473. if ( atEnd ) {
  19474. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19475. } else {
  19476. settings.endingEnd = WrapAroundEnding;
  19477. }
  19478. }
  19479. }
  19480. _scheduleFading( duration, weightNow, weightThen ) {
  19481. const mixer = this._mixer, now = mixer.time;
  19482. let interpolant = this._weightInterpolant;
  19483. if ( interpolant === null ) {
  19484. interpolant = mixer._lendControlInterpolant();
  19485. this._weightInterpolant = interpolant;
  19486. }
  19487. const times = interpolant.parameterPositions,
  19488. values = interpolant.sampleValues;
  19489. times[ 0 ] = now;
  19490. values[ 0 ] = weightNow;
  19491. times[ 1 ] = now + duration;
  19492. values[ 1 ] = weightThen;
  19493. return this;
  19494. }
  19495. }
  19496. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  19497. class AnimationMixer extends EventDispatcher {
  19498. constructor( root ) {
  19499. super();
  19500. this._root = root;
  19501. this._initMemoryManager();
  19502. this._accuIndex = 0;
  19503. this.time = 0;
  19504. this.timeScale = 1.0;
  19505. }
  19506. _bindAction( action, prototypeAction ) {
  19507. const root = action._localRoot || this._root,
  19508. tracks = action._clip.tracks,
  19509. nTracks = tracks.length,
  19510. bindings = action._propertyBindings,
  19511. interpolants = action._interpolants,
  19512. rootUuid = root.uuid,
  19513. bindingsByRoot = this._bindingsByRootAndName;
  19514. let bindingsByName = bindingsByRoot[ rootUuid ];
  19515. if ( bindingsByName === undefined ) {
  19516. bindingsByName = {};
  19517. bindingsByRoot[ rootUuid ] = bindingsByName;
  19518. }
  19519. for ( let i = 0; i !== nTracks; ++ i ) {
  19520. const track = tracks[ i ],
  19521. trackName = track.name;
  19522. let binding = bindingsByName[ trackName ];
  19523. if ( binding !== undefined ) {
  19524. ++ binding.referenceCount;
  19525. bindings[ i ] = binding;
  19526. } else {
  19527. binding = bindings[ i ];
  19528. if ( binding !== undefined ) {
  19529. // existing binding, make sure the cache knows
  19530. if ( binding._cacheIndex === null ) {
  19531. ++ binding.referenceCount;
  19532. this._addInactiveBinding( binding, rootUuid, trackName );
  19533. }
  19534. continue;
  19535. }
  19536. const path = prototypeAction && prototypeAction.
  19537. _propertyBindings[ i ].binding.parsedPath;
  19538. binding = new PropertyMixer(
  19539. PropertyBinding.create( root, trackName, path ),
  19540. track.ValueTypeName, track.getValueSize() );
  19541. ++ binding.referenceCount;
  19542. this._addInactiveBinding( binding, rootUuid, trackName );
  19543. bindings[ i ] = binding;
  19544. }
  19545. interpolants[ i ].resultBuffer = binding.buffer;
  19546. }
  19547. }
  19548. _activateAction( action ) {
  19549. if ( ! this._isActiveAction( action ) ) {
  19550. if ( action._cacheIndex === null ) {
  19551. // this action has been forgotten by the cache, but the user
  19552. // appears to be still using it -> rebind
  19553. const rootUuid = ( action._localRoot || this._root ).uuid,
  19554. clipUuid = action._clip.uuid,
  19555. actionsForClip = this._actionsByClip[ clipUuid ];
  19556. this._bindAction( action,
  19557. actionsForClip && actionsForClip.knownActions[ 0 ] );
  19558. this._addInactiveAction( action, clipUuid, rootUuid );
  19559. }
  19560. const bindings = action._propertyBindings;
  19561. // increment reference counts / sort out state
  19562. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19563. const binding = bindings[ i ];
  19564. if ( binding.useCount ++ === 0 ) {
  19565. this._lendBinding( binding );
  19566. binding.saveOriginalState();
  19567. }
  19568. }
  19569. this._lendAction( action );
  19570. }
  19571. }
  19572. _deactivateAction( action ) {
  19573. if ( this._isActiveAction( action ) ) {
  19574. const bindings = action._propertyBindings;
  19575. // decrement reference counts / sort out state
  19576. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19577. const binding = bindings[ i ];
  19578. if ( -- binding.useCount === 0 ) {
  19579. binding.restoreOriginalState();
  19580. this._takeBackBinding( binding );
  19581. }
  19582. }
  19583. this._takeBackAction( action );
  19584. }
  19585. }
  19586. // Memory manager
  19587. _initMemoryManager() {
  19588. this._actions = []; // 'nActiveActions' followed by inactive ones
  19589. this._nActiveActions = 0;
  19590. this._actionsByClip = {};
  19591. // inside:
  19592. // {
  19593. // knownActions: Array< AnimationAction > - used as prototypes
  19594. // actionByRoot: AnimationAction - lookup
  19595. // }
  19596. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  19597. this._nActiveBindings = 0;
  19598. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  19599. this._controlInterpolants = []; // same game as above
  19600. this._nActiveControlInterpolants = 0;
  19601. const scope = this;
  19602. this.stats = {
  19603. actions: {
  19604. get total() {
  19605. return scope._actions.length;
  19606. },
  19607. get inUse() {
  19608. return scope._nActiveActions;
  19609. }
  19610. },
  19611. bindings: {
  19612. get total() {
  19613. return scope._bindings.length;
  19614. },
  19615. get inUse() {
  19616. return scope._nActiveBindings;
  19617. }
  19618. },
  19619. controlInterpolants: {
  19620. get total() {
  19621. return scope._controlInterpolants.length;
  19622. },
  19623. get inUse() {
  19624. return scope._nActiveControlInterpolants;
  19625. }
  19626. }
  19627. };
  19628. }
  19629. // Memory management for AnimationAction objects
  19630. _isActiveAction( action ) {
  19631. const index = action._cacheIndex;
  19632. return index !== null && index < this._nActiveActions;
  19633. }
  19634. _addInactiveAction( action, clipUuid, rootUuid ) {
  19635. const actions = this._actions,
  19636. actionsByClip = this._actionsByClip;
  19637. let actionsForClip = actionsByClip[ clipUuid ];
  19638. if ( actionsForClip === undefined ) {
  19639. actionsForClip = {
  19640. knownActions: [ action ],
  19641. actionByRoot: {}
  19642. };
  19643. action._byClipCacheIndex = 0;
  19644. actionsByClip[ clipUuid ] = actionsForClip;
  19645. } else {
  19646. const knownActions = actionsForClip.knownActions;
  19647. action._byClipCacheIndex = knownActions.length;
  19648. knownActions.push( action );
  19649. }
  19650. action._cacheIndex = actions.length;
  19651. actions.push( action );
  19652. actionsForClip.actionByRoot[ rootUuid ] = action;
  19653. }
  19654. _removeInactiveAction( action ) {
  19655. const actions = this._actions,
  19656. lastInactiveAction = actions[ actions.length - 1 ],
  19657. cacheIndex = action._cacheIndex;
  19658. lastInactiveAction._cacheIndex = cacheIndex;
  19659. actions[ cacheIndex ] = lastInactiveAction;
  19660. actions.pop();
  19661. action._cacheIndex = null;
  19662. const clipUuid = action._clip.uuid,
  19663. actionsByClip = this._actionsByClip,
  19664. actionsForClip = actionsByClip[ clipUuid ],
  19665. knownActionsForClip = actionsForClip.knownActions,
  19666. lastKnownAction =
  19667. knownActionsForClip[ knownActionsForClip.length - 1 ],
  19668. byClipCacheIndex = action._byClipCacheIndex;
  19669. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  19670. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  19671. knownActionsForClip.pop();
  19672. action._byClipCacheIndex = null;
  19673. const actionByRoot = actionsForClip.actionByRoot,
  19674. rootUuid = ( action._localRoot || this._root ).uuid;
  19675. delete actionByRoot[ rootUuid ];
  19676. if ( knownActionsForClip.length === 0 ) {
  19677. delete actionsByClip[ clipUuid ];
  19678. }
  19679. this._removeInactiveBindingsForAction( action );
  19680. }
  19681. _removeInactiveBindingsForAction( action ) {
  19682. const bindings = action._propertyBindings;
  19683. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19684. const binding = bindings[ i ];
  19685. if ( -- binding.referenceCount === 0 ) {
  19686. this._removeInactiveBinding( binding );
  19687. }
  19688. }
  19689. }
  19690. _lendAction( action ) {
  19691. // [ active actions | inactive actions ]
  19692. // [ active actions >| inactive actions ]
  19693. // s a
  19694. // <-swap->
  19695. // a s
  19696. const actions = this._actions,
  19697. prevIndex = action._cacheIndex,
  19698. lastActiveIndex = this._nActiveActions ++,
  19699. firstInactiveAction = actions[ lastActiveIndex ];
  19700. action._cacheIndex = lastActiveIndex;
  19701. actions[ lastActiveIndex ] = action;
  19702. firstInactiveAction._cacheIndex = prevIndex;
  19703. actions[ prevIndex ] = firstInactiveAction;
  19704. }
  19705. _takeBackAction( action ) {
  19706. // [ active actions | inactive actions ]
  19707. // [ active actions |< inactive actions ]
  19708. // a s
  19709. // <-swap->
  19710. // s a
  19711. const actions = this._actions,
  19712. prevIndex = action._cacheIndex,
  19713. firstInactiveIndex = -- this._nActiveActions,
  19714. lastActiveAction = actions[ firstInactiveIndex ];
  19715. action._cacheIndex = firstInactiveIndex;
  19716. actions[ firstInactiveIndex ] = action;
  19717. lastActiveAction._cacheIndex = prevIndex;
  19718. actions[ prevIndex ] = lastActiveAction;
  19719. }
  19720. // Memory management for PropertyMixer objects
  19721. _addInactiveBinding( binding, rootUuid, trackName ) {
  19722. const bindingsByRoot = this._bindingsByRootAndName,
  19723. bindings = this._bindings;
  19724. let bindingByName = bindingsByRoot[ rootUuid ];
  19725. if ( bindingByName === undefined ) {
  19726. bindingByName = {};
  19727. bindingsByRoot[ rootUuid ] = bindingByName;
  19728. }
  19729. bindingByName[ trackName ] = binding;
  19730. binding._cacheIndex = bindings.length;
  19731. bindings.push( binding );
  19732. }
  19733. _removeInactiveBinding( binding ) {
  19734. const bindings = this._bindings,
  19735. propBinding = binding.binding,
  19736. rootUuid = propBinding.rootNode.uuid,
  19737. trackName = propBinding.path,
  19738. bindingsByRoot = this._bindingsByRootAndName,
  19739. bindingByName = bindingsByRoot[ rootUuid ],
  19740. lastInactiveBinding = bindings[ bindings.length - 1 ],
  19741. cacheIndex = binding._cacheIndex;
  19742. lastInactiveBinding._cacheIndex = cacheIndex;
  19743. bindings[ cacheIndex ] = lastInactiveBinding;
  19744. bindings.pop();
  19745. delete bindingByName[ trackName ];
  19746. if ( Object.keys( bindingByName ).length === 0 ) {
  19747. delete bindingsByRoot[ rootUuid ];
  19748. }
  19749. }
  19750. _lendBinding( binding ) {
  19751. const bindings = this._bindings,
  19752. prevIndex = binding._cacheIndex,
  19753. lastActiveIndex = this._nActiveBindings ++,
  19754. firstInactiveBinding = bindings[ lastActiveIndex ];
  19755. binding._cacheIndex = lastActiveIndex;
  19756. bindings[ lastActiveIndex ] = binding;
  19757. firstInactiveBinding._cacheIndex = prevIndex;
  19758. bindings[ prevIndex ] = firstInactiveBinding;
  19759. }
  19760. _takeBackBinding( binding ) {
  19761. const bindings = this._bindings,
  19762. prevIndex = binding._cacheIndex,
  19763. firstInactiveIndex = -- this._nActiveBindings,
  19764. lastActiveBinding = bindings[ firstInactiveIndex ];
  19765. binding._cacheIndex = firstInactiveIndex;
  19766. bindings[ firstInactiveIndex ] = binding;
  19767. lastActiveBinding._cacheIndex = prevIndex;
  19768. bindings[ prevIndex ] = lastActiveBinding;
  19769. }
  19770. // Memory management of Interpolants for weight and time scale
  19771. _lendControlInterpolant() {
  19772. const interpolants = this._controlInterpolants,
  19773. lastActiveIndex = this._nActiveControlInterpolants ++;
  19774. let interpolant = interpolants[ lastActiveIndex ];
  19775. if ( interpolant === undefined ) {
  19776. interpolant = new LinearInterpolant(
  19777. new Float32Array( 2 ), new Float32Array( 2 ),
  19778. 1, _controlInterpolantsResultBuffer );
  19779. interpolant.__cacheIndex = lastActiveIndex;
  19780. interpolants[ lastActiveIndex ] = interpolant;
  19781. }
  19782. return interpolant;
  19783. }
  19784. _takeBackControlInterpolant( interpolant ) {
  19785. const interpolants = this._controlInterpolants,
  19786. prevIndex = interpolant.__cacheIndex,
  19787. firstInactiveIndex = -- this._nActiveControlInterpolants,
  19788. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  19789. interpolant.__cacheIndex = firstInactiveIndex;
  19790. interpolants[ firstInactiveIndex ] = interpolant;
  19791. lastActiveInterpolant.__cacheIndex = prevIndex;
  19792. interpolants[ prevIndex ] = lastActiveInterpolant;
  19793. }
  19794. // return an action for a clip optionally using a custom root target
  19795. // object (this method allocates a lot of dynamic memory in case a
  19796. // previously unknown clip/root combination is specified)
  19797. clipAction( clip, optionalRoot, blendMode ) {
  19798. const root = optionalRoot || this._root,
  19799. rootUuid = root.uuid;
  19800. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  19801. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  19802. const actionsForClip = this._actionsByClip[ clipUuid ];
  19803. let prototypeAction = null;
  19804. if ( blendMode === undefined ) {
  19805. if ( clipObject !== null ) {
  19806. blendMode = clipObject.blendMode;
  19807. } else {
  19808. blendMode = NormalAnimationBlendMode;
  19809. }
  19810. }
  19811. if ( actionsForClip !== undefined ) {
  19812. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  19813. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  19814. return existingAction;
  19815. }
  19816. // we know the clip, so we don't have to parse all
  19817. // the bindings again but can just copy
  19818. prototypeAction = actionsForClip.knownActions[ 0 ];
  19819. // also, take the clip from the prototype action
  19820. if ( clipObject === null )
  19821. clipObject = prototypeAction._clip;
  19822. }
  19823. // clip must be known when specified via string
  19824. if ( clipObject === null ) return null;
  19825. // allocate all resources required to run it
  19826. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  19827. this._bindAction( newAction, prototypeAction );
  19828. // and make the action known to the memory manager
  19829. this._addInactiveAction( newAction, clipUuid, rootUuid );
  19830. return newAction;
  19831. }
  19832. // get an existing action
  19833. existingAction( clip, optionalRoot ) {
  19834. const root = optionalRoot || this._root,
  19835. rootUuid = root.uuid,
  19836. clipObject = typeof clip === 'string' ?
  19837. AnimationClip.findByName( root, clip ) : clip,
  19838. clipUuid = clipObject ? clipObject.uuid : clip,
  19839. actionsForClip = this._actionsByClip[ clipUuid ];
  19840. if ( actionsForClip !== undefined ) {
  19841. return actionsForClip.actionByRoot[ rootUuid ] || null;
  19842. }
  19843. return null;
  19844. }
  19845. // deactivates all previously scheduled actions
  19846. stopAllAction() {
  19847. const actions = this._actions,
  19848. nActions = this._nActiveActions;
  19849. for ( let i = nActions - 1; i >= 0; -- i ) {
  19850. actions[ i ].stop();
  19851. }
  19852. return this;
  19853. }
  19854. // advance the time and update apply the animation
  19855. update( deltaTime ) {
  19856. deltaTime *= this.timeScale;
  19857. const actions = this._actions,
  19858. nActions = this._nActiveActions,
  19859. time = this.time += deltaTime,
  19860. timeDirection = Math.sign( deltaTime ),
  19861. accuIndex = this._accuIndex ^= 1;
  19862. // run active actions
  19863. for ( let i = 0; i !== nActions; ++ i ) {
  19864. const action = actions[ i ];
  19865. action._update( time, deltaTime, timeDirection, accuIndex );
  19866. }
  19867. // update scene graph
  19868. const bindings = this._bindings,
  19869. nBindings = this._nActiveBindings;
  19870. for ( let i = 0; i !== nBindings; ++ i ) {
  19871. bindings[ i ].apply( accuIndex );
  19872. }
  19873. return this;
  19874. }
  19875. // Allows you to seek to a specific time in an animation.
  19876. setTime( timeInSeconds ) {
  19877. this.time = 0; // Zero out time attribute for AnimationMixer object;
  19878. for ( let i = 0; i < this._actions.length; i ++ ) {
  19879. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  19880. }
  19881. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  19882. }
  19883. // return this mixer's root target object
  19884. getRoot() {
  19885. return this._root;
  19886. }
  19887. // free all resources specific to a particular clip
  19888. uncacheClip( clip ) {
  19889. const actions = this._actions,
  19890. clipUuid = clip.uuid,
  19891. actionsByClip = this._actionsByClip,
  19892. actionsForClip = actionsByClip[ clipUuid ];
  19893. if ( actionsForClip !== undefined ) {
  19894. // note: just calling _removeInactiveAction would mess up the
  19895. // iteration state and also require updating the state we can
  19896. // just throw away
  19897. const actionsToRemove = actionsForClip.knownActions;
  19898. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  19899. const action = actionsToRemove[ i ];
  19900. this._deactivateAction( action );
  19901. const cacheIndex = action._cacheIndex,
  19902. lastInactiveAction = actions[ actions.length - 1 ];
  19903. action._cacheIndex = null;
  19904. action._byClipCacheIndex = null;
  19905. lastInactiveAction._cacheIndex = cacheIndex;
  19906. actions[ cacheIndex ] = lastInactiveAction;
  19907. actions.pop();
  19908. this._removeInactiveBindingsForAction( action );
  19909. }
  19910. delete actionsByClip[ clipUuid ];
  19911. }
  19912. }
  19913. // free all resources specific to a particular root target object
  19914. uncacheRoot( root ) {
  19915. const rootUuid = root.uuid,
  19916. actionsByClip = this._actionsByClip;
  19917. for ( const clipUuid in actionsByClip ) {
  19918. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  19919. action = actionByRoot[ rootUuid ];
  19920. if ( action !== undefined ) {
  19921. this._deactivateAction( action );
  19922. this._removeInactiveAction( action );
  19923. }
  19924. }
  19925. const bindingsByRoot = this._bindingsByRootAndName,
  19926. bindingByName = bindingsByRoot[ rootUuid ];
  19927. if ( bindingByName !== undefined ) {
  19928. for ( const trackName in bindingByName ) {
  19929. const binding = bindingByName[ trackName ];
  19930. binding.restoreOriginalState();
  19931. this._removeInactiveBinding( binding );
  19932. }
  19933. }
  19934. }
  19935. // remove a targeted clip from the cache
  19936. uncacheAction( clip, optionalRoot ) {
  19937. const action = this.existingAction( clip, optionalRoot );
  19938. if ( action !== null ) {
  19939. this._deactivateAction( action );
  19940. this._removeInactiveAction( action );
  19941. }
  19942. }
  19943. }
  19944. let Uniform$1 = class Uniform {
  19945. constructor( value ) {
  19946. this.value = value;
  19947. }
  19948. clone() {
  19949. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  19950. }
  19951. };
  19952. let _id$5 = 0;
  19953. let UniformsGroup$1 = class UniformsGroup extends EventDispatcher {
  19954. constructor() {
  19955. super();
  19956. this.isUniformsGroup = true;
  19957. Object.defineProperty( this, 'id', { value: _id$5 ++ } );
  19958. this.name = '';
  19959. this.usage = StaticDrawUsage;
  19960. this.uniforms = [];
  19961. }
  19962. add( uniform ) {
  19963. this.uniforms.push( uniform );
  19964. return this;
  19965. }
  19966. remove( uniform ) {
  19967. const index = this.uniforms.indexOf( uniform );
  19968. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  19969. return this;
  19970. }
  19971. setName( name ) {
  19972. this.name = name;
  19973. return this;
  19974. }
  19975. setUsage( value ) {
  19976. this.usage = value;
  19977. return this;
  19978. }
  19979. dispose() {
  19980. this.dispatchEvent( { type: 'dispose' } );
  19981. return this;
  19982. }
  19983. copy( source ) {
  19984. this.name = source.name;
  19985. this.usage = source.usage;
  19986. const uniformsSource = source.uniforms;
  19987. this.uniforms.length = 0;
  19988. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  19989. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  19990. for ( let j = 0; j < uniforms.length; j ++ ) {
  19991. this.uniforms.push( uniforms[ j ].clone() );
  19992. }
  19993. }
  19994. return this;
  19995. }
  19996. clone() {
  19997. return new this.constructor().copy( this );
  19998. }
  19999. };
  20000. class InstancedInterleavedBuffer extends InterleavedBuffer {
  20001. constructor( array, stride, meshPerAttribute = 1 ) {
  20002. super( array, stride );
  20003. this.isInstancedInterleavedBuffer = true;
  20004. this.meshPerAttribute = meshPerAttribute;
  20005. }
  20006. copy( source ) {
  20007. super.copy( source );
  20008. this.meshPerAttribute = source.meshPerAttribute;
  20009. return this;
  20010. }
  20011. clone( data ) {
  20012. const ib = super.clone( data );
  20013. ib.meshPerAttribute = this.meshPerAttribute;
  20014. return ib;
  20015. }
  20016. toJSON( data ) {
  20017. const json = super.toJSON( data );
  20018. json.isInstancedInterleavedBuffer = true;
  20019. json.meshPerAttribute = this.meshPerAttribute;
  20020. return json;
  20021. }
  20022. }
  20023. class GLBufferAttribute {
  20024. constructor( buffer, type, itemSize, elementSize, count ) {
  20025. this.isGLBufferAttribute = true;
  20026. this.name = '';
  20027. this.buffer = buffer;
  20028. this.type = type;
  20029. this.itemSize = itemSize;
  20030. this.elementSize = elementSize;
  20031. this.count = count;
  20032. this.version = 0;
  20033. }
  20034. set needsUpdate( value ) {
  20035. if ( value === true ) this.version ++;
  20036. }
  20037. setBuffer( buffer ) {
  20038. this.buffer = buffer;
  20039. return this;
  20040. }
  20041. setType( type, elementSize ) {
  20042. this.type = type;
  20043. this.elementSize = elementSize;
  20044. return this;
  20045. }
  20046. setItemSize( itemSize ) {
  20047. this.itemSize = itemSize;
  20048. return this;
  20049. }
  20050. setCount( count ) {
  20051. this.count = count;
  20052. return this;
  20053. }
  20054. }
  20055. const _matrix = /*@__PURE__*/ new Matrix4();
  20056. class Raycaster {
  20057. constructor( origin, direction, near = 0, far = Infinity ) {
  20058. this.ray = new Ray( origin, direction );
  20059. // direction is assumed to be normalized (for accurate distance calculations)
  20060. this.near = near;
  20061. this.far = far;
  20062. this.camera = null;
  20063. this.layers = new Layers();
  20064. this.params = {
  20065. Mesh: {},
  20066. Line: { threshold: 1 },
  20067. LOD: {},
  20068. Points: { threshold: 1 },
  20069. Sprite: {}
  20070. };
  20071. }
  20072. set( origin, direction ) {
  20073. // direction is assumed to be normalized (for accurate distance calculations)
  20074. this.ray.set( origin, direction );
  20075. }
  20076. setFromCamera( coords, camera ) {
  20077. if ( camera.isPerspectiveCamera ) {
  20078. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  20079. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  20080. this.camera = camera;
  20081. } else if ( camera.isOrthographicCamera ) {
  20082. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  20083. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  20084. this.camera = camera;
  20085. } else {
  20086. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  20087. }
  20088. }
  20089. setFromXRController( controller ) {
  20090. _matrix.identity().extractRotation( controller.matrixWorld );
  20091. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  20092. this.ray.direction.set( 0, 0, - 1 ).applyMatrix4( _matrix );
  20093. return this;
  20094. }
  20095. intersectObject( object, recursive = true, intersects = [] ) {
  20096. intersect( object, this, intersects, recursive );
  20097. intersects.sort( ascSort );
  20098. return intersects;
  20099. }
  20100. intersectObjects( objects, recursive = true, intersects = [] ) {
  20101. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  20102. intersect( objects[ i ], this, intersects, recursive );
  20103. }
  20104. intersects.sort( ascSort );
  20105. return intersects;
  20106. }
  20107. }
  20108. function ascSort( a, b ) {
  20109. return a.distance - b.distance;
  20110. }
  20111. function intersect( object, raycaster, intersects, recursive ) {
  20112. let propagate = true;
  20113. if ( object.layers.test( raycaster.layers ) ) {
  20114. const result = object.raycast( raycaster, intersects );
  20115. if ( result === false ) propagate = false;
  20116. }
  20117. if ( propagate === true && recursive === true ) {
  20118. const children = object.children;
  20119. for ( let i = 0, l = children.length; i < l; i ++ ) {
  20120. intersect( children[ i ], raycaster, intersects, true );
  20121. }
  20122. }
  20123. }
  20124. /**
  20125. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  20126. *
  20127. * phi (the polar angle) is measured from the positive y-axis. The positive y-axis is up.
  20128. * theta (the azimuthal angle) is measured from the positive z-axis.
  20129. */
  20130. class Spherical {
  20131. constructor( radius = 1, phi = 0, theta = 0 ) {
  20132. this.radius = radius;
  20133. this.phi = phi; // polar angle
  20134. this.theta = theta; // azimuthal angle
  20135. return this;
  20136. }
  20137. set( radius, phi, theta ) {
  20138. this.radius = radius;
  20139. this.phi = phi;
  20140. this.theta = theta;
  20141. return this;
  20142. }
  20143. copy( other ) {
  20144. this.radius = other.radius;
  20145. this.phi = other.phi;
  20146. this.theta = other.theta;
  20147. return this;
  20148. }
  20149. // restrict phi to be between EPS and PI-EPS
  20150. makeSafe() {
  20151. const EPS = 0.000001;
  20152. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  20153. return this;
  20154. }
  20155. setFromVector3( v ) {
  20156. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20157. }
  20158. setFromCartesianCoords( x, y, z ) {
  20159. this.radius = Math.sqrt( x * x + y * y + z * z );
  20160. if ( this.radius === 0 ) {
  20161. this.theta = 0;
  20162. this.phi = 0;
  20163. } else {
  20164. this.theta = Math.atan2( x, z );
  20165. this.phi = Math.acos( clamp$1( y / this.radius, - 1, 1 ) );
  20166. }
  20167. return this;
  20168. }
  20169. clone() {
  20170. return new this.constructor().copy( this );
  20171. }
  20172. }
  20173. /**
  20174. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  20175. */
  20176. class Cylindrical {
  20177. constructor( radius = 1, theta = 0, y = 0 ) {
  20178. this.radius = radius; // distance from the origin to a point in the x-z plane
  20179. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  20180. this.y = y; // height above the x-z plane
  20181. return this;
  20182. }
  20183. set( radius, theta, y ) {
  20184. this.radius = radius;
  20185. this.theta = theta;
  20186. this.y = y;
  20187. return this;
  20188. }
  20189. copy( other ) {
  20190. this.radius = other.radius;
  20191. this.theta = other.theta;
  20192. this.y = other.y;
  20193. return this;
  20194. }
  20195. setFromVector3( v ) {
  20196. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20197. }
  20198. setFromCartesianCoords( x, y, z ) {
  20199. this.radius = Math.sqrt( x * x + z * z );
  20200. this.theta = Math.atan2( x, z );
  20201. this.y = y;
  20202. return this;
  20203. }
  20204. clone() {
  20205. return new this.constructor().copy( this );
  20206. }
  20207. }
  20208. const _vector$4 = /*@__PURE__*/ new Vector2();
  20209. class Box2 {
  20210. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  20211. this.isBox2 = true;
  20212. this.min = min;
  20213. this.max = max;
  20214. }
  20215. set( min, max ) {
  20216. this.min.copy( min );
  20217. this.max.copy( max );
  20218. return this;
  20219. }
  20220. setFromPoints( points ) {
  20221. this.makeEmpty();
  20222. for ( let i = 0, il = points.length; i < il; i ++ ) {
  20223. this.expandByPoint( points[ i ] );
  20224. }
  20225. return this;
  20226. }
  20227. setFromCenterAndSize( center, size ) {
  20228. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  20229. this.min.copy( center ).sub( halfSize );
  20230. this.max.copy( center ).add( halfSize );
  20231. return this;
  20232. }
  20233. clone() {
  20234. return new this.constructor().copy( this );
  20235. }
  20236. copy( box ) {
  20237. this.min.copy( box.min );
  20238. this.max.copy( box.max );
  20239. return this;
  20240. }
  20241. makeEmpty() {
  20242. this.min.x = this.min.y = + Infinity;
  20243. this.max.x = this.max.y = - Infinity;
  20244. return this;
  20245. }
  20246. isEmpty() {
  20247. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  20248. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  20249. }
  20250. getCenter( target ) {
  20251. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  20252. }
  20253. getSize( target ) {
  20254. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  20255. }
  20256. expandByPoint( point ) {
  20257. this.min.min( point );
  20258. this.max.max( point );
  20259. return this;
  20260. }
  20261. expandByVector( vector ) {
  20262. this.min.sub( vector );
  20263. this.max.add( vector );
  20264. return this;
  20265. }
  20266. expandByScalar( scalar ) {
  20267. this.min.addScalar( - scalar );
  20268. this.max.addScalar( scalar );
  20269. return this;
  20270. }
  20271. containsPoint( point ) {
  20272. return point.x < this.min.x || point.x > this.max.x ||
  20273. point.y < this.min.y || point.y > this.max.y ? false : true;
  20274. }
  20275. containsBox( box ) {
  20276. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  20277. this.min.y <= box.min.y && box.max.y <= this.max.y;
  20278. }
  20279. getParameter( point, target ) {
  20280. // This can potentially have a divide by zero if the box
  20281. // has a size dimension of 0.
  20282. return target.set(
  20283. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  20284. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  20285. );
  20286. }
  20287. intersectsBox( box ) {
  20288. // using 4 splitting planes to rule out intersections
  20289. return box.max.x < this.min.x || box.min.x > this.max.x ||
  20290. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  20291. }
  20292. clampPoint( point, target ) {
  20293. return target.copy( point ).clamp( this.min, this.max );
  20294. }
  20295. distanceToPoint( point ) {
  20296. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  20297. }
  20298. intersect( box ) {
  20299. this.min.max( box.min );
  20300. this.max.min( box.max );
  20301. if ( this.isEmpty() ) this.makeEmpty();
  20302. return this;
  20303. }
  20304. union( box ) {
  20305. this.min.min( box.min );
  20306. this.max.max( box.max );
  20307. return this;
  20308. }
  20309. translate( offset ) {
  20310. this.min.add( offset );
  20311. this.max.add( offset );
  20312. return this;
  20313. }
  20314. equals( box ) {
  20315. return box.min.equals( this.min ) && box.max.equals( this.max );
  20316. }
  20317. }
  20318. const _startP = /*@__PURE__*/ new Vector3();
  20319. const _startEnd = /*@__PURE__*/ new Vector3();
  20320. class Line3 {
  20321. constructor( start = new Vector3(), end = new Vector3() ) {
  20322. this.start = start;
  20323. this.end = end;
  20324. }
  20325. set( start, end ) {
  20326. this.start.copy( start );
  20327. this.end.copy( end );
  20328. return this;
  20329. }
  20330. copy( line ) {
  20331. this.start.copy( line.start );
  20332. this.end.copy( line.end );
  20333. return this;
  20334. }
  20335. getCenter( target ) {
  20336. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  20337. }
  20338. delta( target ) {
  20339. return target.subVectors( this.end, this.start );
  20340. }
  20341. distanceSq() {
  20342. return this.start.distanceToSquared( this.end );
  20343. }
  20344. distance() {
  20345. return this.start.distanceTo( this.end );
  20346. }
  20347. at( t, target ) {
  20348. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20349. }
  20350. closestPointToPointParameter( point, clampToLine ) {
  20351. _startP.subVectors( point, this.start );
  20352. _startEnd.subVectors( this.end, this.start );
  20353. const startEnd2 = _startEnd.dot( _startEnd );
  20354. const startEnd_startP = _startEnd.dot( _startP );
  20355. let t = startEnd_startP / startEnd2;
  20356. if ( clampToLine ) {
  20357. t = clamp$1( t, 0, 1 );
  20358. }
  20359. return t;
  20360. }
  20361. closestPointToPoint( point, clampToLine, target ) {
  20362. const t = this.closestPointToPointParameter( point, clampToLine );
  20363. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20364. }
  20365. applyMatrix4( matrix ) {
  20366. this.start.applyMatrix4( matrix );
  20367. this.end.applyMatrix4( matrix );
  20368. return this;
  20369. }
  20370. equals( line ) {
  20371. return line.start.equals( this.start ) && line.end.equals( this.end );
  20372. }
  20373. clone() {
  20374. return new this.constructor().copy( this );
  20375. }
  20376. }
  20377. const _vector$3 = /*@__PURE__*/ new Vector3();
  20378. class SpotLightHelper extends Object3D {
  20379. constructor( light, color ) {
  20380. super();
  20381. this.light = light;
  20382. this.matrixAutoUpdate = false;
  20383. this.color = color;
  20384. this.type = 'SpotLightHelper';
  20385. const geometry = new BufferGeometry();
  20386. const positions = [
  20387. 0, 0, 0, 0, 0, 1,
  20388. 0, 0, 0, 1, 0, 1,
  20389. 0, 0, 0, - 1, 0, 1,
  20390. 0, 0, 0, 0, 1, 1,
  20391. 0, 0, 0, 0, - 1, 1
  20392. ];
  20393. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  20394. const p1 = ( i / l ) * Math.PI * 2;
  20395. const p2 = ( j / l ) * Math.PI * 2;
  20396. positions.push(
  20397. Math.cos( p1 ), Math.sin( p1 ), 1,
  20398. Math.cos( p2 ), Math.sin( p2 ), 1
  20399. );
  20400. }
  20401. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  20402. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20403. this.cone = new LineSegments( geometry, material );
  20404. this.add( this.cone );
  20405. this.update();
  20406. }
  20407. dispose() {
  20408. this.cone.geometry.dispose();
  20409. this.cone.material.dispose();
  20410. }
  20411. update() {
  20412. this.light.updateWorldMatrix( true, false );
  20413. this.light.target.updateWorldMatrix( true, false );
  20414. // update the local matrix based on the parent and light target transforms
  20415. if ( this.parent ) {
  20416. this.parent.updateWorldMatrix( true );
  20417. this.matrix
  20418. .copy( this.parent.matrixWorld )
  20419. .invert()
  20420. .multiply( this.light.matrixWorld );
  20421. } else {
  20422. this.matrix.copy( this.light.matrixWorld );
  20423. }
  20424. this.matrixWorld.copy( this.light.matrixWorld );
  20425. const coneLength = this.light.distance ? this.light.distance : 1000;
  20426. const coneWidth = coneLength * Math.tan( this.light.angle );
  20427. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20428. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  20429. this.cone.lookAt( _vector$3 );
  20430. if ( this.color !== undefined ) {
  20431. this.cone.material.color.set( this.color );
  20432. } else {
  20433. this.cone.material.color.copy( this.light.color );
  20434. }
  20435. }
  20436. }
  20437. const _vector$2 = /*@__PURE__*/ new Vector3();
  20438. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  20439. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  20440. class SkeletonHelper extends LineSegments {
  20441. constructor( object ) {
  20442. const bones = getBoneList( object );
  20443. const geometry = new BufferGeometry();
  20444. const vertices = [];
  20445. const colors = [];
  20446. const color1 = new Color( 0, 0, 1 );
  20447. const color2 = new Color( 0, 1, 0 );
  20448. for ( let i = 0; i < bones.length; i ++ ) {
  20449. const bone = bones[ i ];
  20450. if ( bone.parent && bone.parent.isBone ) {
  20451. vertices.push( 0, 0, 0 );
  20452. vertices.push( 0, 0, 0 );
  20453. colors.push( color1.r, color1.g, color1.b );
  20454. colors.push( color2.r, color2.g, color2.b );
  20455. }
  20456. }
  20457. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20458. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20459. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  20460. super( geometry, material );
  20461. this.isSkeletonHelper = true;
  20462. this.type = 'SkeletonHelper';
  20463. this.root = object;
  20464. this.bones = bones;
  20465. this.matrix = object.matrixWorld;
  20466. this.matrixAutoUpdate = false;
  20467. }
  20468. updateMatrixWorld( force ) {
  20469. const bones = this.bones;
  20470. const geometry = this.geometry;
  20471. const position = geometry.getAttribute( 'position' );
  20472. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  20473. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  20474. const bone = bones[ i ];
  20475. if ( bone.parent && bone.parent.isBone ) {
  20476. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  20477. _vector$2.setFromMatrixPosition( _boneMatrix );
  20478. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  20479. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  20480. _vector$2.setFromMatrixPosition( _boneMatrix );
  20481. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  20482. j += 2;
  20483. }
  20484. }
  20485. geometry.getAttribute( 'position' ).needsUpdate = true;
  20486. super.updateMatrixWorld( force );
  20487. }
  20488. dispose() {
  20489. this.geometry.dispose();
  20490. this.material.dispose();
  20491. }
  20492. }
  20493. function getBoneList( object ) {
  20494. const boneList = [];
  20495. if ( object.isBone === true ) {
  20496. boneList.push( object );
  20497. }
  20498. for ( let i = 0; i < object.children.length; i ++ ) {
  20499. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  20500. }
  20501. return boneList;
  20502. }
  20503. class PointLightHelper extends Mesh {
  20504. constructor( light, sphereSize, color ) {
  20505. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  20506. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20507. super( geometry, material );
  20508. this.light = light;
  20509. this.color = color;
  20510. this.type = 'PointLightHelper';
  20511. this.matrix = this.light.matrixWorld;
  20512. this.matrixAutoUpdate = false;
  20513. this.update();
  20514. /*
  20515. // TODO: delete this comment?
  20516. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20517. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20518. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20519. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20520. const d = light.distance;
  20521. if ( d === 0.0 ) {
  20522. this.lightDistance.visible = false;
  20523. } else {
  20524. this.lightDistance.scale.set( d, d, d );
  20525. }
  20526. this.add( this.lightDistance );
  20527. */
  20528. }
  20529. dispose() {
  20530. this.geometry.dispose();
  20531. this.material.dispose();
  20532. }
  20533. update() {
  20534. this.light.updateWorldMatrix( true, false );
  20535. if ( this.color !== undefined ) {
  20536. this.material.color.set( this.color );
  20537. } else {
  20538. this.material.color.copy( this.light.color );
  20539. }
  20540. /*
  20541. const d = this.light.distance;
  20542. if ( d === 0.0 ) {
  20543. this.lightDistance.visible = false;
  20544. } else {
  20545. this.lightDistance.visible = true;
  20546. this.lightDistance.scale.set( d, d, d );
  20547. }
  20548. */
  20549. }
  20550. }
  20551. const _vector$1 = /*@__PURE__*/ new Vector3();
  20552. const _color1 = /*@__PURE__*/ new Color();
  20553. const _color2 = /*@__PURE__*/ new Color();
  20554. class HemisphereLightHelper extends Object3D {
  20555. constructor( light, size, color ) {
  20556. super();
  20557. this.light = light;
  20558. this.matrix = light.matrixWorld;
  20559. this.matrixAutoUpdate = false;
  20560. this.color = color;
  20561. this.type = 'HemisphereLightHelper';
  20562. const geometry = new OctahedronGeometry( size );
  20563. geometry.rotateY( Math.PI * 0.5 );
  20564. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20565. if ( this.color === undefined ) this.material.vertexColors = true;
  20566. const position = geometry.getAttribute( 'position' );
  20567. const colors = new Float32Array( position.count * 3 );
  20568. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  20569. this.add( new Mesh( geometry, this.material ) );
  20570. this.update();
  20571. }
  20572. dispose() {
  20573. this.children[ 0 ].geometry.dispose();
  20574. this.children[ 0 ].material.dispose();
  20575. }
  20576. update() {
  20577. const mesh = this.children[ 0 ];
  20578. if ( this.color !== undefined ) {
  20579. this.material.color.set( this.color );
  20580. } else {
  20581. const colors = mesh.geometry.getAttribute( 'color' );
  20582. _color1.copy( this.light.color );
  20583. _color2.copy( this.light.groundColor );
  20584. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  20585. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  20586. colors.setXYZ( i, color.r, color.g, color.b );
  20587. }
  20588. colors.needsUpdate = true;
  20589. }
  20590. this.light.updateWorldMatrix( true, false );
  20591. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20592. }
  20593. }
  20594. class GridHelper extends LineSegments {
  20595. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  20596. color1 = new Color( color1 );
  20597. color2 = new Color( color2 );
  20598. const center = divisions / 2;
  20599. const step = size / divisions;
  20600. const halfSize = size / 2;
  20601. const vertices = [], colors = [];
  20602. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  20603. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  20604. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  20605. const color = i === center ? color1 : color2;
  20606. color.toArray( colors, j ); j += 3;
  20607. color.toArray( colors, j ); j += 3;
  20608. color.toArray( colors, j ); j += 3;
  20609. color.toArray( colors, j ); j += 3;
  20610. }
  20611. const geometry = new BufferGeometry();
  20612. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20613. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20614. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20615. super( geometry, material );
  20616. this.type = 'GridHelper';
  20617. }
  20618. dispose() {
  20619. this.geometry.dispose();
  20620. this.material.dispose();
  20621. }
  20622. }
  20623. class PolarGridHelper extends LineSegments {
  20624. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  20625. color1 = new Color( color1 );
  20626. color2 = new Color( color2 );
  20627. const vertices = [];
  20628. const colors = [];
  20629. // create the sectors
  20630. if ( sectors > 1 ) {
  20631. for ( let i = 0; i < sectors; i ++ ) {
  20632. const v = ( i / sectors ) * ( Math.PI * 2 );
  20633. const x = Math.sin( v ) * radius;
  20634. const z = Math.cos( v ) * radius;
  20635. vertices.push( 0, 0, 0 );
  20636. vertices.push( x, 0, z );
  20637. const color = ( i & 1 ) ? color1 : color2;
  20638. colors.push( color.r, color.g, color.b );
  20639. colors.push( color.r, color.g, color.b );
  20640. }
  20641. }
  20642. // create the rings
  20643. for ( let i = 0; i < rings; i ++ ) {
  20644. const color = ( i & 1 ) ? color1 : color2;
  20645. const r = radius - ( radius / rings * i );
  20646. for ( let j = 0; j < divisions; j ++ ) {
  20647. // first vertex
  20648. let v = ( j / divisions ) * ( Math.PI * 2 );
  20649. let x = Math.sin( v ) * r;
  20650. let z = Math.cos( v ) * r;
  20651. vertices.push( x, 0, z );
  20652. colors.push( color.r, color.g, color.b );
  20653. // second vertex
  20654. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  20655. x = Math.sin( v ) * r;
  20656. z = Math.cos( v ) * r;
  20657. vertices.push( x, 0, z );
  20658. colors.push( color.r, color.g, color.b );
  20659. }
  20660. }
  20661. const geometry = new BufferGeometry();
  20662. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20663. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20664. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20665. super( geometry, material );
  20666. this.type = 'PolarGridHelper';
  20667. }
  20668. dispose() {
  20669. this.geometry.dispose();
  20670. this.material.dispose();
  20671. }
  20672. }
  20673. const _v1 = /*@__PURE__*/ new Vector3();
  20674. const _v2 = /*@__PURE__*/ new Vector3();
  20675. const _v3 = /*@__PURE__*/ new Vector3();
  20676. class DirectionalLightHelper extends Object3D {
  20677. constructor( light, size, color ) {
  20678. super();
  20679. this.light = light;
  20680. this.matrix = light.matrixWorld;
  20681. this.matrixAutoUpdate = false;
  20682. this.color = color;
  20683. this.type = 'DirectionalLightHelper';
  20684. if ( size === undefined ) size = 1;
  20685. let geometry = new BufferGeometry();
  20686. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  20687. - size, size, 0,
  20688. size, size, 0,
  20689. size, - size, 0,
  20690. - size, - size, 0,
  20691. - size, size, 0
  20692. ], 3 ) );
  20693. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20694. this.lightPlane = new Line( geometry, material );
  20695. this.add( this.lightPlane );
  20696. geometry = new BufferGeometry();
  20697. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  20698. this.targetLine = new Line( geometry, material );
  20699. this.add( this.targetLine );
  20700. this.update();
  20701. }
  20702. dispose() {
  20703. this.lightPlane.geometry.dispose();
  20704. this.lightPlane.material.dispose();
  20705. this.targetLine.geometry.dispose();
  20706. this.targetLine.material.dispose();
  20707. }
  20708. update() {
  20709. this.light.updateWorldMatrix( true, false );
  20710. this.light.target.updateWorldMatrix( true, false );
  20711. _v1.setFromMatrixPosition( this.light.matrixWorld );
  20712. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20713. _v3.subVectors( _v2, _v1 );
  20714. this.lightPlane.lookAt( _v2 );
  20715. if ( this.color !== undefined ) {
  20716. this.lightPlane.material.color.set( this.color );
  20717. this.targetLine.material.color.set( this.color );
  20718. } else {
  20719. this.lightPlane.material.color.copy( this.light.color );
  20720. this.targetLine.material.color.copy( this.light.color );
  20721. }
  20722. this.targetLine.lookAt( _v2 );
  20723. this.targetLine.scale.z = _v3.length();
  20724. }
  20725. }
  20726. const _vector = /*@__PURE__*/ new Vector3();
  20727. const _camera$1 = /*@__PURE__*/ new Camera();
  20728. /**
  20729. * - shows frustum, line of sight and up of the camera
  20730. * - suitable for fast updates
  20731. * - based on frustum visualization in lightgl.js shadowmap example
  20732. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  20733. */
  20734. class CameraHelper extends LineSegments {
  20735. constructor( camera ) {
  20736. const geometry = new BufferGeometry();
  20737. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  20738. const vertices = [];
  20739. const colors = [];
  20740. const pointMap = {};
  20741. // near
  20742. addLine( 'n1', 'n2' );
  20743. addLine( 'n2', 'n4' );
  20744. addLine( 'n4', 'n3' );
  20745. addLine( 'n3', 'n1' );
  20746. // far
  20747. addLine( 'f1', 'f2' );
  20748. addLine( 'f2', 'f4' );
  20749. addLine( 'f4', 'f3' );
  20750. addLine( 'f3', 'f1' );
  20751. // sides
  20752. addLine( 'n1', 'f1' );
  20753. addLine( 'n2', 'f2' );
  20754. addLine( 'n3', 'f3' );
  20755. addLine( 'n4', 'f4' );
  20756. // cone
  20757. addLine( 'p', 'n1' );
  20758. addLine( 'p', 'n2' );
  20759. addLine( 'p', 'n3' );
  20760. addLine( 'p', 'n4' );
  20761. // up
  20762. addLine( 'u1', 'u2' );
  20763. addLine( 'u2', 'u3' );
  20764. addLine( 'u3', 'u1' );
  20765. // target
  20766. addLine( 'c', 't' );
  20767. addLine( 'p', 'c' );
  20768. // cross
  20769. addLine( 'cn1', 'cn2' );
  20770. addLine( 'cn3', 'cn4' );
  20771. addLine( 'cf1', 'cf2' );
  20772. addLine( 'cf3', 'cf4' );
  20773. function addLine( a, b ) {
  20774. addPoint( a );
  20775. addPoint( b );
  20776. }
  20777. function addPoint( id ) {
  20778. vertices.push( 0, 0, 0 );
  20779. colors.push( 0, 0, 0 );
  20780. if ( pointMap[ id ] === undefined ) {
  20781. pointMap[ id ] = [];
  20782. }
  20783. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  20784. }
  20785. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20786. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20787. super( geometry, material );
  20788. this.type = 'CameraHelper';
  20789. this.camera = camera;
  20790. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  20791. this.matrix = camera.matrixWorld;
  20792. this.matrixAutoUpdate = false;
  20793. this.pointMap = pointMap;
  20794. this.update();
  20795. // colors
  20796. const colorFrustum = new Color( 0xffaa00 );
  20797. const colorCone = new Color( 0xff0000 );
  20798. const colorUp = new Color( 0x00aaff );
  20799. const colorTarget = new Color( 0xffffff );
  20800. const colorCross = new Color( 0x333333 );
  20801. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  20802. }
  20803. setColors( frustum, cone, up, target, cross ) {
  20804. const geometry = this.geometry;
  20805. const colorAttribute = geometry.getAttribute( 'color' );
  20806. // near
  20807. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  20808. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  20809. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  20810. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  20811. // far
  20812. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  20813. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  20814. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  20815. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  20816. // sides
  20817. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  20818. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  20819. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  20820. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  20821. // cone
  20822. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  20823. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  20824. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  20825. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  20826. // up
  20827. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  20828. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  20829. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  20830. // target
  20831. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  20832. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  20833. // cross
  20834. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  20835. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  20836. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  20837. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  20838. colorAttribute.needsUpdate = true;
  20839. }
  20840. update() {
  20841. const geometry = this.geometry;
  20842. const pointMap = this.pointMap;
  20843. const w = 1, h = 1;
  20844. // we need just camera projection matrix inverse
  20845. // world matrix must be identity
  20846. _camera$1.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  20847. // center / target
  20848. setPoint( 'c', pointMap, geometry, _camera$1, 0, 0, - 1 );
  20849. setPoint( 't', pointMap, geometry, _camera$1, 0, 0, 1 );
  20850. // near
  20851. setPoint( 'n1', pointMap, geometry, _camera$1, - w, - h, - 1 );
  20852. setPoint( 'n2', pointMap, geometry, _camera$1, w, - h, - 1 );
  20853. setPoint( 'n3', pointMap, geometry, _camera$1, - w, h, - 1 );
  20854. setPoint( 'n4', pointMap, geometry, _camera$1, w, h, - 1 );
  20855. // far
  20856. setPoint( 'f1', pointMap, geometry, _camera$1, - w, - h, 1 );
  20857. setPoint( 'f2', pointMap, geometry, _camera$1, w, - h, 1 );
  20858. setPoint( 'f3', pointMap, geometry, _camera$1, - w, h, 1 );
  20859. setPoint( 'f4', pointMap, geometry, _camera$1, w, h, 1 );
  20860. // up
  20861. setPoint( 'u1', pointMap, geometry, _camera$1, w * 0.7, h * 1.1, - 1 );
  20862. setPoint( 'u2', pointMap, geometry, _camera$1, - w * 0.7, h * 1.1, - 1 );
  20863. setPoint( 'u3', pointMap, geometry, _camera$1, 0, h * 2, - 1 );
  20864. // cross
  20865. setPoint( 'cf1', pointMap, geometry, _camera$1, - w, 0, 1 );
  20866. setPoint( 'cf2', pointMap, geometry, _camera$1, w, 0, 1 );
  20867. setPoint( 'cf3', pointMap, geometry, _camera$1, 0, - h, 1 );
  20868. setPoint( 'cf4', pointMap, geometry, _camera$1, 0, h, 1 );
  20869. setPoint( 'cn1', pointMap, geometry, _camera$1, - w, 0, - 1 );
  20870. setPoint( 'cn2', pointMap, geometry, _camera$1, w, 0, - 1 );
  20871. setPoint( 'cn3', pointMap, geometry, _camera$1, 0, - h, - 1 );
  20872. setPoint( 'cn4', pointMap, geometry, _camera$1, 0, h, - 1 );
  20873. geometry.getAttribute( 'position' ).needsUpdate = true;
  20874. }
  20875. dispose() {
  20876. this.geometry.dispose();
  20877. this.material.dispose();
  20878. }
  20879. }
  20880. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  20881. _vector.set( x, y, z ).unproject( camera );
  20882. const points = pointMap[ point ];
  20883. if ( points !== undefined ) {
  20884. const position = geometry.getAttribute( 'position' );
  20885. for ( let i = 0, l = points.length; i < l; i ++ ) {
  20886. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  20887. }
  20888. }
  20889. }
  20890. const _box = /*@__PURE__*/ new Box3();
  20891. class BoxHelper extends LineSegments {
  20892. constructor( object, color = 0xffff00 ) {
  20893. const indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
  20894. const positions = new Float32Array( 8 * 3 );
  20895. const geometry = new BufferGeometry();
  20896. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  20897. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  20898. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  20899. this.object = object;
  20900. this.type = 'BoxHelper';
  20901. this.matrixAutoUpdate = false;
  20902. this.update();
  20903. }
  20904. update( object ) {
  20905. if ( object !== undefined ) {
  20906. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  20907. }
  20908. if ( this.object !== undefined ) {
  20909. _box.setFromObject( this.object );
  20910. }
  20911. if ( _box.isEmpty() ) return;
  20912. const min = _box.min;
  20913. const max = _box.max;
  20914. /*
  20915. 5____4
  20916. 1/___0/|
  20917. | 6__|_7
  20918. 2/___3/
  20919. 0: max.x, max.y, max.z
  20920. 1: min.x, max.y, max.z
  20921. 2: min.x, min.y, max.z
  20922. 3: max.x, min.y, max.z
  20923. 4: max.x, max.y, min.z
  20924. 5: min.x, max.y, min.z
  20925. 6: min.x, min.y, min.z
  20926. 7: max.x, min.y, min.z
  20927. */
  20928. const position = this.geometry.attributes.position;
  20929. const array = position.array;
  20930. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  20931. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  20932. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  20933. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  20934. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  20935. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  20936. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  20937. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  20938. position.needsUpdate = true;
  20939. this.geometry.computeBoundingSphere();
  20940. }
  20941. setFromObject( object ) {
  20942. this.object = object;
  20943. this.update();
  20944. return this;
  20945. }
  20946. copy( source, recursive ) {
  20947. super.copy( source, recursive );
  20948. this.object = source.object;
  20949. return this;
  20950. }
  20951. dispose() {
  20952. this.geometry.dispose();
  20953. this.material.dispose();
  20954. }
  20955. }
  20956. class Box3Helper extends LineSegments {
  20957. constructor( box, color = 0xffff00 ) {
  20958. const indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
  20959. const positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ];
  20960. const geometry = new BufferGeometry();
  20961. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  20962. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  20963. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  20964. this.box = box;
  20965. this.type = 'Box3Helper';
  20966. this.geometry.computeBoundingSphere();
  20967. }
  20968. updateMatrixWorld( force ) {
  20969. const box = this.box;
  20970. if ( box.isEmpty() ) return;
  20971. box.getCenter( this.position );
  20972. box.getSize( this.scale );
  20973. this.scale.multiplyScalar( 0.5 );
  20974. super.updateMatrixWorld( force );
  20975. }
  20976. dispose() {
  20977. this.geometry.dispose();
  20978. this.material.dispose();
  20979. }
  20980. }
  20981. class PlaneHelper extends Line {
  20982. constructor( plane, size = 1, hex = 0xffff00 ) {
  20983. const color = hex;
  20984. const positions = [ 1, - 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, - 1, 0, 1, 1, 0 ];
  20985. const geometry = new BufferGeometry();
  20986. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  20987. geometry.computeBoundingSphere();
  20988. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  20989. this.type = 'PlaneHelper';
  20990. this.plane = plane;
  20991. this.size = size;
  20992. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  20993. const geometry2 = new BufferGeometry();
  20994. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  20995. geometry2.computeBoundingSphere();
  20996. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  20997. }
  20998. updateMatrixWorld( force ) {
  20999. this.position.set( 0, 0, 0 );
  21000. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  21001. this.lookAt( this.plane.normal );
  21002. this.translateZ( - this.plane.constant );
  21003. super.updateMatrixWorld( force );
  21004. }
  21005. dispose() {
  21006. this.geometry.dispose();
  21007. this.material.dispose();
  21008. this.children[ 0 ].geometry.dispose();
  21009. this.children[ 0 ].material.dispose();
  21010. }
  21011. }
  21012. const _axis = /*@__PURE__*/ new Vector3();
  21013. let _lineGeometry, _coneGeometry;
  21014. class ArrowHelper extends Object3D {
  21015. // dir is assumed to be normalized
  21016. constructor( dir = new Vector3( 0, 0, 1 ), origin = new Vector3( 0, 0, 0 ), length = 1, color = 0xffff00, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  21017. super();
  21018. this.type = 'ArrowHelper';
  21019. if ( _lineGeometry === undefined ) {
  21020. _lineGeometry = new BufferGeometry();
  21021. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  21022. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  21023. _coneGeometry.translate( 0, - 0.5, 0 );
  21024. }
  21025. this.position.copy( origin );
  21026. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21027. this.line.matrixAutoUpdate = false;
  21028. this.add( this.line );
  21029. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  21030. this.cone.matrixAutoUpdate = false;
  21031. this.add( this.cone );
  21032. this.setDirection( dir );
  21033. this.setLength( length, headLength, headWidth );
  21034. }
  21035. setDirection( dir ) {
  21036. // dir is assumed to be normalized
  21037. if ( dir.y > 0.99999 ) {
  21038. this.quaternion.set( 0, 0, 0, 1 );
  21039. } else if ( dir.y < - 0.99999 ) {
  21040. this.quaternion.set( 1, 0, 0, 0 );
  21041. } else {
  21042. _axis.set( dir.z, 0, - dir.x ).normalize();
  21043. const radians = Math.acos( dir.y );
  21044. this.quaternion.setFromAxisAngle( _axis, radians );
  21045. }
  21046. }
  21047. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  21048. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  21049. this.line.updateMatrix();
  21050. this.cone.scale.set( headWidth, headLength, headWidth );
  21051. this.cone.position.y = length;
  21052. this.cone.updateMatrix();
  21053. }
  21054. setColor( color ) {
  21055. this.line.material.color.set( color );
  21056. this.cone.material.color.set( color );
  21057. }
  21058. copy( source ) {
  21059. super.copy( source, false );
  21060. this.line.copy( source.line );
  21061. this.cone.copy( source.cone );
  21062. return this;
  21063. }
  21064. dispose() {
  21065. this.line.geometry.dispose();
  21066. this.line.material.dispose();
  21067. this.cone.geometry.dispose();
  21068. this.cone.material.dispose();
  21069. }
  21070. }
  21071. class AxesHelper extends LineSegments {
  21072. constructor( size = 1 ) {
  21073. const vertices = [
  21074. 0, 0, 0, size, 0, 0,
  21075. 0, 0, 0, 0, size, 0,
  21076. 0, 0, 0, 0, 0, size
  21077. ];
  21078. const colors = [
  21079. 1, 0, 0, 1, 0.6, 0,
  21080. 0, 1, 0, 0.6, 1, 0,
  21081. 0, 0, 1, 0, 0.6, 1
  21082. ];
  21083. const geometry = new BufferGeometry();
  21084. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21085. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  21086. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  21087. super( geometry, material );
  21088. this.type = 'AxesHelper';
  21089. }
  21090. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  21091. const color = new Color();
  21092. const array = this.geometry.attributes.color.array;
  21093. color.set( xAxisColor );
  21094. color.toArray( array, 0 );
  21095. color.toArray( array, 3 );
  21096. color.set( yAxisColor );
  21097. color.toArray( array, 6 );
  21098. color.toArray( array, 9 );
  21099. color.set( zAxisColor );
  21100. color.toArray( array, 12 );
  21101. color.toArray( array, 15 );
  21102. this.geometry.attributes.color.needsUpdate = true;
  21103. return this;
  21104. }
  21105. dispose() {
  21106. this.geometry.dispose();
  21107. this.material.dispose();
  21108. }
  21109. }
  21110. class ShapePath {
  21111. constructor() {
  21112. this.type = 'ShapePath';
  21113. this.color = new Color();
  21114. this.subPaths = [];
  21115. this.currentPath = null;
  21116. }
  21117. moveTo( x, y ) {
  21118. this.currentPath = new Path();
  21119. this.subPaths.push( this.currentPath );
  21120. this.currentPath.moveTo( x, y );
  21121. return this;
  21122. }
  21123. lineTo( x, y ) {
  21124. this.currentPath.lineTo( x, y );
  21125. return this;
  21126. }
  21127. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  21128. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  21129. return this;
  21130. }
  21131. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21132. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  21133. return this;
  21134. }
  21135. splineThru( pts ) {
  21136. this.currentPath.splineThru( pts );
  21137. return this;
  21138. }
  21139. toShapes( isCCW ) {
  21140. function toShapesNoHoles( inSubpaths ) {
  21141. const shapes = [];
  21142. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21143. const tmpPath = inSubpaths[ i ];
  21144. const tmpShape = new Shape();
  21145. tmpShape.curves = tmpPath.curves;
  21146. shapes.push( tmpShape );
  21147. }
  21148. return shapes;
  21149. }
  21150. function isPointInsidePolygon( inPt, inPolygon ) {
  21151. const polyLen = inPolygon.length;
  21152. // inPt on polygon contour => immediate success or
  21153. // toggling of inside/outside at every single! intersection point of an edge
  21154. // with the horizontal line through inPt, left of inPt
  21155. // not counting lowerY endpoints of edges and whole edges on that line
  21156. let inside = false;
  21157. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21158. let edgeLowPt = inPolygon[ p ];
  21159. let edgeHighPt = inPolygon[ q ];
  21160. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  21161. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  21162. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21163. // not parallel
  21164. if ( edgeDy < 0 ) {
  21165. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21166. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21167. }
  21168. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21169. if ( inPt.y === edgeLowPt.y ) {
  21170. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21171. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21172. } else {
  21173. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21174. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21175. if ( perpEdge < 0 ) continue;
  21176. inside = ! inside; // true intersection left of inPt
  21177. }
  21178. } else {
  21179. // parallel or collinear
  21180. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21181. // edge lies on the same horizontal line as inPt
  21182. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21183. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21184. // continue;
  21185. }
  21186. }
  21187. return inside;
  21188. }
  21189. const isClockWise = ShapeUtils.isClockWise;
  21190. const subPaths = this.subPaths;
  21191. if ( subPaths.length === 0 ) return [];
  21192. let solid, tmpPath, tmpShape;
  21193. const shapes = [];
  21194. if ( subPaths.length === 1 ) {
  21195. tmpPath = subPaths[ 0 ];
  21196. tmpShape = new Shape();
  21197. tmpShape.curves = tmpPath.curves;
  21198. shapes.push( tmpShape );
  21199. return shapes;
  21200. }
  21201. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21202. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21203. // console.log("Holes first", holesFirst);
  21204. const betterShapeHoles = [];
  21205. const newShapes = [];
  21206. let newShapeHoles = [];
  21207. let mainIdx = 0;
  21208. let tmpPoints;
  21209. newShapes[ mainIdx ] = undefined;
  21210. newShapeHoles[ mainIdx ] = [];
  21211. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  21212. tmpPath = subPaths[ i ];
  21213. tmpPoints = tmpPath.getPoints();
  21214. solid = isClockWise( tmpPoints );
  21215. solid = isCCW ? ! solid : solid;
  21216. if ( solid ) {
  21217. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21218. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21219. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21220. if ( holesFirst ) mainIdx ++;
  21221. newShapeHoles[ mainIdx ] = [];
  21222. //console.log('cw', i);
  21223. } else {
  21224. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21225. //console.log('ccw', i);
  21226. }
  21227. }
  21228. // only Holes? -> probably all Shapes with wrong orientation
  21229. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21230. if ( newShapes.length > 1 ) {
  21231. let ambiguous = false;
  21232. let toChange = 0;
  21233. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21234. betterShapeHoles[ sIdx ] = [];
  21235. }
  21236. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21237. const sho = newShapeHoles[ sIdx ];
  21238. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21239. const ho = sho[ hIdx ];
  21240. let hole_unassigned = true;
  21241. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21242. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21243. if ( sIdx !== s2Idx ) toChange ++;
  21244. if ( hole_unassigned ) {
  21245. hole_unassigned = false;
  21246. betterShapeHoles[ s2Idx ].push( ho );
  21247. } else {
  21248. ambiguous = true;
  21249. }
  21250. }
  21251. }
  21252. if ( hole_unassigned ) {
  21253. betterShapeHoles[ sIdx ].push( ho );
  21254. }
  21255. }
  21256. }
  21257. if ( toChange > 0 && ambiguous === false ) {
  21258. newShapeHoles = betterShapeHoles;
  21259. }
  21260. }
  21261. let tmpHoles;
  21262. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  21263. tmpShape = newShapes[ i ].s;
  21264. shapes.push( tmpShape );
  21265. tmpHoles = newShapeHoles[ i ];
  21266. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21267. tmpShape.holes.push( tmpHoles[ j ].h );
  21268. }
  21269. }
  21270. //console.log("shape", shapes);
  21271. return shapes;
  21272. }
  21273. }
  21274. class WebGLMultipleRenderTargets extends WebGLRenderTarget { // @deprecated, r162
  21275. constructor( width = 1, height = 1, count = 1, options = {} ) {
  21276. console.warn( 'THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.' );
  21277. super( width, height, { ...options, count } );
  21278. this.isWebGLMultipleRenderTargets = true;
  21279. }
  21280. get texture() {
  21281. return this.textures;
  21282. }
  21283. }
  21284. if ( self.GPUShaderStage === undefined ) {
  21285. self.GPUShaderStage = { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  21286. }
  21287. // statics
  21288. let isAvailable = navigator.gpu !== undefined;
  21289. if ( typeof window !== 'undefined' && isAvailable ) {
  21290. isAvailable = await navigator.gpu.requestAdapter();
  21291. }
  21292. class WebGPU {
  21293. static isAvailable() {
  21294. return Boolean( isAvailable );
  21295. }
  21296. static getStaticAdapter() {
  21297. return isAvailable;
  21298. }
  21299. static getErrorMessage() {
  21300. const message = 'Your browser does not support <a href="https://gpuweb.github.io/gpuweb/" style="color:blue">WebGPU</a> yet';
  21301. const element = document.createElement( 'div' );
  21302. element.id = 'webgpumessage';
  21303. element.style.fontFamily = 'monospace';
  21304. element.style.fontSize = '13px';
  21305. element.style.fontWeight = 'normal';
  21306. element.style.textAlign = 'center';
  21307. element.style.background = '#fff';
  21308. element.style.color = '#000';
  21309. element.style.padding = '1.5em';
  21310. element.style.maxWidth = '400px';
  21311. element.style.margin = '5em auto 0';
  21312. element.innerHTML = message;
  21313. return element;
  21314. }
  21315. }
  21316. class Animation {
  21317. constructor( nodes, info ) {
  21318. this.nodes = nodes;
  21319. this.info = info;
  21320. this.animationLoop = null;
  21321. this.requestId = null;
  21322. this._init();
  21323. }
  21324. _init() {
  21325. const update = ( time, frame ) => {
  21326. this.requestId = self.requestAnimationFrame( update );
  21327. if ( this.info.autoReset === true ) this.info.reset();
  21328. this.nodes.nodeFrame.update();
  21329. this.info.frame = this.nodes.nodeFrame.frameId;
  21330. if ( this.animationLoop !== null ) this.animationLoop( time, frame );
  21331. };
  21332. update();
  21333. }
  21334. dispose() {
  21335. self.cancelAnimationFrame( this.requestId );
  21336. this.requestId = null;
  21337. }
  21338. setAnimationLoop( callback ) {
  21339. this.animationLoop = callback;
  21340. }
  21341. }
  21342. class ChainMap {
  21343. constructor() {
  21344. this.weakMap = new WeakMap();
  21345. }
  21346. get( keys ) {
  21347. let map = this.weakMap;
  21348. for ( let i = 0; i < keys.length; i ++ ) {
  21349. map = map.get( keys[ i ] );
  21350. if ( map === undefined ) return undefined;
  21351. }
  21352. return map.get( keys[ keys.length - 1 ] );
  21353. }
  21354. set( keys, value ) {
  21355. let map = this.weakMap;
  21356. for ( let i = 0; i < keys.length; i ++ ) {
  21357. const key = keys[ i ];
  21358. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  21359. map = map.get( key );
  21360. }
  21361. return map.set( keys[ keys.length - 1 ], value );
  21362. }
  21363. delete( keys ) {
  21364. let map = this.weakMap;
  21365. for ( let i = 0; i < keys.length; i ++ ) {
  21366. map = map.get( keys[ i ] );
  21367. if ( map === undefined ) return false;
  21368. }
  21369. return map.delete( keys[ keys.length - 1 ] );
  21370. }
  21371. }
  21372. const _plane = new Plane();
  21373. let _clippingContextVersion = 0;
  21374. class ClippingContext {
  21375. constructor() {
  21376. this.version = ++ _clippingContextVersion;
  21377. this.globalClippingCount = 0;
  21378. this.localClippingCount = 0;
  21379. this.localClippingEnabled = false;
  21380. this.localClipIntersection = false;
  21381. this.planes = [];
  21382. this.parentVersion = 0;
  21383. this.viewNormalMatrix = new Matrix3();
  21384. }
  21385. projectPlanes( source, offset ) {
  21386. const l = source.length;
  21387. const planes = this.planes;
  21388. for ( let i = 0; i < l; i ++ ) {
  21389. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  21390. const v = planes[ offset + i ];
  21391. const normal = _plane.normal;
  21392. v.x = - normal.x;
  21393. v.y = - normal.y;
  21394. v.z = - normal.z;
  21395. v.w = _plane.constant;
  21396. }
  21397. }
  21398. updateGlobal( renderer, camera ) {
  21399. const rendererClippingPlanes = renderer.clippingPlanes;
  21400. this.viewMatrix = camera.matrixWorldInverse;
  21401. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  21402. let update = false;
  21403. if ( Array.isArray( rendererClippingPlanes ) && rendererClippingPlanes.length !== 0 ) {
  21404. const l = rendererClippingPlanes.length;
  21405. if ( l !== this.globalClippingCount ) {
  21406. const planes = [];
  21407. for ( let i = 0; i < l; i ++ ) {
  21408. planes.push( new Vector4() );
  21409. }
  21410. this.globalClippingCount = l;
  21411. this.planes = planes;
  21412. update = true;
  21413. }
  21414. this.projectPlanes( rendererClippingPlanes, 0 );
  21415. } else if ( this.globalClippingCount !== 0 ) {
  21416. this.globalClippingCount = 0;
  21417. this.planes = [];
  21418. update = true;
  21419. }
  21420. if ( renderer.localClippingEnabled !== this.localClippingEnabled ) {
  21421. this.localClippingEnabled = renderer.localClippingEnabled;
  21422. update = true;
  21423. }
  21424. if ( update ) this.version = _clippingContextVersion ++;
  21425. }
  21426. update( parent, material ) {
  21427. let update = false;
  21428. if ( this !== parent && parent.version !== this.parentVersion ) {
  21429. this.globalClippingCount = material.isShadowNodeMaterial ? 0 : parent.globalClippingCount;
  21430. this.localClippingEnabled = parent.localClippingEnabled;
  21431. this.planes = Array.from( parent.planes );
  21432. this.parentVersion = parent.version;
  21433. this.viewMatrix = parent.viewMatrix;
  21434. this.viewNormalMatrix = parent.viewNormalMatrix;
  21435. update = true;
  21436. }
  21437. if ( this.localClippingEnabled ) {
  21438. const localClippingPlanes = material.clippingPlanes;
  21439. if ( ( Array.isArray( localClippingPlanes ) && localClippingPlanes.length !== 0 ) ) {
  21440. const l = localClippingPlanes.length;
  21441. const planes = this.planes;
  21442. const offset = this.globalClippingCount;
  21443. if ( update || l !== this.localClippingCount ) {
  21444. planes.length = offset + l;
  21445. for ( let i = 0; i < l; i ++ ) {
  21446. planes[ offset + i ] = new Vector4();
  21447. }
  21448. this.localClippingCount = l;
  21449. update = true;
  21450. }
  21451. this.projectPlanes( localClippingPlanes, offset );
  21452. } else if ( this.localClippingCount !== 0 ) {
  21453. this.localClippingCount = 0;
  21454. update = true;
  21455. }
  21456. if ( this.localClipIntersection !== material.clipIntersection ) {
  21457. this.localClipIntersection = material.clipIntersection;
  21458. update = true;
  21459. }
  21460. }
  21461. if ( update ) this.version = _clippingContextVersion ++;
  21462. }
  21463. }
  21464. let id$4 = 0;
  21465. function getKeys( obj ) {
  21466. const keys = Object.keys( obj );
  21467. let proto = Object.getPrototypeOf( obj );
  21468. while ( proto ) {
  21469. const descriptors = Object.getOwnPropertyDescriptors( proto );
  21470. for ( const key in descriptors ) {
  21471. if ( descriptors[ key ] !== undefined ) {
  21472. const descriptor = descriptors[ key ];
  21473. if ( descriptor && typeof descriptor.get === 'function' ) {
  21474. keys.push( key );
  21475. }
  21476. }
  21477. }
  21478. proto = Object.getPrototypeOf( proto );
  21479. }
  21480. return keys;
  21481. }
  21482. class RenderObject {
  21483. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext ) {
  21484. this._nodes = nodes;
  21485. this._geometries = geometries;
  21486. this.id = id$4 ++;
  21487. this.renderer = renderer;
  21488. this.object = object;
  21489. this.material = material;
  21490. this.scene = scene;
  21491. this.camera = camera;
  21492. this.lightsNode = lightsNode;
  21493. this.context = renderContext;
  21494. this.geometry = object.geometry;
  21495. this.version = material.version;
  21496. this.drawRange = null;
  21497. this.attributes = null;
  21498. this.pipeline = null;
  21499. this.vertexBuffers = null;
  21500. this.updateClipping( renderContext.clippingContext );
  21501. this.clippingContextVersion = this.clippingContext.version;
  21502. this.initialNodesCacheKey = this.getNodesCacheKey();
  21503. this.initialCacheKey = this.getCacheKey();
  21504. this._nodeBuilderState = null;
  21505. this._bindings = null;
  21506. this.onDispose = null;
  21507. this.isRenderObject = true;
  21508. this.onMaterialDispose = () => {
  21509. this.dispose();
  21510. };
  21511. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  21512. }
  21513. updateClipping( parent ) {
  21514. const material = this.material;
  21515. let clippingContext = this.clippingContext;
  21516. if ( Array.isArray( material.clippingPlanes ) ) {
  21517. if ( clippingContext === parent || ! clippingContext ) {
  21518. clippingContext = new ClippingContext();
  21519. this.clippingContext = clippingContext;
  21520. }
  21521. clippingContext.update( parent, material );
  21522. } else if ( this.clippingContext !== parent ) {
  21523. this.clippingContext = parent;
  21524. }
  21525. }
  21526. get clippingNeedsUpdate() {
  21527. if ( this.clippingContext.version === this.clippingContextVersion ) return false;
  21528. this.clippingContextVersion = this.clippingContext.version;
  21529. return true;
  21530. }
  21531. getNodeBuilderState() {
  21532. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  21533. }
  21534. getBindings() {
  21535. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  21536. }
  21537. getIndex() {
  21538. return this._geometries.getIndex( this );
  21539. }
  21540. getChainArray() {
  21541. return [ this.object, this.material, this.context, this.lightsNode ];
  21542. }
  21543. getAttributes() {
  21544. if ( this.attributes !== null ) return this.attributes;
  21545. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  21546. const geometry = this.geometry;
  21547. const attributes = [];
  21548. const vertexBuffers = new Set();
  21549. for ( const nodeAttribute of nodeAttributes ) {
  21550. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  21551. if ( attribute === undefined ) continue;
  21552. attributes.push( attribute );
  21553. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  21554. vertexBuffers.add( bufferAttribute );
  21555. }
  21556. this.attributes = attributes;
  21557. this.vertexBuffers = Array.from( vertexBuffers.values() );
  21558. return attributes;
  21559. }
  21560. getVertexBuffers() {
  21561. if ( this.vertexBuffers === null ) this.getAttributes();
  21562. return this.vertexBuffers;
  21563. }
  21564. getMaterialCacheKey() {
  21565. const { object, material } = this;
  21566. let cacheKey = material.customProgramCacheKey();
  21567. for ( const property of getKeys( material ) ) {
  21568. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  21569. let value = material[ property ];
  21570. if ( value !== null ) {
  21571. const type = typeof value;
  21572. if ( type === 'number' ) value = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  21573. else if ( type === 'object' ) value = '{}';
  21574. }
  21575. cacheKey += /*property + ':' +*/ value + ',';
  21576. }
  21577. cacheKey += this.clippingContextVersion + ',';
  21578. if ( object.skeleton ) {
  21579. cacheKey += object.skeleton.bones.length + ',';
  21580. }
  21581. if ( object.morphTargetInfluences ) {
  21582. cacheKey += object.morphTargetInfluences.length + ',';
  21583. }
  21584. if ( object.isBatchedMesh ) {
  21585. cacheKey += object._matricesTexture.uuid + ',';
  21586. if ( object._colorsTexture !== null ) {
  21587. cacheKey += object._colorsTexture.uuid + ',';
  21588. }
  21589. }
  21590. if ( object.count > 1 ) {
  21591. cacheKey += object.count + ',';
  21592. }
  21593. return cacheKey;
  21594. }
  21595. get needsUpdate() {
  21596. return this.initialNodesCacheKey !== this.getNodesCacheKey() || this.clippingNeedsUpdate;
  21597. }
  21598. getNodesCacheKey() {
  21599. // Environment Nodes Cache Key
  21600. return this._nodes.getCacheKey( this.scene, this.lightsNode );
  21601. }
  21602. getCacheKey() {
  21603. return this.getMaterialCacheKey() + ',' + this.getNodesCacheKey();
  21604. }
  21605. dispose() {
  21606. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  21607. this.onDispose();
  21608. }
  21609. }
  21610. class RenderObjects {
  21611. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  21612. this.renderer = renderer;
  21613. this.nodes = nodes;
  21614. this.geometries = geometries;
  21615. this.pipelines = pipelines;
  21616. this.bindings = bindings;
  21617. this.info = info;
  21618. this.chainMaps = {};
  21619. }
  21620. get( object, material, scene, camera, lightsNode, renderContext, passId ) {
  21621. const chainMap = this.getChainMap( passId );
  21622. const chainArray = [ object, material, renderContext, lightsNode ];
  21623. let renderObject = chainMap.get( chainArray );
  21624. if ( renderObject === undefined ) {
  21625. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, passId );
  21626. chainMap.set( chainArray, renderObject );
  21627. } else {
  21628. renderObject.updateClipping( renderContext.clippingContext );
  21629. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  21630. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  21631. renderObject.dispose();
  21632. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, passId );
  21633. } else {
  21634. renderObject.version = material.version;
  21635. }
  21636. }
  21637. }
  21638. return renderObject;
  21639. }
  21640. getChainMap( passId = 'default' ) {
  21641. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  21642. }
  21643. dispose() {
  21644. this.chainMaps = {};
  21645. }
  21646. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, passId ) {
  21647. const chainMap = this.getChainMap( passId );
  21648. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext );
  21649. renderObject.onDispose = () => {
  21650. this.pipelines.delete( renderObject );
  21651. this.bindings.delete( renderObject );
  21652. this.nodes.delete( renderObject );
  21653. chainMap.delete( renderObject.getChainArray() );
  21654. };
  21655. return renderObject;
  21656. }
  21657. }
  21658. class DataMap {
  21659. constructor() {
  21660. this.data = new WeakMap();
  21661. }
  21662. get( object ) {
  21663. let map = this.data.get( object );
  21664. if ( map === undefined ) {
  21665. map = {};
  21666. this.data.set( object, map );
  21667. }
  21668. return map;
  21669. }
  21670. delete( object ) {
  21671. let map;
  21672. if ( this.data.has( object ) ) {
  21673. map = this.data.get( object );
  21674. this.data.delete( object );
  21675. }
  21676. return map;
  21677. }
  21678. has( object ) {
  21679. return this.data.has( object );
  21680. }
  21681. dispose() {
  21682. this.data = new WeakMap();
  21683. }
  21684. }
  21685. const AttributeType = {
  21686. VERTEX: 1,
  21687. INDEX: 2,
  21688. STORAGE: 4
  21689. };
  21690. // size of a chunk in bytes (STD140 layout)
  21691. const GPU_CHUNK_BYTES = 16;
  21692. // @TODO: Move to src/constants.js
  21693. const BlendColorFactor = 211;
  21694. const OneMinusBlendColorFactor = 212;
  21695. class Attributes extends DataMap {
  21696. constructor( backend ) {
  21697. super();
  21698. this.backend = backend;
  21699. }
  21700. delete( attribute ) {
  21701. const attributeData = super.delete( attribute );
  21702. if ( attributeData !== undefined ) {
  21703. this.backend.destroyAttribute( attribute );
  21704. }
  21705. return attributeData;
  21706. }
  21707. update( attribute, type ) {
  21708. const data = this.get( attribute );
  21709. if ( data.version === undefined ) {
  21710. if ( type === AttributeType.VERTEX ) {
  21711. this.backend.createAttribute( attribute );
  21712. } else if ( type === AttributeType.INDEX ) {
  21713. this.backend.createIndexAttribute( attribute );
  21714. } else if ( type === AttributeType.STORAGE ) {
  21715. this.backend.createStorageAttribute( attribute );
  21716. }
  21717. data.version = this._getBufferAttribute( attribute ).version;
  21718. } else {
  21719. const bufferAttribute = this._getBufferAttribute( attribute );
  21720. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  21721. this.backend.updateAttribute( attribute );
  21722. data.version = bufferAttribute.version;
  21723. }
  21724. }
  21725. }
  21726. _getBufferAttribute( attribute ) {
  21727. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  21728. return attribute;
  21729. }
  21730. }
  21731. function arrayNeedsUint32( array ) {
  21732. // assumes larger values usually on last
  21733. for ( let i = array.length - 1; i >= 0; -- i ) {
  21734. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  21735. }
  21736. return false;
  21737. }
  21738. function getWireframeVersion( geometry ) {
  21739. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  21740. }
  21741. function getWireframeIndex( geometry ) {
  21742. const indices = [];
  21743. const geometryIndex = geometry.index;
  21744. const geometryPosition = geometry.attributes.position;
  21745. if ( geometryIndex !== null ) {
  21746. const array = geometryIndex.array;
  21747. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  21748. const a = array[ i + 0 ];
  21749. const b = array[ i + 1 ];
  21750. const c = array[ i + 2 ];
  21751. indices.push( a, b, b, c, c, a );
  21752. }
  21753. } else {
  21754. const array = geometryPosition.array;
  21755. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  21756. const a = i + 0;
  21757. const b = i + 1;
  21758. const c = i + 2;
  21759. indices.push( a, b, b, c, c, a );
  21760. }
  21761. }
  21762. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  21763. attribute.version = getWireframeVersion( geometry );
  21764. return attribute;
  21765. }
  21766. class Geometries extends DataMap {
  21767. constructor( attributes, info ) {
  21768. super();
  21769. this.attributes = attributes;
  21770. this.info = info;
  21771. this.wireframes = new WeakMap();
  21772. this.attributeCall = new WeakMap();
  21773. }
  21774. has( renderObject ) {
  21775. const geometry = renderObject.geometry;
  21776. return super.has( geometry ) && this.get( geometry ).initialized === true;
  21777. }
  21778. updateForRender( renderObject ) {
  21779. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  21780. this.updateAttributes( renderObject );
  21781. }
  21782. initGeometry( renderObject ) {
  21783. const geometry = renderObject.geometry;
  21784. const geometryData = this.get( geometry );
  21785. geometryData.initialized = true;
  21786. this.info.memory.geometries ++;
  21787. const onDispose = () => {
  21788. this.info.memory.geometries --;
  21789. const index = geometry.index;
  21790. const geometryAttributes = renderObject.getAttributes();
  21791. if ( index !== null ) {
  21792. this.attributes.delete( index );
  21793. }
  21794. for ( const geometryAttribute of geometryAttributes ) {
  21795. this.attributes.delete( geometryAttribute );
  21796. }
  21797. const wireframeAttribute = this.wireframes.get( geometry );
  21798. if ( wireframeAttribute !== undefined ) {
  21799. this.attributes.delete( wireframeAttribute );
  21800. }
  21801. geometry.removeEventListener( 'dispose', onDispose );
  21802. };
  21803. geometry.addEventListener( 'dispose', onDispose );
  21804. }
  21805. updateAttributes( renderObject ) {
  21806. const attributes = renderObject.getAttributes();
  21807. for ( const attribute of attributes ) {
  21808. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  21809. this.updateAttribute( attribute, AttributeType.STORAGE );
  21810. } else {
  21811. this.updateAttribute( attribute, AttributeType.VERTEX );
  21812. }
  21813. }
  21814. const index = this.getIndex( renderObject );
  21815. if ( index !== null ) {
  21816. this.updateAttribute( index, AttributeType.INDEX );
  21817. }
  21818. }
  21819. updateAttribute( attribute, type ) {
  21820. const callId = this.info.render.calls;
  21821. if ( ! attribute.isInterleavedBufferAttribute ) {
  21822. if ( this.attributeCall.get( attribute ) !== callId ) {
  21823. this.attributes.update( attribute, type );
  21824. this.attributeCall.set( attribute, callId );
  21825. }
  21826. } else {
  21827. if ( this.attributeCall.get( attribute ) === undefined ) {
  21828. this.attributes.update( attribute, type );
  21829. this.attributeCall.set( attribute, callId );
  21830. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  21831. this.attributes.update( attribute, type );
  21832. this.attributeCall.set( attribute.data, callId );
  21833. this.attributeCall.set( attribute, callId );
  21834. }
  21835. }
  21836. }
  21837. getIndex( renderObject ) {
  21838. const { geometry, material } = renderObject;
  21839. let index = geometry.index;
  21840. if ( material.wireframe === true ) {
  21841. const wireframes = this.wireframes;
  21842. let wireframeAttribute = wireframes.get( geometry );
  21843. if ( wireframeAttribute === undefined ) {
  21844. wireframeAttribute = getWireframeIndex( geometry );
  21845. wireframes.set( geometry, wireframeAttribute );
  21846. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  21847. this.attributes.delete( wireframeAttribute );
  21848. wireframeAttribute = getWireframeIndex( geometry );
  21849. wireframes.set( geometry, wireframeAttribute );
  21850. }
  21851. index = wireframeAttribute;
  21852. }
  21853. return index;
  21854. }
  21855. }
  21856. class Info {
  21857. constructor() {
  21858. this.autoReset = true;
  21859. this.frame = 0;
  21860. this.calls = 0;
  21861. this.render = {
  21862. calls: 0,
  21863. frameCalls: 0,
  21864. drawCalls: 0,
  21865. triangles: 0,
  21866. points: 0,
  21867. lines: 0,
  21868. timestamp: 0,
  21869. previousFrameCalls: 0,
  21870. timestampCalls: 0
  21871. };
  21872. this.compute = {
  21873. calls: 0,
  21874. frameCalls: 0,
  21875. timestamp: 0,
  21876. previousFrameCalls: 0,
  21877. timestampCalls: 0
  21878. };
  21879. this.memory = {
  21880. geometries: 0,
  21881. textures: 0
  21882. };
  21883. }
  21884. update( object, count, instanceCount ) {
  21885. this.render.drawCalls ++;
  21886. if ( object.isMesh || object.isSprite ) {
  21887. this.render.triangles += instanceCount * ( count / 3 );
  21888. } else if ( object.isPoints ) {
  21889. this.render.points += instanceCount * count;
  21890. } else if ( object.isLineSegments ) {
  21891. this.render.lines += instanceCount * ( count / 2 );
  21892. } else if ( object.isLine ) {
  21893. this.render.lines += instanceCount * ( count - 1 );
  21894. } else {
  21895. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  21896. }
  21897. }
  21898. updateTimestamp( type, time ) {
  21899. if ( this[ type ].timestampCalls === 0 ) {
  21900. this[ type ].timestamp = 0;
  21901. }
  21902. this[ type ].timestamp += time;
  21903. this[ type ].timestampCalls ++;
  21904. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  21905. this[ type ].timestampCalls = 0;
  21906. }
  21907. }
  21908. reset() {
  21909. const previousRenderFrameCalls = this.render.frameCalls;
  21910. this.render.previousFrameCalls = previousRenderFrameCalls;
  21911. const previousComputeFrameCalls = this.compute.frameCalls;
  21912. this.compute.previousFrameCalls = previousComputeFrameCalls;
  21913. this.render.drawCalls = 0;
  21914. this.render.frameCalls = 0;
  21915. this.compute.frameCalls = 0;
  21916. this.render.triangles = 0;
  21917. this.render.points = 0;
  21918. this.render.lines = 0;
  21919. }
  21920. dispose() {
  21921. this.reset();
  21922. this.calls = 0;
  21923. this.render.calls = 0;
  21924. this.compute.calls = 0;
  21925. this.render.timestamp = 0;
  21926. this.compute.timestamp = 0;
  21927. this.memory.geometries = 0;
  21928. this.memory.textures = 0;
  21929. }
  21930. }
  21931. class Pipeline {
  21932. constructor( cacheKey ) {
  21933. this.cacheKey = cacheKey;
  21934. this.usedTimes = 0;
  21935. }
  21936. }
  21937. class RenderPipeline extends Pipeline {
  21938. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  21939. super( cacheKey );
  21940. this.vertexProgram = vertexProgram;
  21941. this.fragmentProgram = fragmentProgram;
  21942. }
  21943. }
  21944. class ComputePipeline extends Pipeline {
  21945. constructor( cacheKey, computeProgram ) {
  21946. super( cacheKey );
  21947. this.computeProgram = computeProgram;
  21948. this.isComputePipeline = true;
  21949. }
  21950. }
  21951. let _id$4 = 0;
  21952. class ProgrammableStage {
  21953. constructor( code, type, transforms = null, attributes = null ) {
  21954. this.id = _id$4 ++;
  21955. this.code = code;
  21956. this.stage = type;
  21957. this.transforms = transforms;
  21958. this.attributes = attributes;
  21959. this.usedTimes = 0;
  21960. }
  21961. }
  21962. class Pipelines extends DataMap {
  21963. constructor( backend, nodes ) {
  21964. super();
  21965. this.backend = backend;
  21966. this.nodes = nodes;
  21967. this.bindings = null; // set by the bindings
  21968. this.caches = new Map();
  21969. this.programs = {
  21970. vertex: new Map(),
  21971. fragment: new Map(),
  21972. compute: new Map()
  21973. };
  21974. }
  21975. getForCompute( computeNode, bindings ) {
  21976. const { backend } = this;
  21977. const data = this.get( computeNode );
  21978. if ( this._needsComputeUpdate( computeNode ) ) {
  21979. const previousPipeline = data.pipeline;
  21980. if ( previousPipeline ) {
  21981. previousPipeline.usedTimes --;
  21982. previousPipeline.computeProgram.usedTimes --;
  21983. }
  21984. // get shader
  21985. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  21986. // programmable stage
  21987. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  21988. if ( stageCompute === undefined ) {
  21989. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  21990. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  21991. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  21992. backend.createProgram( stageCompute );
  21993. }
  21994. // determine compute pipeline
  21995. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  21996. let pipeline = this.caches.get( cacheKey );
  21997. if ( pipeline === undefined ) {
  21998. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21999. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  22000. }
  22001. // keep track of all used times
  22002. pipeline.usedTimes ++;
  22003. stageCompute.usedTimes ++;
  22004. //
  22005. data.version = computeNode.version;
  22006. data.pipeline = pipeline;
  22007. }
  22008. return data.pipeline;
  22009. }
  22010. getForRender( renderObject, promises = null ) {
  22011. const { backend } = this;
  22012. const data = this.get( renderObject );
  22013. if ( this._needsRenderUpdate( renderObject ) ) {
  22014. const previousPipeline = data.pipeline;
  22015. if ( previousPipeline ) {
  22016. previousPipeline.usedTimes --;
  22017. previousPipeline.vertexProgram.usedTimes --;
  22018. previousPipeline.fragmentProgram.usedTimes --;
  22019. }
  22020. // get shader
  22021. const nodeBuilderState = renderObject.getNodeBuilderState();
  22022. // programmable stages
  22023. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  22024. if ( stageVertex === undefined ) {
  22025. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  22026. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  22027. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  22028. backend.createProgram( stageVertex );
  22029. }
  22030. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  22031. if ( stageFragment === undefined ) {
  22032. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  22033. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  22034. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  22035. backend.createProgram( stageFragment );
  22036. }
  22037. // determine render pipeline
  22038. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22039. let pipeline = this.caches.get( cacheKey );
  22040. if ( pipeline === undefined ) {
  22041. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  22042. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  22043. } else {
  22044. renderObject.pipeline = pipeline;
  22045. }
  22046. // keep track of all used times
  22047. pipeline.usedTimes ++;
  22048. stageVertex.usedTimes ++;
  22049. stageFragment.usedTimes ++;
  22050. //
  22051. data.pipeline = pipeline;
  22052. }
  22053. return data.pipeline;
  22054. }
  22055. delete( object ) {
  22056. const pipeline = this.get( object ).pipeline;
  22057. if ( pipeline ) {
  22058. // pipeline
  22059. pipeline.usedTimes --;
  22060. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  22061. // programs
  22062. if ( pipeline.isComputePipeline ) {
  22063. pipeline.computeProgram.usedTimes --;
  22064. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  22065. } else {
  22066. pipeline.fragmentProgram.usedTimes --;
  22067. pipeline.vertexProgram.usedTimes --;
  22068. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  22069. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  22070. }
  22071. }
  22072. return super.delete( object );
  22073. }
  22074. dispose() {
  22075. super.dispose();
  22076. this.caches = new Map();
  22077. this.programs = {
  22078. vertex: new Map(),
  22079. fragment: new Map(),
  22080. compute: new Map()
  22081. };
  22082. }
  22083. updateForRender( renderObject ) {
  22084. this.getForRender( renderObject );
  22085. }
  22086. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  22087. // check for existing pipeline
  22088. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  22089. let pipeline = this.caches.get( cacheKey );
  22090. if ( pipeline === undefined ) {
  22091. pipeline = new ComputePipeline( cacheKey, stageCompute );
  22092. this.caches.set( cacheKey, pipeline );
  22093. this.backend.createComputePipeline( pipeline, bindings );
  22094. }
  22095. return pipeline;
  22096. }
  22097. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  22098. // check for existing pipeline
  22099. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22100. let pipeline = this.caches.get( cacheKey );
  22101. if ( pipeline === undefined ) {
  22102. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  22103. this.caches.set( cacheKey, pipeline );
  22104. renderObject.pipeline = pipeline;
  22105. this.backend.createRenderPipeline( renderObject, promises );
  22106. }
  22107. return pipeline;
  22108. }
  22109. _getComputeCacheKey( computeNode, stageCompute ) {
  22110. return computeNode.id + ',' + stageCompute.id;
  22111. }
  22112. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  22113. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  22114. }
  22115. _releasePipeline( pipeline ) {
  22116. this.caches.delete( pipeline.cacheKey );
  22117. }
  22118. _releaseProgram( program ) {
  22119. const code = program.code;
  22120. const stage = program.stage;
  22121. this.programs[ stage ].delete( code );
  22122. }
  22123. _needsComputeUpdate( computeNode ) {
  22124. const data = this.get( computeNode );
  22125. return data.pipeline === undefined || data.version !== computeNode.version;
  22126. }
  22127. _needsRenderUpdate( renderObject ) {
  22128. const data = this.get( renderObject );
  22129. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  22130. }
  22131. }
  22132. class Bindings extends DataMap {
  22133. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  22134. super();
  22135. this.backend = backend;
  22136. this.textures = textures;
  22137. this.pipelines = pipelines;
  22138. this.attributes = attributes;
  22139. this.nodes = nodes;
  22140. this.info = info;
  22141. this.pipelines.bindings = this; // assign bindings to pipelines
  22142. }
  22143. getForRender( renderObject ) {
  22144. const bindings = renderObject.getBindings();
  22145. for ( const bindGroup of bindings ) {
  22146. const groupData = this.get( bindGroup );
  22147. if ( groupData.bindGroup === undefined ) {
  22148. // each object defines an array of bindings (ubos, textures, samplers etc.)
  22149. this._init( bindGroup );
  22150. this.backend.createBindings( bindGroup, bindings );
  22151. groupData.bindGroup = bindGroup;
  22152. }
  22153. }
  22154. return bindings;
  22155. }
  22156. getForCompute( computeNode ) {
  22157. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  22158. for ( const bindGroup of bindings ) {
  22159. const groupData = this.get( bindGroup );
  22160. if ( groupData.bindGroup === undefined ) {
  22161. this._init( bindGroup );
  22162. this.backend.createBindings( bindGroup, bindings );
  22163. groupData.bindGroup = bindGroup;
  22164. }
  22165. }
  22166. return bindings;
  22167. }
  22168. updateForCompute( computeNode ) {
  22169. this._updateBindings( computeNode, this.getForCompute( computeNode ) );
  22170. }
  22171. updateForRender( renderObject ) {
  22172. this._updateBindings( renderObject, this.getForRender( renderObject ) );
  22173. }
  22174. _updateBindings( object, bindings ) {
  22175. for ( const bindGroup of bindings ) {
  22176. this._update( object, bindGroup, bindings );
  22177. }
  22178. }
  22179. _init( bindGroup ) {
  22180. for ( const binding of bindGroup.bindings ) {
  22181. if ( binding.isSampledTexture ) {
  22182. this.textures.updateTexture( binding.texture );
  22183. } else if ( binding.isStorageBuffer ) {
  22184. const attribute = binding.attribute;
  22185. this.attributes.update( attribute, AttributeType.STORAGE );
  22186. }
  22187. }
  22188. }
  22189. _update( object, bindGroup, bindings ) {
  22190. const { backend } = this;
  22191. let needsBindingsUpdate = false;
  22192. // iterate over all bindings and check if buffer updates or a new binding group is required
  22193. for ( const binding of bindGroup.bindings ) {
  22194. if ( binding.isNodeUniformsGroup ) {
  22195. const updated = this.nodes.updateGroup( binding );
  22196. if ( ! updated ) continue;
  22197. }
  22198. if ( binding.isUniformBuffer ) {
  22199. const updated = binding.update();
  22200. if ( updated ) {
  22201. backend.updateBinding( binding );
  22202. }
  22203. } else if ( binding.isSampler ) {
  22204. binding.update();
  22205. } else if ( binding.isSampledTexture ) {
  22206. const texture = binding.texture;
  22207. if ( binding.needsBindingsUpdate ) needsBindingsUpdate = true;
  22208. const updated = binding.update();
  22209. if ( updated ) {
  22210. this.textures.updateTexture( binding.texture );
  22211. }
  22212. const textureData = backend.get( binding.texture );
  22213. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  22214. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  22215. console.error( 'Bindings._update: binding should be available:', binding, updated, binding.texture, binding.textureNode.value );
  22216. this.textures.updateTexture( binding.texture );
  22217. needsBindingsUpdate = true;
  22218. }
  22219. if ( texture.isStorageTexture === true ) {
  22220. const textureData = this.get( texture );
  22221. if ( binding.store === true ) {
  22222. textureData.needsMipmap = true;
  22223. } else if ( texture.generateMipmaps === true && this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  22224. this.backend.generateMipmaps( texture );
  22225. textureData.needsMipmap = false;
  22226. }
  22227. }
  22228. }
  22229. }
  22230. if ( needsBindingsUpdate === true ) {
  22231. const pipeline = this.pipelines.getForRender( object );
  22232. this.backend.updateBindings( bindGroup, bindings, pipeline );
  22233. }
  22234. }
  22235. }
  22236. const NodeShaderStage = {
  22237. VERTEX: 'vertex',
  22238. FRAGMENT: 'fragment'
  22239. };
  22240. const NodeUpdateType = {
  22241. NONE: 'none',
  22242. FRAME: 'frame',
  22243. RENDER: 'render',
  22244. OBJECT: 'object'
  22245. };
  22246. const NodeType = {
  22247. BOOLEAN: 'bool',
  22248. INTEGER: 'int',
  22249. FLOAT: 'float',
  22250. VECTOR2: 'vec2',
  22251. VECTOR3: 'vec3',
  22252. VECTOR4: 'vec4',
  22253. MATRIX2: 'mat2',
  22254. MATRIX3: 'mat3',
  22255. MATRIX4: 'mat4'
  22256. };
  22257. const defaultShaderStages = [ 'fragment', 'vertex' ];
  22258. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  22259. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  22260. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  22261. function getCacheKey( object, force = false ) {
  22262. let cacheKey = '{';
  22263. if ( object.isNode === true ) {
  22264. cacheKey += object.id;
  22265. }
  22266. for ( const { property, childNode } of getNodeChildren( object ) ) {
  22267. cacheKey += ',' + property.slice( 0, - 4 ) + ':' + childNode.getCacheKey( force );
  22268. }
  22269. cacheKey += '}';
  22270. return cacheKey;
  22271. }
  22272. function* getNodeChildren( node, toJSON = false ) {
  22273. for ( const property in node ) {
  22274. // Ignore private properties.
  22275. if ( property.startsWith( '_' ) === true ) continue;
  22276. const object = node[ property ];
  22277. if ( Array.isArray( object ) === true ) {
  22278. for ( let i = 0; i < object.length; i ++ ) {
  22279. const child = object[ i ];
  22280. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  22281. yield { property, index: i, childNode: child };
  22282. }
  22283. }
  22284. } else if ( object && object.isNode === true ) {
  22285. yield { property, childNode: object };
  22286. } else if ( typeof object === 'object' ) {
  22287. for ( const subProperty in object ) {
  22288. const child = object[ subProperty ];
  22289. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  22290. yield { property, index: subProperty, childNode: child };
  22291. }
  22292. }
  22293. }
  22294. }
  22295. }
  22296. function getValueType( value ) {
  22297. if ( value === undefined || value === null ) return null;
  22298. const typeOf = typeof value;
  22299. if ( value.isNode === true ) {
  22300. return 'node';
  22301. } else if ( typeOf === 'number' ) {
  22302. return 'float';
  22303. } else if ( typeOf === 'boolean' ) {
  22304. return 'bool';
  22305. } else if ( typeOf === 'string' ) {
  22306. return 'string';
  22307. } else if ( typeOf === 'function' ) {
  22308. return 'shader';
  22309. } else if ( value.isVector2 === true ) {
  22310. return 'vec2';
  22311. } else if ( value.isVector3 === true ) {
  22312. return 'vec3';
  22313. } else if ( value.isVector4 === true ) {
  22314. return 'vec4';
  22315. } else if ( value.isMatrix3 === true ) {
  22316. return 'mat3';
  22317. } else if ( value.isMatrix4 === true ) {
  22318. return 'mat4';
  22319. } else if ( value.isColor === true ) {
  22320. return 'color';
  22321. } else if ( value instanceof ArrayBuffer ) {
  22322. return 'ArrayBuffer';
  22323. }
  22324. return null;
  22325. }
  22326. function getValueFromType( type, ...params ) {
  22327. const last4 = type ? type.slice( - 4 ) : undefined;
  22328. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  22329. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  22330. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  22331. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  22332. }
  22333. if ( type === 'color' ) {
  22334. return new Color( ...params );
  22335. } else if ( last4 === 'vec2' ) {
  22336. return new Vector2( ...params );
  22337. } else if ( last4 === 'vec3' ) {
  22338. return new Vector3( ...params );
  22339. } else if ( last4 === 'vec4' ) {
  22340. return new Vector4( ...params );
  22341. } else if ( last4 === 'mat3' ) {
  22342. return new Matrix3( ...params );
  22343. } else if ( last4 === 'mat4' ) {
  22344. return new Matrix4( ...params );
  22345. } else if ( type === 'bool' ) {
  22346. return params[ 0 ] || false;
  22347. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  22348. return params[ 0 ] || 0;
  22349. } else if ( type === 'string' ) {
  22350. return params[ 0 ] || '';
  22351. } else if ( type === 'ArrayBuffer' ) {
  22352. return base64ToArrayBuffer( params[ 0 ] );
  22353. }
  22354. return null;
  22355. }
  22356. function arrayBufferToBase64( arrayBuffer ) {
  22357. let chars = '';
  22358. const array = new Uint8Array( arrayBuffer );
  22359. for ( let i = 0; i < array.length; i ++ ) {
  22360. chars += String.fromCharCode( array[ i ] );
  22361. }
  22362. return btoa( chars );
  22363. }
  22364. function base64ToArrayBuffer( base64 ) {
  22365. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  22366. }
  22367. var NodeUtils = /*#__PURE__*/Object.freeze({
  22368. __proto__: null,
  22369. arrayBufferToBase64: arrayBufferToBase64,
  22370. base64ToArrayBuffer: base64ToArrayBuffer,
  22371. getCacheKey: getCacheKey,
  22372. getNodeChildren: getNodeChildren,
  22373. getValueFromType: getValueFromType,
  22374. getValueType: getValueType
  22375. });
  22376. const NodeClasses = new Map();
  22377. let _nodeId = 0;
  22378. class Node extends EventDispatcher {
  22379. constructor( nodeType = null ) {
  22380. super();
  22381. this.nodeType = nodeType;
  22382. this.updateType = NodeUpdateType.NONE;
  22383. this.updateBeforeType = NodeUpdateType.NONE;
  22384. this.updateAfterType = NodeUpdateType.NONE;
  22385. this.uuid = MathUtils.generateUUID();
  22386. this.version = 0;
  22387. this._cacheKey = null;
  22388. this._cacheKeyVersion = 0;
  22389. this.global = false;
  22390. this.isNode = true;
  22391. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  22392. }
  22393. set needsUpdate( value ) {
  22394. if ( value === true ) {
  22395. this.version ++;
  22396. }
  22397. }
  22398. get type() {
  22399. return this.constructor.type;
  22400. }
  22401. onUpdate( callback, updateType ) {
  22402. this.updateType = updateType;
  22403. this.update = callback.bind( this.getSelf() );
  22404. return this;
  22405. }
  22406. onFrameUpdate( callback ) {
  22407. return this.onUpdate( callback, NodeUpdateType.FRAME );
  22408. }
  22409. onRenderUpdate( callback ) {
  22410. return this.onUpdate( callback, NodeUpdateType.RENDER );
  22411. }
  22412. onObjectUpdate( callback ) {
  22413. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  22414. }
  22415. onReference( callback ) {
  22416. this.updateReference = callback.bind( this.getSelf() );
  22417. return this;
  22418. }
  22419. getSelf() {
  22420. // Returns non-node object.
  22421. return this.self || this;
  22422. }
  22423. updateReference( /*state*/ ) {
  22424. return this;
  22425. }
  22426. isGlobal( /*builder*/ ) {
  22427. return this.global;
  22428. }
  22429. * getChildren() {
  22430. for ( const { childNode } of getNodeChildren( this ) ) {
  22431. yield childNode;
  22432. }
  22433. }
  22434. dispose() {
  22435. this.dispatchEvent( { type: 'dispose' } );
  22436. }
  22437. traverse( callback ) {
  22438. callback( this );
  22439. for ( const childNode of this.getChildren() ) {
  22440. childNode.traverse( callback );
  22441. }
  22442. }
  22443. getCacheKey( force = false ) {
  22444. force = force || this.version !== this._cacheKeyVersion;
  22445. if ( force === true || this._cacheKey === null ) {
  22446. this._cacheKey = getCacheKey( this, force );
  22447. this._cacheKeyVersion = this.version;
  22448. }
  22449. return this._cacheKey;
  22450. }
  22451. getHash( /*builder*/ ) {
  22452. return this.uuid;
  22453. }
  22454. getUpdateType() {
  22455. return this.updateType;
  22456. }
  22457. getUpdateBeforeType() {
  22458. return this.updateBeforeType;
  22459. }
  22460. getUpdateAfterType() {
  22461. return this.updateAfterType;
  22462. }
  22463. getElementType( builder ) {
  22464. const type = this.getNodeType( builder );
  22465. const elementType = builder.getElementType( type );
  22466. return elementType;
  22467. }
  22468. getNodeType( builder ) {
  22469. const nodeProperties = builder.getNodeProperties( this );
  22470. if ( nodeProperties.outputNode ) {
  22471. return nodeProperties.outputNode.getNodeType( builder );
  22472. }
  22473. return this.nodeType;
  22474. }
  22475. getShared( builder ) {
  22476. const hash = this.getHash( builder );
  22477. const nodeFromHash = builder.getNodeFromHash( hash );
  22478. return nodeFromHash || this;
  22479. }
  22480. setup( builder ) {
  22481. const nodeProperties = builder.getNodeProperties( this );
  22482. let index = 0;
  22483. for ( const childNode of this.getChildren() ) {
  22484. nodeProperties[ 'node' + index ++ ] = childNode;
  22485. }
  22486. // return a outputNode if exists
  22487. return null;
  22488. }
  22489. construct( builder ) { // @deprecated, r157
  22490. console.warn( 'THREE.Node: construct() is deprecated. Use setup() instead.' );
  22491. return this.setup( builder );
  22492. }
  22493. increaseUsage( builder ) {
  22494. const nodeData = builder.getDataFromNode( this );
  22495. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  22496. return nodeData.usageCount;
  22497. }
  22498. analyze( builder ) {
  22499. const usageCount = this.increaseUsage( builder );
  22500. if ( usageCount === 1 ) {
  22501. // node flow children
  22502. const nodeProperties = builder.getNodeProperties( this );
  22503. for ( const childNode of Object.values( nodeProperties ) ) {
  22504. if ( childNode && childNode.isNode === true ) {
  22505. childNode.build( builder );
  22506. }
  22507. }
  22508. }
  22509. }
  22510. generate( builder, output ) {
  22511. const { outputNode } = builder.getNodeProperties( this );
  22512. if ( outputNode && outputNode.isNode === true ) {
  22513. return outputNode.build( builder, output );
  22514. }
  22515. }
  22516. updateBefore( /*frame*/ ) {
  22517. console.warn( 'Abstract function.' );
  22518. }
  22519. updateAfter( /*frame*/ ) {
  22520. console.warn( 'Abstract function.' );
  22521. }
  22522. update( /*frame*/ ) {
  22523. console.warn( 'Abstract function.' );
  22524. }
  22525. build( builder, output = null ) {
  22526. const refNode = this.getShared( builder );
  22527. if ( this !== refNode ) {
  22528. return refNode.build( builder, output );
  22529. }
  22530. builder.addNode( this );
  22531. builder.addChain( this );
  22532. /* Build stages expected results:
  22533. - "setup" -> Node
  22534. - "analyze" -> null
  22535. - "generate" -> String
  22536. */
  22537. let result = null;
  22538. const buildStage = builder.getBuildStage();
  22539. if ( buildStage === 'setup' ) {
  22540. this.updateReference( builder );
  22541. const properties = builder.getNodeProperties( this );
  22542. if ( properties.initialized !== true ) {
  22543. const stackNodesBeforeSetup = builder.stack.nodes.length;
  22544. properties.initialized = true;
  22545. properties.outputNode = this.setup( builder );
  22546. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  22547. properties.outputNode = builder.stack;
  22548. }
  22549. for ( const childNode of Object.values( properties ) ) {
  22550. if ( childNode && childNode.isNode === true ) {
  22551. childNode.build( builder );
  22552. }
  22553. }
  22554. }
  22555. } else if ( buildStage === 'analyze' ) {
  22556. this.analyze( builder );
  22557. } else if ( buildStage === 'generate' ) {
  22558. const isGenerateOnce = this.generate.length === 1;
  22559. if ( isGenerateOnce ) {
  22560. const type = this.getNodeType( builder );
  22561. const nodeData = builder.getDataFromNode( this );
  22562. result = nodeData.snippet;
  22563. if ( result === undefined ) {
  22564. result = this.generate( builder ) || '';
  22565. nodeData.snippet = result;
  22566. }
  22567. result = builder.format( result, type, output );
  22568. } else {
  22569. result = this.generate( builder, output ) || '';
  22570. }
  22571. }
  22572. builder.removeChain( this );
  22573. return result;
  22574. }
  22575. getSerializeChildren() {
  22576. return getNodeChildren( this );
  22577. }
  22578. serialize( json ) {
  22579. const nodeChildren = this.getSerializeChildren();
  22580. const inputNodes = {};
  22581. for ( const { property, index, childNode } of nodeChildren ) {
  22582. if ( index !== undefined ) {
  22583. if ( inputNodes[ property ] === undefined ) {
  22584. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  22585. }
  22586. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  22587. } else {
  22588. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  22589. }
  22590. }
  22591. if ( Object.keys( inputNodes ).length > 0 ) {
  22592. json.inputNodes = inputNodes;
  22593. }
  22594. }
  22595. deserialize( json ) {
  22596. if ( json.inputNodes !== undefined ) {
  22597. const nodes = json.meta.nodes;
  22598. for ( const property in json.inputNodes ) {
  22599. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  22600. const inputArray = [];
  22601. for ( const uuid of json.inputNodes[ property ] ) {
  22602. inputArray.push( nodes[ uuid ] );
  22603. }
  22604. this[ property ] = inputArray;
  22605. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  22606. const inputObject = {};
  22607. for ( const subProperty in json.inputNodes[ property ] ) {
  22608. const uuid = json.inputNodes[ property ][ subProperty ];
  22609. inputObject[ subProperty ] = nodes[ uuid ];
  22610. }
  22611. this[ property ] = inputObject;
  22612. } else {
  22613. const uuid = json.inputNodes[ property ];
  22614. this[ property ] = nodes[ uuid ];
  22615. }
  22616. }
  22617. }
  22618. }
  22619. toJSON( meta ) {
  22620. const { uuid, type } = this;
  22621. const isRoot = ( meta === undefined || typeof meta === 'string' );
  22622. if ( isRoot ) {
  22623. meta = {
  22624. textures: {},
  22625. images: {},
  22626. nodes: {}
  22627. };
  22628. }
  22629. // serialize
  22630. let data = meta.nodes[ uuid ];
  22631. if ( data === undefined ) {
  22632. data = {
  22633. uuid,
  22634. type,
  22635. meta,
  22636. metadata: {
  22637. version: 4.6,
  22638. type: 'Node',
  22639. generator: 'Node.toJSON'
  22640. }
  22641. };
  22642. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  22643. this.serialize( data );
  22644. delete data.meta;
  22645. }
  22646. // TODO: Copied from Object3D.toJSON
  22647. function extractFromCache( cache ) {
  22648. const values = [];
  22649. for ( const key in cache ) {
  22650. const data = cache[ key ];
  22651. delete data.metadata;
  22652. values.push( data );
  22653. }
  22654. return values;
  22655. }
  22656. if ( isRoot ) {
  22657. const textures = extractFromCache( meta.textures );
  22658. const images = extractFromCache( meta.images );
  22659. const nodes = extractFromCache( meta.nodes );
  22660. if ( textures.length > 0 ) data.textures = textures;
  22661. if ( images.length > 0 ) data.images = images;
  22662. if ( nodes.length > 0 ) data.nodes = nodes;
  22663. }
  22664. return data;
  22665. }
  22666. }
  22667. function addNodeClass( type, nodeClass ) {
  22668. if ( typeof nodeClass !== 'function' || ! type ) throw new Error( `Node class ${ type } is not a class` );
  22669. if ( NodeClasses.has( type ) ) {
  22670. console.warn( `Redefinition of node class ${ type }` );
  22671. return;
  22672. }
  22673. NodeClasses.set( type, nodeClass );
  22674. nodeClass.type = type;
  22675. }
  22676. function createNodeFromType( type ) {
  22677. const Class = NodeClasses.get( type );
  22678. if ( Class !== undefined ) {
  22679. return new Class();
  22680. }
  22681. }
  22682. class TempNode extends Node {
  22683. constructor( type ) {
  22684. super( type );
  22685. this.isTempNode = true;
  22686. }
  22687. hasDependencies( builder ) {
  22688. return builder.getDataFromNode( this ).usageCount > 1;
  22689. }
  22690. build( builder, output ) {
  22691. const buildStage = builder.getBuildStage();
  22692. if ( buildStage === 'generate' ) {
  22693. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  22694. const nodeData = builder.getDataFromNode( this );
  22695. if ( nodeData.propertyName !== undefined ) {
  22696. return builder.format( nodeData.propertyName, type, output );
  22697. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  22698. const snippet = super.build( builder, type );
  22699. const nodeVar = builder.getVarFromNode( this, null, type );
  22700. const propertyName = builder.getPropertyName( nodeVar );
  22701. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  22702. nodeData.snippet = snippet;
  22703. nodeData.propertyName = propertyName;
  22704. return builder.format( nodeData.propertyName, type, output );
  22705. }
  22706. }
  22707. return super.build( builder, output );
  22708. }
  22709. }
  22710. addNodeClass( 'TempNode', TempNode );
  22711. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  22712. constructor( node, indexNode ) {
  22713. super();
  22714. this.node = node;
  22715. this.indexNode = indexNode;
  22716. this.isArrayElementNode = true;
  22717. }
  22718. getNodeType( builder ) {
  22719. return this.node.getElementType( builder );
  22720. }
  22721. generate( builder ) {
  22722. const nodeSnippet = this.node.build( builder );
  22723. const indexSnippet = this.indexNode.build( builder, 'uint' );
  22724. return `${nodeSnippet}[ ${indexSnippet} ]`;
  22725. }
  22726. }
  22727. addNodeClass( 'ArrayElementNode', ArrayElementNode );
  22728. class ConvertNode extends Node {
  22729. constructor( node, convertTo ) {
  22730. super();
  22731. this.node = node;
  22732. this.convertTo = convertTo;
  22733. }
  22734. getNodeType( builder ) {
  22735. const requestType = this.node.getNodeType( builder );
  22736. let convertTo = null;
  22737. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  22738. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  22739. convertTo = overloadingType;
  22740. }
  22741. }
  22742. return convertTo;
  22743. }
  22744. serialize( data ) {
  22745. super.serialize( data );
  22746. data.convertTo = this.convertTo;
  22747. }
  22748. deserialize( data ) {
  22749. super.deserialize( data );
  22750. this.convertTo = data.convertTo;
  22751. }
  22752. generate( builder, output ) {
  22753. const node = this.node;
  22754. const type = this.getNodeType( builder );
  22755. const snippet = node.build( builder, type );
  22756. return builder.format( snippet, type, output );
  22757. }
  22758. }
  22759. addNodeClass( 'ConvertNode', ConvertNode );
  22760. class JoinNode extends TempNode {
  22761. constructor( nodes = [], nodeType = null ) {
  22762. super( nodeType );
  22763. this.nodes = nodes;
  22764. }
  22765. getNodeType( builder ) {
  22766. if ( this.nodeType !== null ) {
  22767. return builder.getVectorType( this.nodeType );
  22768. }
  22769. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  22770. }
  22771. generate( builder, output ) {
  22772. const type = this.getNodeType( builder );
  22773. const nodes = this.nodes;
  22774. const primitiveType = builder.getComponentType( type );
  22775. const snippetValues = [];
  22776. for ( const input of nodes ) {
  22777. let inputSnippet = input.build( builder );
  22778. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  22779. if ( inputPrimitiveType !== primitiveType ) {
  22780. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  22781. }
  22782. snippetValues.push( inputSnippet );
  22783. }
  22784. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  22785. return builder.format( snippet, type, output );
  22786. }
  22787. }
  22788. addNodeClass( 'JoinNode', JoinNode );
  22789. const stringVectorComponents = vectorComponents.join( '' );
  22790. class SplitNode extends Node {
  22791. constructor( node, components = 'x' ) {
  22792. super();
  22793. this.node = node;
  22794. this.components = components;
  22795. this.isSplitNode = true;
  22796. }
  22797. getVectorLength() {
  22798. let vectorLength = this.components.length;
  22799. for ( const c of this.components ) {
  22800. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  22801. }
  22802. return vectorLength;
  22803. }
  22804. getComponentType( builder ) {
  22805. return builder.getComponentType( this.node.getNodeType( builder ) );
  22806. }
  22807. getNodeType( builder ) {
  22808. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  22809. }
  22810. generate( builder, output ) {
  22811. const node = this.node;
  22812. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  22813. let snippet = null;
  22814. if ( nodeTypeLength > 1 ) {
  22815. let type = null;
  22816. const componentsLength = this.getVectorLength();
  22817. if ( componentsLength >= nodeTypeLength ) {
  22818. // needed expand the input node
  22819. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  22820. }
  22821. const nodeSnippet = node.build( builder, type );
  22822. if ( this.components.length === nodeTypeLength && this.components === stringVectorComponents.slice( 0, this.components.length ) ) {
  22823. // unnecessary swizzle
  22824. snippet = builder.format( nodeSnippet, type, output );
  22825. } else {
  22826. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  22827. }
  22828. } else {
  22829. // ignore .components if .node returns float/integer
  22830. snippet = node.build( builder, output );
  22831. }
  22832. return snippet;
  22833. }
  22834. serialize( data ) {
  22835. super.serialize( data );
  22836. data.components = this.components;
  22837. }
  22838. deserialize( data ) {
  22839. super.deserialize( data );
  22840. this.components = data.components;
  22841. }
  22842. }
  22843. addNodeClass( 'SplitNode', SplitNode );
  22844. class SetNode extends TempNode {
  22845. constructor( sourceNode, components, targetNode ) {
  22846. super();
  22847. this.sourceNode = sourceNode;
  22848. this.components = components;
  22849. this.targetNode = targetNode;
  22850. }
  22851. getNodeType( builder ) {
  22852. return this.sourceNode.getNodeType( builder );
  22853. }
  22854. generate( builder ) {
  22855. const { sourceNode, components, targetNode } = this;
  22856. const sourceType = this.getNodeType( builder );
  22857. const targetType = builder.getTypeFromLength( components.length );
  22858. const targetSnippet = targetNode.build( builder, targetType );
  22859. const sourceSnippet = sourceNode.build( builder, sourceType );
  22860. const length = builder.getTypeLength( sourceType );
  22861. const snippetValues = [];
  22862. for ( let i = 0; i < length; i ++ ) {
  22863. const component = vectorComponents[ i ];
  22864. if ( component === components[ 0 ] ) {
  22865. snippetValues.push( targetSnippet );
  22866. i += components.length - 1;
  22867. } else {
  22868. snippetValues.push( sourceSnippet + '.' + component );
  22869. }
  22870. }
  22871. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  22872. }
  22873. }
  22874. addNodeClass( 'SetNode', SetNode );
  22875. class InputNode extends Node {
  22876. constructor( value, nodeType = null ) {
  22877. super( nodeType );
  22878. this.isInputNode = true;
  22879. this.value = value;
  22880. this.precision = null;
  22881. }
  22882. getNodeType( /*builder*/ ) {
  22883. if ( this.nodeType === null ) {
  22884. return getValueType( this.value );
  22885. }
  22886. return this.nodeType;
  22887. }
  22888. getInputType( builder ) {
  22889. return this.getNodeType( builder );
  22890. }
  22891. setPrecision( precision ) {
  22892. this.precision = precision;
  22893. return this;
  22894. }
  22895. serialize( data ) {
  22896. super.serialize( data );
  22897. data.value = this.value;
  22898. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  22899. data.valueType = getValueType( this.value );
  22900. data.nodeType = this.nodeType;
  22901. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  22902. data.precision = this.precision;
  22903. }
  22904. deserialize( data ) {
  22905. super.deserialize( data );
  22906. this.nodeType = data.nodeType;
  22907. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  22908. this.precision = data.precision || null;
  22909. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  22910. }
  22911. generate( /*builder, output*/ ) {
  22912. console.warn( 'Abstract function.' );
  22913. }
  22914. }
  22915. addNodeClass( 'InputNode', InputNode );
  22916. class ConstNode extends InputNode {
  22917. constructor( value, nodeType = null ) {
  22918. super( value, nodeType );
  22919. this.isConstNode = true;
  22920. }
  22921. generateConst( builder ) {
  22922. return builder.generateConst( this.getNodeType( builder ), this.value );
  22923. }
  22924. generate( builder, output ) {
  22925. const type = this.getNodeType( builder );
  22926. return builder.format( this.generateConst( builder ), type, output );
  22927. }
  22928. }
  22929. addNodeClass( 'ConstNode', ConstNode );
  22930. //
  22931. let currentStack = null;
  22932. const NodeElements = new Map(); // @TODO: Currently only a few nodes are added, probably also add others
  22933. function addNodeElement( name, nodeElement ) {
  22934. if ( NodeElements.has( name ) ) {
  22935. console.warn( `Redefinition of node element ${ name }` );
  22936. return;
  22937. }
  22938. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  22939. NodeElements.set( name, nodeElement );
  22940. }
  22941. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  22942. const shaderNodeHandler = {
  22943. setup( NodeClosure, params ) {
  22944. const inputs = params.shift();
  22945. return NodeClosure( nodeObjects( inputs ), ...params );
  22946. },
  22947. get( node, prop, nodeObj ) {
  22948. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22949. if ( node.isStackNode !== true && prop === 'assign' ) {
  22950. return ( ...params ) => {
  22951. currentStack.assign( nodeObj, ...params );
  22952. return nodeObj;
  22953. };
  22954. } else if ( NodeElements.has( prop ) ) {
  22955. const nodeElement = NodeElements.get( prop );
  22956. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  22957. } else if ( prop === 'self' ) {
  22958. return node;
  22959. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  22960. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  22961. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  22962. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  22963. // accessing properties ( swizzle )
  22964. prop = parseSwizzle( prop );
  22965. return nodeObject( new SplitNode( nodeObj, prop ) );
  22966. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  22967. // set properties ( swizzle )
  22968. prop = parseSwizzle( prop.slice( 3 ).toLowerCase() );
  22969. // sort to xyzw sequence
  22970. prop = prop.split( '' ).sort().join( '' );
  22971. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  22972. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  22973. // accessing property
  22974. if ( prop === 'width' ) prop = 'x';
  22975. else if ( prop === 'height' ) prop = 'y';
  22976. else if ( prop === 'depth' ) prop = 'z';
  22977. return nodeObject( new SplitNode( node, prop ) );
  22978. } else if ( /^\d+$/.test( prop ) === true ) {
  22979. // accessing array
  22980. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  22981. }
  22982. }
  22983. return Reflect.get( node, prop, nodeObj );
  22984. },
  22985. set( node, prop, value, nodeObj ) {
  22986. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22987. // setting properties
  22988. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  22989. nodeObj[ prop ].assign( value );
  22990. return true;
  22991. }
  22992. }
  22993. return Reflect.set( node, prop, value, nodeObj );
  22994. }
  22995. };
  22996. const nodeObjectsCacheMap = new WeakMap();
  22997. const nodeBuilderFunctionsCacheMap = new WeakMap();
  22998. const ShaderNodeObject = function ( obj, altType = null ) {
  22999. const type = getValueType( obj );
  23000. if ( type === 'node' ) {
  23001. let nodeObject = nodeObjectsCacheMap.get( obj );
  23002. if ( nodeObject === undefined ) {
  23003. nodeObject = new Proxy( obj, shaderNodeHandler );
  23004. nodeObjectsCacheMap.set( obj, nodeObject );
  23005. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  23006. }
  23007. return nodeObject;
  23008. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  23009. return nodeObject( getConstNode( obj, altType ) );
  23010. } else if ( type === 'shader' ) {
  23011. return tslFn( obj );
  23012. }
  23013. return obj;
  23014. };
  23015. const ShaderNodeObjects = function ( objects, altType = null ) {
  23016. for ( const name in objects ) {
  23017. objects[ name ] = nodeObject( objects[ name ], altType );
  23018. }
  23019. return objects;
  23020. };
  23021. const ShaderNodeArray = function ( array, altType = null ) {
  23022. const len = array.length;
  23023. for ( let i = 0; i < len; i ++ ) {
  23024. array[ i ] = nodeObject( array[ i ], altType );
  23025. }
  23026. return array;
  23027. };
  23028. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  23029. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  23030. if ( scope === null ) {
  23031. return ( ...params ) => {
  23032. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  23033. };
  23034. } else if ( factor !== null ) {
  23035. factor = nodeObject( factor );
  23036. return ( ...params ) => {
  23037. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  23038. };
  23039. } else {
  23040. return ( ...params ) => {
  23041. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  23042. };
  23043. }
  23044. };
  23045. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  23046. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  23047. };
  23048. class ShaderCallNodeInternal extends Node {
  23049. constructor( shaderNode, inputNodes ) {
  23050. super();
  23051. this.shaderNode = shaderNode;
  23052. this.inputNodes = inputNodes;
  23053. }
  23054. getNodeType( builder ) {
  23055. const properties = builder.getNodeProperties( this );
  23056. if ( properties.outputNode === null ) {
  23057. properties.outputNode = this.setupOutput( builder );
  23058. }
  23059. return properties.outputNode.getNodeType( builder );
  23060. }
  23061. call( builder ) {
  23062. const { shaderNode, inputNodes } = this;
  23063. if ( shaderNode.layout ) {
  23064. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  23065. if ( functionNodesCacheMap === undefined ) {
  23066. functionNodesCacheMap = new WeakMap();
  23067. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  23068. }
  23069. let functionNode = functionNodesCacheMap.get( shaderNode );
  23070. if ( functionNode === undefined ) {
  23071. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  23072. functionNodesCacheMap.set( shaderNode, functionNode );
  23073. }
  23074. if ( builder.currentFunctionNode !== null ) {
  23075. builder.currentFunctionNode.includes.push( functionNode );
  23076. }
  23077. return nodeObject( functionNode.call( inputNodes ) );
  23078. }
  23079. const jsFunc = shaderNode.jsFunc;
  23080. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder.stack, builder ) : jsFunc( builder.stack, builder );
  23081. return nodeObject( outputNode );
  23082. }
  23083. setup( builder ) {
  23084. const { outputNode } = builder.getNodeProperties( this );
  23085. return outputNode || this.setupOutput( builder );
  23086. }
  23087. setupOutput( builder ) {
  23088. builder.addStack();
  23089. builder.stack.outputNode = this.call( builder );
  23090. return builder.removeStack();
  23091. }
  23092. generate( builder, output ) {
  23093. const { outputNode } = builder.getNodeProperties( this );
  23094. if ( outputNode === null ) {
  23095. // TSL: It's recommended to use `tslFn` in setup() pass.
  23096. return this.call( builder ).build( builder, output );
  23097. }
  23098. return super.generate( builder, output );
  23099. }
  23100. }
  23101. class ShaderNodeInternal extends Node {
  23102. constructor( jsFunc ) {
  23103. super();
  23104. this.jsFunc = jsFunc;
  23105. this.layout = null;
  23106. this.global = true;
  23107. }
  23108. get isArrayInput() {
  23109. return /^\((\s+)?\[/.test( this.jsFunc.toString() );
  23110. }
  23111. setLayout( layout ) {
  23112. this.layout = layout;
  23113. return this;
  23114. }
  23115. call( inputs = null ) {
  23116. nodeObjects( inputs );
  23117. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  23118. }
  23119. setup() {
  23120. return this.call();
  23121. }
  23122. }
  23123. const bools = [ false, true ];
  23124. const uints = [ 0, 1, 2, 3 ];
  23125. const ints = [ - 1, - 2 ];
  23126. const floats = [ 0.5, 1.5, 1 / 3, 1e-6, 1e6, Math.PI, Math.PI * 2, 1 / Math.PI, 2 / Math.PI, 1 / ( Math.PI * 2 ), Math.PI / 2 ];
  23127. const boolsCacheMap = new Map();
  23128. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  23129. const uintsCacheMap = new Map();
  23130. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  23131. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  23132. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  23133. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  23134. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  23135. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  23136. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  23137. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  23138. const getConstNode = ( value, type ) => {
  23139. if ( constNodesCacheMap.has( value ) ) {
  23140. return constNodesCacheMap.get( value );
  23141. } else if ( value.isNode === true ) {
  23142. return value;
  23143. } else {
  23144. return new ConstNode( value, type );
  23145. }
  23146. };
  23147. const safeGetNodeType = ( node ) => {
  23148. try {
  23149. return node.getNodeType();
  23150. } catch ( _ ) {
  23151. return undefined;
  23152. }
  23153. };
  23154. const ConvertType = function ( type, cacheMap = null ) {
  23155. return ( ...params ) => {
  23156. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  23157. params = [ getValueFromType( type, ...params ) ];
  23158. }
  23159. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  23160. return nodeObject( cacheMap.get( params[ 0 ] ) );
  23161. }
  23162. if ( params.length === 1 ) {
  23163. const node = getConstNode( params[ 0 ], type );
  23164. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  23165. return nodeObject( new ConvertNode( node, type ) );
  23166. }
  23167. const nodes = params.map( param => getConstNode( param ) );
  23168. return nodeObject( new JoinNode( nodes, type ) );
  23169. };
  23170. };
  23171. // exports
  23172. const defined = ( value ) => value && value.value;
  23173. // utils
  23174. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  23175. // shader node base
  23176. function ShaderNode( jsFunc ) {
  23177. return new Proxy( new ShaderNodeInternal( jsFunc ), shaderNodeHandler );
  23178. }
  23179. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  23180. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  23181. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  23182. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  23183. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  23184. const tslFn = ( jsFunc ) => {
  23185. const shaderNode = new ShaderNode( jsFunc );
  23186. const fn = ( ...params ) => {
  23187. let inputs;
  23188. nodeObjects( params );
  23189. if ( params[ 0 ] && params[ 0 ].isNode ) {
  23190. inputs = [ ...params ];
  23191. } else {
  23192. inputs = params[ 0 ];
  23193. }
  23194. return shaderNode.call( inputs );
  23195. };
  23196. fn.shaderNode = shaderNode;
  23197. fn.setLayout = ( layout ) => {
  23198. shaderNode.setLayout( layout );
  23199. return fn;
  23200. };
  23201. return fn;
  23202. };
  23203. addNodeClass( 'ShaderNode', ShaderNode );
  23204. //
  23205. addNodeElement( 'toGlobal', ( node ) => {
  23206. node.global = true;
  23207. return node;
  23208. } );
  23209. //
  23210. const setCurrentStack = ( stack ) => {
  23211. currentStack = stack;
  23212. };
  23213. const getCurrentStack = () => currentStack;
  23214. const If = ( ...params ) => currentStack.if( ...params );
  23215. function append( node ) {
  23216. if ( currentStack ) currentStack.add( node );
  23217. return node;
  23218. }
  23219. addNodeElement( 'append', append );
  23220. // types
  23221. // @TODO: Maybe export from ConstNode.js?
  23222. const color = new ConvertType( 'color' );
  23223. const float = new ConvertType( 'float', cacheMaps.float );
  23224. const int = new ConvertType( 'int', cacheMaps.ints );
  23225. const uint = new ConvertType( 'uint', cacheMaps.uint );
  23226. const bool = new ConvertType( 'bool', cacheMaps.bool );
  23227. const vec2 = new ConvertType( 'vec2' );
  23228. const ivec2 = new ConvertType( 'ivec2' );
  23229. const uvec2 = new ConvertType( 'uvec2' );
  23230. const bvec2 = new ConvertType( 'bvec2' );
  23231. const vec3 = new ConvertType( 'vec3' );
  23232. const ivec3 = new ConvertType( 'ivec3' );
  23233. const uvec3 = new ConvertType( 'uvec3' );
  23234. const bvec3 = new ConvertType( 'bvec3' );
  23235. const vec4 = new ConvertType( 'vec4' );
  23236. const ivec4 = new ConvertType( 'ivec4' );
  23237. const uvec4 = new ConvertType( 'uvec4' );
  23238. const bvec4 = new ConvertType( 'bvec4' );
  23239. const mat2 = new ConvertType( 'mat2' );
  23240. const imat2 = new ConvertType( 'imat2' );
  23241. const umat2 = new ConvertType( 'umat2' );
  23242. const bmat2 = new ConvertType( 'bmat2' );
  23243. const mat3 = new ConvertType( 'mat3' );
  23244. const imat3 = new ConvertType( 'imat3' );
  23245. const umat3 = new ConvertType( 'umat3' );
  23246. const bmat3 = new ConvertType( 'bmat3' );
  23247. const mat4 = new ConvertType( 'mat4' );
  23248. const imat4 = new ConvertType( 'imat4' );
  23249. const umat4 = new ConvertType( 'umat4' );
  23250. const bmat4 = new ConvertType( 'bmat4' );
  23251. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  23252. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  23253. addNodeElement( 'toColor', color );
  23254. addNodeElement( 'toFloat', float );
  23255. addNodeElement( 'toInt', int );
  23256. addNodeElement( 'toUint', uint );
  23257. addNodeElement( 'toBool', bool );
  23258. addNodeElement( 'toVec2', vec2 );
  23259. addNodeElement( 'toIvec2', ivec2 );
  23260. addNodeElement( 'toUvec2', uvec2 );
  23261. addNodeElement( 'toBvec2', bvec2 );
  23262. addNodeElement( 'toVec3', vec3 );
  23263. addNodeElement( 'toIvec3', ivec3 );
  23264. addNodeElement( 'toUvec3', uvec3 );
  23265. addNodeElement( 'toBvec3', bvec3 );
  23266. addNodeElement( 'toVec4', vec4 );
  23267. addNodeElement( 'toIvec4', ivec4 );
  23268. addNodeElement( 'toUvec4', uvec4 );
  23269. addNodeElement( 'toBvec4', bvec4 );
  23270. addNodeElement( 'toMat2', mat2 );
  23271. addNodeElement( 'toImat2', imat2 );
  23272. addNodeElement( 'toUmat2', umat2 );
  23273. addNodeElement( 'toBmat2', bmat2 );
  23274. addNodeElement( 'toMat3', mat3 );
  23275. addNodeElement( 'toImat3', imat3 );
  23276. addNodeElement( 'toUmat3', umat3 );
  23277. addNodeElement( 'toBmat3', bmat3 );
  23278. addNodeElement( 'toMat4', mat4 );
  23279. addNodeElement( 'toImat4', imat4 );
  23280. addNodeElement( 'toUmat4', umat4 );
  23281. addNodeElement( 'toBmat4', bmat4 );
  23282. // basic nodes
  23283. // HACK - we cannot export them from the corresponding files because of the cyclic dependency
  23284. const element = nodeProxy( ArrayElementNode );
  23285. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  23286. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  23287. addNodeElement( 'element', element );
  23288. addNodeElement( 'convert', convert );
  23289. class AssignNode extends TempNode {
  23290. constructor( targetNode, sourceNode ) {
  23291. super();
  23292. this.targetNode = targetNode;
  23293. this.sourceNode = sourceNode;
  23294. }
  23295. hasDependencies() {
  23296. return false;
  23297. }
  23298. getNodeType( builder, output ) {
  23299. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  23300. }
  23301. needsSplitAssign( builder ) {
  23302. const { targetNode } = this;
  23303. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  23304. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  23305. const assignDiferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  23306. return assignDiferentVector;
  23307. }
  23308. return false;
  23309. }
  23310. generate( builder, output ) {
  23311. const { targetNode, sourceNode } = this;
  23312. const needsSplitAssign = this.needsSplitAssign( builder );
  23313. const targetType = targetNode.getNodeType( builder );
  23314. const target = targetNode.context( { assign: true } ).build( builder );
  23315. const source = sourceNode.build( builder, targetType );
  23316. const sourceType = sourceNode.getNodeType( builder );
  23317. const nodeData = builder.getDataFromNode( this );
  23318. //
  23319. let snippet;
  23320. if ( nodeData.initialized === true ) {
  23321. if ( output !== 'void' ) {
  23322. snippet = target;
  23323. }
  23324. } else if ( needsSplitAssign ) {
  23325. const sourceVar = builder.getVarFromNode( this, null, targetType );
  23326. const sourceProperty = builder.getPropertyName( sourceVar );
  23327. builder.addLineFlowCode( `${ sourceProperty } = ${ source }` );
  23328. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  23329. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  23330. const component = targetNode.components[ i ];
  23331. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]` );
  23332. }
  23333. if ( output !== 'void' ) {
  23334. snippet = target;
  23335. }
  23336. } else {
  23337. snippet = `${ target } = ${ source }`;
  23338. if ( output === 'void' || sourceType === 'void' ) {
  23339. builder.addLineFlowCode( snippet );
  23340. if ( output !== 'void' ) {
  23341. snippet = target;
  23342. }
  23343. }
  23344. }
  23345. nodeData.initialized = true;
  23346. return builder.format( snippet, targetType, output );
  23347. }
  23348. }
  23349. const assign = nodeProxy( AssignNode );
  23350. addNodeClass( 'AssignNode', AssignNode );
  23351. addNodeElement( 'assign', assign );
  23352. class VaryingNode extends Node {
  23353. constructor( node, name = null ) {
  23354. super();
  23355. this.node = node;
  23356. this.name = name;
  23357. this.isVaryingNode = true;
  23358. }
  23359. isGlobal() {
  23360. return true;
  23361. }
  23362. getHash( builder ) {
  23363. return this.name || super.getHash( builder );
  23364. }
  23365. getNodeType( builder ) {
  23366. // VaryingNode is auto type
  23367. return this.node.getNodeType( builder );
  23368. }
  23369. setupVarying( builder ) {
  23370. const properties = builder.getNodeProperties( this );
  23371. let varying = properties.varying;
  23372. if ( varying === undefined ) {
  23373. const name = this.name;
  23374. const type = this.getNodeType( builder );
  23375. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  23376. properties.node = this.node;
  23377. }
  23378. // this property can be used to check if the varying can be optimized for a variable
  23379. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  23380. return varying;
  23381. }
  23382. setup( builder ) {
  23383. this.setupVarying( builder );
  23384. }
  23385. analyze( builder ) {
  23386. this.setupVarying( builder );
  23387. return this.node.analyze( builder );
  23388. }
  23389. generate( builder ) {
  23390. const properties = builder.getNodeProperties( this );
  23391. const varying = this.setupVarying( builder );
  23392. if ( properties.propertyName === undefined ) {
  23393. const type = this.getNodeType( builder );
  23394. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  23395. // force node run in vertex stage
  23396. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  23397. properties.propertyName = propertyName;
  23398. }
  23399. return builder.getPropertyName( varying );
  23400. }
  23401. }
  23402. const varying = nodeProxy( VaryingNode );
  23403. addNodeElement( 'varying', varying );
  23404. addNodeClass( 'VaryingNode', VaryingNode );
  23405. class AttributeNode extends Node {
  23406. constructor( attributeName, nodeType = null, defaultNode = null ) {
  23407. super( nodeType );
  23408. this.defaultNode = defaultNode;
  23409. this.global = true;
  23410. this._attributeName = attributeName;
  23411. }
  23412. getHash( builder ) {
  23413. return this.getAttributeName( builder );
  23414. }
  23415. getNodeType( builder ) {
  23416. let nodeType = super.getNodeType( builder );
  23417. if ( nodeType === null ) {
  23418. const attributeName = this.getAttributeName( builder );
  23419. if ( builder.hasGeometryAttribute( attributeName ) ) {
  23420. const attribute = builder.geometry.getAttribute( attributeName );
  23421. nodeType = builder.getTypeFromAttribute( attribute );
  23422. } else {
  23423. nodeType = 'float';
  23424. }
  23425. }
  23426. return nodeType;
  23427. }
  23428. setAttributeName( attributeName ) {
  23429. this._attributeName = attributeName;
  23430. return this;
  23431. }
  23432. getAttributeName( /*builder*/ ) {
  23433. return this._attributeName;
  23434. }
  23435. generate( builder ) {
  23436. const attributeName = this.getAttributeName( builder );
  23437. const nodeType = this.getNodeType( builder );
  23438. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  23439. if ( geometryAttribute === true ) {
  23440. const attribute = builder.geometry.getAttribute( attributeName );
  23441. const attributeType = builder.getTypeFromAttribute( attribute );
  23442. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  23443. if ( builder.shaderStage === 'vertex' ) {
  23444. return builder.format( nodeAttribute.name, attributeType, nodeType );
  23445. } else {
  23446. const nodeVarying = varying( this );
  23447. return nodeVarying.build( builder, nodeType );
  23448. }
  23449. } else {
  23450. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  23451. const { defaultNode } = this;
  23452. if ( defaultNode !== null ) {
  23453. return defaultNode.build( builder, nodeType );
  23454. } else {
  23455. return builder.generateConst( nodeType );
  23456. }
  23457. }
  23458. }
  23459. }
  23460. const attribute = ( name, nodeType, defaultNode ) => nodeObject( new AttributeNode( name, nodeType, nodeObject( defaultNode ) ) );
  23461. addNodeClass( 'AttributeNode', AttributeNode );
  23462. class BypassNode extends Node {
  23463. constructor( returnNode, callNode ) {
  23464. super();
  23465. this.isBypassNode = true;
  23466. this.outputNode = returnNode;
  23467. this.callNode = callNode;
  23468. }
  23469. getNodeType( builder ) {
  23470. return this.outputNode.getNodeType( builder );
  23471. }
  23472. generate( builder ) {
  23473. const snippet = this.callNode.build( builder, 'void' );
  23474. if ( snippet !== '' ) {
  23475. builder.addLineFlowCode( snippet );
  23476. }
  23477. return this.outputNode.build( builder );
  23478. }
  23479. }
  23480. const bypass = nodeProxy( BypassNode );
  23481. addNodeElement( 'bypass', bypass );
  23482. addNodeClass( 'BypassNode', BypassNode );
  23483. class CacheNode extends Node {
  23484. constructor( node, parent = true ) {
  23485. super();
  23486. this.node = node;
  23487. this.parent = parent;
  23488. this.isCacheNode = true;
  23489. }
  23490. getNodeType( builder ) {
  23491. return this.node.getNodeType( builder );
  23492. }
  23493. build( builder, ...params ) {
  23494. const previousCache = builder.getCache();
  23495. const cache = builder.getCacheFromNode( this, parent );
  23496. builder.setCache( cache );
  23497. const data = this.node.build( builder, ...params );
  23498. builder.setCache( previousCache );
  23499. return data;
  23500. }
  23501. }
  23502. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  23503. addNodeElement( 'cache', cache );
  23504. addNodeClass( 'CacheNode', CacheNode );
  23505. class ContextNode extends Node {
  23506. constructor( node, context = {} ) {
  23507. super();
  23508. this.isContextNode = true;
  23509. this.node = node;
  23510. this.context = context;
  23511. }
  23512. getNodeType( builder ) {
  23513. return this.node.getNodeType( builder );
  23514. }
  23515. analyze( builder ) {
  23516. this.node.build( builder );
  23517. }
  23518. setup( builder ) {
  23519. const previousContext = builder.getContext();
  23520. builder.setContext( { ...builder.context, ...this.context } );
  23521. const node = this.node.build( builder );
  23522. builder.setContext( previousContext );
  23523. return node;
  23524. }
  23525. generate( builder, output ) {
  23526. const previousContext = builder.getContext();
  23527. builder.setContext( { ...builder.context, ...this.context } );
  23528. const snippet = this.node.build( builder, output );
  23529. builder.setContext( previousContext );
  23530. return snippet;
  23531. }
  23532. }
  23533. const context = nodeProxy( ContextNode );
  23534. const label = ( node, name ) => context( node, { label: name } );
  23535. addNodeElement( 'context', context );
  23536. addNodeElement( 'label', label );
  23537. addNodeClass( 'ContextNode', ContextNode );
  23538. class IndexNode extends Node {
  23539. constructor( scope ) {
  23540. super( 'uint' );
  23541. this.scope = scope;
  23542. this.isInstanceIndexNode = true;
  23543. }
  23544. generate( builder ) {
  23545. const nodeType = this.getNodeType( builder );
  23546. const scope = this.scope;
  23547. let propertyName;
  23548. if ( scope === IndexNode.VERTEX ) {
  23549. propertyName = builder.getVertexIndex();
  23550. } else if ( scope === IndexNode.INSTANCE ) {
  23551. propertyName = builder.getInstanceIndex();
  23552. } else if ( scope === IndexNode.DRAW ) {
  23553. propertyName = builder.getDrawIndex();
  23554. } else {
  23555. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  23556. }
  23557. let output;
  23558. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  23559. output = propertyName;
  23560. } else {
  23561. const nodeVarying = varying( this );
  23562. output = nodeVarying.build( builder, nodeType );
  23563. }
  23564. return output;
  23565. }
  23566. }
  23567. IndexNode.VERTEX = 'vertex';
  23568. IndexNode.INSTANCE = 'instance';
  23569. IndexNode.DRAW = 'draw';
  23570. const vertexIndex = nodeImmutable( IndexNode, IndexNode.VERTEX );
  23571. const instanceIndex = nodeImmutable( IndexNode, IndexNode.INSTANCE );
  23572. const drawIndex = nodeImmutable( IndexNode, IndexNode.DRAW );
  23573. addNodeClass( 'IndexNode', IndexNode );
  23574. class LightingModel {
  23575. start( /*input, stack, builder*/ ) { }
  23576. finish( /*input, stack, builder*/ ) { }
  23577. direct( /*input, stack, builder*/ ) { }
  23578. directRectArea( /*input, stack, builder*/ ) {}
  23579. indirectDiffuse( /*input, stack, builder*/ ) { }
  23580. indirectSpecular( /*input, stack, builder*/ ) { }
  23581. ambientOcclusion( /*input, stack, builder*/ ) { }
  23582. }
  23583. class VarNode extends Node {
  23584. constructor( node, name = null ) {
  23585. super();
  23586. this.node = node;
  23587. this.name = name;
  23588. this.global = true;
  23589. this.isVarNode = true;
  23590. }
  23591. getHash( builder ) {
  23592. return this.name || super.getHash( builder );
  23593. }
  23594. getNodeType( builder ) {
  23595. return this.node.getNodeType( builder );
  23596. }
  23597. generate( builder ) {
  23598. const { node, name } = this;
  23599. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  23600. const propertyName = builder.getPropertyName( nodeVar );
  23601. const snippet = node.build( builder, nodeVar.type );
  23602. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  23603. return propertyName;
  23604. }
  23605. }
  23606. const temp = nodeProxy( VarNode );
  23607. addNodeElement( 'temp', temp ); // @TODO: Will be removed in the future
  23608. addNodeElement( 'toVar', ( ...params ) => temp( ...params ).append() );
  23609. addNodeClass( 'VarNode', VarNode );
  23610. class NodeAttribute {
  23611. constructor( name, type, node = null ) {
  23612. this.isNodeAttribute = true;
  23613. this.name = name;
  23614. this.type = type;
  23615. this.node = node;
  23616. }
  23617. }
  23618. class NodeUniform {
  23619. constructor( name, type, node ) {
  23620. this.isNodeUniform = true;
  23621. this.name = name;
  23622. this.type = type;
  23623. this.node = node.getSelf();
  23624. }
  23625. get value() {
  23626. return this.node.value;
  23627. }
  23628. set value( val ) {
  23629. this.node.value = val;
  23630. }
  23631. get id() {
  23632. return this.node.id;
  23633. }
  23634. get groupNode() {
  23635. return this.node.groupNode;
  23636. }
  23637. }
  23638. class NodeVar {
  23639. constructor( name, type ) {
  23640. this.isNodeVar = true;
  23641. this.name = name;
  23642. this.type = type;
  23643. }
  23644. }
  23645. class NodeVarying extends NodeVar {
  23646. constructor( name, type ) {
  23647. super( name, type );
  23648. this.needsInterpolation = false;
  23649. this.isNodeVarying = true;
  23650. }
  23651. }
  23652. class NodeCode {
  23653. constructor( name, type, code = '' ) {
  23654. this.name = name;
  23655. this.type = type;
  23656. this.code = code;
  23657. Object.defineProperty( this, 'isNodeCode', { value: true } );
  23658. }
  23659. }
  23660. class NodeKeywords {
  23661. constructor() {
  23662. this.keywords = [];
  23663. this.nodes = {};
  23664. this.keywordsCallback = {};
  23665. }
  23666. getNode( name ) {
  23667. let node = this.nodes[ name ];
  23668. if ( node === undefined && this.keywordsCallback[ name ] !== undefined ) {
  23669. node = this.keywordsCallback[ name ]( name );
  23670. this.nodes[ name ] = node;
  23671. }
  23672. return node;
  23673. }
  23674. addKeyword( name, callback ) {
  23675. this.keywords.push( name );
  23676. this.keywordsCallback[ name ] = callback;
  23677. return this;
  23678. }
  23679. parse( code ) {
  23680. const keywordNames = this.keywords;
  23681. const regExp = new RegExp( `\\b${keywordNames.join( '\\b|\\b' )}\\b`, 'g' );
  23682. const codeKeywords = code.match( regExp );
  23683. const keywordNodes = [];
  23684. if ( codeKeywords !== null ) {
  23685. for ( const keyword of codeKeywords ) {
  23686. const node = this.getNode( keyword );
  23687. if ( node !== undefined && keywordNodes.indexOf( node ) === - 1 ) {
  23688. keywordNodes.push( node );
  23689. }
  23690. }
  23691. }
  23692. return keywordNodes;
  23693. }
  23694. include( builder, code ) {
  23695. const keywordNodes = this.parse( code );
  23696. for ( const keywordNode of keywordNodes ) {
  23697. keywordNode.build( builder );
  23698. }
  23699. }
  23700. }
  23701. let id$3 = 0;
  23702. class NodeCache {
  23703. constructor( parent = null ) {
  23704. this.id = id$3 ++;
  23705. this.nodesData = new WeakMap();
  23706. this.parent = parent;
  23707. }
  23708. getData( node ) {
  23709. let data = this.nodesData.get( node );
  23710. if ( data === undefined && this.parent !== null ) {
  23711. data = this.parent.getData( node );
  23712. }
  23713. return data;
  23714. }
  23715. setData( node, data ) {
  23716. this.nodesData.set( node, data );
  23717. }
  23718. }
  23719. class PropertyNode extends Node {
  23720. constructor( nodeType, name = null, varying = false ) {
  23721. super( nodeType );
  23722. this.name = name;
  23723. this.varying = varying;
  23724. this.isPropertyNode = true;
  23725. }
  23726. getHash( builder ) {
  23727. return this.name || super.getHash( builder );
  23728. }
  23729. isGlobal( /*builder*/ ) {
  23730. return true;
  23731. }
  23732. generate( builder ) {
  23733. let nodeVar;
  23734. if ( this.varying === true ) {
  23735. nodeVar = builder.getVaryingFromNode( this, this.name );
  23736. nodeVar.needsInterpolation = true;
  23737. } else {
  23738. nodeVar = builder.getVarFromNode( this, this.name );
  23739. }
  23740. return builder.getPropertyName( nodeVar );
  23741. }
  23742. }
  23743. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  23744. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  23745. const diffuseColor = nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  23746. const roughness = nodeImmutable( PropertyNode, 'float', 'Roughness' );
  23747. const metalness = nodeImmutable( PropertyNode, 'float', 'Metalness' );
  23748. const clearcoat = nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  23749. const clearcoatRoughness = nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  23750. const sheen = nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  23751. const sheenRoughness = nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  23752. const iridescence = nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  23753. const iridescenceIOR = nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  23754. const iridescenceThickness = nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  23755. const alphaT = nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  23756. const anisotropy = nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  23757. const anisotropyT = nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  23758. const anisotropyB = nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  23759. const specularColor = nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  23760. const specularF90 = nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  23761. const shininess = nodeImmutable( PropertyNode, 'float', 'Shininess' );
  23762. const output = nodeImmutable( PropertyNode, 'vec4', 'Output' );
  23763. const dashSize = nodeImmutable( PropertyNode, 'float', 'dashSize' );
  23764. const gapSize = nodeImmutable( PropertyNode, 'float', 'gapSize' );
  23765. const pointWidth = nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  23766. const ior = nodeImmutable( PropertyNode, 'float', 'IOR' );
  23767. const transmission = nodeImmutable( PropertyNode, 'float', 'Transmission' );
  23768. const thickness = nodeImmutable( PropertyNode, 'float', 'Thickness' );
  23769. const attenuationDistance = nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  23770. const attenuationColor = nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  23771. const dispersion = nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  23772. addNodeClass( 'PropertyNode', PropertyNode );
  23773. class ParameterNode extends PropertyNode {
  23774. constructor( nodeType, name = null ) {
  23775. super( nodeType, name );
  23776. this.isParameterNode = true;
  23777. }
  23778. getHash() {
  23779. return this.uuid;
  23780. }
  23781. generate() {
  23782. return this.name;
  23783. }
  23784. }
  23785. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  23786. addNodeClass( 'ParameterNode', ParameterNode );
  23787. class CodeNode extends Node {
  23788. constructor( code = '', includes = [], language = '' ) {
  23789. super( 'code' );
  23790. this.isCodeNode = true;
  23791. this.code = code;
  23792. this.language = language;
  23793. this.includes = includes;
  23794. }
  23795. isGlobal() {
  23796. return true;
  23797. }
  23798. setIncludes( includes ) {
  23799. this.includes = includes;
  23800. return this;
  23801. }
  23802. getIncludes( /*builder*/ ) {
  23803. return this.includes;
  23804. }
  23805. generate( builder ) {
  23806. const includes = this.getIncludes( builder );
  23807. for ( const include of includes ) {
  23808. include.build( builder );
  23809. }
  23810. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  23811. nodeCode.code = this.code;
  23812. return nodeCode.code;
  23813. }
  23814. serialize( data ) {
  23815. super.serialize( data );
  23816. data.code = this.code;
  23817. data.language = this.language;
  23818. }
  23819. deserialize( data ) {
  23820. super.deserialize( data );
  23821. this.code = data.code;
  23822. this.language = data.language;
  23823. }
  23824. }
  23825. const code = nodeProxy( CodeNode );
  23826. const js = ( src, includes ) => code( src, includes, 'js' );
  23827. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  23828. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  23829. addNodeClass( 'CodeNode', CodeNode );
  23830. class FunctionNode extends CodeNode {
  23831. constructor( code = '', includes = [], language = '' ) {
  23832. super( code, includes, language );
  23833. this.keywords = {};
  23834. }
  23835. getNodeType( builder ) {
  23836. return this.getNodeFunction( builder ).type;
  23837. }
  23838. getInputs( builder ) {
  23839. return this.getNodeFunction( builder ).inputs;
  23840. }
  23841. getNodeFunction( builder ) {
  23842. const nodeData = builder.getDataFromNode( this );
  23843. let nodeFunction = nodeData.nodeFunction;
  23844. if ( nodeFunction === undefined ) {
  23845. nodeFunction = builder.parser.parseFunction( this.code );
  23846. nodeData.nodeFunction = nodeFunction;
  23847. }
  23848. return nodeFunction;
  23849. }
  23850. generate( builder, output ) {
  23851. super.generate( builder );
  23852. const nodeFunction = this.getNodeFunction( builder );
  23853. const name = nodeFunction.name;
  23854. const type = nodeFunction.type;
  23855. const nodeCode = builder.getCodeFromNode( this, type );
  23856. if ( name !== '' ) {
  23857. // use a custom property name
  23858. nodeCode.name = name;
  23859. }
  23860. const propertyName = builder.getPropertyName( nodeCode );
  23861. let code = this.getNodeFunction( builder ).getCode( propertyName );
  23862. const keywords = this.keywords;
  23863. const keywordsProperties = Object.keys( keywords );
  23864. if ( keywordsProperties.length > 0 ) {
  23865. for ( const property of keywordsProperties ) {
  23866. const propertyRegExp = new RegExp( `\\b${property}\\b`, 'g' );
  23867. const nodeProperty = keywords[ property ].build( builder, 'property' );
  23868. code = code.replace( propertyRegExp, nodeProperty );
  23869. }
  23870. }
  23871. nodeCode.code = code + '\n';
  23872. if ( output === 'property' ) {
  23873. return propertyName;
  23874. } else {
  23875. return builder.format( `${ propertyName }()`, type, output );
  23876. }
  23877. }
  23878. }
  23879. const nativeFn = ( code, includes = [], language = '' ) => {
  23880. for ( let i = 0; i < includes.length; i ++ ) {
  23881. const include = includes[ i ];
  23882. // TSL Function: glslFn, wgslFn
  23883. if ( typeof include === 'function' ) {
  23884. includes[ i ] = include.functionNode;
  23885. }
  23886. }
  23887. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  23888. const fn = ( ...params ) => functionNode.call( ...params );
  23889. fn.functionNode = functionNode;
  23890. return fn;
  23891. };
  23892. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  23893. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  23894. addNodeClass( 'FunctionNode', FunctionNode );
  23895. class UniformGroupNode extends Node {
  23896. constructor( name, shared = false ) {
  23897. super( 'string' );
  23898. this.name = name;
  23899. this.version = 0;
  23900. this.shared = shared;
  23901. this.isUniformGroup = true;
  23902. }
  23903. set needsUpdate( value ) {
  23904. if ( value === true ) this.version ++;
  23905. }
  23906. }
  23907. const uniformGroup = ( name ) => new UniformGroupNode( name );
  23908. const sharedUniformGroup = ( name ) => new UniformGroupNode( name, true );
  23909. const frameGroup = sharedUniformGroup( 'frame' );
  23910. const renderGroup = sharedUniformGroup( 'render' );
  23911. const objectGroup = uniformGroup( 'object' );
  23912. addNodeClass( 'UniformGroupNode', UniformGroupNode );
  23913. class UniformNode extends InputNode {
  23914. constructor( value, nodeType = null ) {
  23915. super( value, nodeType );
  23916. this.isUniformNode = true;
  23917. this.name = '';
  23918. this.groupNode = objectGroup;
  23919. }
  23920. label( name ) {
  23921. this.name = name;
  23922. return this;
  23923. }
  23924. setGroup( group ) {
  23925. this.groupNode = group;
  23926. return this;
  23927. }
  23928. getGroup() {
  23929. return this.groupNode;
  23930. }
  23931. getUniformHash( builder ) {
  23932. return this.getHash( builder );
  23933. }
  23934. onUpdate( callback, updateType ) {
  23935. const self = this.getSelf();
  23936. callback = callback.bind( self );
  23937. return super.onUpdate( ( frame ) => {
  23938. const value = callback( frame, self );
  23939. if ( value !== undefined ) {
  23940. this.value = value;
  23941. }
  23942. }, updateType );
  23943. }
  23944. generate( builder, output ) {
  23945. const type = this.getNodeType( builder );
  23946. const hash = this.getUniformHash( builder );
  23947. let sharedNode = builder.getNodeFromHash( hash );
  23948. if ( sharedNode === undefined ) {
  23949. builder.setHashNode( this, hash );
  23950. sharedNode = this;
  23951. }
  23952. const sharedNodeType = sharedNode.getInputType( builder );
  23953. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  23954. const propertyName = builder.getPropertyName( nodeUniform );
  23955. if ( builder.context.label !== undefined ) delete builder.context.label;
  23956. return builder.format( propertyName, type, output );
  23957. }
  23958. }
  23959. const uniform = ( arg1, arg2 ) => {
  23960. const nodeType = getConstNodeType( arg2 || arg1 );
  23961. // @TODO: get ConstNode from .traverse() in the future
  23962. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  23963. return nodeObject( new UniformNode( value, nodeType ) );
  23964. };
  23965. addNodeClass( 'UniformNode', UniformNode );
  23966. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  23967. class TextureSizeNode extends Node {
  23968. constructor( textureNode, levelNode = null ) {
  23969. super( 'uvec2' );
  23970. this.isTextureSizeNode = true;
  23971. this.textureNode = textureNode;
  23972. this.levelNode = levelNode;
  23973. }
  23974. generate( builder, output ) {
  23975. const textureProperty = this.textureNode.build( builder, 'property' );
  23976. const levelNode = this.levelNode.build( builder, 'int' );
  23977. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ levelNode } )`, this.getNodeType( builder ), output );
  23978. }
  23979. }
  23980. const textureSize = nodeProxy( TextureSizeNode );
  23981. addNodeElement( 'textureSize', textureSize );
  23982. addNodeClass( 'TextureSizeNode', TextureSizeNode );
  23983. class OperatorNode extends TempNode {
  23984. constructor( op, aNode, bNode, ...params ) {
  23985. super();
  23986. if ( params.length > 0 ) {
  23987. let finalOp = new OperatorNode( op, aNode, bNode );
  23988. for ( let i = 0; i < params.length - 1; i ++ ) {
  23989. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  23990. }
  23991. aNode = finalOp;
  23992. bNode = params[ params.length - 1 ];
  23993. }
  23994. this.op = op;
  23995. this.aNode = aNode;
  23996. this.bNode = bNode;
  23997. }
  23998. getNodeType( builder, output ) {
  23999. const op = this.op;
  24000. const aNode = this.aNode;
  24001. const bNode = this.bNode;
  24002. const typeA = aNode.getNodeType( builder );
  24003. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  24004. if ( typeA === 'void' || typeB === 'void' ) {
  24005. return 'void';
  24006. } else if ( op === '%' ) {
  24007. return typeA;
  24008. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  24009. return builder.getIntegerType( typeA );
  24010. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  24011. return 'bool';
  24012. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  24013. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  24014. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  24015. } else {
  24016. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  24017. return typeB;
  24018. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  24019. // matrix x vector
  24020. return builder.getVectorFromMatrix( typeA );
  24021. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  24022. // vector x matrix
  24023. return builder.getVectorFromMatrix( typeB );
  24024. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  24025. // anytype x anytype: use the greater length vector
  24026. return typeB;
  24027. }
  24028. return typeA;
  24029. }
  24030. }
  24031. generate( builder, output ) {
  24032. const op = this.op;
  24033. const aNode = this.aNode;
  24034. const bNode = this.bNode;
  24035. const type = this.getNodeType( builder, output );
  24036. let typeA = null;
  24037. let typeB = null;
  24038. if ( type !== 'void' ) {
  24039. typeA = aNode.getNodeType( builder );
  24040. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  24041. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  24042. if ( builder.isVector( typeA ) ) {
  24043. typeB = typeA;
  24044. } else {
  24045. typeA = typeB = 'float';
  24046. }
  24047. } else if ( op === '>>' || op === '<<' ) {
  24048. typeA = type;
  24049. typeB = builder.changeComponentType( typeB, 'uint' );
  24050. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  24051. // matrix x vector
  24052. typeB = builder.getVectorFromMatrix( typeA );
  24053. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  24054. // vector x matrix
  24055. typeA = builder.getVectorFromMatrix( typeB );
  24056. } else {
  24057. // anytype x anytype
  24058. typeA = typeB = type;
  24059. }
  24060. } else {
  24061. typeA = typeB = type;
  24062. }
  24063. const a = aNode.build( builder, typeA );
  24064. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  24065. const outputLength = builder.getTypeLength( output );
  24066. const fnOpSnippet = builder.getFunctionOperator( op );
  24067. if ( output !== 'void' ) {
  24068. if ( op === '<' && outputLength > 1 ) {
  24069. return builder.format( `${ builder.getMethod( 'lessThan' ) }( ${ a }, ${ b } )`, type, output );
  24070. } else if ( op === '<=' && outputLength > 1 ) {
  24071. return builder.format( `${ builder.getMethod( 'lessThanEqual' ) }( ${ a }, ${ b } )`, type, output );
  24072. } else if ( op === '>' && outputLength > 1 ) {
  24073. return builder.format( `${ builder.getMethod( 'greaterThan' ) }( ${ a }, ${ b } )`, type, output );
  24074. } else if ( op === '>=' && outputLength > 1 ) {
  24075. return builder.format( `${ builder.getMethod( 'greaterThanEqual' ) }( ${ a }, ${ b } )`, type, output );
  24076. } else if ( op === '!' || op === '~' ) {
  24077. return builder.format( `(${op}${a})`, typeA, output );
  24078. } else if ( fnOpSnippet ) {
  24079. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  24080. } else {
  24081. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  24082. }
  24083. } else if ( typeA !== 'void' ) {
  24084. if ( fnOpSnippet ) {
  24085. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  24086. } else {
  24087. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  24088. }
  24089. }
  24090. }
  24091. serialize( data ) {
  24092. super.serialize( data );
  24093. data.op = this.op;
  24094. }
  24095. deserialize( data ) {
  24096. super.deserialize( data );
  24097. this.op = data.op;
  24098. }
  24099. }
  24100. const add = nodeProxy( OperatorNode, '+' );
  24101. const sub = nodeProxy( OperatorNode, '-' );
  24102. const mul = nodeProxy( OperatorNode, '*' );
  24103. const div = nodeProxy( OperatorNode, '/' );
  24104. const remainder = nodeProxy( OperatorNode, '%' );
  24105. const equal = nodeProxy( OperatorNode, '==' );
  24106. const notEqual = nodeProxy( OperatorNode, '!=' );
  24107. const lessThan = nodeProxy( OperatorNode, '<' );
  24108. const greaterThan = nodeProxy( OperatorNode, '>' );
  24109. const lessThanEqual = nodeProxy( OperatorNode, '<=' );
  24110. const greaterThanEqual = nodeProxy( OperatorNode, '>=' );
  24111. const and = nodeProxy( OperatorNode, '&&' );
  24112. const or = nodeProxy( OperatorNode, '||' );
  24113. const not = nodeProxy( OperatorNode, '!' );
  24114. const xor = nodeProxy( OperatorNode, '^^' );
  24115. const bitAnd = nodeProxy( OperatorNode, '&' );
  24116. const bitNot = nodeProxy( OperatorNode, '~' );
  24117. const bitOr = nodeProxy( OperatorNode, '|' );
  24118. const bitXor = nodeProxy( OperatorNode, '^' );
  24119. const shiftLeft = nodeProxy( OperatorNode, '<<' );
  24120. const shiftRight = nodeProxy( OperatorNode, '>>' );
  24121. addNodeElement( 'add', add );
  24122. addNodeElement( 'sub', sub );
  24123. addNodeElement( 'mul', mul );
  24124. addNodeElement( 'div', div );
  24125. addNodeElement( 'remainder', remainder );
  24126. addNodeElement( 'equal', equal );
  24127. addNodeElement( 'notEqual', notEqual );
  24128. addNodeElement( 'lessThan', lessThan );
  24129. addNodeElement( 'greaterThan', greaterThan );
  24130. addNodeElement( 'lessThanEqual', lessThanEqual );
  24131. addNodeElement( 'greaterThanEqual', greaterThanEqual );
  24132. addNodeElement( 'and', and );
  24133. addNodeElement( 'or', or );
  24134. addNodeElement( 'not', not );
  24135. addNodeElement( 'xor', xor );
  24136. addNodeElement( 'bitAnd', bitAnd );
  24137. addNodeElement( 'bitNot', bitNot );
  24138. addNodeElement( 'bitOr', bitOr );
  24139. addNodeElement( 'bitXor', bitXor );
  24140. addNodeElement( 'shiftLeft', shiftLeft );
  24141. addNodeElement( 'shiftRight', shiftRight );
  24142. addNodeClass( 'OperatorNode', OperatorNode );
  24143. class MathNode extends TempNode {
  24144. constructor( method, aNode, bNode = null, cNode = null ) {
  24145. super();
  24146. this.method = method;
  24147. this.aNode = aNode;
  24148. this.bNode = bNode;
  24149. this.cNode = cNode;
  24150. }
  24151. getInputType( builder ) {
  24152. const aType = this.aNode.getNodeType( builder );
  24153. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  24154. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  24155. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  24156. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  24157. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  24158. if ( aLen > bLen && aLen > cLen ) {
  24159. return aType;
  24160. } else if ( bLen > cLen ) {
  24161. return bType;
  24162. } else if ( cLen > aLen ) {
  24163. return cType;
  24164. }
  24165. return aType;
  24166. }
  24167. getNodeType( builder ) {
  24168. const method = this.method;
  24169. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  24170. return 'float';
  24171. } else if ( method === MathNode.CROSS ) {
  24172. return 'vec3';
  24173. } else if ( method === MathNode.ALL ) {
  24174. return 'bool';
  24175. } else if ( method === MathNode.EQUALS ) {
  24176. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  24177. } else if ( method === MathNode.MOD ) {
  24178. return this.aNode.getNodeType( builder );
  24179. } else {
  24180. return this.getInputType( builder );
  24181. }
  24182. }
  24183. generate( builder, output ) {
  24184. const method = this.method;
  24185. const type = this.getNodeType( builder );
  24186. const inputType = this.getInputType( builder );
  24187. const a = this.aNode;
  24188. const b = this.bNode;
  24189. const c = this.cNode;
  24190. const isWebGL = builder.renderer.isWebGLRenderer === true;
  24191. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  24192. // dir can be either a direction vector or a normal vector
  24193. // upper-left 3x3 of matrix is assumed to be orthogonal
  24194. let tA = a;
  24195. let tB = b;
  24196. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  24197. tB = vec4( vec3( tB ), 0.0 );
  24198. } else {
  24199. tA = vec4( vec3( tA ), 0.0 );
  24200. }
  24201. const mulNode = mul( tA, tB ).xyz;
  24202. return normalize( mulNode ).build( builder, output );
  24203. } else if ( method === MathNode.NEGATE ) {
  24204. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  24205. } else if ( method === MathNode.ONE_MINUS ) {
  24206. return sub( 1.0, a ).build( builder, output );
  24207. } else if ( method === MathNode.RECIPROCAL ) {
  24208. return div( 1.0, a ).build( builder, output );
  24209. } else if ( method === MathNode.DIFFERENCE ) {
  24210. return abs( sub( a, b ) ).build( builder, output );
  24211. } else {
  24212. const params = [];
  24213. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  24214. params.push(
  24215. a.build( builder, type ),
  24216. b.build( builder, type )
  24217. );
  24218. } else if ( method === MathNode.STEP ) {
  24219. params.push(
  24220. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  24221. b.build( builder, inputType )
  24222. );
  24223. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  24224. params.push(
  24225. a.build( builder, inputType ),
  24226. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  24227. );
  24228. } else if ( method === MathNode.REFRACT ) {
  24229. params.push(
  24230. a.build( builder, inputType ),
  24231. b.build( builder, inputType ),
  24232. c.build( builder, 'float' )
  24233. );
  24234. } else if ( method === MathNode.MIX ) {
  24235. params.push(
  24236. a.build( builder, inputType ),
  24237. b.build( builder, inputType ),
  24238. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  24239. );
  24240. } else {
  24241. params.push( a.build( builder, inputType ) );
  24242. if ( b !== null ) params.push( b.build( builder, inputType ) );
  24243. if ( c !== null ) params.push( c.build( builder, inputType ) );
  24244. }
  24245. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  24246. }
  24247. }
  24248. serialize( data ) {
  24249. super.serialize( data );
  24250. data.method = this.method;
  24251. }
  24252. deserialize( data ) {
  24253. super.deserialize( data );
  24254. this.method = data.method;
  24255. }
  24256. }
  24257. // 1 input
  24258. MathNode.ALL = 'all';
  24259. MathNode.ANY = 'any';
  24260. MathNode.EQUALS = 'equals';
  24261. MathNode.RADIANS = 'radians';
  24262. MathNode.DEGREES = 'degrees';
  24263. MathNode.EXP = 'exp';
  24264. MathNode.EXP2 = 'exp2';
  24265. MathNode.LOG = 'log';
  24266. MathNode.LOG2 = 'log2';
  24267. MathNode.SQRT = 'sqrt';
  24268. MathNode.INVERSE_SQRT = 'inversesqrt';
  24269. MathNode.FLOOR = 'floor';
  24270. MathNode.CEIL = 'ceil';
  24271. MathNode.NORMALIZE = 'normalize';
  24272. MathNode.FRACT = 'fract';
  24273. MathNode.SIN = 'sin';
  24274. MathNode.COS = 'cos';
  24275. MathNode.TAN = 'tan';
  24276. MathNode.ASIN = 'asin';
  24277. MathNode.ACOS = 'acos';
  24278. MathNode.ATAN = 'atan';
  24279. MathNode.ABS = 'abs';
  24280. MathNode.SIGN = 'sign';
  24281. MathNode.LENGTH = 'length';
  24282. MathNode.NEGATE = 'negate';
  24283. MathNode.ONE_MINUS = 'oneMinus';
  24284. MathNode.DFDX = 'dFdx';
  24285. MathNode.DFDY = 'dFdy';
  24286. MathNode.ROUND = 'round';
  24287. MathNode.RECIPROCAL = 'reciprocal';
  24288. MathNode.TRUNC = 'trunc';
  24289. MathNode.FWIDTH = 'fwidth';
  24290. MathNode.BITCAST = 'bitcast';
  24291. MathNode.TRANSPOSE = 'transpose';
  24292. // 2 inputs
  24293. MathNode.ATAN2 = 'atan2';
  24294. MathNode.MIN = 'min';
  24295. MathNode.MAX = 'max';
  24296. MathNode.MOD = 'mod';
  24297. MathNode.STEP = 'step';
  24298. MathNode.REFLECT = 'reflect';
  24299. MathNode.DISTANCE = 'distance';
  24300. MathNode.DIFFERENCE = 'difference';
  24301. MathNode.DOT = 'dot';
  24302. MathNode.CROSS = 'cross';
  24303. MathNode.POW = 'pow';
  24304. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  24305. // 3 inputs
  24306. MathNode.MIX = 'mix';
  24307. MathNode.CLAMP = 'clamp';
  24308. MathNode.REFRACT = 'refract';
  24309. MathNode.SMOOTHSTEP = 'smoothstep';
  24310. MathNode.FACEFORWARD = 'faceforward';
  24311. const EPSILON = float( 1e-6 );
  24312. const INFINITY = float( 1e6 );
  24313. const PI = float( Math.PI );
  24314. const PI2 = float( Math.PI * 2 );
  24315. const all = nodeProxy( MathNode, MathNode.ALL );
  24316. const any = nodeProxy( MathNode, MathNode.ANY );
  24317. const equals = nodeProxy( MathNode, MathNode.EQUALS );
  24318. const radians = nodeProxy( MathNode, MathNode.RADIANS );
  24319. const degrees = nodeProxy( MathNode, MathNode.DEGREES );
  24320. const exp = nodeProxy( MathNode, MathNode.EXP );
  24321. const exp2 = nodeProxy( MathNode, MathNode.EXP2 );
  24322. const log = nodeProxy( MathNode, MathNode.LOG );
  24323. const log2 = nodeProxy( MathNode, MathNode.LOG2 );
  24324. const sqrt = nodeProxy( MathNode, MathNode.SQRT );
  24325. const inverseSqrt = nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  24326. const floor = nodeProxy( MathNode, MathNode.FLOOR );
  24327. const ceil = nodeProxy( MathNode, MathNode.CEIL );
  24328. const normalize = nodeProxy( MathNode, MathNode.NORMALIZE );
  24329. const fract = nodeProxy( MathNode, MathNode.FRACT );
  24330. const sin = nodeProxy( MathNode, MathNode.SIN );
  24331. const cos = nodeProxy( MathNode, MathNode.COS );
  24332. const tan = nodeProxy( MathNode, MathNode.TAN );
  24333. const asin = nodeProxy( MathNode, MathNode.ASIN );
  24334. const acos = nodeProxy( MathNode, MathNode.ACOS );
  24335. const atan = nodeProxy( MathNode, MathNode.ATAN );
  24336. const abs = nodeProxy( MathNode, MathNode.ABS );
  24337. const sign = nodeProxy( MathNode, MathNode.SIGN );
  24338. const length = nodeProxy( MathNode, MathNode.LENGTH );
  24339. const negate = nodeProxy( MathNode, MathNode.NEGATE );
  24340. const oneMinus = nodeProxy( MathNode, MathNode.ONE_MINUS );
  24341. const dFdx = nodeProxy( MathNode, MathNode.DFDX );
  24342. const dFdy = nodeProxy( MathNode, MathNode.DFDY );
  24343. const round = nodeProxy( MathNode, MathNode.ROUND );
  24344. const reciprocal = nodeProxy( MathNode, MathNode.RECIPROCAL );
  24345. const trunc = nodeProxy( MathNode, MathNode.TRUNC );
  24346. const fwidth = nodeProxy( MathNode, MathNode.FWIDTH );
  24347. const bitcast = nodeProxy( MathNode, MathNode.BITCAST );
  24348. const transpose = nodeProxy( MathNode, MathNode.TRANSPOSE );
  24349. const atan2 = nodeProxy( MathNode, MathNode.ATAN2 );
  24350. const min$1 = nodeProxy( MathNode, MathNode.MIN );
  24351. const max$1 = nodeProxy( MathNode, MathNode.MAX );
  24352. const mod = nodeProxy( MathNode, MathNode.MOD );
  24353. const step = nodeProxy( MathNode, MathNode.STEP );
  24354. const reflect = nodeProxy( MathNode, MathNode.REFLECT );
  24355. const distance = nodeProxy( MathNode, MathNode.DISTANCE );
  24356. const difference = nodeProxy( MathNode, MathNode.DIFFERENCE );
  24357. const dot = nodeProxy( MathNode, MathNode.DOT );
  24358. const cross = nodeProxy( MathNode, MathNode.CROSS );
  24359. const pow = nodeProxy( MathNode, MathNode.POW );
  24360. const pow2 = nodeProxy( MathNode, MathNode.POW, 2 );
  24361. const pow3 = nodeProxy( MathNode, MathNode.POW, 3 );
  24362. const pow4 = nodeProxy( MathNode, MathNode.POW, 4 );
  24363. const transformDirection = nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  24364. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  24365. const lengthSq = ( a ) => dot( a, a );
  24366. const mix = nodeProxy( MathNode, MathNode.MIX );
  24367. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  24368. const saturate = ( value ) => clamp( value );
  24369. const refract = nodeProxy( MathNode, MathNode.REFRACT );
  24370. const smoothstep = nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  24371. const faceForward = nodeProxy( MathNode, MathNode.FACEFORWARD );
  24372. const rand = tslFn( ( [ uv ] ) => {
  24373. const a = 12.9898, b = 78.233, c = 43758.5453;
  24374. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  24375. return fract( sin( sn ).mul( c ) );
  24376. } );
  24377. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  24378. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  24379. addNodeElement( 'all', all );
  24380. addNodeElement( 'any', any );
  24381. addNodeElement( 'equals', equals );
  24382. addNodeElement( 'radians', radians );
  24383. addNodeElement( 'degrees', degrees );
  24384. addNodeElement( 'exp', exp );
  24385. addNodeElement( 'exp2', exp2 );
  24386. addNodeElement( 'log', log );
  24387. addNodeElement( 'log2', log2 );
  24388. addNodeElement( 'sqrt', sqrt );
  24389. addNodeElement( 'inverseSqrt', inverseSqrt );
  24390. addNodeElement( 'floor', floor );
  24391. addNodeElement( 'ceil', ceil );
  24392. addNodeElement( 'normalize', normalize );
  24393. addNodeElement( 'fract', fract );
  24394. addNodeElement( 'sin', sin );
  24395. addNodeElement( 'cos', cos );
  24396. addNodeElement( 'tan', tan );
  24397. addNodeElement( 'asin', asin );
  24398. addNodeElement( 'acos', acos );
  24399. addNodeElement( 'atan', atan );
  24400. addNodeElement( 'abs', abs );
  24401. addNodeElement( 'sign', sign );
  24402. addNodeElement( 'length', length );
  24403. addNodeElement( 'lengthSq', lengthSq );
  24404. addNodeElement( 'negate', negate );
  24405. addNodeElement( 'oneMinus', oneMinus );
  24406. addNodeElement( 'dFdx', dFdx );
  24407. addNodeElement( 'dFdy', dFdy );
  24408. addNodeElement( 'round', round );
  24409. addNodeElement( 'reciprocal', reciprocal );
  24410. addNodeElement( 'trunc', trunc );
  24411. addNodeElement( 'fwidth', fwidth );
  24412. addNodeElement( 'atan2', atan2 );
  24413. addNodeElement( 'min', min$1 );
  24414. addNodeElement( 'max', max$1 );
  24415. addNodeElement( 'mod', mod );
  24416. addNodeElement( 'step', step );
  24417. addNodeElement( 'reflect', reflect );
  24418. addNodeElement( 'distance', distance );
  24419. addNodeElement( 'dot', dot );
  24420. addNodeElement( 'cross', cross );
  24421. addNodeElement( 'pow', pow );
  24422. addNodeElement( 'pow2', pow2 );
  24423. addNodeElement( 'pow3', pow3 );
  24424. addNodeElement( 'pow4', pow4 );
  24425. addNodeElement( 'transformDirection', transformDirection );
  24426. addNodeElement( 'mix', mixElement );
  24427. addNodeElement( 'clamp', clamp );
  24428. addNodeElement( 'refract', refract );
  24429. addNodeElement( 'smoothstep', smoothstepElement );
  24430. addNodeElement( 'faceForward', faceForward );
  24431. addNodeElement( 'difference', difference );
  24432. addNodeElement( 'saturate', saturate );
  24433. addNodeElement( 'cbrt', cbrt );
  24434. addNodeElement( 'transpose', transpose );
  24435. addNodeElement( 'rand', rand );
  24436. addNodeClass( 'MathNode', MathNode );
  24437. const sRGBToLinearShader = tslFn( ( inputs ) => {
  24438. const { value } = inputs;
  24439. const { rgb } = value;
  24440. const a = rgb.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  24441. const b = rgb.mul( 0.0773993808 );
  24442. const factor = rgb.lessThanEqual( 0.04045 );
  24443. const rgbResult = mix( a, b, factor );
  24444. return vec4( rgbResult, value.a );
  24445. } );
  24446. const LinearTosRGBShader = tslFn( ( inputs ) => {
  24447. const { value } = inputs;
  24448. const { rgb } = value;
  24449. const a = rgb.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  24450. const b = rgb.mul( 12.92 );
  24451. const factor = rgb.lessThanEqual( 0.0031308 );
  24452. const rgbResult = mix( a, b, factor );
  24453. return vec4( rgbResult, value.a );
  24454. } );
  24455. const getColorSpaceMethod = ( colorSpace ) => {
  24456. let method = null;
  24457. if ( colorSpace === LinearSRGBColorSpace ) {
  24458. method = 'Linear';
  24459. } else if ( colorSpace === SRGBColorSpace ) {
  24460. method = 'sRGB';
  24461. }
  24462. return method;
  24463. };
  24464. const getMethod = ( source, target ) => {
  24465. return getColorSpaceMethod( source ) + 'To' + getColorSpaceMethod( target );
  24466. };
  24467. class ColorSpaceNode extends TempNode {
  24468. constructor( method, node ) {
  24469. super( 'vec4' );
  24470. this.method = method;
  24471. this.node = node;
  24472. }
  24473. setup() {
  24474. const { method, node } = this;
  24475. if ( method === ColorSpaceNode.LINEAR_TO_LINEAR )
  24476. return node;
  24477. return Methods[ method ]( { value: node } );
  24478. }
  24479. }
  24480. ColorSpaceNode.LINEAR_TO_LINEAR = 'LinearToLinear';
  24481. ColorSpaceNode.LINEAR_TO_sRGB = 'LinearTosRGB';
  24482. ColorSpaceNode.sRGB_TO_LINEAR = 'sRGBToLinear';
  24483. const Methods = {
  24484. [ ColorSpaceNode.LINEAR_TO_sRGB ]: LinearTosRGBShader,
  24485. [ ColorSpaceNode.sRGB_TO_LINEAR ]: sRGBToLinearShader
  24486. };
  24487. const linearToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( getMethod( LinearSRGBColorSpace, colorSpace ), nodeObject( node ) ) );
  24488. const colorSpaceToLinear = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( getMethod( colorSpace, LinearSRGBColorSpace ), nodeObject( node ) ) );
  24489. const linearTosRGB = nodeProxy( ColorSpaceNode, ColorSpaceNode.LINEAR_TO_sRGB );
  24490. const sRGBToLinear = nodeProxy( ColorSpaceNode, ColorSpaceNode.sRGB_TO_LINEAR );
  24491. addNodeElement( 'linearTosRGB', linearTosRGB );
  24492. addNodeElement( 'sRGBToLinear', sRGBToLinear );
  24493. addNodeElement( 'linearToColorSpace', linearToColorSpace );
  24494. addNodeElement( 'colorSpaceToLinear', colorSpaceToLinear );
  24495. addNodeClass( 'ColorSpaceNode', ColorSpaceNode );
  24496. class ExpressionNode extends Node {
  24497. constructor( snippet = '', nodeType = 'void' ) {
  24498. super( nodeType );
  24499. this.snippet = snippet;
  24500. }
  24501. generate( builder, output ) {
  24502. const type = this.getNodeType( builder );
  24503. const snippet = this.snippet;
  24504. if ( type === 'void' ) {
  24505. builder.addLineFlowCode( snippet );
  24506. } else {
  24507. return builder.format( `( ${ snippet } )`, type, output );
  24508. }
  24509. }
  24510. }
  24511. const expression = nodeProxy( ExpressionNode );
  24512. addNodeClass( 'ExpressionNode', ExpressionNode );
  24513. class MaxMipLevelNode extends UniformNode {
  24514. constructor( textureNode ) {
  24515. super( 0 );
  24516. this.textureNode = textureNode;
  24517. this.updateType = NodeUpdateType.FRAME;
  24518. }
  24519. get texture() {
  24520. return this.textureNode.value;
  24521. }
  24522. update() {
  24523. const texture = this.texture;
  24524. const images = texture.images;
  24525. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  24526. if ( image && image.width !== undefined ) {
  24527. const { width, height } = image;
  24528. this.value = Math.log2( Math.max( width, height ) );
  24529. }
  24530. }
  24531. }
  24532. const maxMipLevel = nodeProxy( MaxMipLevelNode );
  24533. addNodeClass( 'MaxMipLevelNode', MaxMipLevelNode );
  24534. class TextureNode extends UniformNode {
  24535. constructor( value, uvNode = null, levelNode = null ) {
  24536. super( value );
  24537. this.isTextureNode = true;
  24538. this.uvNode = uvNode;
  24539. this.levelNode = levelNode;
  24540. this.compareNode = null;
  24541. this.depthNode = null;
  24542. this.gradNode = null;
  24543. this.sampler = true;
  24544. this.updateMatrix = false;
  24545. this.updateType = NodeUpdateType.NONE;
  24546. this.referenceNode = null;
  24547. this._value = value;
  24548. this.setUpdateMatrix( uvNode === null );
  24549. }
  24550. set value( value ) {
  24551. if ( this.referenceNode ) {
  24552. this.referenceNode.value = value;
  24553. } else {
  24554. this._value = value;
  24555. }
  24556. }
  24557. get value() {
  24558. return this.referenceNode ? this.referenceNode.value : this._value;
  24559. }
  24560. getUniformHash( /*builder*/ ) {
  24561. return this.value.uuid;
  24562. }
  24563. getNodeType( /*builder*/ ) {
  24564. if ( this.value.isDepthTexture === true ) return 'float';
  24565. if ( this.value.type === UnsignedIntType ) {
  24566. return 'uvec4';
  24567. } else if ( this.value.type === IntType ) {
  24568. return 'ivec4';
  24569. }
  24570. return 'vec4';
  24571. }
  24572. getInputType( /*builder*/ ) {
  24573. return 'texture';
  24574. }
  24575. getDefaultUV() {
  24576. return uv( this.value.channel );
  24577. }
  24578. updateReference( /*state*/ ) {
  24579. return this.value;
  24580. }
  24581. getTransformedUV( uvNode ) {
  24582. const texture = this.value;
  24583. return uniform( texture.matrix ).mul( vec3( uvNode, 1 ) ).xy;
  24584. }
  24585. setUpdateMatrix( value ) {
  24586. this.updateMatrix = value;
  24587. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  24588. return this;
  24589. }
  24590. setupUV( builder, uvNode ) {
  24591. const texture = this.value;
  24592. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  24593. uvNode = uvNode.setY( uvNode.y.oneMinus() );
  24594. }
  24595. return uvNode;
  24596. }
  24597. setup( builder ) {
  24598. const properties = builder.getNodeProperties( this );
  24599. properties.referenceNode = this.referenceNode;
  24600. //
  24601. let uvNode = this.uvNode;
  24602. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  24603. uvNode = builder.context.getUV( this );
  24604. }
  24605. if ( ! uvNode ) uvNode = this.getDefaultUV();
  24606. if ( this.updateMatrix === true ) {
  24607. uvNode = this.getTransformedUV( uvNode );
  24608. }
  24609. uvNode = this.setupUV( builder, uvNode );
  24610. //
  24611. let levelNode = this.levelNode;
  24612. if ( levelNode === null && builder.context.getTextureLevel ) {
  24613. levelNode = builder.context.getTextureLevel( this );
  24614. }
  24615. //
  24616. properties.uvNode = uvNode;
  24617. properties.levelNode = levelNode;
  24618. properties.compareNode = this.compareNode;
  24619. properties.gradNode = this.gradNode;
  24620. properties.depthNode = this.depthNode;
  24621. }
  24622. generateUV( builder, uvNode ) {
  24623. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  24624. }
  24625. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  24626. const texture = this.value;
  24627. let snippet;
  24628. if ( levelSnippet ) {
  24629. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  24630. } else if ( gradSnippet ) {
  24631. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  24632. } else if ( compareSnippet ) {
  24633. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  24634. } else if ( this.sampler === false ) {
  24635. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  24636. } else {
  24637. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  24638. }
  24639. return snippet;
  24640. }
  24641. generate( builder, output ) {
  24642. const properties = builder.getNodeProperties( this );
  24643. const texture = this.value;
  24644. if ( ! texture || texture.isTexture !== true ) {
  24645. throw new Error( 'TextureNode: Need a three.js texture.' );
  24646. }
  24647. const textureProperty = super.generate( builder, 'property' );
  24648. if ( output === 'sampler' ) {
  24649. return textureProperty + '_sampler';
  24650. } else if ( builder.isReference( output ) ) {
  24651. return textureProperty;
  24652. } else {
  24653. const nodeData = builder.getDataFromNode( this );
  24654. let propertyName = nodeData.propertyName;
  24655. if ( propertyName === undefined ) {
  24656. const { uvNode, levelNode, compareNode, depthNode, gradNode } = properties;
  24657. const uvSnippet = this.generateUV( builder, uvNode );
  24658. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  24659. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  24660. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  24661. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  24662. const nodeVar = builder.getVarFromNode( this );
  24663. propertyName = builder.getPropertyName( nodeVar );
  24664. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, depthSnippet, compareSnippet, gradSnippet );
  24665. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  24666. nodeData.snippet = snippet;
  24667. nodeData.propertyName = propertyName;
  24668. }
  24669. let snippet = propertyName;
  24670. const nodeType = this.getNodeType( builder );
  24671. if ( builder.needsColorSpaceToLinear( texture ) ) {
  24672. snippet = colorSpaceToLinear( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  24673. }
  24674. return builder.format( snippet, nodeType, output );
  24675. }
  24676. }
  24677. setSampler( value ) {
  24678. this.sampler = value;
  24679. return this;
  24680. }
  24681. getSampler() {
  24682. return this.sampler;
  24683. }
  24684. // @TODO: Move to TSL
  24685. uv( uvNode ) {
  24686. const textureNode = this.clone();
  24687. textureNode.uvNode = uvNode;
  24688. textureNode.referenceNode = this;
  24689. return nodeObject( textureNode );
  24690. }
  24691. blur( levelNode ) {
  24692. const textureNode = this.clone();
  24693. textureNode.levelNode = levelNode.mul( maxMipLevel( textureNode ) );
  24694. textureNode.referenceNode = this;
  24695. return nodeObject( textureNode );
  24696. }
  24697. level( levelNode ) {
  24698. const textureNode = this.clone();
  24699. textureNode.levelNode = levelNode;
  24700. textureNode.referenceNode = this;
  24701. return textureNode;
  24702. }
  24703. size( levelNode ) {
  24704. return textureSize( this, levelNode );
  24705. }
  24706. compare( compareNode ) {
  24707. const textureNode = this.clone();
  24708. textureNode.compareNode = nodeObject( compareNode );
  24709. textureNode.referenceNode = this;
  24710. return nodeObject( textureNode );
  24711. }
  24712. grad( gradNodeX, gradNodeY ) {
  24713. const textureNode = this.clone();
  24714. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  24715. textureNode.referenceNode = this;
  24716. return nodeObject( textureNode );
  24717. }
  24718. depth( depthNode ) {
  24719. const textureNode = this.clone();
  24720. textureNode.depthNode = nodeObject( depthNode );
  24721. textureNode.referenceNode = this;
  24722. return nodeObject( textureNode );
  24723. }
  24724. // --
  24725. serialize( data ) {
  24726. super.serialize( data );
  24727. data.value = this.value.toJSON( data.meta ).uuid;
  24728. }
  24729. deserialize( data ) {
  24730. super.deserialize( data );
  24731. this.value = data.meta.textures[ data.value ];
  24732. }
  24733. update() {
  24734. const texture = this.value;
  24735. if ( texture.matrixAutoUpdate === true ) {
  24736. texture.updateMatrix();
  24737. }
  24738. }
  24739. clone() {
  24740. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode );
  24741. newNode.sampler = this.sampler;
  24742. return newNode;
  24743. }
  24744. }
  24745. const texture = nodeProxy( TextureNode );
  24746. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  24747. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  24748. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  24749. addNodeElement( 'texture', texture );
  24750. //addNodeElement( 'textureLevel', textureLevel );
  24751. addNodeClass( 'TextureNode', TextureNode );
  24752. class BufferNode extends UniformNode {
  24753. constructor( value, bufferType, bufferCount = 0 ) {
  24754. super( value, bufferType );
  24755. this.isBufferNode = true;
  24756. this.bufferType = bufferType;
  24757. this.bufferCount = bufferCount;
  24758. }
  24759. getElementType( builder ) {
  24760. return this.getNodeType( builder );
  24761. }
  24762. getInputType( /*builder*/ ) {
  24763. return 'buffer';
  24764. }
  24765. }
  24766. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  24767. addNodeClass( 'BufferNode', BufferNode );
  24768. class UniformsElementNode extends ArrayElementNode {
  24769. constructor( arrayBuffer, indexNode ) {
  24770. super( arrayBuffer, indexNode );
  24771. this.isArrayBufferElementNode = true;
  24772. }
  24773. getNodeType( builder ) {
  24774. return this.node.getElementType( builder );
  24775. }
  24776. generate( builder ) {
  24777. const snippet = super.generate( builder );
  24778. const type = this.getNodeType();
  24779. return builder.format( snippet, 'vec4', type );
  24780. }
  24781. }
  24782. class UniformsNode extends BufferNode {
  24783. constructor( value, elementType = null ) {
  24784. super( null, 'vec4' );
  24785. this.array = value;
  24786. this.elementType = elementType;
  24787. this._elementType = null;
  24788. this._elementLength = 0;
  24789. this.updateType = NodeUpdateType.RENDER;
  24790. this.isArrayBufferNode = true;
  24791. }
  24792. getElementType() {
  24793. return this.elementType || this._elementType;
  24794. }
  24795. getElementLength() {
  24796. return this._elementLength;
  24797. }
  24798. update( /*frame*/ ) {
  24799. const { array, value } = this;
  24800. const elementLength = this.getElementLength();
  24801. const elementType = this.getElementType();
  24802. if ( elementLength === 1 ) {
  24803. for ( let i = 0; i < array.length; i ++ ) {
  24804. const index = i * 4;
  24805. value[ index ] = array[ i ];
  24806. }
  24807. } else if ( elementType === 'color' ) {
  24808. for ( let i = 0; i < array.length; i ++ ) {
  24809. const index = i * 4;
  24810. const vector = array[ i ];
  24811. value[ index ] = vector.r;
  24812. value[ index + 1 ] = vector.g;
  24813. value[ index + 2 ] = vector.b || 0;
  24814. //value[ index + 3 ] = vector.a || 0;
  24815. }
  24816. } else {
  24817. for ( let i = 0; i < array.length; i ++ ) {
  24818. const index = i * 4;
  24819. const vector = array[ i ];
  24820. value[ index ] = vector.x;
  24821. value[ index + 1 ] = vector.y;
  24822. value[ index + 2 ] = vector.z || 0;
  24823. value[ index + 3 ] = vector.w || 0;
  24824. }
  24825. }
  24826. }
  24827. setup( builder ) {
  24828. const length = this.array.length;
  24829. this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType;
  24830. this._elementLength = builder.getTypeLength( this._elementType );
  24831. let arrayType = Float32Array;
  24832. if ( this._elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  24833. else if ( this._elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  24834. this.value = new arrayType( length * 4 );
  24835. this.bufferCount = length;
  24836. this.bufferType = builder.changeComponentType( 'vec4', builder.getComponentType( this._elementType ) );
  24837. return super.setup( builder );
  24838. }
  24839. element( indexNode ) {
  24840. return nodeObject( new UniformsElementNode( this, nodeObject( indexNode ) ) );
  24841. }
  24842. }
  24843. const uniforms = ( values, nodeType ) => nodeObject( new UniformsNode( values, nodeType ) );
  24844. addNodeClass( 'UniformsNode', UniformsNode );
  24845. class ReferenceElementNode extends ArrayElementNode {
  24846. constructor( referenceNode, indexNode ) {
  24847. super( referenceNode, indexNode );
  24848. this.referenceNode = referenceNode;
  24849. this.isReferenceElementNode = true;
  24850. }
  24851. getNodeType() {
  24852. return this.referenceNode.uniformType;
  24853. }
  24854. generate( builder ) {
  24855. const snippet = super.generate( builder );
  24856. const arrayType = this.referenceNode.getNodeType();
  24857. const elementType = this.getNodeType();
  24858. return builder.format( snippet, arrayType, elementType );
  24859. }
  24860. }
  24861. class ReferenceNode extends Node {
  24862. constructor( property, uniformType, object = null, count = null ) {
  24863. super();
  24864. this.property = property;
  24865. this.uniformType = uniformType;
  24866. this.object = object;
  24867. this.count = count;
  24868. this.properties = property.split( '.' );
  24869. this.reference = null;
  24870. this.node = null;
  24871. this.updateType = NodeUpdateType.OBJECT;
  24872. }
  24873. element( indexNode ) {
  24874. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  24875. }
  24876. setNodeType( uniformType ) {
  24877. let node = null;
  24878. if ( this.count !== null ) {
  24879. node = buffer( null, uniformType, this.count );
  24880. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  24881. node = uniforms( null, uniformType );
  24882. } else if ( uniformType === 'texture' ) {
  24883. node = texture( null );
  24884. } else {
  24885. node = uniform( null, uniformType );
  24886. }
  24887. this.node = node;
  24888. }
  24889. getNodeType( builder ) {
  24890. if ( this.node === null ) {
  24891. this.updateValue();
  24892. }
  24893. return this.node.getNodeType( builder );
  24894. }
  24895. getValueFromReference( object = this.reference ) {
  24896. const { properties } = this;
  24897. let value = object[ properties[ 0 ] ];
  24898. for ( let i = 1; i < properties.length; i ++ ) {
  24899. value = value[ properties[ i ] ];
  24900. }
  24901. return value;
  24902. }
  24903. updateReference( state ) {
  24904. this.reference = this.object !== null ? this.object : state.object;
  24905. return this.reference;
  24906. }
  24907. setup() {
  24908. this.updateValue();
  24909. return this.node;
  24910. }
  24911. update( /*frame*/ ) {
  24912. this.updateValue();
  24913. }
  24914. updateValue() {
  24915. if ( this.node === null ) this.setNodeType( this.uniformType );
  24916. const value = this.getValueFromReference();
  24917. if ( Array.isArray( value ) ) {
  24918. this.node.array = value;
  24919. } else {
  24920. this.node.value = value;
  24921. }
  24922. }
  24923. }
  24924. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  24925. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  24926. addNodeClass( 'ReferenceNode', ReferenceNode );
  24927. class MaterialReferenceNode extends ReferenceNode {
  24928. constructor( property, inputType, material = null ) {
  24929. super( property, inputType, material );
  24930. this.material = material;
  24931. //this.updateType = NodeUpdateType.RENDER;
  24932. }
  24933. /*setNodeType( node ) {
  24934. super.setNodeType( node );
  24935. this.node.groupNode = renderGroup;
  24936. }*/
  24937. updateReference( state ) {
  24938. this.reference = this.material !== null ? this.material : state.material;
  24939. return this.reference;
  24940. }
  24941. }
  24942. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  24943. addNodeClass( 'MaterialReferenceNode', MaterialReferenceNode );
  24944. const cameraGroup = /*#__PURE__*/ sharedUniformGroup( 'camera' ).onRenderUpdate( () => {
  24945. cameraGroup.needsUpdate = true;
  24946. } );
  24947. const cameraNear = /*#__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  24948. const cameraFar = /*#__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  24949. const cameraLogDepth = /*#__PURE__*/ uniform( 'float' ).label( 'cameraLogDepth' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  24950. const cameraProjectionMatrix = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  24951. const cameraProjectionMatrixInverse = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  24952. const cameraViewMatrix = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  24953. const cameraWorldMatrix = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  24954. const cameraNormalMatrix = /*#__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  24955. const cameraPosition = /*#__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  24956. class Object3DNode extends Node {
  24957. constructor( scope = Object3DNode.VIEW_MATRIX, object3d = null ) {
  24958. super();
  24959. this.scope = scope;
  24960. this.object3d = object3d;
  24961. this.updateType = NodeUpdateType.OBJECT;
  24962. this._uniformNode = new UniformNode( null );
  24963. }
  24964. getNodeType() {
  24965. const scope = this.scope;
  24966. if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) {
  24967. return 'mat4';
  24968. } else if ( scope === Object3DNode.NORMAL_MATRIX ) {
  24969. return 'mat3';
  24970. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  24971. return 'vec3';
  24972. }
  24973. }
  24974. update( frame ) {
  24975. const object = this.object3d;
  24976. const uniformNode = this._uniformNode;
  24977. const scope = this.scope;
  24978. if ( scope === Object3DNode.VIEW_MATRIX ) {
  24979. uniformNode.value = object.modelViewMatrix;
  24980. } else if ( scope === Object3DNode.NORMAL_MATRIX ) {
  24981. uniformNode.value = object.normalMatrix;
  24982. } else if ( scope === Object3DNode.WORLD_MATRIX ) {
  24983. uniformNode.value = object.matrixWorld;
  24984. } else if ( scope === Object3DNode.POSITION ) {
  24985. uniformNode.value = uniformNode.value || new Vector3();
  24986. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  24987. } else if ( scope === Object3DNode.SCALE ) {
  24988. uniformNode.value = uniformNode.value || new Vector3();
  24989. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  24990. } else if ( scope === Object3DNode.DIRECTION ) {
  24991. uniformNode.value = uniformNode.value || new Vector3();
  24992. object.getWorldDirection( uniformNode.value );
  24993. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  24994. const camera = frame.camera;
  24995. uniformNode.value = uniformNode.value || new Vector3();
  24996. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  24997. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  24998. }
  24999. }
  25000. generate( builder ) {
  25001. const scope = this.scope;
  25002. if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) {
  25003. this._uniformNode.nodeType = 'mat4';
  25004. } else if ( scope === Object3DNode.NORMAL_MATRIX ) {
  25005. this._uniformNode.nodeType = 'mat3';
  25006. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  25007. this._uniformNode.nodeType = 'vec3';
  25008. }
  25009. return this._uniformNode.build( builder );
  25010. }
  25011. serialize( data ) {
  25012. super.serialize( data );
  25013. data.scope = this.scope;
  25014. }
  25015. deserialize( data ) {
  25016. super.deserialize( data );
  25017. this.scope = data.scope;
  25018. }
  25019. }
  25020. Object3DNode.VIEW_MATRIX = 'viewMatrix';
  25021. Object3DNode.NORMAL_MATRIX = 'normalMatrix';
  25022. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  25023. Object3DNode.POSITION = 'position';
  25024. Object3DNode.SCALE = 'scale';
  25025. Object3DNode.VIEW_POSITION = 'viewPosition';
  25026. Object3DNode.DIRECTION = 'direction';
  25027. const objectDirection = nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  25028. const objectViewMatrix = nodeProxy( Object3DNode, Object3DNode.VIEW_MATRIX );
  25029. const objectNormalMatrix = nodeProxy( Object3DNode, Object3DNode.NORMAL_MATRIX );
  25030. const objectWorldMatrix = nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  25031. const objectPosition = nodeProxy( Object3DNode, Object3DNode.POSITION );
  25032. const objectScale = nodeProxy( Object3DNode, Object3DNode.SCALE );
  25033. const objectViewPosition = nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  25034. addNodeClass( 'Object3DNode', Object3DNode );
  25035. class ModelNode extends Object3DNode {
  25036. constructor( scope = ModelNode.VIEW_MATRIX ) {
  25037. super( scope );
  25038. }
  25039. update( frame ) {
  25040. this.object3d = frame.object;
  25041. super.update( frame );
  25042. }
  25043. }
  25044. const modelDirection = nodeImmutable( ModelNode, ModelNode.DIRECTION );
  25045. const modelViewMatrix = nodeImmutable( ModelNode, ModelNode.VIEW_MATRIX ).label( 'modelViewMatrix' ).temp( 'ModelViewMatrix' );
  25046. const modelNormalMatrix = nodeImmutable( ModelNode, ModelNode.NORMAL_MATRIX );
  25047. const modelWorldMatrix = nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  25048. const modelPosition = nodeImmutable( ModelNode, ModelNode.POSITION );
  25049. const modelScale = nodeImmutable( ModelNode, ModelNode.SCALE );
  25050. const modelViewPosition = nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  25051. const modelWorldMatrixInverse = uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  25052. addNodeClass( 'ModelNode', ModelNode );
  25053. const normalGeometry = /*#__PURE__*/ attribute( 'normal', 'vec3', vec3( 0, 1, 0 ) );
  25054. const normalLocal = /*#__PURE__*/ normalGeometry.toVar( 'normalLocal' );
  25055. const normalView = /*#__PURE__*/ varying( modelNormalMatrix.mul( normalLocal ), 'v_normalView' ).normalize().toVar( 'normalView' );
  25056. const normalWorld = /*#__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'transformedNormalWorld' );
  25057. const transformedNormalView = /*#__PURE__*/ property( 'vec3', 'transformedNormalView' );
  25058. const transformedNormalWorld = /*#__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedNormalWorld' );
  25059. const transformedClearcoatNormalView = /*#__PURE__*/ property( 'vec3', 'transformedClearcoatNormalView' );
  25060. const _propertyCache = new Map();
  25061. class MaterialNode extends Node {
  25062. constructor( scope ) {
  25063. super();
  25064. this.scope = scope;
  25065. }
  25066. getCache( property, type ) {
  25067. let node = _propertyCache.get( property );
  25068. if ( node === undefined ) {
  25069. node = materialReference( property, type );
  25070. _propertyCache.set( property, node );
  25071. }
  25072. return node;
  25073. }
  25074. getFloat( property ) {
  25075. return this.getCache( property, 'float' );
  25076. }
  25077. getColor( property ) {
  25078. return this.getCache( property, 'color' );
  25079. }
  25080. getTexture( property ) {
  25081. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  25082. }
  25083. setup( builder ) {
  25084. const material = builder.context.material;
  25085. const scope = this.scope;
  25086. let node = null;
  25087. if ( scope === MaterialNode.COLOR ) {
  25088. const colorNode = this.getColor( scope );
  25089. if ( material.map && material.map.isTexture === true ) {
  25090. node = colorNode.mul( this.getTexture( 'map' ) );
  25091. } else {
  25092. node = colorNode;
  25093. }
  25094. } else if ( scope === MaterialNode.OPACITY ) {
  25095. const opacityNode = this.getFloat( scope );
  25096. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  25097. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  25098. } else {
  25099. node = opacityNode;
  25100. }
  25101. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  25102. if ( material.specularMap && material.specularMap.isTexture === true ) {
  25103. node = this.getTexture( 'specular' ).r;
  25104. } else {
  25105. node = float( 1 );
  25106. }
  25107. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  25108. const specularIntensity = this.getFloat( scope );
  25109. if ( material.specularMap ) {
  25110. node = specularIntensity.mul( this.getTexture( scope ).a );
  25111. } else {
  25112. node = specularIntensity;
  25113. }
  25114. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  25115. const specularColorNode = this.getColor( scope );
  25116. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  25117. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  25118. } else {
  25119. node = specularColorNode;
  25120. }
  25121. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  25122. const roughnessNode = this.getFloat( scope );
  25123. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  25124. node = roughnessNode.mul( this.getTexture( scope ).g );
  25125. } else {
  25126. node = roughnessNode;
  25127. }
  25128. } else if ( scope === MaterialNode.METALNESS ) {
  25129. const metalnessNode = this.getFloat( scope );
  25130. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  25131. node = metalnessNode.mul( this.getTexture( scope ).b );
  25132. } else {
  25133. node = metalnessNode;
  25134. }
  25135. } else if ( scope === MaterialNode.EMISSIVE ) {
  25136. const emissiveNode = this.getColor( scope );
  25137. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  25138. node = emissiveNode.mul( this.getTexture( scope ) );
  25139. } else {
  25140. node = emissiveNode;
  25141. }
  25142. } else if ( scope === MaterialNode.NORMAL ) {
  25143. if ( material.normalMap ) {
  25144. node = this.getTexture( 'normal' ).normalMap( this.getCache( 'normalScale', 'vec2' ) );
  25145. } else if ( material.bumpMap ) {
  25146. node = this.getTexture( 'bump' ).r.bumpMap( this.getFloat( 'bumpScale' ) );
  25147. } else {
  25148. node = normalView;
  25149. }
  25150. } else if ( scope === MaterialNode.CLEARCOAT ) {
  25151. const clearcoatNode = this.getFloat( scope );
  25152. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  25153. node = clearcoatNode.mul( this.getTexture( scope ).r );
  25154. } else {
  25155. node = clearcoatNode;
  25156. }
  25157. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  25158. const clearcoatRoughnessNode = this.getFloat( scope );
  25159. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  25160. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  25161. } else {
  25162. node = clearcoatRoughnessNode;
  25163. }
  25164. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  25165. if ( material.clearcoatNormalMap ) {
  25166. node = this.getTexture( scope ).normalMap( this.getCache( scope + 'Scale', 'vec2' ) );
  25167. } else {
  25168. node = normalView;
  25169. }
  25170. } else if ( scope === MaterialNode.SHEEN ) {
  25171. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  25172. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  25173. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  25174. } else {
  25175. node = sheenNode;
  25176. }
  25177. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  25178. const sheenRoughnessNode = this.getFloat( scope );
  25179. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  25180. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  25181. } else {
  25182. node = sheenRoughnessNode;
  25183. }
  25184. node = node.clamp( 0.07, 1.0 );
  25185. } else if ( scope === MaterialNode.ANISOTROPY ) {
  25186. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  25187. const anisotropyPolar = this.getTexture( scope );
  25188. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  25189. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  25190. } else {
  25191. node = materialAnisotropyVector;
  25192. }
  25193. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  25194. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  25195. if ( material.iridescenceThicknessMap ) {
  25196. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  25197. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  25198. } else {
  25199. node = iridescenceThicknessMaximum;
  25200. }
  25201. } else if ( scope === MaterialNode.TRANSMISSION ) {
  25202. const transmissionNode = this.getFloat( scope );
  25203. if ( material.transmissionMap ) {
  25204. node = transmissionNode.mul( this.getTexture( scope ).r );
  25205. } else {
  25206. node = transmissionNode;
  25207. }
  25208. } else if ( scope === MaterialNode.THICKNESS ) {
  25209. const thicknessNode = this.getFloat( scope );
  25210. if ( material.thicknessMap ) {
  25211. node = thicknessNode.mul( this.getTexture( scope ).g );
  25212. } else {
  25213. node = thicknessNode;
  25214. }
  25215. } else if ( scope === MaterialNode.IOR ) {
  25216. node = this.getFloat( scope );
  25217. } else {
  25218. const outputType = this.getNodeType( builder );
  25219. node = this.getCache( scope, outputType );
  25220. }
  25221. return node;
  25222. }
  25223. }
  25224. MaterialNode.ALPHA_TEST = 'alphaTest';
  25225. MaterialNode.COLOR = 'color';
  25226. MaterialNode.OPACITY = 'opacity';
  25227. MaterialNode.SHININESS = 'shininess';
  25228. MaterialNode.SPECULAR = 'specular';
  25229. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  25230. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  25231. MaterialNode.SPECULAR_COLOR = 'specularColor';
  25232. MaterialNode.REFLECTIVITY = 'reflectivity';
  25233. MaterialNode.ROUGHNESS = 'roughness';
  25234. MaterialNode.METALNESS = 'metalness';
  25235. MaterialNode.NORMAL = 'normal';
  25236. MaterialNode.CLEARCOAT = 'clearcoat';
  25237. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  25238. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  25239. MaterialNode.EMISSIVE = 'emissive';
  25240. MaterialNode.ROTATION = 'rotation';
  25241. MaterialNode.SHEEN = 'sheen';
  25242. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  25243. MaterialNode.ANISOTROPY = 'anisotropy';
  25244. MaterialNode.IRIDESCENCE = 'iridescence';
  25245. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  25246. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  25247. MaterialNode.IOR = 'ior';
  25248. MaterialNode.TRANSMISSION = 'transmission';
  25249. MaterialNode.THICKNESS = 'thickness';
  25250. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  25251. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  25252. MaterialNode.LINE_SCALE = 'scale';
  25253. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  25254. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  25255. MaterialNode.LINE_WIDTH = 'linewidth';
  25256. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  25257. MaterialNode.POINT_WIDTH = 'pointWidth';
  25258. MaterialNode.DISPERSION = 'dispersion';
  25259. const materialAlphaTest = nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  25260. const materialColor = nodeImmutable( MaterialNode, MaterialNode.COLOR );
  25261. const materialShininess = nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  25262. const materialEmissive = nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  25263. const materialOpacity = nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  25264. const materialSpecular = nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  25265. const materialSpecularIntensity = nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  25266. const materialSpecularColor = nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  25267. const materialSpecularStrength = nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  25268. const materialReflectivity = nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  25269. const materialRoughness = nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  25270. const materialMetalness = nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  25271. const materialNormal = nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  25272. const materialClearcoat = nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  25273. const materialClearcoatRoughness = nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  25274. const materialClearcoatNormal = nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  25275. const materialRotation = nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  25276. const materialSheen = nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  25277. const materialSheenRoughness = nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  25278. const materialAnisotropy = nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  25279. const materialIridescence = nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  25280. const materialIridescenceIOR = nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  25281. const materialIridescenceThickness = nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  25282. const materialTransmission = nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  25283. const materialThickness = nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  25284. const materialIOR = nodeImmutable( MaterialNode, MaterialNode.IOR );
  25285. const materialAttenuationDistance = nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  25286. const materialAttenuationColor = nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  25287. const materialLineScale = nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  25288. const materialLineDashSize = nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  25289. const materialLineGapSize = nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  25290. const materialLineWidth = nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  25291. const materialLineDashOffset = nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  25292. const materialPointWidth = nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  25293. const materialDispersion = nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  25294. const materialAnisotropyVector = uniform( new Vector2() ).onReference( function ( frame ) {
  25295. return frame.material;
  25296. } ).onRenderUpdate( function ( { material } ) {
  25297. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  25298. } );
  25299. addNodeClass( 'MaterialNode', MaterialNode );
  25300. const positionGeometry = /*#__PURE__*/ attribute( 'position', 'vec3' );
  25301. const positionLocal = /*#__PURE__*/ positionGeometry.toVar( 'positionLocal' );
  25302. const positionWorld = /*#__PURE__*/ varying( modelWorldMatrix.mul( positionLocal ).xyz, 'v_positionWorld' );
  25303. const positionWorldDirection = /*#__PURE__*/ varying( positionLocal.transformDirection( modelWorldMatrix ), 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  25304. const positionView = /*#__PURE__*/ varying( modelViewMatrix.mul( positionLocal ).xyz, 'v_positionView' );
  25305. const positionViewDirection = /*#__PURE__*/ varying( positionView.negate(), 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  25306. class ModelViewProjectionNode extends TempNode {
  25307. constructor( positionNode = null ) {
  25308. super( 'vec4' );
  25309. this.positionNode = positionNode;
  25310. }
  25311. setup( builder ) {
  25312. if ( builder.shaderStage === 'fragment' ) {
  25313. return varying( builder.context.mvp );
  25314. }
  25315. const position = this.positionNode || positionLocal;
  25316. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( position );
  25317. }
  25318. }
  25319. const modelViewProjection = nodeProxy( ModelViewProjectionNode );
  25320. addNodeClass( 'ModelViewProjectionNode', ModelViewProjectionNode );
  25321. class BufferAttributeNode extends InputNode {
  25322. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  25323. super( value, bufferType );
  25324. this.isBufferNode = true;
  25325. this.bufferType = bufferType;
  25326. this.bufferStride = bufferStride;
  25327. this.bufferOffset = bufferOffset;
  25328. this.usage = StaticDrawUsage;
  25329. this.instanced = false;
  25330. this.attribute = null;
  25331. this.global = true;
  25332. if ( value && value.isBufferAttribute === true ) {
  25333. this.attribute = value;
  25334. this.usage = value.usage;
  25335. this.instanced = value.isInstancedBufferAttribute;
  25336. }
  25337. }
  25338. getHash( builder ) {
  25339. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  25340. let bufferData = builder.globalCache.getData( this.value );
  25341. if ( bufferData === undefined ) {
  25342. bufferData = {
  25343. node: this
  25344. };
  25345. builder.globalCache.setData( this.value, bufferData );
  25346. }
  25347. return bufferData.node.uuid;
  25348. }
  25349. return this.uuid;
  25350. }
  25351. getNodeType( builder ) {
  25352. if ( this.bufferType === null ) {
  25353. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  25354. }
  25355. return this.bufferType;
  25356. }
  25357. setup( builder ) {
  25358. if ( this.attribute !== null ) return;
  25359. const type = this.getNodeType( builder );
  25360. const array = this.value;
  25361. const itemSize = builder.getTypeLength( type );
  25362. const stride = this.bufferStride || itemSize;
  25363. const offset = this.bufferOffset;
  25364. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  25365. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  25366. buffer.setUsage( this.usage );
  25367. this.attribute = bufferAttribute;
  25368. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  25369. }
  25370. generate( builder ) {
  25371. const nodeType = this.getNodeType( builder );
  25372. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  25373. const propertyName = builder.getPropertyName( nodeAttribute );
  25374. let output = null;
  25375. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  25376. this.name = propertyName;
  25377. output = propertyName;
  25378. } else {
  25379. const nodeVarying = varying( this );
  25380. output = nodeVarying.build( builder, nodeType );
  25381. }
  25382. return output;
  25383. }
  25384. getInputType( /*builder*/ ) {
  25385. return 'bufferAttribute';
  25386. }
  25387. setUsage( value ) {
  25388. this.usage = value;
  25389. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  25390. this.attribute.usage = value;
  25391. }
  25392. return this;
  25393. }
  25394. setInstanced( value ) {
  25395. this.instanced = value;
  25396. return this;
  25397. }
  25398. }
  25399. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  25400. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  25401. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  25402. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  25403. addNodeElement( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  25404. addNodeClass( 'BufferAttributeNode', BufferAttributeNode );
  25405. class InstanceNode extends Node {
  25406. constructor( instanceMesh ) {
  25407. super( 'void' );
  25408. this.instanceMesh = instanceMesh;
  25409. this.instanceMatrixNode = null;
  25410. this.instanceColorNode = null;
  25411. this.updateType = NodeUpdateType.FRAME;
  25412. this.buffer = null;
  25413. this.bufferColor = null;
  25414. }
  25415. setup( /*builder*/ ) {
  25416. let instanceMatrixNode = this.instanceMatrixNode;
  25417. const instanceMesh = this.instanceMesh;
  25418. if ( instanceMatrixNode === null ) {
  25419. const instanceAttribute = instanceMesh.instanceMatrix;
  25420. const buffer = new InstancedInterleavedBuffer( instanceAttribute.array, 16, 1 );
  25421. this.buffer = buffer;
  25422. const bufferFn = instanceAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25423. const instanceBuffers = [
  25424. // F.Signature -> bufferAttribute( array, type, stride, offset )
  25425. bufferFn( buffer, 'vec4', 16, 0 ),
  25426. bufferFn( buffer, 'vec4', 16, 4 ),
  25427. bufferFn( buffer, 'vec4', 16, 8 ),
  25428. bufferFn( buffer, 'vec4', 16, 12 )
  25429. ];
  25430. instanceMatrixNode = mat4( ...instanceBuffers );
  25431. this.instanceMatrixNode = instanceMatrixNode;
  25432. }
  25433. const instanceColorAttribute = instanceMesh.instanceColor;
  25434. if ( instanceColorAttribute && this.instanceColorNode === null ) {
  25435. const buffer = new InstancedBufferAttribute( instanceColorAttribute.array, 3 );
  25436. const bufferFn = instanceColorAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25437. this.bufferColor = buffer;
  25438. this.instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  25439. }
  25440. // POSITION
  25441. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  25442. // NORMAL
  25443. const m = mat3( instanceMatrixNode[ 0 ].xyz, instanceMatrixNode[ 1 ].xyz, instanceMatrixNode[ 2 ].xyz );
  25444. const transformedNormal = normalLocal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  25445. const instanceNormal = m.mul( transformedNormal ).xyz;
  25446. // ASSIGNS
  25447. positionLocal.assign( instancePosition );
  25448. normalLocal.assign( instanceNormal );
  25449. // COLOR
  25450. if ( this.instanceColorNode !== null ) {
  25451. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  25452. }
  25453. }
  25454. update( /*frame*/ ) {
  25455. if ( this.instanceMesh.instanceMatrix.usage !== DynamicDrawUsage && this.instanceMesh.instanceMatrix.version !== this.buffer.version ) {
  25456. this.buffer.version = this.instanceMesh.instanceMatrix.version;
  25457. }
  25458. if ( this.instanceMesh.instanceColor && this.instanceMesh.instanceColor.usage !== DynamicDrawUsage && this.instanceMesh.instanceColor.version !== this.bufferColor.version ) {
  25459. this.bufferColor.version = this.instanceMesh.instanceColor.version;
  25460. }
  25461. }
  25462. }
  25463. const instance = nodeProxy( InstanceNode );
  25464. addNodeClass( 'InstanceNode', InstanceNode );
  25465. const tangentGeometry = /*#__PURE__*/ tslFn( ( stack, builder ) => {
  25466. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  25467. builder.geometry.computeTangents();
  25468. }
  25469. return attribute( 'tangent', 'vec4' );
  25470. } )();
  25471. const tangentLocal = /*#__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  25472. const tangentView = /*#__PURE__*/ varying( modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz, 'v_tangentView' ).normalize().toVar( 'tangentView' );
  25473. const tangentWorld = /*#__PURE__*/ varying( tangentView.transformDirection( cameraViewMatrix ), 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  25474. const transformedTangentView = /*#__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  25475. const transformedTangentWorld = /*#__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  25476. class BatchNode extends Node {
  25477. constructor( batchMesh ) {
  25478. super( 'void' );
  25479. this.batchMesh = batchMesh;
  25480. this.instanceColorNode = null;
  25481. this.batchingIdNode = null;
  25482. }
  25483. setup( builder ) {
  25484. // POSITION
  25485. if ( this.batchingIdNode === null ) {
  25486. if ( builder.getDrawIndex() === null ) {
  25487. this.batchingIdNode = instanceIndex;
  25488. } else {
  25489. this.batchingIdNode = drawIndex;
  25490. }
  25491. }
  25492. const getIndirectIndex = tslFn( ( [ id ] ) => {
  25493. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  25494. const x = int( id ).remainder( int( size ) );
  25495. const y = int( id ).div( int( size ) );
  25496. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ), null, 'uvec4' ).x;
  25497. } ).setLayout( {
  25498. name: 'getIndirectIndex',
  25499. type: 'uint',
  25500. inputs: [
  25501. { name: 'id', type: 'int' }
  25502. ]
  25503. } );
  25504. const matriceTexture = this.batchMesh._matricesTexture;
  25505. const size = textureSize( textureLoad( matriceTexture ), 0 );
  25506. const j = float( getIndirectIndex( int( this.batchingIdNode ) ) ).mul( 4 ).toVar();
  25507. const x = int( j.mod( size ) );
  25508. const y = int( j ).div( int( size ) );
  25509. const batchingMatrix = mat4(
  25510. textureLoad( matriceTexture, ivec2( x, y ) ),
  25511. textureLoad( matriceTexture, ivec2( x.add( 1 ), y ) ),
  25512. textureLoad( matriceTexture, ivec2( x.add( 2 ), y ) ),
  25513. textureLoad( matriceTexture, ivec2( x.add( 3 ), y ) )
  25514. );
  25515. const bm = mat3(
  25516. batchingMatrix[ 0 ].xyz,
  25517. batchingMatrix[ 1 ].xyz,
  25518. batchingMatrix[ 2 ].xyz
  25519. );
  25520. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  25521. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  25522. const batchingNormal = bm.mul( transformedNormal ).xyz;
  25523. normalLocal.assign( batchingNormal );
  25524. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25525. tangentLocal.mulAssign( bm );
  25526. }
  25527. }
  25528. }
  25529. const batch = nodeProxy( BatchNode );
  25530. addNodeClass( 'batch', BatchNode );
  25531. class SkinningNode extends Node {
  25532. constructor( skinnedMesh, useReference = false ) {
  25533. super( 'void' );
  25534. this.skinnedMesh = skinnedMesh;
  25535. this.useReference = useReference;
  25536. this.updateType = NodeUpdateType.OBJECT;
  25537. //
  25538. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  25539. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  25540. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  25541. if ( useReference ) {
  25542. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  25543. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  25544. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  25545. } else {
  25546. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  25547. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  25548. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  25549. }
  25550. this.bindMatrixNode = bindMatrixNode;
  25551. this.bindMatrixInverseNode = bindMatrixInverseNode;
  25552. this.boneMatricesNode = boneMatricesNode;
  25553. }
  25554. setup( builder ) {
  25555. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode, boneMatricesNode } = this;
  25556. const boneMatX = boneMatricesNode.element( skinIndexNode.x );
  25557. const boneMatY = boneMatricesNode.element( skinIndexNode.y );
  25558. const boneMatZ = boneMatricesNode.element( skinIndexNode.z );
  25559. const boneMatW = boneMatricesNode.element( skinIndexNode.w );
  25560. // POSITION
  25561. const skinVertex = bindMatrixNode.mul( positionLocal );
  25562. const skinned = add(
  25563. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  25564. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  25565. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  25566. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  25567. );
  25568. const skinPosition = bindMatrixInverseNode.mul( skinned ).xyz;
  25569. // NORMAL
  25570. let skinMatrix = add(
  25571. skinWeightNode.x.mul( boneMatX ),
  25572. skinWeightNode.y.mul( boneMatY ),
  25573. skinWeightNode.z.mul( boneMatZ ),
  25574. skinWeightNode.w.mul( boneMatW )
  25575. );
  25576. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  25577. const skinNormal = skinMatrix.transformDirection( normalLocal ).xyz;
  25578. // ASSIGNS
  25579. positionLocal.assign( skinPosition );
  25580. normalLocal.assign( skinNormal );
  25581. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25582. tangentLocal.assign( skinNormal );
  25583. }
  25584. }
  25585. generate( builder, output ) {
  25586. if ( output !== 'void' ) {
  25587. return positionLocal.build( builder, output );
  25588. }
  25589. }
  25590. update( frame ) {
  25591. const object = this.useReference ? frame.object : this.skinnedMesh;
  25592. object.skeleton.update();
  25593. }
  25594. }
  25595. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  25596. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  25597. addNodeClass( 'SkinningNode', SkinningNode );
  25598. class LoopNode extends Node {
  25599. constructor( params = [] ) {
  25600. super();
  25601. this.params = params;
  25602. }
  25603. getVarName( index ) {
  25604. return String.fromCharCode( 'i'.charCodeAt() + index );
  25605. }
  25606. getProperties( builder ) {
  25607. const properties = builder.getNodeProperties( this );
  25608. if ( properties.stackNode !== undefined ) return properties;
  25609. //
  25610. const inputs = {};
  25611. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25612. const param = this.params[ i ];
  25613. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  25614. const type = ( param.isNode !== true && param.type ) || 'int';
  25615. inputs[ name ] = expression( name, type );
  25616. }
  25617. const stack = builder.addStack(); // TODO: cache() it
  25618. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  25619. properties.stackNode = stack;
  25620. builder.removeStack();
  25621. return properties;
  25622. }
  25623. getNodeType( builder ) {
  25624. const { returnsNode } = this.getProperties( builder );
  25625. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  25626. }
  25627. setup( builder ) {
  25628. // setup properties
  25629. this.getProperties( builder );
  25630. }
  25631. generate( builder ) {
  25632. const properties = this.getProperties( builder );
  25633. const params = this.params;
  25634. const stackNode = properties.stackNode;
  25635. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  25636. const param = params[ i ];
  25637. let start = null, end = null, name = null, type = null, condition = null, update = null;
  25638. if ( param.isNode ) {
  25639. type = 'int';
  25640. name = this.getVarName( i );
  25641. start = '0';
  25642. end = param.build( builder, type );
  25643. condition = '<';
  25644. } else {
  25645. type = param.type || 'int';
  25646. name = param.name || this.getVarName( i );
  25647. start = param.start;
  25648. end = param.end;
  25649. condition = param.condition;
  25650. update = param.update;
  25651. if ( typeof start === 'number' ) start = start.toString();
  25652. else if ( start && start.isNode ) start = start.build( builder, type );
  25653. if ( typeof end === 'number' ) end = end.toString();
  25654. else if ( end && end.isNode ) end = end.build( builder, type );
  25655. if ( start !== undefined && end === undefined ) {
  25656. start = start + ' - 1';
  25657. end = '0';
  25658. condition = '>=';
  25659. } else if ( end !== undefined && start === undefined ) {
  25660. start = '0';
  25661. condition = '<';
  25662. }
  25663. if ( condition === undefined ) {
  25664. if ( Number( start ) > Number( end ) ) {
  25665. condition = '>=';
  25666. } else {
  25667. condition = '<';
  25668. }
  25669. }
  25670. }
  25671. const internalParam = { start, end, condition };
  25672. //
  25673. const startSnippet = internalParam.start;
  25674. const endSnippet = internalParam.end;
  25675. let declarationSnippet = '';
  25676. let conditionalSnippet = '';
  25677. let updateSnippet = '';
  25678. if ( ! update ) {
  25679. if ( type === 'int' || type === 'uint' ) {
  25680. if ( condition.includes( '<' ) ) update = '++';
  25681. else update = '--';
  25682. } else {
  25683. if ( condition.includes( '<' ) ) update = '+= 1.';
  25684. else update = '-= 1.';
  25685. }
  25686. }
  25687. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  25688. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  25689. updateSnippet += name + ' ' + update;
  25690. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  25691. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  25692. }
  25693. const stackSnippet = stackNode.build( builder, 'void' );
  25694. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  25695. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  25696. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25697. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  25698. }
  25699. builder.addFlowTab();
  25700. return returnsSnippet;
  25701. }
  25702. }
  25703. const loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  25704. const Continue = () => expression( 'continue' ).append();
  25705. const Break = () => expression( 'break' ).append();
  25706. addNodeElement( 'loop', ( returns, ...params ) => bypass( returns, loop( ...params ) ) );
  25707. addNodeClass( 'LoopNode', LoopNode );
  25708. const morphTextures = new WeakMap();
  25709. const morphVec4 = new Vector4();
  25710. const getMorph = tslFn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  25711. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  25712. const y = texelIndex.div( width );
  25713. const x = texelIndex.sub( y.mul( width ) );
  25714. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  25715. return bufferAttrib.mul( influence );
  25716. } );
  25717. function getEntry( geometry ) {
  25718. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  25719. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  25720. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  25721. // instead of using attributes, the WebGL 2 code path encodes morph targets
  25722. // into an array of data textures. Each layer represents a single morph target.
  25723. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  25724. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  25725. let entry = morphTextures.get( geometry );
  25726. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  25727. if ( entry !== undefined ) entry.texture.dispose();
  25728. const morphTargets = geometry.morphAttributes.position || [];
  25729. const morphNormals = geometry.morphAttributes.normal || [];
  25730. const morphColors = geometry.morphAttributes.color || [];
  25731. let vertexDataCount = 0;
  25732. if ( hasMorphPosition === true ) vertexDataCount = 1;
  25733. if ( hasMorphNormals === true ) vertexDataCount = 2;
  25734. if ( hasMorphColors === true ) vertexDataCount = 3;
  25735. let width = geometry.attributes.position.count * vertexDataCount;
  25736. let height = 1;
  25737. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  25738. if ( width > maxTextureSize ) {
  25739. height = Math.ceil( width / maxTextureSize );
  25740. width = maxTextureSize;
  25741. }
  25742. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  25743. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  25744. bufferTexture.type = FloatType;
  25745. bufferTexture.needsUpdate = true;
  25746. // fill buffer
  25747. const vertexDataStride = vertexDataCount * 4;
  25748. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  25749. const morphTarget = morphTargets[ i ];
  25750. const morphNormal = morphNormals[ i ];
  25751. const morphColor = morphColors[ i ];
  25752. const offset = width * height * 4 * i;
  25753. for ( let j = 0; j < morphTarget.count; j ++ ) {
  25754. const stride = j * vertexDataStride;
  25755. if ( hasMorphPosition === true ) {
  25756. morphVec4.fromBufferAttribute( morphTarget, j );
  25757. buffer[ offset + stride + 0 ] = morphVec4.x;
  25758. buffer[ offset + stride + 1 ] = morphVec4.y;
  25759. buffer[ offset + stride + 2 ] = morphVec4.z;
  25760. buffer[ offset + stride + 3 ] = 0;
  25761. }
  25762. if ( hasMorphNormals === true ) {
  25763. morphVec4.fromBufferAttribute( morphNormal, j );
  25764. buffer[ offset + stride + 4 ] = morphVec4.x;
  25765. buffer[ offset + stride + 5 ] = morphVec4.y;
  25766. buffer[ offset + stride + 6 ] = morphVec4.z;
  25767. buffer[ offset + stride + 7 ] = 0;
  25768. }
  25769. if ( hasMorphColors === true ) {
  25770. morphVec4.fromBufferAttribute( morphColor, j );
  25771. buffer[ offset + stride + 8 ] = morphVec4.x;
  25772. buffer[ offset + stride + 9 ] = morphVec4.y;
  25773. buffer[ offset + stride + 10 ] = morphVec4.z;
  25774. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morphVec4.w : 1;
  25775. }
  25776. }
  25777. }
  25778. entry = {
  25779. count: morphTargetsCount,
  25780. texture: bufferTexture,
  25781. stride: vertexDataCount,
  25782. size: new Vector2( width, height )
  25783. };
  25784. morphTextures.set( geometry, entry );
  25785. function disposeTexture() {
  25786. bufferTexture.dispose();
  25787. morphTextures.delete( geometry );
  25788. geometry.removeEventListener( 'dispose', disposeTexture );
  25789. }
  25790. geometry.addEventListener( 'dispose', disposeTexture );
  25791. }
  25792. return entry;
  25793. }
  25794. class MorphNode extends Node {
  25795. constructor( mesh ) {
  25796. super( 'void' );
  25797. this.mesh = mesh;
  25798. this.morphBaseInfluence = uniform( 1 );
  25799. this.updateType = NodeUpdateType.OBJECT;
  25800. }
  25801. setup( builder ) {
  25802. const { geometry } = builder;
  25803. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  25804. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  25805. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  25806. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  25807. // nodes
  25808. const { texture: bufferMap, stride, size } = getEntry( geometry );
  25809. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  25810. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  25811. const width = int( size.width );
  25812. loop( morphTargetsCount, ( { i } ) => {
  25813. const influence = float( 0 ).toVar();
  25814. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  25815. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  25816. } else {
  25817. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  25818. }
  25819. if ( hasMorphPosition === true ) {
  25820. positionLocal.addAssign( getMorph( {
  25821. bufferMap,
  25822. influence,
  25823. stride,
  25824. width,
  25825. depth: i,
  25826. offset: int( 0 )
  25827. } ) );
  25828. }
  25829. if ( hasMorphNormals === true ) {
  25830. normalLocal.addAssign( getMorph( {
  25831. bufferMap,
  25832. influence,
  25833. stride,
  25834. width,
  25835. depth: i,
  25836. offset: int( 1 )
  25837. } ) );
  25838. }
  25839. } );
  25840. }
  25841. update() {
  25842. const morphBaseInfluence = this.morphBaseInfluence;
  25843. if ( this.mesh.geometry.morphTargetsRelative ) {
  25844. morphBaseInfluence.value = 1;
  25845. } else {
  25846. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  25847. }
  25848. }
  25849. }
  25850. const morphReference = nodeProxy( MorphNode );
  25851. addNodeClass( 'MorphNode', MorphNode );
  25852. const reflectView = /*#__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  25853. const reflectVector = /*#__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  25854. class CubeTextureNode extends TextureNode {
  25855. constructor( value, uvNode = null, levelNode = null ) {
  25856. super( value, uvNode, levelNode );
  25857. this.isCubeTextureNode = true;
  25858. }
  25859. getInputType( /*builder*/ ) {
  25860. return 'cubeTexture';
  25861. }
  25862. getDefaultUV() {
  25863. return reflectVector;
  25864. }
  25865. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  25866. setupUV( builder, uvNode ) {
  25867. const texture = this.value;
  25868. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  25869. return vec3( uvNode.x.negate(), uvNode.yz );
  25870. } else {
  25871. return uvNode;
  25872. }
  25873. }
  25874. generateUV( builder, cubeUV ) {
  25875. return cubeUV.build( builder, 'vec3' );
  25876. }
  25877. }
  25878. const cubeTexture = nodeProxy( CubeTextureNode );
  25879. addNodeElement( 'cubeTexture', cubeTexture );
  25880. addNodeClass( 'CubeTextureNode', CubeTextureNode );
  25881. class LightingNode extends Node {
  25882. constructor() {
  25883. super( 'vec3' );
  25884. }
  25885. generate( /*builder*/ ) {
  25886. console.warn( 'Abstract function.' );
  25887. }
  25888. }
  25889. addNodeClass( 'LightingNode', LightingNode );
  25890. let overrideMaterial = null;
  25891. class AnalyticLightNode extends LightingNode {
  25892. constructor( light = null ) {
  25893. super();
  25894. this.updateType = NodeUpdateType.FRAME;
  25895. this.light = light;
  25896. this.rtt = null;
  25897. this.shadowNode = null;
  25898. this.shadowMaskNode = null;
  25899. this.color = new Color();
  25900. this._defaultColorNode = uniform( this.color );
  25901. this.colorNode = this._defaultColorNode;
  25902. this.isAnalyticLightNode = true;
  25903. }
  25904. getCacheKey() {
  25905. return super.getCacheKey() + '-' + ( this.light.id + '-' + ( this.light.castShadow ? '1' : '0' ) );
  25906. }
  25907. getHash() {
  25908. return this.light.uuid;
  25909. }
  25910. setupShadow( builder ) {
  25911. const { object } = builder;
  25912. if ( object.receiveShadow === false ) return;
  25913. let shadowNode = this.shadowNode;
  25914. if ( shadowNode === null ) {
  25915. if ( overrideMaterial === null ) {
  25916. overrideMaterial = builder.createNodeMaterial();
  25917. overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 );
  25918. overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode
  25919. }
  25920. const shadow = this.light.shadow;
  25921. const rtt = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  25922. const depthTexture = new DepthTexture();
  25923. depthTexture.minFilter = NearestFilter;
  25924. depthTexture.magFilter = NearestFilter;
  25925. depthTexture.image.width = shadow.mapSize.width;
  25926. depthTexture.image.height = shadow.mapSize.height;
  25927. depthTexture.compareFunction = LessCompare;
  25928. rtt.depthTexture = depthTexture;
  25929. shadow.camera.updateProjectionMatrix();
  25930. //
  25931. const shadowIntensity = reference( 'intensity', 'float', shadow );
  25932. const bias = reference( 'bias', 'float', shadow );
  25933. const normalBias = reference( 'normalBias', 'float', shadow );
  25934. const position = object.material.shadowPositionNode || positionWorld;
  25935. let shadowCoord = uniform( shadow.matrix ).mul( position.add( normalWorld.mul( normalBias ) ) );
  25936. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  25937. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  25938. .and( shadowCoord.x.lessThanEqual( 1 ) )
  25939. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  25940. .and( shadowCoord.y.lessThanEqual( 1 ) )
  25941. .and( shadowCoord.z.lessThanEqual( 1 ) );
  25942. let coordZ = shadowCoord.z.add( bias );
  25943. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  25944. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Convertion [ 0, 1 ] to [ - 1, 1 ]
  25945. }
  25946. shadowCoord = vec3(
  25947. shadowCoord.x,
  25948. shadowCoord.y.oneMinus(), // follow webgpu standards
  25949. coordZ
  25950. );
  25951. const textureCompare = ( depthTexture, shadowCoord, compare ) => texture( depthTexture, shadowCoord ).compare( compare );
  25952. //const textureCompare = ( depthTexture, shadowCoord, compare ) => compare.step( texture( depthTexture, shadowCoord ) );
  25953. // BasicShadowMap
  25954. shadowNode = textureCompare( depthTexture, shadowCoord.xy, shadowCoord.z );
  25955. // PCFShadowMap
  25956. /*
  25957. const mapSize = reference( 'mapSize', 'vec2', shadow );
  25958. const radius = reference( 'radius', 'float', shadow );
  25959. const texelSize = vec2( 1 ).div( mapSize );
  25960. const dx0 = texelSize.x.negate().mul( radius );
  25961. const dy0 = texelSize.y.negate().mul( radius );
  25962. const dx1 = texelSize.x.mul( radius );
  25963. const dy1 = texelSize.y.mul( radius );
  25964. const dx2 = dx0.mul( 2 );
  25965. const dy2 = dy0.mul( 2 );
  25966. const dx3 = dx1.mul( 2 );
  25967. const dy3 = dy1.mul( 2 );
  25968. shadowNode = add(
  25969. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  25970. textureCompare( depthTexture, shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  25971. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  25972. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  25973. textureCompare( depthTexture, shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  25974. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  25975. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  25976. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  25977. textureCompare( depthTexture, shadowCoord.xy, shadowCoord.z ),
  25978. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  25979. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  25980. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  25981. textureCompare( depthTexture, shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  25982. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  25983. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  25984. textureCompare( depthTexture, shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  25985. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  25986. ).mul( 1 / 17 );
  25987. */
  25988. //
  25989. const shadowColor = texture( rtt.texture, shadowCoord );
  25990. const shadowMaskNode = frustumTest.mix( 1, shadowNode.mix( shadowColor.a.mix( 1, shadowColor ), 1 ) );
  25991. this.rtt = rtt;
  25992. this.colorNode = this.colorNode.mul( mix( 1, shadowMaskNode, shadowIntensity ) );
  25993. this.shadowNode = shadowNode;
  25994. this.shadowMaskNode = shadowMaskNode;
  25995. //
  25996. this.updateBeforeType = NodeUpdateType.RENDER;
  25997. }
  25998. }
  25999. setup( builder ) {
  26000. if ( this.light.castShadow ) this.setupShadow( builder );
  26001. else if ( this.shadowNode !== null ) this.disposeShadow();
  26002. }
  26003. updateShadow( frame ) {
  26004. const { rtt, light } = this;
  26005. const { renderer, scene, camera } = frame;
  26006. const currentOverrideMaterial = scene.overrideMaterial;
  26007. scene.overrideMaterial = overrideMaterial;
  26008. rtt.setSize( light.shadow.mapSize.width, light.shadow.mapSize.height );
  26009. light.shadow.updateMatrices( light );
  26010. light.shadow.camera.layers.mask = camera.layers.mask;
  26011. const currentToneMapping = renderer.toneMapping;
  26012. const currentRenderTarget = renderer.getRenderTarget();
  26013. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  26014. renderer.setRenderObjectFunction( ( object, ...params ) => {
  26015. if ( object.castShadow === true ) {
  26016. renderer.renderObject( object, ...params );
  26017. }
  26018. } );
  26019. renderer.setRenderTarget( rtt );
  26020. renderer.toneMapping = NoToneMapping;
  26021. renderer.render( scene, light.shadow.camera );
  26022. renderer.setRenderTarget( currentRenderTarget );
  26023. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  26024. renderer.toneMapping = currentToneMapping;
  26025. scene.overrideMaterial = currentOverrideMaterial;
  26026. }
  26027. disposeShadow() {
  26028. this.rtt.dispose();
  26029. this.shadowNode = null;
  26030. this.shadowMaskNode = null;
  26031. this.rtt = null;
  26032. this.colorNode = this._defaultColorNode;
  26033. }
  26034. updateBefore( frame ) {
  26035. const { light } = this;
  26036. if ( light.castShadow ) this.updateShadow( frame );
  26037. }
  26038. update( /*frame*/ ) {
  26039. const { light } = this;
  26040. this.color.copy( light.color ).multiplyScalar( light.intensity );
  26041. }
  26042. }
  26043. addNodeClass( 'AnalyticLightNode', AnalyticLightNode );
  26044. const LightNodes = new WeakMap();
  26045. const sortLights = ( lights ) => {
  26046. return lights.sort( ( a, b ) => a.id - b.id );
  26047. };
  26048. class LightsNode extends Node {
  26049. constructor( lightNodes = [] ) {
  26050. super( 'vec3' );
  26051. this.totalDiffuseNode = vec3().temp( 'totalDiffuse' );
  26052. this.totalSpecularNode = vec3().temp( 'totalSpecular' );
  26053. this.outgoingLightNode = vec3().temp( 'outgoingLight' );
  26054. this.lightNodes = lightNodes;
  26055. this._hash = null;
  26056. }
  26057. get hasLight() {
  26058. return this.lightNodes.length > 0;
  26059. }
  26060. getHash() {
  26061. if ( this._hash === null ) {
  26062. const hash = [];
  26063. for ( const lightNode of this.lightNodes ) {
  26064. hash.push( lightNode.getHash() );
  26065. }
  26066. this._hash = 'lights-' + hash.join( ',' );
  26067. }
  26068. return this._hash;
  26069. }
  26070. analyze( builder ) {
  26071. const properties = builder.getDataFromNode( this );
  26072. for ( const node of properties.nodes ) {
  26073. node.build( builder );
  26074. }
  26075. }
  26076. setup( builder ) {
  26077. const context = builder.context;
  26078. const lightingModel = context.lightingModel;
  26079. let outgoingLightNode = this.outgoingLightNode;
  26080. if ( lightingModel ) {
  26081. const { lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  26082. context.outgoingLight = outgoingLightNode;
  26083. const stack = builder.addStack();
  26084. //
  26085. const properties = builder.getDataFromNode( this );
  26086. properties.nodes = stack.nodes;
  26087. //
  26088. lightingModel.start( context, stack, builder );
  26089. // lights
  26090. for ( const lightNode of lightNodes ) {
  26091. lightNode.build( builder );
  26092. }
  26093. //
  26094. lightingModel.indirectDiffuse( context, stack, builder );
  26095. lightingModel.indirectSpecular( context, stack, builder );
  26096. lightingModel.ambientOcclusion( context, stack, builder );
  26097. //
  26098. const { backdrop, backdropAlpha } = context;
  26099. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  26100. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  26101. if ( backdrop !== null ) {
  26102. if ( backdropAlpha !== null ) {
  26103. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  26104. } else {
  26105. totalDiffuse = vec3( backdrop );
  26106. }
  26107. context.material.transparent = true;
  26108. }
  26109. totalDiffuseNode.assign( totalDiffuse );
  26110. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  26111. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  26112. //
  26113. lightingModel.finish( context, stack, builder );
  26114. //
  26115. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  26116. }
  26117. return outgoingLightNode;
  26118. }
  26119. _getLightNodeById( id ) {
  26120. for ( const lightNode of this.lightNodes ) {
  26121. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  26122. return lightNode;
  26123. }
  26124. }
  26125. return null;
  26126. }
  26127. fromLights( lights = [] ) {
  26128. const lightNodes = [];
  26129. lights = sortLights( lights );
  26130. for ( const light of lights ) {
  26131. let lightNode = this._getLightNodeById( light.id );
  26132. if ( lightNode === null ) {
  26133. const lightClass = light.constructor;
  26134. const lightNodeClass = LightNodes.has( lightClass ) ? LightNodes.get( lightClass ) : AnalyticLightNode;
  26135. lightNode = nodeObject( new lightNodeClass( light ) );
  26136. }
  26137. lightNodes.push( lightNode );
  26138. }
  26139. this.lightNodes = lightNodes;
  26140. this._hash = null;
  26141. return this;
  26142. }
  26143. }
  26144. const lights = ( lights ) => nodeObject( new LightsNode().fromLights( lights ) );
  26145. const lightsNode = nodeProxy( LightsNode );
  26146. function addLightNode( lightClass, lightNodeClass ) {
  26147. if ( LightNodes.has( lightClass ) ) {
  26148. console.warn( `Redefinition of light node ${ lightNodeClass.type }` );
  26149. return;
  26150. }
  26151. if ( typeof lightClass !== 'function' ) throw new Error( `Light ${ lightClass.name } is not a class` );
  26152. if ( typeof lightNodeClass !== 'function' || ! lightNodeClass.type ) throw new Error( `Light node ${ lightNodeClass.type } is not a class` );
  26153. LightNodes.set( lightClass, lightNodeClass );
  26154. }
  26155. class AONode extends LightingNode {
  26156. constructor( aoNode = null ) {
  26157. super();
  26158. this.aoNode = aoNode;
  26159. }
  26160. setup( builder ) {
  26161. const aoIntensity = 1;
  26162. const aoNode = this.aoNode.x.sub( 1.0 ).mul( aoIntensity ).add( 1.0 );
  26163. builder.context.ambientOcclusion.mulAssign( aoNode );
  26164. }
  26165. }
  26166. addNodeClass( 'AONode', AONode );
  26167. class LightingContextNode extends ContextNode {
  26168. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  26169. super( node );
  26170. this.lightingModel = lightingModel;
  26171. this.backdropNode = backdropNode;
  26172. this.backdropAlphaNode = backdropAlphaNode;
  26173. this._context = null;
  26174. }
  26175. getContext() {
  26176. const { backdropNode, backdropAlphaNode } = this;
  26177. const directDiffuse = vec3().temp( 'directDiffuse' ),
  26178. directSpecular = vec3().temp( 'directSpecular' ),
  26179. indirectDiffuse = vec3().temp( 'indirectDiffuse' ),
  26180. indirectSpecular = vec3().temp( 'indirectSpecular' );
  26181. const reflectedLight = {
  26182. directDiffuse,
  26183. directSpecular,
  26184. indirectDiffuse,
  26185. indirectSpecular
  26186. };
  26187. const context = {
  26188. radiance: vec3().temp( 'radiance' ),
  26189. irradiance: vec3().temp( 'irradiance' ),
  26190. iblIrradiance: vec3().temp( 'iblIrradiance' ),
  26191. ambientOcclusion: float( 1 ).temp( 'ambientOcclusion' ),
  26192. reflectedLight,
  26193. backdrop: backdropNode,
  26194. backdropAlpha: backdropAlphaNode
  26195. };
  26196. return context;
  26197. }
  26198. setup( builder ) {
  26199. this.context = this._context || ( this._context = this.getContext() );
  26200. this.context.lightingModel = this.lightingModel || builder.context.lightingModel;
  26201. return super.setup( builder );
  26202. }
  26203. }
  26204. const lightingContext = nodeProxy( LightingContextNode );
  26205. addNodeElement( 'lightingContext', lightingContext );
  26206. addNodeClass( 'LightingContextNode', LightingContextNode );
  26207. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  26208. const bitangentGeometry = /*#__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  26209. const bitangentLocal = /*#__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  26210. const bitangentView = /*#__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  26211. const bitangentWorld = /*#__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  26212. const transformedBitangentView = /*#__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  26213. const transformedBitangentWorld = /*#__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  26214. const TBNViewMatrix = mat3( tangentView, bitangentView, normalView );
  26215. const parallaxDirection = positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  26216. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  26217. const transformedBentNormalView = ( () => {
  26218. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  26219. let bentNormal = anisotropyB.cross( positionViewDirection );
  26220. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  26221. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  26222. return bentNormal;
  26223. } )();
  26224. class CondNode extends Node {
  26225. constructor( condNode, ifNode, elseNode = null ) {
  26226. super();
  26227. this.condNode = condNode;
  26228. this.ifNode = ifNode;
  26229. this.elseNode = elseNode;
  26230. }
  26231. getNodeType( builder ) {
  26232. const ifType = this.ifNode.getNodeType( builder );
  26233. if ( this.elseNode !== null ) {
  26234. const elseType = this.elseNode.getNodeType( builder );
  26235. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  26236. return elseType;
  26237. }
  26238. }
  26239. return ifType;
  26240. }
  26241. setup( builder ) {
  26242. const properties = builder.getNodeProperties( this );
  26243. properties.condNode = this.condNode.cache();
  26244. properties.ifNode = this.ifNode.cache();
  26245. properties.elseNode = this.elseNode ? this.elseNode.cache() : null;
  26246. }
  26247. generate( builder, output ) {
  26248. const type = this.getNodeType( builder );
  26249. const nodeData = builder.getDataFromNode( this );
  26250. if ( nodeData.nodeProperty !== undefined ) {
  26251. return nodeData.nodeProperty;
  26252. }
  26253. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  26254. const needsOutput = output !== 'void';
  26255. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  26256. nodeData.nodeProperty = nodeProperty;
  26257. const nodeSnippet = condNode.build( builder, 'bool' );
  26258. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  26259. let ifSnippet = ifNode.build( builder, type );
  26260. if ( ifSnippet ) {
  26261. if ( needsOutput ) {
  26262. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  26263. } else {
  26264. ifSnippet = 'return ' + ifSnippet + ';';
  26265. }
  26266. }
  26267. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  26268. if ( elseNode !== null ) {
  26269. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  26270. let elseSnippet = elseNode.build( builder, type );
  26271. if ( elseSnippet ) {
  26272. if ( needsOutput ) {
  26273. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  26274. } else {
  26275. elseSnippet = 'return ' + elseSnippet + ';';
  26276. }
  26277. }
  26278. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  26279. } else {
  26280. builder.addFlowCode( '\n\n' );
  26281. }
  26282. return builder.format( nodeProperty, type, output );
  26283. }
  26284. }
  26285. const cond = nodeProxy( CondNode );
  26286. addNodeElement( 'cond', cond );
  26287. addNodeClass( 'CondNode', CondNode );
  26288. // These defines must match with PMREMGenerator
  26289. const cubeUV_r0 = float( 1.0 );
  26290. const cubeUV_m0 = float( - 2.0 );
  26291. const cubeUV_r1 = float( 0.8 );
  26292. const cubeUV_m1 = float( - 1.0 );
  26293. const cubeUV_r4 = float( 0.4 );
  26294. const cubeUV_m4 = float( 2.0 );
  26295. const cubeUV_r5 = float( 0.305 );
  26296. const cubeUV_m5 = float( 3.0 );
  26297. const cubeUV_r6 = float( 0.21 );
  26298. const cubeUV_m6 = float( 4.0 );
  26299. const cubeUV_minMipLevel = float( 4.0 );
  26300. const cubeUV_minTileSize = float( 16.0 );
  26301. // These shader functions convert between the UV coordinates of a single face of
  26302. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  26303. // sampling a textureCube (not generally normalized ).
  26304. const getFace = tslFn( ( [ direction ] ) => {
  26305. const absDirection = vec3( abs( direction ) ).toVar();
  26306. const face = float( - 1.0 ).toVar();
  26307. If( absDirection.x.greaterThan( absDirection.z ), () => {
  26308. If( absDirection.x.greaterThan( absDirection.y ), () => {
  26309. face.assign( cond( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  26310. } ).else( () => {
  26311. face.assign( cond( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  26312. } );
  26313. } ).else( () => {
  26314. If( absDirection.z.greaterThan( absDirection.y ), () => {
  26315. face.assign( cond( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  26316. } ).else( () => {
  26317. face.assign( cond( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  26318. } );
  26319. } );
  26320. return face;
  26321. } ).setLayout( {
  26322. name: 'getFace',
  26323. type: 'float',
  26324. inputs: [
  26325. { name: 'direction', type: 'vec3' }
  26326. ]
  26327. } );
  26328. // RH coordinate system; PMREM face-indexing convention
  26329. const getUV = tslFn( ( [ direction, face ] ) => {
  26330. const uv = vec2().toVar();
  26331. If( face.equal( 0.0 ), () => {
  26332. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  26333. } ).elseif( face.equal( 1.0 ), () => {
  26334. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  26335. } ).elseif( face.equal( 2.0 ), () => {
  26336. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  26337. } ).elseif( face.equal( 3.0 ), () => {
  26338. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  26339. } ).elseif( face.equal( 4.0 ), () => {
  26340. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  26341. } ).else( () => {
  26342. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  26343. } );
  26344. return mul( 0.5, uv.add( 1.0 ) );
  26345. } ).setLayout( {
  26346. name: 'getUV',
  26347. type: 'vec2',
  26348. inputs: [
  26349. { name: 'direction', type: 'vec3' },
  26350. { name: 'face', type: 'float' }
  26351. ]
  26352. } );
  26353. const roughnessToMip = tslFn( ( [ roughness ] ) => {
  26354. const mip = float( 0.0 ).toVar();
  26355. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  26356. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  26357. } ).elseif( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  26358. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  26359. } ).elseif( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  26360. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  26361. } ).elseif( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  26362. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  26363. } ).else( () => {
  26364. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  26365. } );
  26366. return mip;
  26367. } ).setLayout( {
  26368. name: 'roughnessToMip',
  26369. type: 'float',
  26370. inputs: [
  26371. { name: 'roughness', type: 'float' }
  26372. ]
  26373. } );
  26374. // RH coordinate system; PMREM face-indexing convention
  26375. const getDirection = tslFn( ( [ uv_immutable, face ] ) => {
  26376. const uv = uv_immutable.toVar();
  26377. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  26378. const direction = vec3( uv, 1.0 ).toVar();
  26379. If( face.equal( 0.0 ), () => {
  26380. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  26381. } ).elseif( face.equal( 1.0 ), () => {
  26382. direction.assign( direction.xzy );
  26383. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  26384. } ).elseif( face.equal( 2.0 ), () => {
  26385. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  26386. } ).elseif( face.equal( 3.0 ), () => {
  26387. direction.assign( direction.zyx );
  26388. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  26389. } ).elseif( face.equal( 4.0 ), () => {
  26390. direction.assign( direction.xzy );
  26391. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  26392. } ).elseif( face.equal( 5.0 ), () => {
  26393. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  26394. } );
  26395. return direction;
  26396. } ).setLayout( {
  26397. name: 'getDirection',
  26398. type: 'vec3',
  26399. inputs: [
  26400. { name: 'uv', type: 'vec2' },
  26401. { name: 'face', type: 'float' }
  26402. ]
  26403. } );
  26404. //
  26405. const textureCubeUV = tslFn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  26406. const roughness = float( roughness_immutable );
  26407. const sampleDir = vec3( sampleDir_immutable );
  26408. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  26409. const mipF = fract( mip );
  26410. const mipInt = floor( mip );
  26411. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  26412. If( mipF.notEqual( 0.0 ), () => {
  26413. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  26414. color0.assign( mix( color0, color1, mipF ) );
  26415. } );
  26416. return color0;
  26417. } );
  26418. const bilinearCubeUV = tslFn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  26419. const mipInt = float( mipInt_immutable ).toVar();
  26420. const direction = vec3( direction_immutable );
  26421. const face = float( getFace( direction ) ).toVar();
  26422. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  26423. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  26424. const faceSize = float( exp2( mipInt ) ).toVar();
  26425. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  26426. If( face.greaterThan( 2.0 ), () => {
  26427. uv.y.addAssign( faceSize );
  26428. face.subAssign( 3.0 );
  26429. } );
  26430. uv.x.addAssign( face.mul( faceSize ) );
  26431. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  26432. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  26433. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  26434. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  26435. return envMap.uv( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  26436. } );
  26437. const getSample = tslFn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  26438. const cosTheta = cos( theta );
  26439. // Rodrigues' axis-angle rotation
  26440. const sampleDirection = outputDirection.mul( cosTheta )
  26441. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  26442. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  26443. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  26444. } );
  26445. const blur = tslFn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  26446. const axis = vec3( cond( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  26447. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  26448. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  26449. } );
  26450. axis.assign( normalize( axis ) );
  26451. const gl_FragColor = vec3().toVar();
  26452. 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 } ) ) );
  26453. loop( { start: int( 1 ), end: n }, ( { i } ) => {
  26454. If( i.greaterThanEqual( samples ), () => {
  26455. Break();
  26456. } );
  26457. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  26458. 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 } ) ) );
  26459. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  26460. } );
  26461. return vec4( gl_FragColor, 1 );
  26462. } );
  26463. let _generator = null;
  26464. const _cache = new WeakMap();
  26465. function _generateCubeUVSize( imageHeight ) {
  26466. const maxMip = Math.log2( imageHeight ) - 2;
  26467. const texelHeight = 1.0 / imageHeight;
  26468. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  26469. return { texelWidth, texelHeight, maxMip };
  26470. }
  26471. function _getPMREMFromTexture( texture ) {
  26472. let cacheTexture = _cache.get( texture );
  26473. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  26474. if ( pmremVersion !== texture.pmremVersion ) {
  26475. if ( texture.isCubeTexture ) {
  26476. if ( texture.source.data.some( ( texture ) => texture === undefined ) ) {
  26477. throw new Error( 'PMREMNode: Undefined texture in CubeTexture. Use onLoad callback or async loader' );
  26478. }
  26479. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  26480. } else {
  26481. if ( texture.image === undefined ) {
  26482. throw new Error( 'PMREMNode: Undefined image in Texture. Use onLoad callback or async loader' );
  26483. }
  26484. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  26485. }
  26486. cacheTexture.pmremVersion = texture.pmremVersion;
  26487. _cache.set( texture, cacheTexture );
  26488. }
  26489. return cacheTexture.texture;
  26490. }
  26491. class PMREMNode extends TempNode {
  26492. constructor( value, uvNode = null, levelNode = null ) {
  26493. super( 'vec3' );
  26494. this._value = value;
  26495. this._pmrem = null;
  26496. this.uvNode = uvNode;
  26497. this.levelNode = levelNode;
  26498. this._generator = null;
  26499. this._texture = texture( null );
  26500. this._width = uniform( 0 );
  26501. this._height = uniform( 0 );
  26502. this._maxMip = uniform( 0 );
  26503. this.updateBeforeType = NodeUpdateType.RENDER;
  26504. }
  26505. set value( value ) {
  26506. this._value = value;
  26507. this._pmrem = null;
  26508. }
  26509. get value() {
  26510. return this._value;
  26511. }
  26512. updateFromTexture( texture ) {
  26513. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  26514. this._texture.value = texture;
  26515. this._width.value = cubeUVSize.texelWidth;
  26516. this._height.value = cubeUVSize.texelHeight;
  26517. this._maxMip.value = cubeUVSize.maxMip;
  26518. }
  26519. updateBefore() {
  26520. let pmrem = this._pmrem;
  26521. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  26522. const texture = this._value;
  26523. if ( pmremVersion !== texture.pmremVersion ) {
  26524. if ( texture.isPMREMTexture === true ) {
  26525. pmrem = texture;
  26526. } else {
  26527. pmrem = _getPMREMFromTexture( texture );
  26528. }
  26529. this._pmrem = pmrem;
  26530. this.updateFromTexture( pmrem );
  26531. }
  26532. }
  26533. setup( builder ) {
  26534. if ( _generator === null ) {
  26535. _generator = builder.createPMREMGenerator();
  26536. }
  26537. //
  26538. this.updateBefore( builder );
  26539. //
  26540. let uvNode = this.uvNode;
  26541. if ( uvNode === null && builder.context.getUV ) {
  26542. uvNode = builder.context.getUV( this );
  26543. }
  26544. //
  26545. const texture = this.value;
  26546. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  26547. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  26548. }
  26549. //
  26550. let levelNode = this.levelNode;
  26551. if ( levelNode === null && builder.context.getTextureLevel ) {
  26552. levelNode = builder.context.getTextureLevel( this );
  26553. }
  26554. //
  26555. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  26556. }
  26557. }
  26558. const pmremTexture = nodeProxy( PMREMNode );
  26559. addNodeClass( 'PMREMNode', PMREMNode );
  26560. const envNodeCache = new WeakMap();
  26561. class EnvironmentNode extends LightingNode {
  26562. constructor( envNode = null ) {
  26563. super();
  26564. this.envNode = envNode;
  26565. }
  26566. setup( builder ) {
  26567. let envNode = this.envNode;
  26568. if ( envNode.isTextureNode ) {
  26569. let cacheEnvNode = envNodeCache.get( envNode.value );
  26570. if ( cacheEnvNode === undefined ) {
  26571. cacheEnvNode = pmremTexture( envNode.value );
  26572. envNodeCache.set( envNode.value, cacheEnvNode );
  26573. }
  26574. envNode = cacheEnvNode;
  26575. }
  26576. //
  26577. const { material } = builder;
  26578. const envMap = material.envMap;
  26579. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  26580. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  26581. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  26582. const radiance = context( envNode, createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  26583. const irradiance = context( envNode, createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  26584. const isolateRadiance = cache( radiance );
  26585. const isolateIrradiance = cache( irradiance );
  26586. //
  26587. builder.context.radiance.addAssign( isolateRadiance );
  26588. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  26589. //
  26590. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  26591. if ( clearcoatRadiance ) {
  26592. const clearcoatRadianceContext = context( envNode, createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  26593. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  26594. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  26595. }
  26596. }
  26597. }
  26598. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  26599. let reflectVec = null;
  26600. return {
  26601. getUV: () => {
  26602. if ( reflectVec === null ) {
  26603. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  26604. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  26605. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  26606. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  26607. }
  26608. return reflectVec;
  26609. },
  26610. getTextureLevel: () => {
  26611. return roughnessNode;
  26612. }
  26613. };
  26614. };
  26615. const createIrradianceContext = ( normalWorldNode ) => {
  26616. return {
  26617. getUV: () => {
  26618. return normalWorldNode;
  26619. },
  26620. getTextureLevel: () => {
  26621. return float( 1.0 );
  26622. }
  26623. };
  26624. };
  26625. addNodeClass( 'EnvironmentNode', EnvironmentNode );
  26626. class IrradianceNode extends LightingNode {
  26627. constructor( node ) {
  26628. super();
  26629. this.node = node;
  26630. }
  26631. setup( builder ) {
  26632. builder.context.irradiance.addAssign( this.node );
  26633. }
  26634. }
  26635. addNodeClass( 'IrradianceNode', IrradianceNode );
  26636. let resolution, viewportResult;
  26637. class ViewportNode extends Node {
  26638. constructor( scope ) {
  26639. super();
  26640. this.scope = scope;
  26641. this.isViewportNode = true;
  26642. }
  26643. getNodeType() {
  26644. if ( this.scope === ViewportNode.VIEWPORT ) return 'vec4';
  26645. else if ( this.scope === ViewportNode.COORDINATE ) return 'vec3';
  26646. else return 'vec2';
  26647. }
  26648. getUpdateType() {
  26649. let updateType = NodeUpdateType.NONE;
  26650. if ( this.scope === ViewportNode.RESOLUTION || this.scope === ViewportNode.VIEWPORT ) {
  26651. updateType = NodeUpdateType.RENDER;
  26652. }
  26653. this.updateType = updateType;
  26654. return updateType;
  26655. }
  26656. update( { renderer } ) {
  26657. if ( this.scope === ViewportNode.VIEWPORT ) {
  26658. renderer.getViewport( viewportResult );
  26659. } else {
  26660. renderer.getDrawingBufferSize( resolution );
  26661. }
  26662. }
  26663. setup( /*builder*/ ) {
  26664. const scope = this.scope;
  26665. let output = null;
  26666. if ( scope === ViewportNode.RESOLUTION ) {
  26667. output = uniform( resolution || ( resolution = new Vector2() ) );
  26668. } else if ( scope === ViewportNode.VIEWPORT ) {
  26669. output = uniform( viewportResult || ( viewportResult = new Vector4() ) );
  26670. } else {
  26671. output = viewportCoordinate.div( viewportResolution );
  26672. let outX = output.x;
  26673. let outY = output.y;
  26674. if ( /bottom/i.test( scope ) ) outY = outY.oneMinus();
  26675. if ( /right/i.test( scope ) ) outX = outX.oneMinus();
  26676. output = vec2( outX, outY );
  26677. }
  26678. return output;
  26679. }
  26680. generate( builder ) {
  26681. if ( this.scope === ViewportNode.COORDINATE ) {
  26682. let coord = builder.getFragCoord();
  26683. if ( builder.isFlipY() ) {
  26684. // follow webgpu standards
  26685. const resolution = builder.getNodeProperties( viewportResolution ).outputNode.build( builder );
  26686. coord = `${ builder.getType( 'vec3' ) }( ${ coord }.x, ${ resolution }.y - ${ coord }.y, ${ coord }.z )`;
  26687. }
  26688. return coord;
  26689. }
  26690. return super.generate( builder );
  26691. }
  26692. }
  26693. ViewportNode.COORDINATE = 'coordinate';
  26694. ViewportNode.RESOLUTION = 'resolution';
  26695. ViewportNode.VIEWPORT = 'viewport';
  26696. ViewportNode.TOP_LEFT = 'topLeft';
  26697. ViewportNode.BOTTOM_LEFT = 'bottomLeft';
  26698. ViewportNode.TOP_RIGHT = 'topRight';
  26699. ViewportNode.BOTTOM_RIGHT = 'bottomRight';
  26700. const viewportCoordinate = nodeImmutable( ViewportNode, ViewportNode.COORDINATE );
  26701. const viewportResolution = nodeImmutable( ViewportNode, ViewportNode.RESOLUTION );
  26702. const viewport = nodeImmutable( ViewportNode, ViewportNode.VIEWPORT );
  26703. const viewportTopLeft = nodeImmutable( ViewportNode, ViewportNode.TOP_LEFT );
  26704. const viewportBottomLeft = nodeImmutable( ViewportNode, ViewportNode.BOTTOM_LEFT );
  26705. const viewportTopRight = nodeImmutable( ViewportNode, ViewportNode.TOP_RIGHT );
  26706. const viewportBottomRight = nodeImmutable( ViewportNode, ViewportNode.BOTTOM_RIGHT );
  26707. addNodeClass( 'ViewportNode', ViewportNode );
  26708. const _size$5 = new Vector2();
  26709. class ViewportTextureNode extends TextureNode {
  26710. constructor( uvNode = viewportTopLeft, levelNode = null, framebufferTexture = null ) {
  26711. if ( framebufferTexture === null ) {
  26712. framebufferTexture = new FramebufferTexture();
  26713. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  26714. }
  26715. super( framebufferTexture, uvNode, levelNode );
  26716. this.generateMipmaps = false;
  26717. this.isOutputTextureNode = true;
  26718. this.updateBeforeType = NodeUpdateType.FRAME;
  26719. }
  26720. updateBefore( frame ) {
  26721. const renderer = frame.renderer;
  26722. renderer.getDrawingBufferSize( _size$5 );
  26723. //
  26724. const framebufferTexture = this.value;
  26725. if ( framebufferTexture.image.width !== _size$5.width || framebufferTexture.image.height !== _size$5.height ) {
  26726. framebufferTexture.image.width = _size$5.width;
  26727. framebufferTexture.image.height = _size$5.height;
  26728. framebufferTexture.needsUpdate = true;
  26729. }
  26730. //
  26731. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  26732. framebufferTexture.generateMipmaps = this.generateMipmaps;
  26733. renderer.copyFramebufferToTexture( framebufferTexture );
  26734. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  26735. }
  26736. clone() {
  26737. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  26738. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  26739. return viewportTextureNode;
  26740. }
  26741. }
  26742. const viewportTexture = nodeProxy( ViewportTextureNode );
  26743. const viewportMipTexture = nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  26744. addNodeElement( 'viewportTexture', viewportTexture );
  26745. addNodeElement( 'viewportMipTexture', viewportMipTexture );
  26746. addNodeClass( 'ViewportTextureNode', ViewportTextureNode );
  26747. let sharedDepthbuffer = null;
  26748. class ViewportDepthTextureNode extends ViewportTextureNode {
  26749. constructor( uvNode = viewportTopLeft, levelNode = null ) {
  26750. if ( sharedDepthbuffer === null ) {
  26751. sharedDepthbuffer = new DepthTexture();
  26752. }
  26753. super( uvNode, levelNode, sharedDepthbuffer );
  26754. }
  26755. }
  26756. const viewportDepthTexture = nodeProxy( ViewportDepthTextureNode );
  26757. addNodeElement( 'viewportDepthTexture', viewportDepthTexture );
  26758. addNodeClass( 'ViewportDepthTextureNode', ViewportDepthTextureNode );
  26759. class ViewportDepthNode extends Node {
  26760. constructor( scope, valueNode = null ) {
  26761. super( 'float' );
  26762. this.scope = scope;
  26763. this.valueNode = valueNode;
  26764. this.isViewportDepthNode = true;
  26765. }
  26766. generate( builder ) {
  26767. const { scope } = this;
  26768. if ( scope === ViewportDepthNode.DEPTH ) {
  26769. return builder.getFragDepth();
  26770. }
  26771. return super.generate( builder );
  26772. }
  26773. setup( { camera } ) {
  26774. const { scope } = this;
  26775. const texture = this.valueNode;
  26776. let node = null;
  26777. if ( scope === ViewportDepthNode.DEPTH ) {
  26778. if ( texture !== null ) {
  26779. node = depthBase().assign( texture );
  26780. } else {
  26781. if ( camera.isPerspectiveCamera ) {
  26782. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  26783. } else {
  26784. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26785. }
  26786. }
  26787. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  26788. if ( texture !== null ) {
  26789. if ( camera.isPerspectiveCamera ) {
  26790. const viewZ = perspectiveDepthToViewZ( texture, cameraNear, cameraFar );
  26791. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  26792. } else {
  26793. node = texture;
  26794. }
  26795. } else {
  26796. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26797. }
  26798. }
  26799. return node;
  26800. }
  26801. }
  26802. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  26803. // -near maps to 0; -far maps to 1
  26804. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  26805. // maps orthographic depth in [ 0, 1 ] to viewZ
  26806. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  26807. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  26808. // -near maps to 0; -far maps to 1
  26809. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  26810. // maps perspective depth in [ 0, 1 ] to viewZ
  26811. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  26812. ViewportDepthNode.DEPTH = 'depth';
  26813. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  26814. const depthBase = nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH );
  26815. const depth = nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  26816. const linearDepth = nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  26817. const viewportLinearDepth = linearDepth( viewportDepthTexture() );
  26818. depth.assign = ( value ) => depthBase( value );
  26819. addNodeClass( 'ViewportDepthNode', ViewportDepthNode );
  26820. class ClippingNode extends Node {
  26821. constructor( scope = ClippingNode.DEFAULT ) {
  26822. super();
  26823. this.scope = scope;
  26824. }
  26825. setup( builder ) {
  26826. super.setup( builder );
  26827. const clippingContext = builder.clippingContext;
  26828. const { localClipIntersection, localClippingCount, globalClippingCount } = clippingContext;
  26829. const numClippingPlanes = globalClippingCount + localClippingCount;
  26830. const numUnionClippingPlanes = localClipIntersection ? numClippingPlanes - localClippingCount : numClippingPlanes;
  26831. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  26832. return this.setupAlphaToCoverage( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26833. } else {
  26834. return this.setupDefault( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26835. }
  26836. }
  26837. setupAlphaToCoverage( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26838. return tslFn( () => {
  26839. const clippingPlanes = uniforms( planes );
  26840. const distanceToPlane = property( 'float', 'distanceToPlane' );
  26841. const distanceGradient = property( 'float', 'distanceToGradient' );
  26842. const clipOpacity = property( 'float', 'clipOpacity' );
  26843. clipOpacity.assign( 1 );
  26844. let plane;
  26845. loop( numUnionClippingPlanes, ( { i } ) => {
  26846. plane = clippingPlanes.element( i );
  26847. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26848. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26849. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  26850. clipOpacity.equal( 0.0 ).discard();
  26851. } );
  26852. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26853. const unionClipOpacity = property( 'float', 'unionclipOpacity' );
  26854. unionClipOpacity.assign( 1 );
  26855. loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26856. plane = clippingPlanes.element( i );
  26857. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26858. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26859. unionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  26860. } );
  26861. clipOpacity.mulAssign( unionClipOpacity.oneMinus() );
  26862. }
  26863. diffuseColor.a.mulAssign( clipOpacity );
  26864. diffuseColor.a.equal( 0.0 ).discard();
  26865. } )();
  26866. }
  26867. setupDefault( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26868. return tslFn( () => {
  26869. const clippingPlanes = uniforms( planes );
  26870. let plane;
  26871. loop( numUnionClippingPlanes, ( { i } ) => {
  26872. plane = clippingPlanes.element( i );
  26873. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  26874. } );
  26875. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26876. const clipped = property( 'bool', 'clipped' );
  26877. clipped.assign( true );
  26878. loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26879. plane = clippingPlanes.element( i );
  26880. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  26881. } );
  26882. clipped.discard();
  26883. }
  26884. } )();
  26885. }
  26886. }
  26887. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  26888. ClippingNode.DEFAULT = 'default';
  26889. const clipping = () => nodeObject( new ClippingNode() );
  26890. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  26891. class FrontFacingNode extends Node {
  26892. constructor() {
  26893. super( 'bool' );
  26894. this.isFrontFacingNode = true;
  26895. }
  26896. generate( builder ) {
  26897. const { renderer, material } = builder;
  26898. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  26899. if ( material.side === BackSide ) {
  26900. return 'false';
  26901. }
  26902. }
  26903. return builder.getFrontFacing();
  26904. }
  26905. }
  26906. const frontFacing = nodeImmutable( FrontFacingNode );
  26907. const faceDirection = float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  26908. addNodeClass( 'FrontFacingNode', FrontFacingNode );
  26909. const NodeMaterials = new Map();
  26910. class NodeMaterial extends Material {
  26911. constructor() {
  26912. super();
  26913. this.isNodeMaterial = true;
  26914. this.type = this.constructor.type;
  26915. this.forceSinglePass = false;
  26916. this.fog = true;
  26917. this.lights = true;
  26918. this.normals = true;
  26919. this.lightsNode = null;
  26920. this.envNode = null;
  26921. this.aoNode = null;
  26922. this.colorNode = null;
  26923. this.normalNode = null;
  26924. this.opacityNode = null;
  26925. this.backdropNode = null;
  26926. this.backdropAlphaNode = null;
  26927. this.alphaTestNode = null;
  26928. this.positionNode = null;
  26929. this.depthNode = null;
  26930. this.shadowNode = null;
  26931. this.shadowPositionNode = null;
  26932. this.outputNode = null;
  26933. this.fragmentNode = null;
  26934. this.vertexNode = null;
  26935. }
  26936. customProgramCacheKey() {
  26937. return this.type + getCacheKey( this );
  26938. }
  26939. build( builder ) {
  26940. this.setup( builder );
  26941. }
  26942. setup( builder ) {
  26943. // < VERTEX STAGE >
  26944. builder.addStack();
  26945. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  26946. builder.addFlow( 'vertex', builder.removeStack() );
  26947. // < FRAGMENT STAGE >
  26948. builder.addStack();
  26949. let resultNode;
  26950. const clippingNode = this.setupClipping( builder );
  26951. if ( this.depthWrite === true ) this.setupDepth( builder );
  26952. if ( this.fragmentNode === null ) {
  26953. if ( this.normals === true ) this.setupNormal( builder );
  26954. this.setupDiffuseColor( builder );
  26955. this.setupVariants( builder );
  26956. const outgoingLightNode = this.setupLighting( builder );
  26957. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  26958. // force unsigned floats - useful for RenderTargets
  26959. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  26960. resultNode = this.setupOutput( builder, basicOutput );
  26961. // OUTPUT NODE
  26962. output.assign( resultNode );
  26963. //
  26964. if ( this.outputNode !== null ) resultNode = this.outputNode;
  26965. } else {
  26966. let fragmentNode = this.fragmentNode;
  26967. if ( fragmentNode.isOutputStructNode !== true ) {
  26968. fragmentNode = vec4( fragmentNode );
  26969. }
  26970. resultNode = this.setupOutput( builder, fragmentNode );
  26971. }
  26972. builder.stack.outputNode = resultNode;
  26973. builder.addFlow( 'fragment', builder.removeStack() );
  26974. }
  26975. setupClipping( builder ) {
  26976. if ( builder.clippingContext === null ) return null;
  26977. const { globalClippingCount, localClippingCount } = builder.clippingContext;
  26978. let result = null;
  26979. if ( globalClippingCount || localClippingCount ) {
  26980. if ( this.alphaToCoverage ) {
  26981. // to be added to flow when the color/alpha value has been determined
  26982. result = clippingAlpha();
  26983. } else {
  26984. builder.stack.add( clipping() );
  26985. }
  26986. }
  26987. return result;
  26988. }
  26989. setupDepth( builder ) {
  26990. const { renderer } = builder;
  26991. // Depth
  26992. let depthNode = this.depthNode;
  26993. if ( depthNode === null && renderer.logarithmicDepthBuffer === true ) {
  26994. const fragDepth = modelViewProjection().w.add( 1 );
  26995. depthNode = fragDepth.log2().mul( cameraLogDepth ).mul( 0.5 );
  26996. }
  26997. if ( depthNode !== null ) {
  26998. depth.assign( depthNode ).append();
  26999. }
  27000. }
  27001. setupPosition( builder ) {
  27002. const { object } = builder;
  27003. const geometry = object.geometry;
  27004. builder.addStack();
  27005. // Vertex
  27006. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  27007. morphReference( object ).append();
  27008. }
  27009. if ( object.isSkinnedMesh === true ) {
  27010. skinningReference( object ).append();
  27011. }
  27012. if ( this.displacementMap ) {
  27013. const displacementMap = materialReference( 'displacementMap', 'texture' );
  27014. const displacementScale = materialReference( 'displacementScale', 'float' );
  27015. const displacementBias = materialReference( 'displacementBias', 'float' );
  27016. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  27017. }
  27018. if ( object.isBatchedMesh ) {
  27019. batch( object ).append();
  27020. }
  27021. if ( ( object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  27022. instance( object ).append();
  27023. }
  27024. if ( this.positionNode !== null ) {
  27025. positionLocal.assign( this.positionNode );
  27026. }
  27027. const mvp = modelViewProjection();
  27028. builder.context.vertex = builder.removeStack();
  27029. builder.context.mvp = mvp;
  27030. return mvp;
  27031. }
  27032. setupDiffuseColor( { object, geometry } ) {
  27033. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  27034. // VERTEX COLORS
  27035. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  27036. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  27037. }
  27038. // Instanced colors
  27039. if ( object.instanceColor ) {
  27040. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  27041. colorNode = instanceColor.mul( colorNode );
  27042. }
  27043. // COLOR
  27044. diffuseColor.assign( colorNode );
  27045. // OPACITY
  27046. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  27047. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  27048. // ALPHA TEST
  27049. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  27050. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  27051. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  27052. }
  27053. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  27054. diffuseColor.a.assign( 1.0 );
  27055. }
  27056. }
  27057. setupVariants( /*builder*/ ) {
  27058. // Interface function.
  27059. }
  27060. setupNormal() {
  27061. // NORMAL VIEW
  27062. if ( this.flatShading === true ) {
  27063. const normalNode = positionView.dFdx().cross( positionView.dFdy() ).normalize();
  27064. transformedNormalView.assign( normalNode.mul( faceDirection ) );
  27065. } else {
  27066. const normalNode = this.normalNode ? vec3( this.normalNode ) : materialNormal;
  27067. transformedNormalView.assign( normalNode.mul( faceDirection ) );
  27068. }
  27069. }
  27070. getEnvNode( builder ) {
  27071. let node = null;
  27072. if ( this.envNode ) {
  27073. node = this.envNode;
  27074. } else if ( this.envMap ) {
  27075. node = this.envMap.isCubeTexture ? cubeTexture( this.envMap ) : texture( this.envMap );
  27076. } else if ( builder.environmentNode ) {
  27077. node = builder.environmentNode;
  27078. }
  27079. return node;
  27080. }
  27081. setupLights( builder ) {
  27082. const envNode = this.getEnvNode( builder );
  27083. //
  27084. const materialLightsNode = [];
  27085. if ( envNode ) {
  27086. materialLightsNode.push( new EnvironmentNode( envNode ) );
  27087. }
  27088. if ( builder.material.lightMap ) {
  27089. materialLightsNode.push( new IrradianceNode( materialReference( 'lightMap', 'texture' ) ) );
  27090. }
  27091. if ( this.aoNode !== null || builder.material.aoMap ) {
  27092. const aoNode = this.aoNode !== null ? this.aoNode : texture( builder.material.aoMap );
  27093. materialLightsNode.push( new AONode( aoNode ) );
  27094. }
  27095. let lightsN = this.lightsNode || builder.lightsNode;
  27096. if ( materialLightsNode.length > 0 ) {
  27097. lightsN = lightsNode( [ ...lightsN.lightNodes, ...materialLightsNode ] );
  27098. }
  27099. return lightsN;
  27100. }
  27101. setupLightingModel( /*builder*/ ) {
  27102. // Interface function.
  27103. }
  27104. setupLighting( builder ) {
  27105. const { material } = builder;
  27106. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  27107. // OUTGOING LIGHT
  27108. const lights = this.lights === true || this.lightsNode !== null;
  27109. const lightsNode = lights ? this.setupLights( builder ) : null;
  27110. let outgoingLightNode = diffuseColor.rgb;
  27111. if ( lightsNode && lightsNode.hasLight !== false ) {
  27112. const lightingModel = this.setupLightingModel( builder );
  27113. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  27114. } else if ( backdropNode !== null ) {
  27115. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  27116. }
  27117. // EMISSIVE
  27118. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  27119. outgoingLightNode = outgoingLightNode.add( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  27120. }
  27121. return outgoingLightNode;
  27122. }
  27123. setupOutput( builder, outputNode ) {
  27124. // FOG
  27125. if ( this.fog === true ) {
  27126. const fogNode = builder.fogNode;
  27127. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  27128. }
  27129. return outputNode;
  27130. }
  27131. setDefaultValues( material ) {
  27132. // This approach is to reuse the native refreshUniforms*
  27133. // and turn available the use of features like transmission and environment in core
  27134. for ( const property in material ) {
  27135. const value = material[ property ];
  27136. if ( this[ property ] === undefined ) {
  27137. this[ property ] = value;
  27138. if ( value && value.clone ) this[ property ] = value.clone();
  27139. }
  27140. }
  27141. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  27142. for ( const key in descriptors ) {
  27143. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  27144. descriptors[ key ].get !== undefined ) {
  27145. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  27146. }
  27147. }
  27148. }
  27149. toJSON( meta ) {
  27150. const isRoot = ( meta === undefined || typeof meta === 'string' );
  27151. if ( isRoot ) {
  27152. meta = {
  27153. textures: {},
  27154. images: {},
  27155. nodes: {}
  27156. };
  27157. }
  27158. const data = Material.prototype.toJSON.call( this, meta );
  27159. const nodeChildren = getNodeChildren( this );
  27160. data.inputNodes = {};
  27161. for ( const { property, childNode } of nodeChildren ) {
  27162. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  27163. }
  27164. // TODO: Copied from Object3D.toJSON
  27165. function extractFromCache( cache ) {
  27166. const values = [];
  27167. for ( const key in cache ) {
  27168. const data = cache[ key ];
  27169. delete data.metadata;
  27170. values.push( data );
  27171. }
  27172. return values;
  27173. }
  27174. if ( isRoot ) {
  27175. const textures = extractFromCache( meta.textures );
  27176. const images = extractFromCache( meta.images );
  27177. const nodes = extractFromCache( meta.nodes );
  27178. if ( textures.length > 0 ) data.textures = textures;
  27179. if ( images.length > 0 ) data.images = images;
  27180. if ( nodes.length > 0 ) data.nodes = nodes;
  27181. }
  27182. return data;
  27183. }
  27184. copy( source ) {
  27185. this.lightsNode = source.lightsNode;
  27186. this.envNode = source.envNode;
  27187. this.colorNode = source.colorNode;
  27188. this.normalNode = source.normalNode;
  27189. this.opacityNode = source.opacityNode;
  27190. this.backdropNode = source.backdropNode;
  27191. this.backdropAlphaNode = source.backdropAlphaNode;
  27192. this.alphaTestNode = source.alphaTestNode;
  27193. this.positionNode = source.positionNode;
  27194. this.depthNode = source.depthNode;
  27195. this.shadowNode = source.shadowNode;
  27196. this.shadowPositionNode = source.shadowPositionNode;
  27197. this.outputNode = source.outputNode;
  27198. this.fragmentNode = source.fragmentNode;
  27199. this.vertexNode = source.vertexNode;
  27200. return super.copy( source );
  27201. }
  27202. static fromMaterial( material ) {
  27203. if ( material.isNodeMaterial === true ) { // is already a node material
  27204. return material;
  27205. }
  27206. const type = material.type.replace( 'Material', 'NodeMaterial' );
  27207. const nodeMaterial = createNodeMaterialFromType( type );
  27208. if ( nodeMaterial === undefined ) {
  27209. throw new Error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  27210. }
  27211. for ( const key in material ) {
  27212. nodeMaterial[ key ] = material[ key ];
  27213. }
  27214. return nodeMaterial;
  27215. }
  27216. }
  27217. function addNodeMaterial( type, nodeMaterial ) {
  27218. if ( typeof nodeMaterial !== 'function' || ! type ) throw new Error( `Node material ${ type } is not a class` );
  27219. if ( NodeMaterials.has( type ) ) {
  27220. console.warn( `Redefinition of node material ${ type }` );
  27221. return;
  27222. }
  27223. NodeMaterials.set( type, nodeMaterial );
  27224. nodeMaterial.type = type;
  27225. }
  27226. function createNodeMaterialFromType( type ) {
  27227. const Material = NodeMaterials.get( type );
  27228. if ( Material !== undefined ) {
  27229. return new Material();
  27230. }
  27231. }
  27232. addNodeMaterial( 'NodeMaterial', NodeMaterial );
  27233. class Uniform {
  27234. constructor( name, value ) {
  27235. this.name = name;
  27236. this.value = value;
  27237. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  27238. this.itemSize = 0;
  27239. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  27240. }
  27241. setValue( value ) {
  27242. this.value = value;
  27243. }
  27244. getValue() {
  27245. return this.value;
  27246. }
  27247. }
  27248. class NumberUniform extends Uniform {
  27249. constructor( name, value = 0 ) {
  27250. super( name, value );
  27251. this.isNumberUniform = true;
  27252. this.boundary = 4;
  27253. this.itemSize = 1;
  27254. }
  27255. }
  27256. class Vector2Uniform extends Uniform {
  27257. constructor( name, value = new Vector2() ) {
  27258. super( name, value );
  27259. this.isVector2Uniform = true;
  27260. this.boundary = 8;
  27261. this.itemSize = 2;
  27262. }
  27263. }
  27264. class Vector3Uniform extends Uniform {
  27265. constructor( name, value = new Vector3() ) {
  27266. super( name, value );
  27267. this.isVector3Uniform = true;
  27268. this.boundary = 16;
  27269. this.itemSize = 3;
  27270. }
  27271. }
  27272. class Vector4Uniform extends Uniform {
  27273. constructor( name, value = new Vector4() ) {
  27274. super( name, value );
  27275. this.isVector4Uniform = true;
  27276. this.boundary = 16;
  27277. this.itemSize = 4;
  27278. }
  27279. }
  27280. class ColorUniform extends Uniform {
  27281. constructor( name, value = new Color() ) {
  27282. super( name, value );
  27283. this.isColorUniform = true;
  27284. this.boundary = 16;
  27285. this.itemSize = 3;
  27286. }
  27287. }
  27288. class Matrix3Uniform extends Uniform {
  27289. constructor( name, value = new Matrix3() ) {
  27290. super( name, value );
  27291. this.isMatrix3Uniform = true;
  27292. this.boundary = 48;
  27293. this.itemSize = 12;
  27294. }
  27295. }
  27296. class Matrix4Uniform extends Uniform {
  27297. constructor( name, value = new Matrix4() ) {
  27298. super( name, value );
  27299. this.isMatrix4Uniform = true;
  27300. this.boundary = 64;
  27301. this.itemSize = 16;
  27302. }
  27303. }
  27304. class NumberNodeUniform extends NumberUniform {
  27305. constructor( nodeUniform ) {
  27306. super( nodeUniform.name, nodeUniform.value );
  27307. this.nodeUniform = nodeUniform;
  27308. }
  27309. getValue() {
  27310. return this.nodeUniform.value;
  27311. }
  27312. }
  27313. class Vector2NodeUniform extends Vector2Uniform {
  27314. constructor( nodeUniform ) {
  27315. super( nodeUniform.name, nodeUniform.value );
  27316. this.nodeUniform = nodeUniform;
  27317. }
  27318. getValue() {
  27319. return this.nodeUniform.value;
  27320. }
  27321. }
  27322. class Vector3NodeUniform extends Vector3Uniform {
  27323. constructor( nodeUniform ) {
  27324. super( nodeUniform.name, nodeUniform.value );
  27325. this.nodeUniform = nodeUniform;
  27326. }
  27327. getValue() {
  27328. return this.nodeUniform.value;
  27329. }
  27330. }
  27331. class Vector4NodeUniform extends Vector4Uniform {
  27332. constructor( nodeUniform ) {
  27333. super( nodeUniform.name, nodeUniform.value );
  27334. this.nodeUniform = nodeUniform;
  27335. }
  27336. getValue() {
  27337. return this.nodeUniform.value;
  27338. }
  27339. }
  27340. class ColorNodeUniform extends ColorUniform {
  27341. constructor( nodeUniform ) {
  27342. super( nodeUniform.name, nodeUniform.value );
  27343. this.nodeUniform = nodeUniform;
  27344. }
  27345. getValue() {
  27346. return this.nodeUniform.value;
  27347. }
  27348. }
  27349. class Matrix3NodeUniform extends Matrix3Uniform {
  27350. constructor( nodeUniform ) {
  27351. super( nodeUniform.name, nodeUniform.value );
  27352. this.nodeUniform = nodeUniform;
  27353. }
  27354. getValue() {
  27355. return this.nodeUniform.value;
  27356. }
  27357. }
  27358. class Matrix4NodeUniform extends Matrix4Uniform {
  27359. constructor( nodeUniform ) {
  27360. super( nodeUniform.name, nodeUniform.value );
  27361. this.nodeUniform = nodeUniform;
  27362. }
  27363. getValue() {
  27364. return this.nodeUniform.value;
  27365. }
  27366. }
  27367. class StackNode extends Node {
  27368. constructor( parent = null ) {
  27369. super();
  27370. this.nodes = [];
  27371. this.outputNode = null;
  27372. this.parent = parent;
  27373. this._currentCond = null;
  27374. this.isStackNode = true;
  27375. }
  27376. getNodeType( builder ) {
  27377. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  27378. }
  27379. add( node ) {
  27380. this.nodes.push( node );
  27381. return this;
  27382. }
  27383. if( boolNode, method ) {
  27384. const methodNode = new ShaderNode( method );
  27385. this._currentCond = cond( boolNode, methodNode );
  27386. return this.add( this._currentCond );
  27387. }
  27388. elseif( boolNode, method ) {
  27389. const methodNode = new ShaderNode( method );
  27390. const ifNode = cond( boolNode, methodNode );
  27391. this._currentCond.elseNode = ifNode;
  27392. this._currentCond = ifNode;
  27393. return this;
  27394. }
  27395. else( method ) {
  27396. this._currentCond.elseNode = new ShaderNode( method );
  27397. return this;
  27398. }
  27399. build( builder, ...params ) {
  27400. const previousStack = getCurrentStack();
  27401. setCurrentStack( this );
  27402. for ( const node of this.nodes ) {
  27403. node.build( builder, 'void' );
  27404. }
  27405. setCurrentStack( previousStack );
  27406. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  27407. }
  27408. }
  27409. const stack = nodeProxy( StackNode );
  27410. addNodeClass( 'StackNode', StackNode );
  27411. class EquirectUVNode extends TempNode {
  27412. constructor( dirNode = positionWorldDirection ) {
  27413. super( 'vec2' );
  27414. this.dirNode = dirNode;
  27415. }
  27416. setup() {
  27417. const dir = this.dirNode;
  27418. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  27419. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  27420. return vec2( u, v );
  27421. }
  27422. }
  27423. const equirectUV = nodeProxy( EquirectUVNode );
  27424. addNodeClass( 'EquirectUVNode', EquirectUVNode );
  27425. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  27426. class CubeRenderTarget extends WebGLCubeRenderTarget {
  27427. constructor( size = 1, options = {} ) {
  27428. super( size, options );
  27429. this.isCubeRenderTarget = true;
  27430. }
  27431. fromEquirectangularTexture( renderer, texture$1 ) {
  27432. const currentMinFilter = texture$1.minFilter;
  27433. const currentGenerateMipmaps = texture$1.generateMipmaps;
  27434. texture$1.generateMipmaps = true;
  27435. this.texture.type = texture$1.type;
  27436. this.texture.colorSpace = texture$1.colorSpace;
  27437. this.texture.generateMipmaps = texture$1.generateMipmaps;
  27438. this.texture.minFilter = texture$1.minFilter;
  27439. this.texture.magFilter = texture$1.magFilter;
  27440. const geometry = new BoxGeometry( 5, 5, 5 );
  27441. const uvNode = equirectUV( positionWorldDirection );
  27442. const material = createNodeMaterialFromType( 'MeshBasicNodeMaterial' );
  27443. material.colorNode = texture( texture$1, uvNode, 0 );
  27444. material.side = BackSide;
  27445. material.blending = NoBlending;
  27446. const mesh = new Mesh( geometry, material );
  27447. const scene = new Scene();
  27448. scene.add( mesh );
  27449. // Avoid blurred poles
  27450. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  27451. const camera = new CubeCamera( 1, 10, this );
  27452. camera.update( renderer, scene );
  27453. texture$1.minFilter = currentMinFilter;
  27454. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  27455. mesh.geometry.dispose();
  27456. mesh.material.dispose();
  27457. return this;
  27458. }
  27459. }
  27460. const LOD_MIN = 4;
  27461. // The standard deviations (radians) associated with the extra mips. These are
  27462. // chosen to approximate a Trowbridge-Reitz distribution function times the
  27463. // geometric shadowing function. These sigma values squared must match the
  27464. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  27465. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  27466. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  27467. // samples and exit early, but not recompile the shader.
  27468. const MAX_SAMPLES = 20;
  27469. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  27470. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  27471. const _clearColor$1 = /*@__PURE__*/ new Color();
  27472. let _oldTarget = null;
  27473. let _oldActiveCubeFace = 0;
  27474. let _oldActiveMipmapLevel = 0;
  27475. // Golden Ratio
  27476. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  27477. const INV_PHI = 1 / PHI;
  27478. // Vertices of a dodecahedron (except the opposites, which represent the
  27479. // same axis), used as axis directions evenly spread on a sphere.
  27480. const _axisDirections = [
  27481. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  27482. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  27483. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  27484. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  27485. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  27486. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  27487. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  27488. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  27489. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  27490. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  27491. ];
  27492. //
  27493. // WebGPU Face indices
  27494. const _faceLib = [
  27495. 3, 1, 5,
  27496. 0, 4, 2
  27497. ];
  27498. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  27499. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  27500. /**
  27501. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  27502. * (PMREM) from a cubeMap environment texture. This allows different levels of
  27503. * blur to be quickly accessed based on material roughness. It is packed into a
  27504. * special CubeUV format that allows us to perform custom interpolation so that
  27505. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  27506. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  27507. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  27508. * higher roughness levels. In this way we maintain resolution to smoothly
  27509. * interpolate diffuse lighting while limiting sampling computation.
  27510. *
  27511. * Paper: Fast, Accurate Image-Based Lighting
  27512. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  27513. */
  27514. class PMREMGenerator {
  27515. constructor( renderer ) {
  27516. this._renderer = renderer;
  27517. this._pingPongRenderTarget = null;
  27518. this._lodMax = 0;
  27519. this._cubeSize = 0;
  27520. this._lodPlanes = [];
  27521. this._sizeLods = [];
  27522. this._sigmas = [];
  27523. this._lodMeshes = [];
  27524. this._blurMaterial = null;
  27525. this._cubemapMaterial = null;
  27526. this._equirectMaterial = null;
  27527. this._backgroundBox = null;
  27528. }
  27529. /**
  27530. * Generates a PMREM from a supplied Scene, which can be faster than using an
  27531. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  27532. * in radians to be applied to the scene before PMREM generation. Optional near
  27533. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  27534. * is placed at the origin).
  27535. */
  27536. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  27537. _oldTarget = this._renderer.getRenderTarget();
  27538. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  27539. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  27540. this._setSize( 256 );
  27541. const cubeUVRenderTarget = this._allocateTargets();
  27542. cubeUVRenderTarget.depthBuffer = true;
  27543. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  27544. if ( sigma > 0 ) {
  27545. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  27546. }
  27547. this._applyPMREM( cubeUVRenderTarget );
  27548. this._cleanup( cubeUVRenderTarget );
  27549. return cubeUVRenderTarget;
  27550. }
  27551. /**
  27552. * Generates a PMREM from an equirectangular texture, which can be either LDR
  27553. * or HDR. The ideal input image size is 1k (1024 x 512),
  27554. * as this matches best with the 256 x 256 cubemap output.
  27555. */
  27556. fromEquirectangular( equirectangular, renderTarget = null ) {
  27557. return this._fromTexture( equirectangular, renderTarget );
  27558. }
  27559. /**
  27560. * Generates a PMREM from an cubemap texture, which can be either LDR
  27561. * or HDR. The ideal input cube size is 256 x 256,
  27562. * as this matches best with the 256 x 256 cubemap output.
  27563. */
  27564. fromCubemap( cubemap, renderTarget = null ) {
  27565. return this._fromTexture( cubemap, renderTarget );
  27566. }
  27567. /**
  27568. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  27569. * your texture's network fetch for increased concurrency.
  27570. */
  27571. compileCubemapShader() {
  27572. if ( this._cubemapMaterial === null ) {
  27573. this._cubemapMaterial = _getCubemapMaterial();
  27574. this._compileMaterial( this._cubemapMaterial );
  27575. }
  27576. }
  27577. /**
  27578. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  27579. * your texture's network fetch for increased concurrency.
  27580. */
  27581. compileEquirectangularShader() {
  27582. if ( this._equirectMaterial === null ) {
  27583. this._equirectMaterial = _getEquirectMaterial();
  27584. this._compileMaterial( this._equirectMaterial );
  27585. }
  27586. }
  27587. /**
  27588. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  27589. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  27590. * one of them will cause any others to also become unusable.
  27591. */
  27592. dispose() {
  27593. this._dispose();
  27594. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  27595. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  27596. if ( this._backgroundBox !== null ) {
  27597. this._backgroundBox.geometry.dispose();
  27598. this._backgroundBox.material.dispose();
  27599. }
  27600. }
  27601. // private interface
  27602. _setSize( cubeSize ) {
  27603. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  27604. this._cubeSize = Math.pow( 2, this._lodMax );
  27605. }
  27606. _dispose() {
  27607. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  27608. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  27609. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  27610. this._lodPlanes[ i ].dispose();
  27611. }
  27612. }
  27613. _cleanup( outputTarget ) {
  27614. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  27615. outputTarget.scissorTest = false;
  27616. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  27617. }
  27618. _fromTexture( texture, renderTarget ) {
  27619. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  27620. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  27621. } else { // Equirectangular
  27622. this._setSize( texture.image.width / 4 );
  27623. }
  27624. _oldTarget = this._renderer.getRenderTarget();
  27625. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  27626. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  27627. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  27628. this._textureToCubeUV( texture, cubeUVRenderTarget );
  27629. this._applyPMREM( cubeUVRenderTarget );
  27630. this._cleanup( cubeUVRenderTarget );
  27631. return cubeUVRenderTarget;
  27632. }
  27633. _allocateTargets() {
  27634. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  27635. const height = 4 * this._cubeSize;
  27636. const params = {
  27637. magFilter: LinearFilter,
  27638. minFilter: LinearFilter,
  27639. generateMipmaps: false,
  27640. type: HalfFloatType,
  27641. format: RGBAFormat,
  27642. colorSpace: LinearSRGBColorSpace,
  27643. //depthBuffer: false
  27644. };
  27645. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  27646. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  27647. if ( this._pingPongRenderTarget !== null ) {
  27648. this._dispose();
  27649. }
  27650. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  27651. const { _lodMax } = this;
  27652. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  27653. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  27654. }
  27655. return cubeUVRenderTarget;
  27656. }
  27657. _compileMaterial( material ) {
  27658. const tmpMesh = this._lodMeshes[ 0 ];
  27659. tmpMesh.material = material;
  27660. this._renderer.compile( tmpMesh, _flatCamera );
  27661. }
  27662. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  27663. const cubeCamera = _cubeCamera;
  27664. cubeCamera.near = near;
  27665. cubeCamera.far = far;
  27666. // px, py, pz, nx, ny, nz
  27667. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  27668. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  27669. const renderer = this._renderer;
  27670. const originalAutoClear = renderer.autoClear;
  27671. renderer.getClearColor( _clearColor$1 );
  27672. renderer.autoClear = false;
  27673. let backgroundBox = this._backgroundBox;
  27674. if ( backgroundBox === null ) {
  27675. const backgroundMaterial = new MeshBasicMaterial( {
  27676. name: 'PMREM.Background',
  27677. side: BackSide,
  27678. depthWrite: false,
  27679. depthTest: false
  27680. } );
  27681. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  27682. }
  27683. let useSolidColor = false;
  27684. const background = scene.background;
  27685. if ( background ) {
  27686. if ( background.isColor ) {
  27687. backgroundBox.material.color.copy( background );
  27688. scene.background = null;
  27689. useSolidColor = true;
  27690. }
  27691. } else {
  27692. backgroundBox.material.color.copy( _clearColor$1 );
  27693. useSolidColor = true;
  27694. }
  27695. renderer.setRenderTarget( cubeUVRenderTarget );
  27696. renderer.clear();
  27697. if ( useSolidColor ) {
  27698. renderer.render( backgroundBox, cubeCamera );
  27699. }
  27700. for ( let i = 0; i < 6; i ++ ) {
  27701. const col = i % 3;
  27702. if ( col === 0 ) {
  27703. cubeCamera.up.set( 0, upSign[ i ], 0 );
  27704. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  27705. } else if ( col === 1 ) {
  27706. cubeCamera.up.set( 0, 0, upSign[ i ] );
  27707. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  27708. } else {
  27709. cubeCamera.up.set( 0, upSign[ i ], 0 );
  27710. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  27711. }
  27712. const size = this._cubeSize;
  27713. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  27714. renderer.render( scene, cubeCamera );
  27715. }
  27716. renderer.autoClear = originalAutoClear;
  27717. scene.background = background;
  27718. }
  27719. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  27720. const renderer = this._renderer;
  27721. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  27722. if ( isCubeTexture ) {
  27723. if ( this._cubemapMaterial === null ) {
  27724. this._cubemapMaterial = _getCubemapMaterial( texture );
  27725. }
  27726. } else {
  27727. if ( this._equirectMaterial === null ) {
  27728. this._equirectMaterial = _getEquirectMaterial( texture );
  27729. }
  27730. }
  27731. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  27732. material.fragmentNode.value = texture;
  27733. const mesh = this._lodMeshes[ 0 ];
  27734. mesh.material = material;
  27735. const size = this._cubeSize;
  27736. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  27737. renderer.setRenderTarget( cubeUVRenderTarget );
  27738. renderer.render( mesh, _flatCamera );
  27739. }
  27740. _applyPMREM( cubeUVRenderTarget ) {
  27741. const renderer = this._renderer;
  27742. const autoClear = renderer.autoClear;
  27743. renderer.autoClear = false;
  27744. const n = this._lodPlanes.length;
  27745. for ( let i = 1; i < n; i ++ ) {
  27746. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  27747. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  27748. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  27749. }
  27750. renderer.autoClear = autoClear;
  27751. }
  27752. /**
  27753. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  27754. * vertically and horizontally, but this breaks down on a cube. Here we apply
  27755. * the blur latitudinally (around the poles), and then longitudinally (towards
  27756. * the poles) to approximate the orthogonally-separable blur. It is least
  27757. * accurate at the poles, but still does a decent job.
  27758. */
  27759. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  27760. const pingPongRenderTarget = this._pingPongRenderTarget;
  27761. this._halfBlur(
  27762. cubeUVRenderTarget,
  27763. pingPongRenderTarget,
  27764. lodIn,
  27765. lodOut,
  27766. sigma,
  27767. 'latitudinal',
  27768. poleAxis );
  27769. this._halfBlur(
  27770. pingPongRenderTarget,
  27771. cubeUVRenderTarget,
  27772. lodOut,
  27773. lodOut,
  27774. sigma,
  27775. 'longitudinal',
  27776. poleAxis );
  27777. }
  27778. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  27779. const renderer = this._renderer;
  27780. const blurMaterial = this._blurMaterial;
  27781. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  27782. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  27783. }
  27784. // Number of standard deviations at which to cut off the discrete approximation.
  27785. const STANDARD_DEVIATIONS = 3;
  27786. const blurMesh = this._lodMeshes[ lodOut ];
  27787. blurMesh.material = blurMaterial;
  27788. const blurUniforms = blurMaterial.uniforms;
  27789. const pixels = this._sizeLods[ lodIn ] - 1;
  27790. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  27791. const sigmaPixels = sigmaRadians / radiansPerPixel;
  27792. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  27793. if ( samples > MAX_SAMPLES ) {
  27794. console.warn( `sigmaRadians, ${
  27795. sigmaRadians}, is too large and will clip, as it requested ${
  27796. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  27797. }
  27798. const weights = [];
  27799. let sum = 0;
  27800. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  27801. const x = i / sigmaPixels;
  27802. const weight = Math.exp( - x * x / 2 );
  27803. weights.push( weight );
  27804. if ( i === 0 ) {
  27805. sum += weight;
  27806. } else if ( i < samples ) {
  27807. sum += 2 * weight;
  27808. }
  27809. }
  27810. for ( let i = 0; i < weights.length; i ++ ) {
  27811. weights[ i ] = weights[ i ] / sum;
  27812. }
  27813. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  27814. blurUniforms.envMap.value = targetIn.texture;
  27815. blurUniforms.samples.value = samples;
  27816. blurUniforms.weights.array = weights;
  27817. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  27818. if ( poleAxis ) {
  27819. blurUniforms.poleAxis.value = poleAxis;
  27820. }
  27821. const { _lodMax } = this;
  27822. blurUniforms.dTheta.value = radiansPerPixel;
  27823. blurUniforms.mipInt.value = _lodMax - lodIn;
  27824. const outputSize = this._sizeLods[ lodOut ];
  27825. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  27826. const y = 4 * ( this._cubeSize - outputSize );
  27827. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  27828. renderer.setRenderTarget( targetOut );
  27829. renderer.render( blurMesh, _flatCamera );
  27830. }
  27831. }
  27832. function _createPlanes( lodMax ) {
  27833. const lodPlanes = [];
  27834. const sizeLods = [];
  27835. const sigmas = [];
  27836. const lodMeshes = [];
  27837. let lod = lodMax;
  27838. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  27839. for ( let i = 0; i < totalLods; i ++ ) {
  27840. const sizeLod = Math.pow( 2, lod );
  27841. sizeLods.push( sizeLod );
  27842. let sigma = 1.0 / sizeLod;
  27843. if ( i > lodMax - LOD_MIN ) {
  27844. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  27845. } else if ( i === 0 ) {
  27846. sigma = 0;
  27847. }
  27848. sigmas.push( sigma );
  27849. const texelSize = 1.0 / ( sizeLod - 2 );
  27850. const min = - texelSize;
  27851. const max = 1 + texelSize;
  27852. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  27853. const cubeFaces = 6;
  27854. const vertices = 6;
  27855. const positionSize = 3;
  27856. const uvSize = 2;
  27857. const faceIndexSize = 1;
  27858. const position = new Float32Array( positionSize * vertices * cubeFaces );
  27859. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  27860. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  27861. for ( let face = 0; face < cubeFaces; face ++ ) {
  27862. const x = ( face % 3 ) * 2 / 3 - 1;
  27863. const y = face > 2 ? 0 : - 1;
  27864. const coordinates = [
  27865. x, y, 0,
  27866. x + 2 / 3, y, 0,
  27867. x + 2 / 3, y + 1, 0,
  27868. x, y, 0,
  27869. x + 2 / 3, y + 1, 0,
  27870. x, y + 1, 0
  27871. ];
  27872. const faceIdx = _faceLib[ face ];
  27873. position.set( coordinates, positionSize * vertices * faceIdx );
  27874. uv.set( uv1, uvSize * vertices * faceIdx );
  27875. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  27876. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  27877. }
  27878. const planes = new BufferGeometry();
  27879. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  27880. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  27881. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  27882. lodPlanes.push( planes );
  27883. lodMeshes.push( new Mesh( planes, null ) );
  27884. if ( lod > LOD_MIN ) {
  27885. lod --;
  27886. }
  27887. }
  27888. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  27889. }
  27890. function _createRenderTarget( width, height, params ) {
  27891. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  27892. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  27893. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  27894. cubeUVRenderTarget.texture.isPMREMTexture = true;
  27895. cubeUVRenderTarget.scissorTest = true;
  27896. return cubeUVRenderTarget;
  27897. }
  27898. function _setViewport( target, x, y, width, height ) {
  27899. const viewY = target.height - height - y;
  27900. target.viewport.set( x, viewY, width, height );
  27901. target.scissor.set( x, viewY, width, height );
  27902. }
  27903. function _getMaterial() {
  27904. const material = new NodeMaterial();
  27905. material.depthTest = false;
  27906. material.depthWrite = false;
  27907. material.blending = NoBlending;
  27908. return material;
  27909. }
  27910. function _getBlurShader( lodMax, width, height ) {
  27911. const weights = uniforms( new Array( MAX_SAMPLES ).fill( 0 ) );
  27912. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  27913. const dTheta = uniform( 0 );
  27914. const n = float( MAX_SAMPLES );
  27915. const latitudinal = uniform( 0 ); // false, bool
  27916. const samples = uniform( 1 ); // int
  27917. const envMap = texture( null );
  27918. const mipInt = uniform( 0 ); // int
  27919. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  27920. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  27921. const CUBEUV_MAX_MIP = float( lodMax );
  27922. const materialUniforms = {
  27923. n,
  27924. latitudinal,
  27925. weights,
  27926. poleAxis,
  27927. outputDirection,
  27928. dTheta,
  27929. samples,
  27930. envMap,
  27931. mipInt,
  27932. CUBEUV_TEXEL_WIDTH,
  27933. CUBEUV_TEXEL_HEIGHT,
  27934. CUBEUV_MAX_MIP
  27935. };
  27936. const material = _getMaterial();
  27937. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  27938. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  27939. return material;
  27940. }
  27941. function _getCubemapMaterial( envTexture ) {
  27942. const material = _getMaterial();
  27943. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  27944. return material;
  27945. }
  27946. function _getEquirectMaterial( envTexture ) {
  27947. const material = _getMaterial();
  27948. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  27949. return material;
  27950. }
  27951. let _id$3 = 0;
  27952. class BindGroup {
  27953. constructor( name = '', bindings = [] ) {
  27954. this.name = name;
  27955. this.bindings = bindings;
  27956. this.id = _id$3 ++;
  27957. }
  27958. }
  27959. const rendererCache = new WeakMap();
  27960. const typeFromLength = new Map( [
  27961. [ 2, 'vec2' ],
  27962. [ 3, 'vec3' ],
  27963. [ 4, 'vec4' ],
  27964. [ 9, 'mat3' ],
  27965. [ 16, 'mat4' ]
  27966. ] );
  27967. const typeFromArray = new Map( [
  27968. [ Int8Array, 'int' ],
  27969. [ Int16Array, 'int' ],
  27970. [ Int32Array, 'int' ],
  27971. [ Uint8Array, 'uint' ],
  27972. [ Uint16Array, 'uint' ],
  27973. [ Uint32Array, 'uint' ],
  27974. [ Float32Array, 'float' ]
  27975. ] );
  27976. const toFloat = ( value ) => {
  27977. value = Number( value );
  27978. return value + ( value % 1 ? '' : '.0' );
  27979. };
  27980. class NodeBuilder {
  27981. constructor( object, renderer, parser ) {
  27982. this.object = object;
  27983. this.material = ( object && object.material ) || null;
  27984. this.geometry = ( object && object.geometry ) || null;
  27985. this.renderer = renderer;
  27986. this.parser = parser;
  27987. this.scene = null;
  27988. this.camera = null;
  27989. this.nodes = [];
  27990. this.updateNodes = [];
  27991. this.updateBeforeNodes = [];
  27992. this.updateAfterNodes = [];
  27993. this.hashNodes = {};
  27994. this.lightsNode = null;
  27995. this.environmentNode = null;
  27996. this.fogNode = null;
  27997. this.clippingContext = null;
  27998. this.vertexShader = null;
  27999. this.fragmentShader = null;
  28000. this.computeShader = null;
  28001. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  28002. this.flowCode = { vertex: '', fragment: '', compute: '' };
  28003. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  28004. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  28005. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  28006. this.bindingsIndexes = {};
  28007. this.bindGroups = null;
  28008. this.attributes = [];
  28009. this.bufferAttributes = [];
  28010. this.varyings = [];
  28011. this.codes = {};
  28012. this.vars = {};
  28013. this.flow = { code: '' };
  28014. this.chaining = [];
  28015. this.stack = stack();
  28016. this.stacks = [];
  28017. this.tab = '\t';
  28018. this.instanceBindGroups = true;
  28019. this.currentFunctionNode = null;
  28020. this.context = {
  28021. keywords: new NodeKeywords(),
  28022. material: this.material
  28023. };
  28024. this.cache = new NodeCache();
  28025. this.globalCache = this.cache;
  28026. this.flowsData = new WeakMap();
  28027. this.shaderStage = null;
  28028. this.buildStage = null;
  28029. }
  28030. getBingGroupsCache() {
  28031. let bindGroupsCache = rendererCache.get( this.renderer );
  28032. if ( bindGroupsCache === undefined ) {
  28033. bindGroupsCache = new ChainMap();
  28034. rendererCache.set( this.renderer, bindGroupsCache );
  28035. }
  28036. return bindGroupsCache;
  28037. }
  28038. createRenderTarget( width, height, options ) {
  28039. return new RenderTarget( width, height, options );
  28040. }
  28041. createCubeRenderTarget( size, options ) {
  28042. return new CubeRenderTarget( size, options );
  28043. }
  28044. createPMREMGenerator() {
  28045. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  28046. return new PMREMGenerator( this.renderer );
  28047. }
  28048. includes( node ) {
  28049. return this.nodes.includes( node );
  28050. }
  28051. _getBindGroup( groupName, bindings ) {
  28052. const bindGroupsCache = this.getBingGroupsCache();
  28053. // cache individual uniforms group
  28054. const bindingsArray = [];
  28055. let sharedGroup = true;
  28056. for ( const binding of bindings ) {
  28057. if ( binding.groupNode.shared === true ) {
  28058. // nodes is the chainmap key
  28059. const nodes = binding.getNodes();
  28060. let sharedBinding = bindGroupsCache.get( nodes );
  28061. if ( sharedBinding === undefined ) {
  28062. bindGroupsCache.set( nodes, binding );
  28063. sharedBinding = binding;
  28064. }
  28065. bindingsArray.push( sharedBinding );
  28066. } else {
  28067. bindingsArray.push( binding );
  28068. sharedGroup = false;
  28069. }
  28070. }
  28071. //
  28072. let bindGroup;
  28073. if ( sharedGroup ) {
  28074. bindGroup = bindGroupsCache.get( bindingsArray );
  28075. if ( bindGroup === undefined ) {
  28076. bindGroup = new BindGroup( groupName, bindingsArray );
  28077. bindGroupsCache.set( bindingsArray, bindGroup );
  28078. }
  28079. } else {
  28080. bindGroup = new BindGroup( groupName, bindingsArray );
  28081. }
  28082. return bindGroup;
  28083. }
  28084. getBindGroupArray( groupName, shaderStage ) {
  28085. const bindings = this.bindings[ shaderStage ];
  28086. let bindGroup = bindings[ groupName ];
  28087. if ( bindGroup === undefined ) {
  28088. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  28089. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  28090. }
  28091. bindings[ groupName ] = bindGroup = [];
  28092. }
  28093. return bindGroup;
  28094. }
  28095. getBindings() {
  28096. let bindingsGroups = this.bindGroups;
  28097. if ( bindingsGroups === null ) {
  28098. const groups = {};
  28099. const bindings = this.bindings;
  28100. for ( const shaderStage of shaderStages ) {
  28101. for ( const groupName in bindings[ shaderStage ] ) {
  28102. const uniforms = bindings[ shaderStage ][ groupName ];
  28103. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  28104. groupUniforms.push( ...uniforms );
  28105. }
  28106. }
  28107. bindingsGroups = [];
  28108. for ( const groupName in groups ) {
  28109. const group = groups[ groupName ];
  28110. const bindingsGroup = this._getBindGroup( groupName, group );
  28111. bindingsGroups.push( bindingsGroup );
  28112. }
  28113. this.bindGroups = bindingsGroups;
  28114. }
  28115. return bindingsGroups;
  28116. }
  28117. setHashNode( node, hash ) {
  28118. this.hashNodes[ hash ] = node;
  28119. }
  28120. addNode( node ) {
  28121. if ( this.nodes.includes( node ) === false ) {
  28122. this.nodes.push( node );
  28123. this.setHashNode( node, node.getHash( this ) );
  28124. }
  28125. }
  28126. buildUpdateNodes() {
  28127. for ( const node of this.nodes ) {
  28128. const updateType = node.getUpdateType();
  28129. const updateBeforeType = node.getUpdateBeforeType();
  28130. const updateAfterType = node.getUpdateAfterType();
  28131. if ( updateType !== NodeUpdateType.NONE ) {
  28132. this.updateNodes.push( node.getSelf() );
  28133. }
  28134. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  28135. this.updateBeforeNodes.push( node );
  28136. }
  28137. if ( updateAfterType !== NodeUpdateType.NONE ) {
  28138. this.updateAfterNodes.push( node );
  28139. }
  28140. }
  28141. }
  28142. get currentNode() {
  28143. return this.chaining[ this.chaining.length - 1 ];
  28144. }
  28145. isFilteredTexture( texture ) {
  28146. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  28147. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  28148. }
  28149. addChain( node ) {
  28150. /*
  28151. if ( this.chaining.indexOf( node ) !== - 1 ) {
  28152. console.warn( 'Recursive node: ', node );
  28153. }
  28154. */
  28155. this.chaining.push( node );
  28156. }
  28157. removeChain( node ) {
  28158. const lastChain = this.chaining.pop();
  28159. if ( lastChain !== node ) {
  28160. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  28161. }
  28162. }
  28163. getMethod( method ) {
  28164. return method;
  28165. }
  28166. getNodeFromHash( hash ) {
  28167. return this.hashNodes[ hash ];
  28168. }
  28169. addFlow( shaderStage, node ) {
  28170. this.flowNodes[ shaderStage ].push( node );
  28171. return node;
  28172. }
  28173. setContext( context ) {
  28174. this.context = context;
  28175. }
  28176. getContext() {
  28177. return this.context;
  28178. }
  28179. setCache( cache ) {
  28180. this.cache = cache;
  28181. }
  28182. getCache() {
  28183. return this.cache;
  28184. }
  28185. getCacheFromNode( node, parent = true ) {
  28186. const data = this.getDataFromNode( node );
  28187. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  28188. return data.cache;
  28189. }
  28190. isAvailable( /*name*/ ) {
  28191. return false;
  28192. }
  28193. getVertexIndex() {
  28194. console.warn( 'Abstract function.' );
  28195. }
  28196. getInstanceIndex() {
  28197. console.warn( 'Abstract function.' );
  28198. }
  28199. getDrawIndex() {
  28200. console.warn( 'Abstract function.' );
  28201. }
  28202. getFrontFacing() {
  28203. console.warn( 'Abstract function.' );
  28204. }
  28205. getFragCoord() {
  28206. console.warn( 'Abstract function.' );
  28207. }
  28208. isFlipY() {
  28209. return false;
  28210. }
  28211. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  28212. console.warn( 'Abstract function.' );
  28213. }
  28214. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  28215. console.warn( 'Abstract function.' );
  28216. }
  28217. generateConst( type, value = null ) {
  28218. if ( value === null ) {
  28219. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  28220. else if ( type === 'bool' ) value = false;
  28221. else if ( type === 'color' ) value = new Color();
  28222. else if ( type === 'vec2' ) value = new Vector2();
  28223. else if ( type === 'vec3' ) value = new Vector3();
  28224. else if ( type === 'vec4' ) value = new Vector4();
  28225. }
  28226. if ( type === 'float' ) return toFloat( value );
  28227. if ( type === 'int' ) return `${ Math.round( value ) }`;
  28228. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  28229. if ( type === 'bool' ) return value ? 'true' : 'false';
  28230. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  28231. const typeLength = this.getTypeLength( type );
  28232. const componentType = this.getComponentType( type );
  28233. const generateConst = value => this.generateConst( componentType, value );
  28234. if ( typeLength === 2 ) {
  28235. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  28236. } else if ( typeLength === 3 ) {
  28237. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  28238. } else if ( typeLength === 4 ) {
  28239. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  28240. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  28241. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  28242. } else if ( typeLength > 4 ) {
  28243. return `${ this.getType( type ) }()`;
  28244. }
  28245. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  28246. }
  28247. getType( type ) {
  28248. if ( type === 'color' ) return 'vec3';
  28249. return type;
  28250. }
  28251. hasGeometryAttribute( name ) {
  28252. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  28253. }
  28254. getAttribute( name, type ) {
  28255. const attributes = this.attributes;
  28256. // find attribute
  28257. for ( const attribute of attributes ) {
  28258. if ( attribute.name === name ) {
  28259. return attribute;
  28260. }
  28261. }
  28262. // create a new if no exist
  28263. const attribute = new NodeAttribute( name, type );
  28264. attributes.push( attribute );
  28265. return attribute;
  28266. }
  28267. getPropertyName( node/*, shaderStage*/ ) {
  28268. return node.name;
  28269. }
  28270. isVector( type ) {
  28271. return /vec\d/.test( type );
  28272. }
  28273. isMatrix( type ) {
  28274. return /mat\d/.test( type );
  28275. }
  28276. isReference( type ) {
  28277. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  28278. }
  28279. needsColorSpaceToLinear( /*texture*/ ) {
  28280. return false;
  28281. }
  28282. getComponentTypeFromTexture( texture ) {
  28283. const type = texture.type;
  28284. if ( texture.isDataTexture ) {
  28285. if ( type === IntType ) return 'int';
  28286. if ( type === UnsignedIntType ) return 'uint';
  28287. }
  28288. return 'float';
  28289. }
  28290. getElementType( type ) {
  28291. if ( type === 'mat2' ) return 'vec2';
  28292. if ( type === 'mat3' ) return 'vec3';
  28293. if ( type === 'mat4' ) return 'vec4';
  28294. return this.getComponentType( type );
  28295. }
  28296. getComponentType( type ) {
  28297. type = this.getVectorType( type );
  28298. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  28299. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  28300. if ( componentType === null ) return null;
  28301. if ( componentType[ 1 ] === 'b' ) return 'bool';
  28302. if ( componentType[ 1 ] === 'i' ) return 'int';
  28303. if ( componentType[ 1 ] === 'u' ) return 'uint';
  28304. return 'float';
  28305. }
  28306. getVectorType( type ) {
  28307. if ( type === 'color' ) return 'vec3';
  28308. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  28309. return type;
  28310. }
  28311. getTypeFromLength( length, componentType = 'float' ) {
  28312. if ( length === 1 ) return componentType;
  28313. const baseType = typeFromLength.get( length );
  28314. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  28315. return prefix + baseType;
  28316. }
  28317. getTypeFromArray( array ) {
  28318. return typeFromArray.get( array.constructor );
  28319. }
  28320. getTypeFromAttribute( attribute ) {
  28321. let dataAttribute = attribute;
  28322. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  28323. const array = dataAttribute.array;
  28324. const itemSize = attribute.itemSize;
  28325. const normalized = attribute.normalized;
  28326. let arrayType;
  28327. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  28328. arrayType = this.getTypeFromArray( array );
  28329. }
  28330. return this.getTypeFromLength( itemSize, arrayType );
  28331. }
  28332. getTypeLength( type ) {
  28333. const vecType = this.getVectorType( type );
  28334. const vecNum = /vec([2-4])/.exec( vecType );
  28335. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  28336. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  28337. if ( /mat2/.test( type ) === true ) return 4;
  28338. if ( /mat3/.test( type ) === true ) return 9;
  28339. if ( /mat4/.test( type ) === true ) return 16;
  28340. return 0;
  28341. }
  28342. getVectorFromMatrix( type ) {
  28343. return type.replace( 'mat', 'vec' );
  28344. }
  28345. changeComponentType( type, newComponentType ) {
  28346. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  28347. }
  28348. getIntegerType( type ) {
  28349. const componentType = this.getComponentType( type );
  28350. if ( componentType === 'int' || componentType === 'uint' ) return type;
  28351. return this.changeComponentType( type, 'int' );
  28352. }
  28353. addStack() {
  28354. this.stack = stack( this.stack );
  28355. this.stacks.push( getCurrentStack() || this.stack );
  28356. setCurrentStack( this.stack );
  28357. return this.stack;
  28358. }
  28359. removeStack() {
  28360. const lastStack = this.stack;
  28361. this.stack = lastStack.parent;
  28362. setCurrentStack( this.stacks.pop() );
  28363. return lastStack;
  28364. }
  28365. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  28366. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  28367. let nodeData = cache.getData( node );
  28368. if ( nodeData === undefined ) {
  28369. nodeData = {};
  28370. cache.setData( node, nodeData );
  28371. }
  28372. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  28373. return nodeData[ shaderStage ];
  28374. }
  28375. getNodeProperties( node, shaderStage = 'any' ) {
  28376. const nodeData = this.getDataFromNode( node, shaderStage );
  28377. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  28378. }
  28379. getBufferAttributeFromNode( node, type ) {
  28380. const nodeData = this.getDataFromNode( node );
  28381. let bufferAttribute = nodeData.bufferAttribute;
  28382. if ( bufferAttribute === undefined ) {
  28383. const index = this.uniforms.index ++;
  28384. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  28385. this.bufferAttributes.push( bufferAttribute );
  28386. nodeData.bufferAttribute = bufferAttribute;
  28387. }
  28388. return bufferAttribute;
  28389. }
  28390. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  28391. const nodeData = this.getDataFromNode( node, shaderStage );
  28392. if ( nodeData.structType === undefined ) {
  28393. const index = this.structs.index ++;
  28394. node.name = `StructType${ index }`;
  28395. this.structs[ shaderStage ].push( node );
  28396. nodeData.structType = node;
  28397. }
  28398. return node;
  28399. }
  28400. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  28401. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  28402. let nodeUniform = nodeData.uniform;
  28403. if ( nodeUniform === undefined ) {
  28404. const index = this.uniforms.index ++;
  28405. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  28406. this.uniforms[ shaderStage ].push( nodeUniform );
  28407. nodeData.uniform = nodeUniform;
  28408. }
  28409. return nodeUniform;
  28410. }
  28411. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  28412. const nodeData = this.getDataFromNode( node, shaderStage );
  28413. let nodeVar = nodeData.variable;
  28414. if ( nodeVar === undefined ) {
  28415. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  28416. if ( name === null ) name = 'nodeVar' + vars.length;
  28417. nodeVar = new NodeVar( name, type );
  28418. vars.push( nodeVar );
  28419. nodeData.variable = nodeVar;
  28420. }
  28421. return nodeVar;
  28422. }
  28423. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  28424. const nodeData = this.getDataFromNode( node, 'any' );
  28425. let nodeVarying = nodeData.varying;
  28426. if ( nodeVarying === undefined ) {
  28427. const varyings = this.varyings;
  28428. const index = varyings.length;
  28429. if ( name === null ) name = 'nodeVarying' + index;
  28430. nodeVarying = new NodeVarying( name, type );
  28431. varyings.push( nodeVarying );
  28432. nodeData.varying = nodeVarying;
  28433. }
  28434. return nodeVarying;
  28435. }
  28436. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  28437. const nodeData = this.getDataFromNode( node );
  28438. let nodeCode = nodeData.code;
  28439. if ( nodeCode === undefined ) {
  28440. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  28441. const index = codes.length;
  28442. nodeCode = new NodeCode( 'nodeCode' + index, type );
  28443. codes.push( nodeCode );
  28444. nodeData.code = nodeCode;
  28445. }
  28446. return nodeCode;
  28447. }
  28448. addLineFlowCode( code ) {
  28449. if ( code === '' ) return this;
  28450. code = this.tab + code;
  28451. if ( ! /;\s*$/.test( code ) ) {
  28452. code = code + ';\n';
  28453. }
  28454. this.flow.code += code;
  28455. return this;
  28456. }
  28457. addFlowCode( code ) {
  28458. this.flow.code += code;
  28459. return this;
  28460. }
  28461. addFlowTab() {
  28462. this.tab += '\t';
  28463. return this;
  28464. }
  28465. removeFlowTab() {
  28466. this.tab = this.tab.slice( 0, - 1 );
  28467. return this;
  28468. }
  28469. getFlowData( node/*, shaderStage*/ ) {
  28470. return this.flowsData.get( node );
  28471. }
  28472. flowNode( node ) {
  28473. const output = node.getNodeType( this );
  28474. const flowData = this.flowChildNode( node, output );
  28475. this.flowsData.set( node, flowData );
  28476. return flowData;
  28477. }
  28478. buildFunctionNode( shaderNode ) {
  28479. const fn = new FunctionNode();
  28480. const previous = this.currentFunctionNode;
  28481. this.currentFunctionNode = fn;
  28482. fn.code = this.buildFunctionCode( shaderNode );
  28483. this.currentFunctionNode = previous;
  28484. return fn;
  28485. }
  28486. flowShaderNode( shaderNode ) {
  28487. const layout = shaderNode.layout;
  28488. let inputs;
  28489. if ( shaderNode.isArrayInput ) {
  28490. inputs = [];
  28491. for ( const input of layout.inputs ) {
  28492. inputs.push( new ParameterNode( input.type, input.name ) );
  28493. }
  28494. } else {
  28495. inputs = {};
  28496. for ( const input of layout.inputs ) {
  28497. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  28498. }
  28499. }
  28500. //
  28501. shaderNode.layout = null;
  28502. const callNode = shaderNode.call( inputs );
  28503. const flowData = this.flowStagesNode( callNode, layout.type );
  28504. shaderNode.layout = layout;
  28505. return flowData;
  28506. }
  28507. flowStagesNode( node, output = null ) {
  28508. const previousFlow = this.flow;
  28509. const previousVars = this.vars;
  28510. const previousCache = this.cache;
  28511. const previousBuildStage = this.buildStage;
  28512. const previousStack = this.stack;
  28513. const flow = {
  28514. code: ''
  28515. };
  28516. this.flow = flow;
  28517. this.vars = {};
  28518. this.cache = new NodeCache();
  28519. this.stack = stack();
  28520. for ( const buildStage of defaultBuildStages ) {
  28521. this.setBuildStage( buildStage );
  28522. flow.result = node.build( this, output );
  28523. }
  28524. flow.vars = this.getVars( this.shaderStage );
  28525. this.flow = previousFlow;
  28526. this.vars = previousVars;
  28527. this.cache = previousCache;
  28528. this.stack = previousStack;
  28529. this.setBuildStage( previousBuildStage );
  28530. return flow;
  28531. }
  28532. getFunctionOperator() {
  28533. return null;
  28534. }
  28535. flowChildNode( node, output = null ) {
  28536. const previousFlow = this.flow;
  28537. const flow = {
  28538. code: ''
  28539. };
  28540. this.flow = flow;
  28541. flow.result = node.build( this, output );
  28542. this.flow = previousFlow;
  28543. return flow;
  28544. }
  28545. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  28546. const previousShaderStage = this.shaderStage;
  28547. this.setShaderStage( shaderStage );
  28548. const flowData = this.flowChildNode( node, output );
  28549. if ( propertyName !== null ) {
  28550. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  28551. }
  28552. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  28553. this.setShaderStage( previousShaderStage );
  28554. return flowData;
  28555. }
  28556. getAttributesArray() {
  28557. return this.attributes.concat( this.bufferAttributes );
  28558. }
  28559. getAttributes( /*shaderStage*/ ) {
  28560. console.warn( 'Abstract function.' );
  28561. }
  28562. getVaryings( /*shaderStage*/ ) {
  28563. console.warn( 'Abstract function.' );
  28564. }
  28565. getVar( type, name ) {
  28566. return `${ this.getType( type ) } ${ name }`;
  28567. }
  28568. getVars( shaderStage ) {
  28569. let snippet = '';
  28570. const vars = this.vars[ shaderStage ];
  28571. if ( vars !== undefined ) {
  28572. for ( const variable of vars ) {
  28573. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  28574. }
  28575. }
  28576. return snippet;
  28577. }
  28578. getUniforms( /*shaderStage*/ ) {
  28579. console.warn( 'Abstract function.' );
  28580. }
  28581. getCodes( shaderStage ) {
  28582. const codes = this.codes[ shaderStage ];
  28583. let code = '';
  28584. if ( codes !== undefined ) {
  28585. for ( const nodeCode of codes ) {
  28586. code += nodeCode.code + '\n';
  28587. }
  28588. }
  28589. return code;
  28590. }
  28591. getHash() {
  28592. return this.vertexShader + this.fragmentShader + this.computeShader;
  28593. }
  28594. setShaderStage( shaderStage ) {
  28595. this.shaderStage = shaderStage;
  28596. }
  28597. getShaderStage() {
  28598. return this.shaderStage;
  28599. }
  28600. setBuildStage( buildStage ) {
  28601. this.buildStage = buildStage;
  28602. }
  28603. getBuildStage() {
  28604. return this.buildStage;
  28605. }
  28606. buildCode() {
  28607. console.warn( 'Abstract function.' );
  28608. }
  28609. build() {
  28610. const { object, material } = this;
  28611. if ( material !== null ) {
  28612. NodeMaterial.fromMaterial( material ).build( this );
  28613. } else {
  28614. this.addFlow( 'compute', object );
  28615. }
  28616. // setup() -> stage 1: create possible new nodes and returns an output reference node
  28617. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  28618. // generate() -> stage 3: generate shader
  28619. for ( const buildStage of defaultBuildStages ) {
  28620. this.setBuildStage( buildStage );
  28621. if ( this.context.vertex && this.context.vertex.isNode ) {
  28622. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  28623. }
  28624. for ( const shaderStage of shaderStages ) {
  28625. this.setShaderStage( shaderStage );
  28626. const flowNodes = this.flowNodes[ shaderStage ];
  28627. for ( const node of flowNodes ) {
  28628. if ( buildStage === 'generate' ) {
  28629. this.flowNode( node );
  28630. } else {
  28631. node.build( this );
  28632. }
  28633. }
  28634. }
  28635. }
  28636. this.setBuildStage( null );
  28637. this.setShaderStage( null );
  28638. // stage 4: build code for a specific output
  28639. this.buildCode();
  28640. this.buildUpdateNodes();
  28641. return this;
  28642. }
  28643. getNodeUniform( uniformNode, type ) {
  28644. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  28645. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  28646. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  28647. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  28648. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  28649. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  28650. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  28651. throw new Error( `Uniform "${type}" not declared.` );
  28652. }
  28653. createNodeMaterial( type = 'NodeMaterial' ) {
  28654. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  28655. return createNodeMaterialFromType( type );
  28656. }
  28657. format( snippet, fromType, toType ) {
  28658. fromType = this.getVectorType( fromType );
  28659. toType = this.getVectorType( toType );
  28660. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  28661. return snippet;
  28662. }
  28663. const fromTypeLength = this.getTypeLength( fromType );
  28664. const toTypeLength = this.getTypeLength( toType );
  28665. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  28666. // @TODO: ignore for now
  28667. return snippet;
  28668. }
  28669. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  28670. // @TODO: ignore for now
  28671. return snippet;
  28672. }
  28673. if ( fromTypeLength === toTypeLength ) {
  28674. return `${ this.getType( toType ) }( ${ snippet } )`;
  28675. }
  28676. if ( fromTypeLength > toTypeLength ) {
  28677. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  28678. }
  28679. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  28680. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  28681. }
  28682. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  28683. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  28684. }
  28685. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  28686. // convert a number value to vector type, e.g:
  28687. // vec3( 1u ) -> vec3( float( 1u ) )
  28688. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  28689. }
  28690. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  28691. }
  28692. getSignature() {
  28693. return `// Three.js r${ REVISION } - Node System\n`;
  28694. }
  28695. }
  28696. class NodeFrame {
  28697. constructor() {
  28698. this.time = 0;
  28699. this.deltaTime = 0;
  28700. this.frameId = 0;
  28701. this.renderId = 0;
  28702. this.startTime = null;
  28703. this.updateMap = new WeakMap();
  28704. this.updateBeforeMap = new WeakMap();
  28705. this.updateAfterMap = new WeakMap();
  28706. this.renderer = null;
  28707. this.material = null;
  28708. this.camera = null;
  28709. this.object = null;
  28710. this.scene = null;
  28711. }
  28712. _getMaps( referenceMap, nodeRef ) {
  28713. let maps = referenceMap.get( nodeRef );
  28714. if ( maps === undefined ) {
  28715. maps = {
  28716. renderMap: new WeakMap(),
  28717. frameMap: new WeakMap()
  28718. };
  28719. referenceMap.set( nodeRef, maps );
  28720. }
  28721. return maps;
  28722. }
  28723. updateBeforeNode( node ) {
  28724. const updateType = node.getUpdateBeforeType();
  28725. const reference = node.updateReference( this );
  28726. if ( updateType === NodeUpdateType.FRAME ) {
  28727. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  28728. if ( frameMap.get( reference ) !== this.frameId ) {
  28729. if ( node.updateBefore( this ) !== false ) {
  28730. frameMap.set( reference, this.frameId );
  28731. }
  28732. }
  28733. } else if ( updateType === NodeUpdateType.RENDER ) {
  28734. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  28735. if ( renderMap.get( reference ) !== this.renderId ) {
  28736. if ( node.updateBefore( this ) !== false ) {
  28737. renderMap.set( reference, this.renderId );
  28738. }
  28739. }
  28740. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28741. node.updateBefore( this );
  28742. }
  28743. }
  28744. updateAfterNode( node ) {
  28745. const updateType = node.getUpdateAfterType();
  28746. const reference = node.updateReference( this );
  28747. if ( updateType === NodeUpdateType.FRAME ) {
  28748. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  28749. if ( frameMap.get( reference ) !== this.frameId ) {
  28750. if ( node.updateAfter( this ) !== false ) {
  28751. frameMap.set( reference, this.frameId );
  28752. }
  28753. }
  28754. } else if ( updateType === NodeUpdateType.RENDER ) {
  28755. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  28756. if ( renderMap.get( reference ) !== this.renderId ) {
  28757. if ( node.updateAfter( this ) !== false ) {
  28758. renderMap.set( reference, this.renderId );
  28759. }
  28760. }
  28761. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28762. node.updateAfter( this );
  28763. }
  28764. }
  28765. updateNode( node ) {
  28766. const updateType = node.getUpdateType();
  28767. const reference = node.updateReference( this );
  28768. if ( updateType === NodeUpdateType.FRAME ) {
  28769. const { frameMap } = this._getMaps( this.updateMap, reference );
  28770. if ( frameMap.get( reference ) !== this.frameId ) {
  28771. if ( node.update( this ) !== false ) {
  28772. frameMap.set( reference, this.frameId );
  28773. }
  28774. }
  28775. } else if ( updateType === NodeUpdateType.RENDER ) {
  28776. const { renderMap } = this._getMaps( this.updateMap, reference );
  28777. if ( renderMap.get( reference ) !== this.renderId ) {
  28778. if ( node.update( this ) !== false ) {
  28779. renderMap.set( reference, this.renderId );
  28780. }
  28781. }
  28782. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28783. node.update( this );
  28784. }
  28785. }
  28786. update() {
  28787. this.frameId ++;
  28788. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  28789. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  28790. this.lastTime = performance.now();
  28791. this.time += this.deltaTime;
  28792. }
  28793. }
  28794. class NodeFunctionInput {
  28795. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  28796. this.type = type;
  28797. this.name = name;
  28798. this.count = count;
  28799. this.qualifier = qualifier;
  28800. this.isConst = isConst;
  28801. }
  28802. }
  28803. NodeFunctionInput.isNodeFunctionInput = true;
  28804. class StructTypeNode extends Node {
  28805. constructor( types ) {
  28806. super();
  28807. this.types = types;
  28808. this.isStructTypeNode = true;
  28809. }
  28810. getMemberTypes() {
  28811. return this.types;
  28812. }
  28813. }
  28814. addNodeClass( 'StructTypeNode', StructTypeNode );
  28815. class OutputStructNode extends Node {
  28816. constructor( ...members ) {
  28817. super();
  28818. this.members = members;
  28819. this.isOutputStructNode = true;
  28820. }
  28821. setup( builder ) {
  28822. super.setup( builder );
  28823. const members = this.members;
  28824. const types = [];
  28825. for ( let i = 0; i < members.length; i ++ ) {
  28826. types.push( members[ i ].getNodeType( builder ) );
  28827. }
  28828. this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name;
  28829. }
  28830. generate( builder, output ) {
  28831. const propertyName = builder.getOutputStructName();
  28832. const members = this.members;
  28833. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  28834. for ( let i = 0; i < members.length; i ++ ) {
  28835. const snippet = members[ i ].build( builder, output );
  28836. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }` );
  28837. }
  28838. return propertyName;
  28839. }
  28840. }
  28841. const outputStruct = nodeProxy( OutputStructNode );
  28842. addNodeClass( 'OutputStructNode', OutputStructNode );
  28843. class HashNode extends Node {
  28844. constructor( seedNode ) {
  28845. super();
  28846. this.seedNode = seedNode;
  28847. }
  28848. setup( /*builder*/ ) {
  28849. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  28850. const state = this.seedNode.toUint().mul( 747796405 ).add( 2891336453 );
  28851. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  28852. const result = word.shiftRight( 22 ).bitXor( word );
  28853. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  28854. }
  28855. }
  28856. const hash = nodeProxy( HashNode );
  28857. addNodeElement( 'hash', hash );
  28858. addNodeClass( 'HashNode', HashNode );
  28859. // remapping functions https://iquilezles.org/articles/functions/
  28860. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  28861. 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 ) );
  28862. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  28863. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  28864. addNodeElement( 'parabola', parabola );
  28865. addNodeElement( 'gain', gain );
  28866. addNodeElement( 'pcurve', pcurve );
  28867. addNodeElement( 'sinc', sinc );
  28868. // https://github.com/cabbibo/glsl-tri-noise-3d
  28869. const tri = tslFn( ( [ x ] ) => {
  28870. return x.fract().sub( .5 ).abs();
  28871. } );
  28872. const tri3 = tslFn( ( [ p ] ) => {
  28873. 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. ) ) ) ) );
  28874. } );
  28875. const triNoise3D = tslFn( ( [ p_immutable, spd, time ] ) => {
  28876. const p = vec3( p_immutable ).toVar();
  28877. const z = float( 1.4 ).toVar();
  28878. const rz = float( 0.0 ).toVar();
  28879. const bp = vec3( p ).toVar();
  28880. loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  28881. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  28882. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  28883. bp.mulAssign( 1.8 );
  28884. z.mulAssign( 1.5 );
  28885. p.mulAssign( 1.2 );
  28886. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  28887. rz.addAssign( t.div( z ) );
  28888. bp.addAssign( 0.14 );
  28889. } );
  28890. return rz;
  28891. } );
  28892. // layouts
  28893. tri.setLayout( {
  28894. name: 'tri',
  28895. type: 'float',
  28896. inputs: [
  28897. { name: 'x', type: 'float' }
  28898. ]
  28899. } );
  28900. tri3.setLayout( {
  28901. name: 'tri3',
  28902. type: 'vec3',
  28903. inputs: [
  28904. { name: 'p', type: 'vec3' }
  28905. ]
  28906. } );
  28907. triNoise3D.setLayout( {
  28908. name: 'triNoise3D',
  28909. type: 'float',
  28910. inputs: [
  28911. { name: 'p', type: 'vec3' },
  28912. { name: 'spd', type: 'float' },
  28913. { name: 'time', type: 'float' }
  28914. ]
  28915. } );
  28916. let discardExpression;
  28917. class DiscardNode extends CondNode {
  28918. constructor( condNode ) {
  28919. discardExpression = discardExpression || expression( 'discard' );
  28920. super( condNode, discardExpression );
  28921. }
  28922. }
  28923. const inlineDiscard = nodeProxy( DiscardNode );
  28924. const discard = ( condNode ) => inlineDiscard( condNode ).append();
  28925. const Return = () => expression( 'return' ).append();
  28926. addNodeElement( 'discard', discard ); // @TODO: Check... this cause a little confusing using in chaining
  28927. addNodeClass( 'DiscardNode', DiscardNode );
  28928. class FunctionOverloadingNode extends Node {
  28929. constructor( functionNodes = [], ...parametersNodes ) {
  28930. super();
  28931. this.functionNodes = functionNodes;
  28932. this.parametersNodes = parametersNodes;
  28933. this._candidateFnCall = null;
  28934. this.global = true;
  28935. }
  28936. getNodeType() {
  28937. return this.functionNodes[ 0 ].shaderNode.layout.type;
  28938. }
  28939. setup( builder ) {
  28940. const params = this.parametersNodes;
  28941. let candidateFnCall = this._candidateFnCall;
  28942. if ( candidateFnCall === null ) {
  28943. let candidateFn = null;
  28944. let candidateScore = - 1;
  28945. for ( const functionNode of this.functionNodes ) {
  28946. const shaderNode = functionNode.shaderNode;
  28947. const layout = shaderNode.layout;
  28948. if ( layout === null ) {
  28949. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  28950. }
  28951. const inputs = layout.inputs;
  28952. if ( params.length === inputs.length ) {
  28953. let score = 0;
  28954. for ( let i = 0; i < params.length; i ++ ) {
  28955. const param = params[ i ];
  28956. const input = inputs[ i ];
  28957. if ( param.getNodeType( builder ) === input.type ) {
  28958. score ++;
  28959. } else {
  28960. score = 0;
  28961. }
  28962. }
  28963. if ( score > candidateScore ) {
  28964. candidateFn = functionNode;
  28965. candidateScore = score;
  28966. }
  28967. }
  28968. }
  28969. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  28970. }
  28971. return candidateFnCall;
  28972. }
  28973. }
  28974. const overloadingBaseFn = nodeProxy( FunctionOverloadingNode );
  28975. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  28976. addNodeClass( 'FunctionOverloadingNode', FunctionOverloadingNode );
  28977. class MatcapUVNode extends TempNode {
  28978. constructor() {
  28979. super( 'vec2' );
  28980. }
  28981. setup() {
  28982. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  28983. const y = positionViewDirection.cross( x );
  28984. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  28985. }
  28986. }
  28987. const matcapUV = nodeImmutable( MatcapUVNode );
  28988. addNodeClass( 'MatcapUVNode', MatcapUVNode );
  28989. class TimerNode extends UniformNode {
  28990. constructor( scope = TimerNode.LOCAL, scale = 1, value = 0 ) {
  28991. super( value );
  28992. this.scope = scope;
  28993. this.scale = scale;
  28994. this.updateType = NodeUpdateType.FRAME;
  28995. }
  28996. /*
  28997. @TODO:
  28998. getNodeType( builder ) {
  28999. const scope = this.scope;
  29000. if ( scope === TimerNode.FRAME ) {
  29001. return 'uint';
  29002. }
  29003. return 'float';
  29004. }
  29005. */
  29006. update( frame ) {
  29007. const scope = this.scope;
  29008. const scale = this.scale;
  29009. if ( scope === TimerNode.LOCAL ) {
  29010. this.value += frame.deltaTime * scale;
  29011. } else if ( scope === TimerNode.DELTA ) {
  29012. this.value = frame.deltaTime * scale;
  29013. } else if ( scope === TimerNode.FRAME ) {
  29014. this.value = frame.frameId;
  29015. } else {
  29016. // global
  29017. this.value = frame.time * scale;
  29018. }
  29019. }
  29020. serialize( data ) {
  29021. super.serialize( data );
  29022. data.scope = this.scope;
  29023. data.scale = this.scale;
  29024. }
  29025. deserialize( data ) {
  29026. super.deserialize( data );
  29027. this.scope = data.scope;
  29028. this.scale = data.scale;
  29029. }
  29030. }
  29031. TimerNode.LOCAL = 'local';
  29032. TimerNode.GLOBAL = 'global';
  29033. TimerNode.DELTA = 'delta';
  29034. TimerNode.FRAME = 'frame';
  29035. // @TODO: add support to use node in timeScale
  29036. const timerLocal = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.LOCAL, timeScale, value ) );
  29037. const timerGlobal = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.GLOBAL, timeScale, value ) );
  29038. const timerDelta = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.DELTA, timeScale, value ) );
  29039. const frameId = nodeImmutable( TimerNode, TimerNode.FRAME ).toUint();
  29040. addNodeClass( 'TimerNode', TimerNode );
  29041. class OscNode extends Node {
  29042. constructor( method = OscNode.SINE, timeNode = timerLocal() ) {
  29043. super();
  29044. this.method = method;
  29045. this.timeNode = timeNode;
  29046. }
  29047. getNodeType( builder ) {
  29048. return this.timeNode.getNodeType( builder );
  29049. }
  29050. setup() {
  29051. const method = this.method;
  29052. const timeNode = nodeObject( this.timeNode );
  29053. let outputNode = null;
  29054. if ( method === OscNode.SINE ) {
  29055. outputNode = timeNode.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  29056. } else if ( method === OscNode.SQUARE ) {
  29057. outputNode = timeNode.fract().round();
  29058. } else if ( method === OscNode.TRIANGLE ) {
  29059. outputNode = timeNode.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  29060. } else if ( method === OscNode.SAWTOOTH ) {
  29061. outputNode = timeNode.fract();
  29062. }
  29063. return outputNode;
  29064. }
  29065. serialize( data ) {
  29066. super.serialize( data );
  29067. data.method = this.method;
  29068. }
  29069. deserialize( data ) {
  29070. super.deserialize( data );
  29071. this.method = data.method;
  29072. }
  29073. }
  29074. OscNode.SINE = 'sine';
  29075. OscNode.SQUARE = 'square';
  29076. OscNode.TRIANGLE = 'triangle';
  29077. OscNode.SAWTOOTH = 'sawtooth';
  29078. const oscSine = nodeProxy( OscNode, OscNode.SINE );
  29079. const oscSquare = nodeProxy( OscNode, OscNode.SQUARE );
  29080. const oscTriangle = nodeProxy( OscNode, OscNode.TRIANGLE );
  29081. const oscSawtooth = nodeProxy( OscNode, OscNode.SAWTOOTH );
  29082. addNodeClass( 'OscNode', OscNode );
  29083. class PackingNode extends TempNode {
  29084. constructor( scope, node ) {
  29085. super();
  29086. this.scope = scope;
  29087. this.node = node;
  29088. }
  29089. getNodeType( builder ) {
  29090. return this.node.getNodeType( builder );
  29091. }
  29092. setup() {
  29093. const { scope, node } = this;
  29094. let result = null;
  29095. if ( scope === PackingNode.DIRECTION_TO_COLOR ) {
  29096. result = node.mul( 0.5 ).add( 0.5 );
  29097. } else if ( scope === PackingNode.COLOR_TO_DIRECTION ) {
  29098. result = node.mul( 2.0 ).sub( 1 );
  29099. }
  29100. return result;
  29101. }
  29102. }
  29103. PackingNode.DIRECTION_TO_COLOR = 'directionToColor';
  29104. PackingNode.COLOR_TO_DIRECTION = 'colorToDirection';
  29105. const directionToColor = nodeProxy( PackingNode, PackingNode.DIRECTION_TO_COLOR );
  29106. const colorToDirection = nodeProxy( PackingNode, PackingNode.COLOR_TO_DIRECTION );
  29107. addNodeElement( 'directionToColor', directionToColor );
  29108. addNodeElement( 'colorToDirection', colorToDirection );
  29109. addNodeClass( 'PackingNode', PackingNode );
  29110. class RemapNode extends Node {
  29111. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  29112. super();
  29113. this.node = node;
  29114. this.inLowNode = inLowNode;
  29115. this.inHighNode = inHighNode;
  29116. this.outLowNode = outLowNode;
  29117. this.outHighNode = outHighNode;
  29118. this.doClamp = true;
  29119. }
  29120. setup() {
  29121. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  29122. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  29123. if ( doClamp === true ) t = t.clamp();
  29124. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  29125. }
  29126. }
  29127. const remap = nodeProxy( RemapNode, null, null, { doClamp: false } );
  29128. const remapClamp = nodeProxy( RemapNode );
  29129. addNodeElement( 'remap', remap );
  29130. addNodeElement( 'remapClamp', remapClamp );
  29131. addNodeClass( 'RemapNode', RemapNode );
  29132. class RotateUVNode extends TempNode {
  29133. constructor( uvNode, rotationNode, centerNode = vec2( 0.5 ) ) {
  29134. super( 'vec2' );
  29135. this.uvNode = uvNode;
  29136. this.rotationNode = rotationNode;
  29137. this.centerNode = centerNode;
  29138. }
  29139. setup() {
  29140. const { uvNode, rotationNode, centerNode } = this;
  29141. const vector = uvNode.sub( centerNode );
  29142. return vector.rotate( rotationNode ).add( centerNode );
  29143. }
  29144. }
  29145. const rotateUV = nodeProxy( RotateUVNode );
  29146. addNodeElement( 'rotateUV', rotateUV );
  29147. addNodeClass( 'RotateUVNode', RotateUVNode );
  29148. class RotateNode extends TempNode {
  29149. constructor( positionNode, rotationNode ) {
  29150. super();
  29151. this.positionNode = positionNode;
  29152. this.rotationNode = rotationNode;
  29153. }
  29154. getNodeType( builder ) {
  29155. return this.positionNode.getNodeType( builder );
  29156. }
  29157. setup( builder ) {
  29158. const { rotationNode, positionNode } = this;
  29159. const nodeType = this.getNodeType( builder );
  29160. if ( nodeType === 'vec2' ) {
  29161. const cosAngle = rotationNode.cos();
  29162. const sinAngle = rotationNode.sin();
  29163. const rotationMatrix = mat2(
  29164. cosAngle, sinAngle,
  29165. sinAngle.negate(), cosAngle
  29166. );
  29167. return rotationMatrix.mul( positionNode );
  29168. } else {
  29169. const rotation = rotationNode;
  29170. 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 ) );
  29171. 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 ) );
  29172. 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 ) );
  29173. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  29174. }
  29175. }
  29176. }
  29177. const rotate = nodeProxy( RotateNode );
  29178. addNodeElement( 'rotate', rotate );
  29179. addNodeClass( 'RotateNode', RotateNode );
  29180. class SpriteSheetUVNode extends Node {
  29181. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  29182. super( 'vec2' );
  29183. this.countNode = countNode;
  29184. this.uvNode = uvNode;
  29185. this.frameNode = frameNode;
  29186. }
  29187. setup() {
  29188. const { frameNode, uvNode, countNode } = this;
  29189. const { width, height } = countNode;
  29190. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  29191. const column = frameNum.mod( width );
  29192. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  29193. const scale = countNode.reciprocal();
  29194. const uvFrameOffset = vec2( column, row );
  29195. return uvNode.add( uvFrameOffset ).mul( scale );
  29196. }
  29197. }
  29198. const spritesheetUV = nodeProxy( SpriteSheetUVNode );
  29199. addNodeClass( 'SpriteSheetUVNode', SpriteSheetUVNode );
  29200. class StorageArrayElementNode extends ArrayElementNode {
  29201. constructor( storageBufferNode, indexNode ) {
  29202. super( storageBufferNode, indexNode );
  29203. this.isStorageArrayElementNode = true;
  29204. }
  29205. set storageBufferNode( value ) {
  29206. this.node = value;
  29207. }
  29208. get storageBufferNode() {
  29209. return this.node;
  29210. }
  29211. setup( builder ) {
  29212. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  29213. if ( ! this.node.instanceIndex && this.node.bufferObject === true ) {
  29214. builder.setupPBO( this.node );
  29215. }
  29216. }
  29217. return super.setup( builder );
  29218. }
  29219. generate( builder, output ) {
  29220. let snippet;
  29221. const isAssignContext = builder.context.assign;
  29222. //
  29223. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  29224. const { node } = this;
  29225. if ( ! node.instanceIndex && this.node.bufferObject === true && isAssignContext !== true ) {
  29226. snippet = builder.generatePBO( this );
  29227. } else {
  29228. snippet = node.build( builder );
  29229. }
  29230. } else {
  29231. snippet = super.generate( builder );
  29232. }
  29233. if ( isAssignContext !== true ) {
  29234. const type = this.getNodeType( builder );
  29235. snippet = builder.format( snippet, type, output );
  29236. }
  29237. return snippet;
  29238. }
  29239. }
  29240. const storageElement = nodeProxy( StorageArrayElementNode );
  29241. addNodeElement( 'storageElement', storageElement );
  29242. addNodeClass( 'StorageArrayElementNode', StorageArrayElementNode );
  29243. class TriplanarTexturesNode extends Node {
  29244. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  29245. super( 'vec4' );
  29246. this.textureXNode = textureXNode;
  29247. this.textureYNode = textureYNode;
  29248. this.textureZNode = textureZNode;
  29249. this.scaleNode = scaleNode;
  29250. this.positionNode = positionNode;
  29251. this.normalNode = normalNode;
  29252. }
  29253. setup() {
  29254. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  29255. // Ref: https://github.com/keijiro/StandardTriplanar
  29256. // Blending factor of triplanar mapping
  29257. let bf = normalNode.abs().normalize();
  29258. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  29259. // Triplanar mapping
  29260. const tx = positionNode.yz.mul( scaleNode );
  29261. const ty = positionNode.zx.mul( scaleNode );
  29262. const tz = positionNode.xy.mul( scaleNode );
  29263. // Base color
  29264. const textureX = textureXNode.value;
  29265. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  29266. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  29267. const cx = texture( textureX, tx ).mul( bf.x );
  29268. const cy = texture( textureY, ty ).mul( bf.y );
  29269. const cz = texture( textureZ, tz ).mul( bf.z );
  29270. return add( cx, cy, cz );
  29271. }
  29272. }
  29273. const triplanarTextures = nodeProxy( TriplanarTexturesNode );
  29274. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  29275. addNodeElement( 'triplanarTexture', triplanarTexture );
  29276. addNodeClass( 'TriplanarTexturesNode', TriplanarTexturesNode );
  29277. const _reflectorPlane = new Plane();
  29278. const _normal = new Vector3();
  29279. const _reflectorWorldPosition = new Vector3();
  29280. const _cameraWorldPosition = new Vector3();
  29281. const _rotationMatrix = new Matrix4();
  29282. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  29283. const clipPlane = new Vector4();
  29284. const _view = new Vector3();
  29285. const _target = new Vector3();
  29286. const _q = new Vector4();
  29287. const _size$4 = new Vector2();
  29288. const _defaultRT = new RenderTarget();
  29289. const _defaultUV = vec2( viewportTopLeft.x.oneMinus(), viewportTopLeft.y );
  29290. let _inReflector = false;
  29291. class ReflectorNode extends TextureNode {
  29292. constructor( parameters = {} ) {
  29293. super( _defaultRT.texture, _defaultUV );
  29294. const {
  29295. target = new Object3D(),
  29296. resolution = 1,
  29297. generateMipmaps = false,
  29298. bounces = true
  29299. } = parameters;
  29300. //
  29301. this.target = target;
  29302. this.resolution = resolution;
  29303. this.generateMipmaps = generateMipmaps;
  29304. this.bounces = bounces;
  29305. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  29306. this.virtualCameras = new WeakMap();
  29307. this.renderTargets = new WeakMap();
  29308. }
  29309. _updateResolution( renderTarget, renderer ) {
  29310. const resolution = this.resolution;
  29311. renderer.getDrawingBufferSize( _size$4 );
  29312. renderTarget.setSize( Math.round( _size$4.width * resolution ), Math.round( _size$4.height * resolution ) );
  29313. }
  29314. setup( builder ) {
  29315. this._updateResolution( _defaultRT, builder.renderer );
  29316. return super.setup( builder );
  29317. }
  29318. getTextureNode() {
  29319. return this.textureNode;
  29320. }
  29321. getVirtualCamera( camera ) {
  29322. let virtualCamera = this.virtualCameras.get( camera );
  29323. if ( virtualCamera === undefined ) {
  29324. virtualCamera = camera.clone();
  29325. this.virtualCameras.set( camera, virtualCamera );
  29326. }
  29327. return virtualCamera;
  29328. }
  29329. getRenderTarget( camera ) {
  29330. let renderTarget = this.renderTargets.get( camera );
  29331. if ( renderTarget === undefined ) {
  29332. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  29333. if ( this.generateMipmaps === true ) {
  29334. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  29335. renderTarget.texture.generateMipmaps = true;
  29336. }
  29337. this.renderTargets.set( camera, renderTarget );
  29338. }
  29339. return renderTarget;
  29340. }
  29341. updateBefore( frame ) {
  29342. if ( this.bounces === false && _inReflector ) return false;
  29343. _inReflector = true;
  29344. const { scene, camera, renderer, material } = frame;
  29345. const { target } = this;
  29346. const virtualCamera = this.getVirtualCamera( camera );
  29347. const renderTarget = this.getRenderTarget( virtualCamera );
  29348. renderer.getDrawingBufferSize( _size$4 );
  29349. this._updateResolution( renderTarget, renderer );
  29350. //
  29351. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  29352. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  29353. _rotationMatrix.extractRotation( target.matrixWorld );
  29354. _normal.set( 0, 0, 1 );
  29355. _normal.applyMatrix4( _rotationMatrix );
  29356. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  29357. // Avoid rendering when reflector is facing away
  29358. if ( _view.dot( _normal ) > 0 ) return;
  29359. _view.reflect( _normal ).negate();
  29360. _view.add( _reflectorWorldPosition );
  29361. _rotationMatrix.extractRotation( camera.matrixWorld );
  29362. _lookAtPosition.set( 0, 0, - 1 );
  29363. _lookAtPosition.applyMatrix4( _rotationMatrix );
  29364. _lookAtPosition.add( _cameraWorldPosition );
  29365. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  29366. _target.reflect( _normal ).negate();
  29367. _target.add( _reflectorWorldPosition );
  29368. //
  29369. virtualCamera.coordinateSystem = camera.coordinateSystem;
  29370. virtualCamera.position.copy( _view );
  29371. virtualCamera.up.set( 0, 1, 0 );
  29372. virtualCamera.up.applyMatrix4( _rotationMatrix );
  29373. virtualCamera.up.reflect( _normal );
  29374. virtualCamera.lookAt( _target );
  29375. virtualCamera.near = camera.near;
  29376. virtualCamera.far = camera.far;
  29377. virtualCamera.updateMatrixWorld();
  29378. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  29379. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  29380. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  29381. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  29382. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  29383. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  29384. const projectionMatrix = virtualCamera.projectionMatrix;
  29385. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  29386. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  29387. _q.z = - 1.0;
  29388. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  29389. // Calculate the scaled plane vector
  29390. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  29391. const clipBias = 0;
  29392. // Replacing the third row of the projection matrix
  29393. projectionMatrix.elements[ 2 ] = clipPlane.x;
  29394. projectionMatrix.elements[ 6 ] = clipPlane.y;
  29395. projectionMatrix.elements[ 10 ] = clipPlane.z - clipBias;
  29396. projectionMatrix.elements[ 14 ] = clipPlane.w;
  29397. //
  29398. this.value = renderTarget.texture;
  29399. material.visible = false;
  29400. const currentRenderTarget = renderer.getRenderTarget();
  29401. renderer.setRenderTarget( renderTarget );
  29402. renderer.render( scene, virtualCamera );
  29403. renderer.setRenderTarget( currentRenderTarget );
  29404. material.visible = true;
  29405. _inReflector = false;
  29406. }
  29407. }
  29408. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  29409. // Helper for passes that need to fill the viewport with a single quad.
  29410. const _camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  29411. // https://github.com/mrdoob/three.js/pull/21358
  29412. class QuadGeometry extends BufferGeometry {
  29413. constructor( flipY = false ) {
  29414. super();
  29415. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  29416. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  29417. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  29418. }
  29419. }
  29420. const _geometry = new QuadGeometry();
  29421. class QuadMesh extends Mesh {
  29422. constructor( material = null ) {
  29423. super( _geometry, material );
  29424. this.camera = _camera;
  29425. }
  29426. renderAsync( renderer ) {
  29427. return renderer.renderAsync( this, _camera );
  29428. }
  29429. render( renderer ) {
  29430. renderer.render( this, _camera );
  29431. }
  29432. }
  29433. const _quadMesh = new QuadMesh( new NodeMaterial() );
  29434. const _size$3 = new Vector2();
  29435. class RTTNode extends TextureNode {
  29436. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  29437. const renderTarget = new RenderTarget( width, height, options );
  29438. super( renderTarget.texture, uv() );
  29439. this.node = node;
  29440. this.width = width;
  29441. this.height = height;
  29442. this.renderTarget = renderTarget;
  29443. this.textureNeedsUpdate = true;
  29444. this.autoUpdate = true;
  29445. this.updateMap = new WeakMap();
  29446. this.updateBeforeType = NodeUpdateType.RENDER;
  29447. }
  29448. get autoSize() {
  29449. return this.width === null;
  29450. }
  29451. setSize( width, height ) {
  29452. this.width = width;
  29453. this.height = height;
  29454. this.renderTarget.setSize( width, height );
  29455. this.textureNeedsUpdate = true;
  29456. }
  29457. updateBefore( { renderer } ) {
  29458. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  29459. this.textureNeedsUpdate = false;
  29460. //
  29461. if ( this.autoSize === true ) {
  29462. const size = renderer.getSize( _size$3 );
  29463. this.setSize( size.width, size.height );
  29464. }
  29465. //
  29466. _quadMesh.material.fragmentNode = this.node;
  29467. //
  29468. const currentRenderTarget = renderer.getRenderTarget();
  29469. renderer.setRenderTarget( this.renderTarget );
  29470. _quadMesh.render( renderer );
  29471. renderer.setRenderTarget( currentRenderTarget );
  29472. }
  29473. clone() {
  29474. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  29475. newNode.sampler = this.sampler;
  29476. newNode.referenceNode = this;
  29477. return newNode;
  29478. }
  29479. }
  29480. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  29481. addNodeElement( 'toTexture', ( node, ...params ) => node.isTextureNode ? node : rtt( node, ...params ) );
  29482. addNodeClass( 'RTTNode', RTTNode );
  29483. class VertexColorNode extends AttributeNode {
  29484. constructor( index = 0 ) {
  29485. super( null, 'vec4' );
  29486. this.isVertexColorNode = true;
  29487. this.index = index;
  29488. }
  29489. getAttributeName( /*builder*/ ) {
  29490. const index = this.index;
  29491. return 'color' + ( index > 0 ? index : '' );
  29492. }
  29493. generate( builder ) {
  29494. const attributeName = this.getAttributeName( builder );
  29495. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  29496. let result;
  29497. if ( geometryAttribute === true ) {
  29498. result = super.generate( builder );
  29499. } else {
  29500. // Vertex color fallback should be white
  29501. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  29502. }
  29503. return result;
  29504. }
  29505. serialize( data ) {
  29506. super.serialize( data );
  29507. data.index = this.index;
  29508. }
  29509. deserialize( data ) {
  29510. super.deserialize( data );
  29511. this.index = data.index;
  29512. }
  29513. }
  29514. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  29515. addNodeClass( 'VertexColorNode', VertexColorNode );
  29516. class RendererReferenceNode extends ReferenceNode {
  29517. constructor( property, inputType, renderer = null ) {
  29518. super( property, inputType, renderer );
  29519. this.renderer = renderer;
  29520. }
  29521. updateReference( state ) {
  29522. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  29523. return this.reference;
  29524. }
  29525. }
  29526. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  29527. addNodeClass( 'RendererReferenceNode', RendererReferenceNode );
  29528. // Mipped Bicubic Texture Filtering by N8
  29529. // https://www.shadertoy.com/view/Dl2SDW
  29530. const bC = 1.0 / 6.0;
  29531. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  29532. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  29533. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  29534. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  29535. const g0 = ( a ) => w0( a ).add( w1( a ) );
  29536. const g1 = ( a ) => w2( a ).add( w3( a ) );
  29537. // h0 and h1 are the two offset functions
  29538. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  29539. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  29540. const bicubic = ( textureNode, texelSize, lod ) => {
  29541. const uv = textureNode.uvNode;
  29542. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  29543. const iuv = floor( uvScaled );
  29544. const fuv = fract( uvScaled );
  29545. const g0x = g0( fuv.x );
  29546. const g1x = g1( fuv.x );
  29547. const h0x = h0( fuv.x );
  29548. const h1x = h1( fuv.x );
  29549. const h0y = h0( fuv.y );
  29550. const h1y = h1( fuv.y );
  29551. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  29552. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  29553. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  29554. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  29555. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.uv( p0 ).level( lod ) ), g1x.mul( textureNode.uv( p1 ).level( lod ) ) ) );
  29556. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.uv( p2 ).level( lod ) ), g1x.mul( textureNode.uv( p3 ).level( lod ) ) ) );
  29557. return a.add( b );
  29558. };
  29559. const textureBicubicMethod = ( textureNode, lodNode ) => {
  29560. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  29561. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  29562. const fLodSizeInv = div( 1.0, fLodSize );
  29563. const cLodSizeInv = div( 1.0, cLodSize );
  29564. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  29565. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  29566. return fract( lodNode ).mix( fSample, cSample );
  29567. };
  29568. class TextureBicubicNode extends TempNode {
  29569. constructor( textureNode, blurNode = float( 3 ) ) {
  29570. super( 'vec4' );
  29571. this.textureNode = textureNode;
  29572. this.blurNode = blurNode;
  29573. }
  29574. setup() {
  29575. return textureBicubicMethod( this.textureNode, this.blurNode );
  29576. }
  29577. }
  29578. const textureBicubic = nodeProxy( TextureBicubicNode );
  29579. addNodeElement( 'bicubic', textureBicubic );
  29580. addNodeClass( 'TextureBicubicNode', TextureBicubicNode );
  29581. class PointUVNode extends Node {
  29582. constructor() {
  29583. super( 'vec2' );
  29584. this.isPointUVNode = true;
  29585. }
  29586. generate( /*builder*/ ) {
  29587. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  29588. }
  29589. }
  29590. const pointUV = nodeImmutable( PointUVNode );
  29591. addNodeClass( 'PointUVNode', PointUVNode );
  29592. class SceneNode extends Node {
  29593. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  29594. super();
  29595. this.scope = scope;
  29596. this.scene = scene;
  29597. }
  29598. setup( builder ) {
  29599. const scope = this.scope;
  29600. const scene = this.scene !== null ? this.scene : builder.scene;
  29601. let output;
  29602. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  29603. output = reference( 'backgroundBlurriness', 'float', scene );
  29604. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  29605. output = reference( 'backgroundIntensity', 'float', scene );
  29606. } else {
  29607. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  29608. }
  29609. return output;
  29610. }
  29611. }
  29612. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  29613. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  29614. const backgroundBlurriness = nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  29615. const backgroundIntensity = nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  29616. addNodeClass( 'SceneNode', SceneNode );
  29617. const GPUPrimitiveTopology = {
  29618. PointList: 'point-list',
  29619. LineList: 'line-list',
  29620. LineStrip: 'line-strip',
  29621. TriangleList: 'triangle-list',
  29622. TriangleStrip: 'triangle-strip',
  29623. };
  29624. const GPUCompareFunction = {
  29625. Never: 'never',
  29626. Less: 'less',
  29627. Equal: 'equal',
  29628. LessEqual: 'less-equal',
  29629. Greater: 'greater',
  29630. NotEqual: 'not-equal',
  29631. GreaterEqual: 'greater-equal',
  29632. Always: 'always'
  29633. };
  29634. const GPUStoreOp = {
  29635. Store: 'store',
  29636. Discard: 'discard'
  29637. };
  29638. const GPULoadOp = {
  29639. Load: 'load',
  29640. Clear: 'clear'
  29641. };
  29642. const GPUFrontFace = {
  29643. CCW: 'ccw',
  29644. CW: 'cw'
  29645. };
  29646. const GPUCullMode = {
  29647. None: 'none',
  29648. Front: 'front',
  29649. Back: 'back'
  29650. };
  29651. const GPUIndexFormat = {
  29652. Uint16: 'uint16',
  29653. Uint32: 'uint32'
  29654. };
  29655. const GPUTextureFormat = {
  29656. // 8-bit formats
  29657. R8Unorm: 'r8unorm',
  29658. R8Snorm: 'r8snorm',
  29659. R8Uint: 'r8uint',
  29660. R8Sint: 'r8sint',
  29661. // 16-bit formats
  29662. R16Uint: 'r16uint',
  29663. R16Sint: 'r16sint',
  29664. R16Float: 'r16float',
  29665. RG8Unorm: 'rg8unorm',
  29666. RG8Snorm: 'rg8snorm',
  29667. RG8Uint: 'rg8uint',
  29668. RG8Sint: 'rg8sint',
  29669. // 32-bit formats
  29670. R32Uint: 'r32uint',
  29671. R32Sint: 'r32sint',
  29672. R32Float: 'r32float',
  29673. RG16Uint: 'rg16uint',
  29674. RG16Sint: 'rg16sint',
  29675. RG16Float: 'rg16float',
  29676. RGBA8Unorm: 'rgba8unorm',
  29677. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  29678. RGBA8Snorm: 'rgba8snorm',
  29679. RGBA8Uint: 'rgba8uint',
  29680. RGBA8Sint: 'rgba8sint',
  29681. BGRA8Unorm: 'bgra8unorm',
  29682. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  29683. // Packed 32-bit formats
  29684. RGB9E5UFloat: 'rgb9e5ufloat',
  29685. RGB10A2Unorm: 'rgb10a2unorm',
  29686. RG11B10uFloat: 'rgb10a2unorm',
  29687. // 64-bit formats
  29688. RG32Uint: 'rg32uint',
  29689. RG32Sint: 'rg32sint',
  29690. RG32Float: 'rg32float',
  29691. RGBA16Uint: 'rgba16uint',
  29692. RGBA16Sint: 'rgba16sint',
  29693. RGBA16Float: 'rgba16float',
  29694. // 128-bit formats
  29695. RGBA32Uint: 'rgba32uint',
  29696. RGBA32Sint: 'rgba32sint',
  29697. RGBA32Float: 'rgba32float',
  29698. // Depth and stencil formats
  29699. Stencil8: 'stencil8',
  29700. Depth16Unorm: 'depth16unorm',
  29701. Depth24Plus: 'depth24plus',
  29702. Depth24PlusStencil8: 'depth24plus-stencil8',
  29703. Depth32Float: 'depth32float',
  29704. // 'depth32float-stencil8' extension
  29705. Depth32FloatStencil8: 'depth32float-stencil8',
  29706. // BC compressed formats usable if 'texture-compression-bc' is both
  29707. // supported by the device/user agent and enabled in requestDevice.
  29708. BC1RGBAUnorm: 'bc1-rgba-unorm',
  29709. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  29710. BC2RGBAUnorm: 'bc2-rgba-unorm',
  29711. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  29712. BC3RGBAUnorm: 'bc3-rgba-unorm',
  29713. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  29714. BC4RUnorm: 'bc4-r-unorm',
  29715. BC4RSnorm: 'bc4-r-snorm',
  29716. BC5RGUnorm: 'bc5-rg-unorm',
  29717. BC5RGSnorm: 'bc5-rg-snorm',
  29718. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  29719. BC6HRGBFloat: 'bc6h-rgb-float',
  29720. BC7RGBAUnorm: 'bc7-rgba-unorm',
  29721. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  29722. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  29723. // supported by the device/user agent and enabled in requestDevice.
  29724. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  29725. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  29726. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  29727. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  29728. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  29729. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  29730. EACR11Unorm: 'eac-r11unorm',
  29731. EACR11Snorm: 'eac-r11snorm',
  29732. EACRG11Unorm: 'eac-rg11unorm',
  29733. EACRG11Snorm: 'eac-rg11snorm',
  29734. // ASTC compressed formats usable if 'texture-compression-astc' is both
  29735. // supported by the device/user agent and enabled in requestDevice.
  29736. ASTC4x4Unorm: 'astc-4x4-unorm',
  29737. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  29738. ASTC5x4Unorm: 'astc-5x4-unorm',
  29739. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  29740. ASTC5x5Unorm: 'astc-5x5-unorm',
  29741. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  29742. ASTC6x5Unorm: 'astc-6x5-unorm',
  29743. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  29744. ASTC6x6Unorm: 'astc-6x6-unorm',
  29745. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  29746. ASTC8x5Unorm: 'astc-8x5-unorm',
  29747. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  29748. ASTC8x6Unorm: 'astc-8x6-unorm',
  29749. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  29750. ASTC8x8Unorm: 'astc-8x8-unorm',
  29751. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  29752. ASTC10x5Unorm: 'astc-10x5-unorm',
  29753. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  29754. ASTC10x6Unorm: 'astc-10x6-unorm',
  29755. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  29756. ASTC10x8Unorm: 'astc-10x8-unorm',
  29757. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  29758. ASTC10x10Unorm: 'astc-10x10-unorm',
  29759. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  29760. ASTC12x10Unorm: 'astc-12x10-unorm',
  29761. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  29762. ASTC12x12Unorm: 'astc-12x12-unorm',
  29763. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  29764. };
  29765. const GPUAddressMode = {
  29766. ClampToEdge: 'clamp-to-edge',
  29767. Repeat: 'repeat',
  29768. MirrorRepeat: 'mirror-repeat'
  29769. };
  29770. const GPUFilterMode = {
  29771. Linear: 'linear',
  29772. Nearest: 'nearest'
  29773. };
  29774. const GPUBlendFactor = {
  29775. Zero: 'zero',
  29776. One: 'one',
  29777. Src: 'src',
  29778. OneMinusSrc: 'one-minus-src',
  29779. SrcAlpha: 'src-alpha',
  29780. OneMinusSrcAlpha: 'one-minus-src-alpha',
  29781. Dst: 'dst',
  29782. OneMinusDstColor: 'one-minus-dst',
  29783. DstAlpha: 'dst-alpha',
  29784. OneMinusDstAlpha: 'one-minus-dst-alpha',
  29785. SrcAlphaSaturated: 'src-alpha-saturated',
  29786. Constant: 'constant',
  29787. OneMinusConstant: 'one-minus-constant'
  29788. };
  29789. const GPUBlendOperation = {
  29790. Add: 'add',
  29791. Subtract: 'subtract',
  29792. ReverseSubtract: 'reverse-subtract',
  29793. Min: 'min',
  29794. Max: 'max'
  29795. };
  29796. const GPUColorWriteFlags = {
  29797. None: 0,
  29798. Red: 0x1,
  29799. Green: 0x2,
  29800. Blue: 0x4,
  29801. Alpha: 0x8,
  29802. All: 0xF
  29803. };
  29804. const GPUStencilOperation = {
  29805. Keep: 'keep',
  29806. Zero: 'zero',
  29807. Replace: 'replace',
  29808. Invert: 'invert',
  29809. IncrementClamp: 'increment-clamp',
  29810. DecrementClamp: 'decrement-clamp',
  29811. IncrementWrap: 'increment-wrap',
  29812. DecrementWrap: 'decrement-wrap'
  29813. };
  29814. const GPUBufferBindingType = {
  29815. Uniform: 'uniform',
  29816. Storage: 'storage',
  29817. ReadOnlyStorage: 'read-only-storage'
  29818. };
  29819. const GPUStorageTextureAccess = {
  29820. WriteOnly: 'write-only',
  29821. ReadOnly: 'read-only',
  29822. ReadWrite: 'read-write',
  29823. };
  29824. const GPUTextureSampleType = {
  29825. Float: 'float',
  29826. UnfilterableFloat: 'unfilterable-float',
  29827. Depth: 'depth',
  29828. SInt: 'sint',
  29829. UInt: 'uint'
  29830. };
  29831. const GPUTextureDimension = {
  29832. OneD: '1d',
  29833. TwoD: '2d',
  29834. ThreeD: '3d'
  29835. };
  29836. const GPUTextureViewDimension = {
  29837. OneD: '1d',
  29838. TwoD: '2d',
  29839. TwoDArray: '2d-array',
  29840. Cube: 'cube',
  29841. CubeArray: 'cube-array',
  29842. ThreeD: '3d'
  29843. };
  29844. const GPUTextureAspect = {
  29845. All: 'all',
  29846. StencilOnly: 'stencil-only',
  29847. DepthOnly: 'depth-only'
  29848. };
  29849. const GPUInputStepMode = {
  29850. Vertex: 'vertex',
  29851. Instance: 'instance'
  29852. };
  29853. const GPUFeatureName = {
  29854. DepthClipControl: 'depth-clip-control',
  29855. Depth32FloatStencil8: 'depth32float-stencil8',
  29856. TextureCompressionBC: 'texture-compression-bc',
  29857. TextureCompressionETC2: 'texture-compression-etc2',
  29858. TextureCompressionASTC: 'texture-compression-astc',
  29859. TimestampQuery: 'timestamp-query',
  29860. IndirectFirstInstance: 'indirect-first-instance',
  29861. ShaderF16: 'shader-f16',
  29862. RG11B10UFloat: 'rg11b10ufloat-renderable',
  29863. BGRA8UNormStorage: 'bgra8unorm-storage',
  29864. Float32Filterable: 'float32-filterable'
  29865. };
  29866. class StorageBufferNode extends BufferNode {
  29867. constructor( value, bufferType, bufferCount = 0 ) {
  29868. super( value, bufferType, bufferCount );
  29869. this.isStorageBufferNode = true;
  29870. this.access = GPUBufferBindingType.Storage;
  29871. this.bufferObject = false;
  29872. this.bufferCount = bufferCount;
  29873. this._attribute = null;
  29874. this._varying = null;
  29875. this.global = true;
  29876. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  29877. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  29878. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  29879. else value.isStorageBufferAttribute = true;
  29880. }
  29881. }
  29882. getHash( builder ) {
  29883. if ( this.bufferCount === 0 ) {
  29884. let bufferData = builder.globalCache.getData( this.value );
  29885. if ( bufferData === undefined ) {
  29886. bufferData = {
  29887. node: this
  29888. };
  29889. builder.globalCache.setData( this.value, bufferData );
  29890. }
  29891. return bufferData.node.uuid;
  29892. }
  29893. return this.uuid;
  29894. }
  29895. getInputType( /*builder*/ ) {
  29896. return 'storageBuffer';
  29897. }
  29898. element( indexNode ) {
  29899. return storageElement( this, indexNode );
  29900. }
  29901. setBufferObject( value ) {
  29902. this.bufferObject = value;
  29903. return this;
  29904. }
  29905. setAccess( value ) {
  29906. this.access = value;
  29907. return this;
  29908. }
  29909. toReadOnly() {
  29910. return this.setAccess( GPUBufferBindingType.ReadOnlyStorage );
  29911. }
  29912. generate( builder ) {
  29913. if ( builder.isAvailable( 'storageBuffer' ) ) {
  29914. return super.generate( builder );
  29915. }
  29916. const nodeType = this.getNodeType( builder );
  29917. if ( this._attribute === null ) {
  29918. this._attribute = bufferAttribute( this.value );
  29919. this._varying = varying( this._attribute );
  29920. }
  29921. const output = this._varying.build( builder, nodeType );
  29922. builder.registerTransform( output, this._attribute );
  29923. return output;
  29924. }
  29925. }
  29926. // Read-Write Storage
  29927. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  29928. const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) );
  29929. addNodeClass( 'StorageBufferNode', StorageBufferNode );
  29930. class StorageTextureNode extends TextureNode {
  29931. constructor( value, uvNode, storeNode = null ) {
  29932. super( value, uvNode );
  29933. this.storeNode = storeNode;
  29934. this.isStorageTextureNode = true;
  29935. this.access = GPUStorageTextureAccess.WriteOnly;
  29936. }
  29937. getInputType( /*builder*/ ) {
  29938. return 'storageTexture';
  29939. }
  29940. setup( builder ) {
  29941. super.setup( builder );
  29942. const properties = builder.getNodeProperties( this );
  29943. properties.storeNode = this.storeNode;
  29944. }
  29945. setAccess( value ) {
  29946. this.access = value;
  29947. return this;
  29948. }
  29949. generate( builder, output ) {
  29950. let snippet;
  29951. if ( this.storeNode !== null ) {
  29952. snippet = this.generateStore( builder );
  29953. } else {
  29954. snippet = super.generate( builder, output );
  29955. }
  29956. return snippet;
  29957. }
  29958. toReadOnly() {
  29959. return this.setAccess( GPUStorageTextureAccess.ReadOnly );
  29960. }
  29961. toWriteOnly() {
  29962. return this.setAccess( GPUStorageTextureAccess.WriteOnly );
  29963. }
  29964. generateStore( builder ) {
  29965. const properties = builder.getNodeProperties( this );
  29966. const { uvNode, storeNode } = properties;
  29967. const textureProperty = super.generate( builder, 'property' );
  29968. const uvSnippet = uvNode.build( builder, 'uvec2' );
  29969. const storeSnippet = storeNode.build( builder, 'vec4' );
  29970. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  29971. builder.addLineFlowCode( snippet );
  29972. }
  29973. }
  29974. const storageTexture = nodeProxy( StorageTextureNode );
  29975. const textureStore = ( value, uvNode, storeNode ) => {
  29976. const node = storageTexture( value, uvNode, storeNode );
  29977. if ( storeNode !== null ) node.append();
  29978. return node;
  29979. };
  29980. addNodeClass( 'StorageTextureNode', StorageTextureNode );
  29981. const normal = tslFn( ( { texture, uv } ) => {
  29982. const epsilon = 0.0001;
  29983. const ret = vec3().temp();
  29984. If( uv.x.lessThan( epsilon ), () => {
  29985. ret.assign( vec3( 1, 0, 0 ) );
  29986. } ).elseif( uv.y.lessThan( epsilon ), () => {
  29987. ret.assign( vec3( 0, 1, 0 ) );
  29988. } ).elseif( uv.z.lessThan( epsilon ), () => {
  29989. ret.assign( vec3( 0, 0, 1 ) );
  29990. } ).elseif( uv.x.greaterThan( 1 - epsilon ), () => {
  29991. ret.assign( vec3( - 1, 0, 0 ) );
  29992. } ).elseif( uv.y.greaterThan( 1 - epsilon ), () => {
  29993. ret.assign( vec3( 0, - 1, 0 ) );
  29994. } ).elseif( uv.z.greaterThan( 1 - epsilon ), () => {
  29995. ret.assign( vec3( 0, 0, - 1 ) );
  29996. } ).else( () => {
  29997. const step = 0.01;
  29998. 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 );
  29999. 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 );
  30000. 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 );
  30001. ret.assign( vec3( x, y, z ) );
  30002. } );
  30003. return ret.normalize();
  30004. } );
  30005. class Texture3DNode extends TextureNode {
  30006. constructor( value, uvNode = null, levelNode = null ) {
  30007. super( value, uvNode, levelNode );
  30008. this.isTexture3DNode = true;
  30009. }
  30010. getInputType( /*builder*/ ) {
  30011. return 'texture3D';
  30012. }
  30013. getDefaultUV() {
  30014. return vec3( 0.5, 0.5, 0.5 );
  30015. }
  30016. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  30017. setupUV( builder, uvNode ) {
  30018. return uvNode;
  30019. }
  30020. generateUV( builder, uvNode ) {
  30021. return uvNode.build( builder, 'vec3' );
  30022. }
  30023. normal( uvNode ) {
  30024. return normal( { texture: this, uv: uvNode } );
  30025. }
  30026. }
  30027. const texture3D = nodeProxy( Texture3DNode );
  30028. addNodeClass( 'Texture3DNode', Texture3DNode );
  30029. class UserDataNode extends ReferenceNode {
  30030. constructor( property, inputType, userData = null ) {
  30031. super( property, inputType, userData );
  30032. this.userData = userData;
  30033. }
  30034. update( frame ) {
  30035. this.reference = this.userData !== null ? this.userData : frame.object.userData;
  30036. super.update( frame );
  30037. }
  30038. }
  30039. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  30040. addNodeClass( 'UserDataNode', UserDataNode );
  30041. const BurnNode = tslFn( ( { base, blend } ) => {
  30042. const fn = ( c ) => blend[ c ].lessThan( EPSILON ).cond( blend[ c ], base[ c ].oneMinus().div( blend[ c ] ).oneMinus().max( 0 ) );
  30043. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  30044. } ).setLayout( {
  30045. name: 'burnColor',
  30046. type: 'vec3',
  30047. inputs: [
  30048. { name: 'base', type: 'vec3' },
  30049. { name: 'blend', type: 'vec3' }
  30050. ]
  30051. } );
  30052. const DodgeNode = tslFn( ( { base, blend } ) => {
  30053. const fn = ( c ) => blend[ c ].equal( 1.0 ).cond( blend[ c ], base[ c ].div( blend[ c ].oneMinus() ).max( 0 ) );
  30054. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  30055. } ).setLayout( {
  30056. name: 'dodgeColor',
  30057. type: 'vec3',
  30058. inputs: [
  30059. { name: 'base', type: 'vec3' },
  30060. { name: 'blend', type: 'vec3' }
  30061. ]
  30062. } );
  30063. const ScreenNode = tslFn( ( { base, blend } ) => {
  30064. const fn = ( c ) => base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus();
  30065. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  30066. } ).setLayout( {
  30067. name: 'screenColor',
  30068. type: 'vec3',
  30069. inputs: [
  30070. { name: 'base', type: 'vec3' },
  30071. { name: 'blend', type: 'vec3' }
  30072. ]
  30073. } );
  30074. const OverlayNode = tslFn( ( { base, blend } ) => {
  30075. const fn = ( c ) => base[ c ].lessThan( 0.5 ).cond( base[ c ].mul( blend[ c ], 2.0 ), base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus() );
  30076. //const fn = ( c ) => mix( base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus(), base[ c ].mul( blend[ c ], 2.0 ), step( base[ c ], 0.5 ) );
  30077. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  30078. } ).setLayout( {
  30079. name: 'overlayColor',
  30080. type: 'vec3',
  30081. inputs: [
  30082. { name: 'base', type: 'vec3' },
  30083. { name: 'blend', type: 'vec3' }
  30084. ]
  30085. } );
  30086. class BlendModeNode extends TempNode {
  30087. constructor( blendMode, baseNode, blendNode ) {
  30088. super();
  30089. this.blendMode = blendMode;
  30090. this.baseNode = baseNode;
  30091. this.blendNode = blendNode;
  30092. }
  30093. setup() {
  30094. const { blendMode, baseNode, blendNode } = this;
  30095. const params = { base: baseNode, blend: blendNode };
  30096. let outputNode = null;
  30097. if ( blendMode === BlendModeNode.BURN ) {
  30098. outputNode = BurnNode( params );
  30099. } else if ( blendMode === BlendModeNode.DODGE ) {
  30100. outputNode = DodgeNode( params );
  30101. } else if ( blendMode === BlendModeNode.SCREEN ) {
  30102. outputNode = ScreenNode( params );
  30103. } else if ( blendMode === BlendModeNode.OVERLAY ) {
  30104. outputNode = OverlayNode( params );
  30105. }
  30106. return outputNode;
  30107. }
  30108. }
  30109. BlendModeNode.BURN = 'burn';
  30110. BlendModeNode.DODGE = 'dodge';
  30111. BlendModeNode.SCREEN = 'screen';
  30112. BlendModeNode.OVERLAY = 'overlay';
  30113. const burn = nodeProxy( BlendModeNode, BlendModeNode.BURN );
  30114. const dodge = nodeProxy( BlendModeNode, BlendModeNode.DODGE );
  30115. const overlay = nodeProxy( BlendModeNode, BlendModeNode.OVERLAY );
  30116. const screen = nodeProxy( BlendModeNode, BlendModeNode.SCREEN );
  30117. addNodeElement( 'burn', burn );
  30118. addNodeElement( 'dodge', dodge );
  30119. addNodeElement( 'overlay', overlay );
  30120. addNodeElement( 'screen', screen );
  30121. addNodeClass( 'BlendModeNode', BlendModeNode );
  30122. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  30123. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  30124. const dHdxy_fwd = tslFn( ( { textureNode, bumpScale } ) => {
  30125. // It's used to preserve the same TextureNode instance
  30126. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  30127. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  30128. return vec2(
  30129. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  30130. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  30131. ).mul( bumpScale );
  30132. } );
  30133. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  30134. const perturbNormalArb = tslFn( ( inputs ) => {
  30135. const { surf_pos, surf_norm, dHdxy } = inputs;
  30136. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  30137. const vSigmaX = surf_pos.dFdx().normalize();
  30138. const vSigmaY = surf_pos.dFdy().normalize();
  30139. const vN = surf_norm; // normalized
  30140. const R1 = vSigmaY.cross( vN );
  30141. const R2 = vN.cross( vSigmaX );
  30142. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  30143. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  30144. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  30145. } );
  30146. class BumpMapNode extends TempNode {
  30147. constructor( textureNode, scaleNode = null ) {
  30148. super( 'vec3' );
  30149. this.textureNode = textureNode;
  30150. this.scaleNode = scaleNode;
  30151. }
  30152. setup() {
  30153. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  30154. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  30155. return perturbNormalArb( {
  30156. surf_pos: positionView,
  30157. surf_norm: normalView,
  30158. dHdxy
  30159. } );
  30160. }
  30161. }
  30162. const bumpMap = nodeProxy( BumpMapNode );
  30163. addNodeElement( 'bumpMap', bumpMap );
  30164. addNodeClass( 'BumpMapNode', BumpMapNode );
  30165. const saturationNode = tslFn( ( { color, adjustment } ) => {
  30166. return adjustment.mix( luminance( color.rgb ), color.rgb );
  30167. } );
  30168. const vibranceNode = tslFn( ( { color, adjustment } ) => {
  30169. const average = add( color.r, color.g, color.b ).div( 3.0 );
  30170. const mx = color.r.max( color.g.max( color.b ) );
  30171. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  30172. return mix( color.rgb, mx, amt );
  30173. } );
  30174. const hueNode = tslFn( ( { color, adjustment } ) => {
  30175. const k = vec3( 0.57735, 0.57735, 0.57735 );
  30176. const cosAngle = adjustment.cos();
  30177. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  30178. } );
  30179. class ColorAdjustmentNode extends TempNode {
  30180. constructor( method, colorNode, adjustmentNode = float( 1 ) ) {
  30181. super( 'vec3' );
  30182. this.method = method;
  30183. this.colorNode = colorNode;
  30184. this.adjustmentNode = adjustmentNode;
  30185. }
  30186. setup() {
  30187. const { method, colorNode, adjustmentNode } = this;
  30188. const callParams = { color: colorNode, adjustment: adjustmentNode };
  30189. let outputNode = null;
  30190. if ( method === ColorAdjustmentNode.SATURATION ) {
  30191. outputNode = saturationNode( callParams );
  30192. } else if ( method === ColorAdjustmentNode.VIBRANCE ) {
  30193. outputNode = vibranceNode( callParams );
  30194. } else if ( method === ColorAdjustmentNode.HUE ) {
  30195. outputNode = hueNode( callParams );
  30196. } else {
  30197. console.error( `${ this.type }: Method "${ this.method }" not supported!` );
  30198. }
  30199. return outputNode;
  30200. }
  30201. }
  30202. ColorAdjustmentNode.SATURATION = 'saturation';
  30203. ColorAdjustmentNode.VIBRANCE = 'vibrance';
  30204. ColorAdjustmentNode.HUE = 'hue';
  30205. const saturation = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.SATURATION );
  30206. const vibrance = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.VIBRANCE );
  30207. const hue = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.HUE );
  30208. const lumaCoeffs = vec3( 0.2125, 0.7154, 0.0721 );
  30209. const luminance = ( color, luma = lumaCoeffs ) => dot( color, luma );
  30210. const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) );
  30211. addNodeElement( 'saturation', saturation );
  30212. addNodeElement( 'vibrance', vibrance );
  30213. addNodeElement( 'hue', hue );
  30214. addNodeElement( 'threshold', threshold );
  30215. addNodeClass( 'ColorAdjustmentNode', ColorAdjustmentNode );
  30216. // Normal Mapping Without Precomputed Tangents
  30217. // http://www.thetenthplanet.de/archives/1180
  30218. const perturbNormal2Arb = tslFn( ( inputs ) => {
  30219. const { eye_pos, surf_norm, mapN, uv } = inputs;
  30220. const q0 = eye_pos.dFdx();
  30221. const q1 = eye_pos.dFdy();
  30222. const st0 = uv.dFdx();
  30223. const st1 = uv.dFdy();
  30224. const N = surf_norm; // normalized
  30225. const q1perp = q1.cross( N );
  30226. const q0perp = N.cross( q0 );
  30227. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  30228. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  30229. const det = T.dot( T ).max( B.dot( B ) );
  30230. const scale = faceDirection.mul( det.inverseSqrt() );
  30231. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  30232. } );
  30233. class NormalMapNode extends TempNode {
  30234. constructor( node, scaleNode = null ) {
  30235. super( 'vec3' );
  30236. this.node = node;
  30237. this.scaleNode = scaleNode;
  30238. this.normalMapType = TangentSpaceNormalMap;
  30239. }
  30240. setup( builder ) {
  30241. const { normalMapType, scaleNode } = this;
  30242. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  30243. if ( scaleNode !== null ) {
  30244. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  30245. }
  30246. let outputNode = null;
  30247. if ( normalMapType === ObjectSpaceNormalMap ) {
  30248. outputNode = modelNormalMatrix.mul( normalMap ).normalize();
  30249. } else if ( normalMapType === TangentSpaceNormalMap ) {
  30250. const tangent = builder.hasGeometryAttribute( 'tangent' );
  30251. if ( tangent === true ) {
  30252. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  30253. } else {
  30254. outputNode = perturbNormal2Arb( {
  30255. eye_pos: positionView,
  30256. surf_norm: normalView,
  30257. mapN: normalMap,
  30258. uv: uv()
  30259. } );
  30260. }
  30261. }
  30262. return outputNode;
  30263. }
  30264. }
  30265. const normalMap = nodeProxy( NormalMapNode );
  30266. addNodeElement( 'normalMap', normalMap );
  30267. addNodeClass( 'NormalMapNode', NormalMapNode );
  30268. class PosterizeNode extends TempNode {
  30269. constructor( sourceNode, stepsNode ) {
  30270. super();
  30271. this.sourceNode = sourceNode;
  30272. this.stepsNode = stepsNode;
  30273. }
  30274. setup() {
  30275. const { sourceNode, stepsNode } = this;
  30276. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  30277. }
  30278. }
  30279. const posterize = nodeProxy( PosterizeNode );
  30280. addNodeElement( 'posterize', posterize );
  30281. addNodeClass( 'PosterizeNode', PosterizeNode );
  30282. // exposure only
  30283. const LinearToneMappingNode = tslFn( ( { color, exposure } ) => {
  30284. return color.mul( exposure ).clamp();
  30285. } );
  30286. // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
  30287. const ReinhardToneMappingNode = tslFn( ( { color, exposure } ) => {
  30288. color = color.mul( exposure );
  30289. return color.div( color.add( 1.0 ) ).clamp();
  30290. } );
  30291. // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
  30292. const OptimizedCineonToneMappingNode = tslFn( ( { color, exposure } ) => {
  30293. // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson
  30294. color = color.mul( exposure );
  30295. color = color.sub( 0.004 ).max( 0.0 );
  30296. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  30297. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  30298. return a.div( b ).pow( 2.2 );
  30299. } );
  30300. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  30301. const RRTAndODTFit = tslFn( ( { color } ) => {
  30302. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  30303. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  30304. return a.div( b );
  30305. } );
  30306. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  30307. const ACESFilmicToneMappingNode = tslFn( ( { color, exposure } ) => {
  30308. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  30309. const ACESInputMat = mat3(
  30310. 0.59719, 0.35458, 0.04823,
  30311. 0.07600, 0.90834, 0.01566,
  30312. 0.02840, 0.13383, 0.83777
  30313. );
  30314. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  30315. const ACESOutputMat = mat3(
  30316. 1.60475, - 0.53108, - 0.07367,
  30317. - 0.10208, 1.10813, - 0.00605,
  30318. - 0.00327, - 0.07276, 1.07602
  30319. );
  30320. color = color.mul( exposure ).div( 0.6 );
  30321. color = ACESInputMat.mul( color );
  30322. // Apply RRT and ODT
  30323. color = RRTAndODTFit( { color } );
  30324. color = ACESOutputMat.mul( color );
  30325. // Clamp to [0, 1]
  30326. return color.clamp();
  30327. } );
  30328. 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 ) );
  30329. 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 ) );
  30330. const agxDefaultContrastApprox = tslFn( ( [ x_immutable ] ) => {
  30331. const x = vec3( x_immutable ).toVar();
  30332. const x2 = vec3( x.mul( x ) ).toVar();
  30333. const x4 = vec3( x2.mul( x2 ) ).toVar();
  30334. 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 ) ) ) );
  30335. } );
  30336. const AGXToneMappingNode = tslFn( ( { color, exposure } ) => {
  30337. const colortone = vec3( color ).toVar();
  30338. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  30339. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  30340. const AgxMinEv = float( - 12.47393 );
  30341. const AgxMaxEv = float( 4.026069 );
  30342. colortone.mulAssign( exposure );
  30343. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  30344. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  30345. colortone.assign( max$1( colortone, 1e-10 ) );
  30346. colortone.assign( log2( colortone ) );
  30347. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  30348. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  30349. colortone.assign( agxDefaultContrastApprox( colortone ) );
  30350. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  30351. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  30352. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  30353. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  30354. return colortone;
  30355. } );
  30356. // https://modelviewer.dev/examples/tone-mapping
  30357. const NeutralToneMappingNode = tslFn( ( { color, exposure } ) => {
  30358. const StartCompression = float( 0.8 - 0.04 );
  30359. const Desaturation = float( 0.15 );
  30360. color = color.mul( exposure );
  30361. const x = min$1( color.r, min$1( color.g, color.b ) );
  30362. const offset = cond( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  30363. color.subAssign( offset );
  30364. const peak = max$1( color.r, max$1( color.g, color.b ) );
  30365. If( peak.lessThan( StartCompression ), () => {
  30366. return color;
  30367. } );
  30368. const d = sub( 1, StartCompression );
  30369. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  30370. color.mulAssign( newPeak.div( peak ) );
  30371. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  30372. return mix( color, vec3( newPeak ), g );
  30373. } ).setLayout( {
  30374. name: 'NeutralToneMapping',
  30375. type: 'vec3',
  30376. inputs: [
  30377. { name: 'color', type: 'vec3' },
  30378. { name: 'exposure', type: 'float' }
  30379. ]
  30380. } );
  30381. const toneMappingLib = {
  30382. [ LinearToneMapping ]: LinearToneMappingNode,
  30383. [ ReinhardToneMapping ]: ReinhardToneMappingNode,
  30384. [ CineonToneMapping ]: OptimizedCineonToneMappingNode,
  30385. [ ACESFilmicToneMapping ]: ACESFilmicToneMappingNode,
  30386. [ AgXToneMapping ]: AGXToneMappingNode,
  30387. [ NeutralToneMapping ]: NeutralToneMappingNode
  30388. };
  30389. class ToneMappingNode extends TempNode {
  30390. constructor( toneMapping = NoToneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  30391. super( 'vec3' );
  30392. this.toneMapping = toneMapping;
  30393. this.exposureNode = exposureNode;
  30394. this.colorNode = colorNode;
  30395. }
  30396. getCacheKey() {
  30397. let cacheKey = super.getCacheKey();
  30398. cacheKey = '{toneMapping:' + this.toneMapping + ',nodes:' + cacheKey + '}';
  30399. return cacheKey;
  30400. }
  30401. setup( builder ) {
  30402. const colorNode = this.colorNode || builder.context.color;
  30403. const toneMapping = this.toneMapping;
  30404. if ( toneMapping === NoToneMapping ) return colorNode;
  30405. const toneMappingParams = { exposure: this.exposureNode, color: colorNode };
  30406. const toneMappingNode = toneMappingLib[ toneMapping ];
  30407. let outputNode = null;
  30408. if ( toneMappingNode ) {
  30409. outputNode = toneMappingNode( toneMappingParams );
  30410. } else {
  30411. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  30412. outputNode = colorNode;
  30413. }
  30414. return outputNode;
  30415. }
  30416. }
  30417. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  30418. const toneMappingExposure = rendererReference( 'toneMappingExposure', 'float' );
  30419. addNodeElement( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  30420. addNodeClass( 'ToneMappingNode', ToneMappingNode );
  30421. let _sharedFramebuffer = null;
  30422. class ViewportSharedTextureNode extends ViewportTextureNode {
  30423. constructor( uvNode = viewportTopLeft, levelNode = null ) {
  30424. if ( _sharedFramebuffer === null ) {
  30425. _sharedFramebuffer = new FramebufferTexture();
  30426. }
  30427. super( uvNode, levelNode, _sharedFramebuffer );
  30428. }
  30429. updateReference() {
  30430. return this;
  30431. }
  30432. }
  30433. const viewportSharedTexture = nodeProxy( ViewportSharedTextureNode );
  30434. addNodeElement( 'viewportSharedTexture', viewportSharedTexture );
  30435. addNodeClass( 'ViewportSharedTextureNode', ViewportSharedTextureNode );
  30436. const _size$2 = new Vector2();
  30437. class PassTextureNode extends TextureNode {
  30438. constructor( passNode, texture ) {
  30439. super( texture );
  30440. this.passNode = passNode;
  30441. this.setUpdateMatrix( false );
  30442. }
  30443. setup( builder ) {
  30444. this.passNode.build( builder );
  30445. return super.setup( builder );
  30446. }
  30447. clone() {
  30448. return new this.constructor( this.passNode, this.value );
  30449. }
  30450. }
  30451. class PassNode extends TempNode {
  30452. constructor( scope, scene, camera ) {
  30453. super( 'vec4' );
  30454. this.scope = scope;
  30455. this.scene = scene;
  30456. this.camera = camera;
  30457. this._pixelRatio = 1;
  30458. this._width = 1;
  30459. this._height = 1;
  30460. const depthTexture = new DepthTexture();
  30461. depthTexture.isRenderTargetTexture = true;
  30462. //depthTexture.type = FloatType;
  30463. depthTexture.name = 'PostProcessingDepth';
  30464. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType } );
  30465. renderTarget.texture.name = 'PostProcessing';
  30466. renderTarget.depthTexture = depthTexture;
  30467. this.renderTarget = renderTarget;
  30468. this.updateBeforeType = NodeUpdateType.FRAME;
  30469. this._textureNode = nodeObject( new PassTextureNode( this, renderTarget.texture ) );
  30470. this._depthTextureNode = nodeObject( new PassTextureNode( this, depthTexture ) );
  30471. this._linearDepthNode = null;
  30472. this._viewZNode = null;
  30473. this._cameraNear = uniform( 0 );
  30474. this._cameraFar = uniform( 0 );
  30475. this.isPassNode = true;
  30476. }
  30477. isGlobal() {
  30478. return true;
  30479. }
  30480. getTextureNode() {
  30481. return this._textureNode;
  30482. }
  30483. getTextureDepthNode() {
  30484. return this._depthTextureNode;
  30485. }
  30486. getViewZNode() {
  30487. if ( this._viewZNode === null ) {
  30488. const cameraNear = this._cameraNear;
  30489. const cameraFar = this._cameraFar;
  30490. this._viewZNode = perspectiveDepthToViewZ( this._depthTextureNode, cameraNear, cameraFar );
  30491. }
  30492. return this._viewZNode;
  30493. }
  30494. getLinearDepthNode() {
  30495. if ( this._linearDepthNode === null ) {
  30496. const cameraNear = this._cameraNear;
  30497. const cameraFar = this._cameraFar;
  30498. // TODO: just if ( builder.camera.isPerspectiveCamera )
  30499. this._linearDepthNode = viewZToOrthographicDepth( this.getViewZNode(), cameraNear, cameraFar );
  30500. }
  30501. return this._linearDepthNode;
  30502. }
  30503. setup() {
  30504. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  30505. }
  30506. updateBefore( frame ) {
  30507. const { renderer } = frame;
  30508. const { scene, camera } = this;
  30509. this._pixelRatio = renderer.getPixelRatio();
  30510. const size = renderer.getSize( _size$2 );
  30511. this.setSize( size.width, size.height );
  30512. const currentToneMapping = renderer.toneMapping;
  30513. const currentToneMappingNode = renderer.toneMappingNode;
  30514. const currentRenderTarget = renderer.getRenderTarget();
  30515. this._cameraNear.value = camera.near;
  30516. this._cameraFar.value = camera.far;
  30517. renderer.toneMapping = NoToneMapping;
  30518. renderer.toneMappingNode = null;
  30519. renderer.setRenderTarget( this.renderTarget );
  30520. renderer.render( scene, camera );
  30521. renderer.toneMapping = currentToneMapping;
  30522. renderer.toneMappingNode = currentToneMappingNode;
  30523. renderer.setRenderTarget( currentRenderTarget );
  30524. }
  30525. setSize( width, height ) {
  30526. this._width = width;
  30527. this._height = height;
  30528. const effectiveWidth = this._width * this._pixelRatio;
  30529. const effectiveHeight = this._height * this._pixelRatio;
  30530. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  30531. }
  30532. setPixelRatio( pixelRatio ) {
  30533. this._pixelRatio = pixelRatio;
  30534. this.setSize( this._width, this._height );
  30535. }
  30536. dispose() {
  30537. this.renderTarget.dispose();
  30538. }
  30539. }
  30540. PassNode.COLOR = 'color';
  30541. PassNode.DEPTH = 'depth';
  30542. const pass = ( scene, camera ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera ) );
  30543. const texturePass = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  30544. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  30545. addNodeClass( 'PassNode', PassNode );
  30546. // WebGPU: The use of a single QuadMesh for both gaussian blur passes results in a single RenderObject with a SampledTexture binding that
  30547. // alternates between source textures and triggers creation of new BindGroups and BindGroupLayouts every frame.
  30548. const quadMesh1 = new QuadMesh();
  30549. const quadMesh2 = new QuadMesh();
  30550. class GaussianBlurNode extends TempNode {
  30551. constructor( textureNode, directionNode = null, sigma = 2 ) {
  30552. super( 'vec4' );
  30553. this.textureNode = textureNode;
  30554. this.directionNode = directionNode;
  30555. this.sigma = sigma;
  30556. this._invSize = uniform( new Vector2() );
  30557. this._passDirection = uniform( new Vector2() );
  30558. this._horizontalRT = new RenderTarget();
  30559. this._horizontalRT.texture.name = 'GaussianBlurNode.horizontal';
  30560. this._verticalRT = new RenderTarget();
  30561. this._verticalRT.texture.name = 'GaussianBlurNode.vertical';
  30562. this._textureNode = texturePass( this, this._verticalRT.texture );
  30563. this.updateBeforeType = NodeUpdateType.RENDER;
  30564. this.resolution = new Vector2( 1, 1 );
  30565. }
  30566. setSize( width, height ) {
  30567. width = Math.max( Math.round( width * this.resolution.x ), 1 );
  30568. height = Math.max( Math.round( height * this.resolution.y ), 1 );
  30569. this._invSize.value.set( 1 / width, 1 / height );
  30570. this._horizontalRT.setSize( width, height );
  30571. this._verticalRT.setSize( width, height );
  30572. }
  30573. updateBefore( frame ) {
  30574. const { renderer } = frame;
  30575. const textureNode = this.textureNode;
  30576. const map = textureNode.value;
  30577. const currentRenderTarget = renderer.getRenderTarget();
  30578. const currentTexture = textureNode.value;
  30579. quadMesh1.material = this._material;
  30580. quadMesh2.material = this._material;
  30581. this.setSize( map.image.width, map.image.height );
  30582. const textureType = map.type;
  30583. this._horizontalRT.texture.type = textureType;
  30584. this._verticalRT.texture.type = textureType;
  30585. // horizontal
  30586. renderer.setRenderTarget( this._horizontalRT );
  30587. this._passDirection.value.set( 1, 0 );
  30588. quadMesh1.render( renderer );
  30589. // vertical
  30590. textureNode.value = this._horizontalRT.texture;
  30591. renderer.setRenderTarget( this._verticalRT );
  30592. this._passDirection.value.set( 0, 1 );
  30593. quadMesh2.render( renderer );
  30594. // restore
  30595. renderer.setRenderTarget( currentRenderTarget );
  30596. textureNode.value = currentTexture;
  30597. }
  30598. getTextureNode() {
  30599. return this._textureNode;
  30600. }
  30601. setup( builder ) {
  30602. const textureNode = this.textureNode;
  30603. if ( textureNode.isTextureNode !== true ) {
  30604. console.error( 'GaussianBlurNode requires a TextureNode.' );
  30605. return vec4();
  30606. }
  30607. //
  30608. const uvNode = textureNode.uvNode || uv();
  30609. const directionNode = vec2( this.directionNode || 1 );
  30610. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30611. const blur = tslFn( () => {
  30612. const kernelSize = 3 + ( 2 * this.sigma );
  30613. const gaussianCoefficients = this._getCoefficients( kernelSize );
  30614. const invSize = this._invSize;
  30615. const direction = directionNode.mul( this._passDirection );
  30616. const weightSum = float( gaussianCoefficients[ 0 ] ).toVar();
  30617. const diffuseSum = vec4( sampleTexture( uvNode ).mul( weightSum ) ).toVar();
  30618. for ( let i = 1; i < kernelSize; i ++ ) {
  30619. const x = float( i );
  30620. const w = float( gaussianCoefficients[ i ] );
  30621. const uvOffset = vec2( direction.mul( invSize.mul( x ) ) ).toVar();
  30622. const sample1 = vec4( sampleTexture( uvNode.add( uvOffset ) ) );
  30623. const sample2 = vec4( sampleTexture( uvNode.sub( uvOffset ) ) );
  30624. diffuseSum.addAssign( sample1.add( sample2 ).mul( w ) );
  30625. weightSum.addAssign( mul( 2.0, w ) );
  30626. }
  30627. return diffuseSum.div( weightSum );
  30628. } );
  30629. //
  30630. const material = this._material || ( this._material = builder.createNodeMaterial() );
  30631. material.fragmentNode = blur();
  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 = texturePass( 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 currentToneMapping = renderer.toneMapping;
  30680. const currentToneMappingNode = renderer.toneMappingNode;
  30681. const currentRenderTarget = renderer.getRenderTarget();
  30682. const currentTexture = textureNode.value;
  30683. this.textureNodeOld.value = this._oldRT.texture;
  30684. // comp
  30685. renderer.toneMapping = NoToneMapping;
  30686. renderer.toneMappingNode = null;
  30687. renderer.setRenderTarget( this._compRT );
  30688. quadMeshComp.render( renderer );
  30689. // Swap the textures
  30690. const temp = this._oldRT;
  30691. this._oldRT = this._compRT;
  30692. this._compRT = temp;
  30693. renderer.toneMapping = currentToneMapping;
  30694. renderer.toneMappingNode = currentToneMappingNode;
  30695. renderer.setRenderTarget( currentRenderTarget );
  30696. textureNode.value = currentTexture;
  30697. }
  30698. setup( builder ) {
  30699. const textureNode = this.textureNode;
  30700. const textureNodeOld = this.textureNodeOld;
  30701. //
  30702. const uvNode = textureNode.uvNode || uv();
  30703. textureNodeOld.uvNode = uvNode;
  30704. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30705. const when_gt = tslFn( ( [ x_immutable, y_immutable ] ) => {
  30706. const y = float( y_immutable ).toVar();
  30707. const x = vec4( x_immutable ).toVar();
  30708. return max$1( sign( x.sub( y ) ), 0.0 );
  30709. } );
  30710. const afterImg = tslFn( () => {
  30711. const texelOld = vec4( textureNodeOld );
  30712. const texelNew = vec4( sampleTexture( uvNode ) );
  30713. texelOld.mulAssign( this.damp.mul( when_gt( texelOld, 0.1 ) ) );
  30714. return max$1( texelNew, texelOld );
  30715. } );
  30716. //
  30717. const materialComposed = this._materialComposed || ( this._materialComposed = builder.createNodeMaterial() );
  30718. materialComposed.fragmentNode = afterImg();
  30719. quadMeshComp.material = materialComposed;
  30720. //
  30721. const properties = builder.getNodeProperties( this );
  30722. properties.textureNode = textureNode;
  30723. //
  30724. return this._textureNode;
  30725. }
  30726. }
  30727. const afterImage = ( node, damp ) => nodeObject( new AfterImageNode( nodeObject( node ).toTexture(), damp ) );
  30728. addNodeElement( 'afterImage', afterImage );
  30729. const quadMesh$1 = new QuadMesh();
  30730. class AnamorphicNode extends TempNode {
  30731. constructor( textureNode, tresholdNode, scaleNode, samples ) {
  30732. super( 'vec4' );
  30733. this.textureNode = textureNode;
  30734. this.tresholdNode = tresholdNode;
  30735. this.scaleNode = scaleNode;
  30736. this.colorNode = vec3( 0.1, 0.0, 1.0 );
  30737. this.samples = samples;
  30738. this.resolution = new Vector2( 1, 1 );
  30739. this._renderTarget = new RenderTarget();
  30740. this._renderTarget.texture.name = 'anamorphic';
  30741. this._invSize = uniform( new Vector2() );
  30742. this._textureNode = texturePass( this, this._renderTarget.texture );
  30743. this.updateBeforeType = NodeUpdateType.RENDER;
  30744. }
  30745. getTextureNode() {
  30746. return this._textureNode;
  30747. }
  30748. setSize( width, height ) {
  30749. this._invSize.value.set( 1 / width, 1 / height );
  30750. width = Math.max( Math.round( width * this.resolution.x ), 1 );
  30751. height = Math.max( Math.round( height * this.resolution.y ), 1 );
  30752. this._renderTarget.setSize( width, height );
  30753. }
  30754. updateBefore( frame ) {
  30755. const { renderer } = frame;
  30756. const textureNode = this.textureNode;
  30757. const map = textureNode.value;
  30758. this._renderTarget.texture.type = map.type;
  30759. const currentRenderTarget = renderer.getRenderTarget();
  30760. const currentTexture = textureNode.value;
  30761. quadMesh$1.material = this._material;
  30762. this.setSize( map.image.width, map.image.height );
  30763. // render
  30764. renderer.setRenderTarget( this._renderTarget );
  30765. quadMesh$1.render( renderer );
  30766. // restore
  30767. renderer.setRenderTarget( currentRenderTarget );
  30768. textureNode.value = currentTexture;
  30769. }
  30770. setup( builder ) {
  30771. const textureNode = this.textureNode;
  30772. const uvNode = textureNode.uvNode || uv();
  30773. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30774. const anamorph = tslFn( () => {
  30775. const samples = this.samples;
  30776. const halfSamples = Math.floor( samples / 2 );
  30777. const total = vec3( 0 ).toVar();
  30778. loop( { start: - halfSamples, end: halfSamples }, ( { i } ) => {
  30779. const softness = float( i ).abs().div( halfSamples ).oneMinus();
  30780. const uv = vec2( uvNode.x.add( this._invSize.x.mul( i ).mul( this.scaleNode ) ), uvNode.y );
  30781. const color = sampleTexture( uv );
  30782. const pass = threshold( color, this.tresholdNode ).mul( softness );
  30783. total.addAssign( pass );
  30784. } );
  30785. return total.mul( this.colorNode );
  30786. } );
  30787. //
  30788. const material = this._material || ( this._material = builder.createNodeMaterial() );
  30789. material.fragmentNode = anamorph();
  30790. //
  30791. const properties = builder.getNodeProperties( this );
  30792. properties.textureNode = textureNode;
  30793. //
  30794. return this._textureNode;
  30795. }
  30796. }
  30797. const anamorphic = ( node, threshold = .9, scale = 3, samples = 32 ) => nodeObject( new AnamorphicNode( nodeObject( node ).toTexture(), nodeObject( threshold ), nodeObject( scale ), samples ) );
  30798. addNodeElement( 'anamorphic', anamorphic );
  30799. class SobelOperatorNode extends TempNode {
  30800. constructor( textureNode ) {
  30801. super();
  30802. this.textureNode = textureNode;
  30803. this.updateBeforeType = NodeUpdateType.RENDER;
  30804. this._invSize = uniform( new Vector2() );
  30805. }
  30806. updateBefore() {
  30807. const map = this.textureNode.value;
  30808. this._invSize.value.set( 1 / map.image.width, 1 / map.image.height );
  30809. }
  30810. setup() {
  30811. const { textureNode } = this;
  30812. const uvNode = textureNode.uvNode || uv();
  30813. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30814. const sobel = tslFn( () => {
  30815. // Sobel Edge Detection (see https://youtu.be/uihBwtPIBxM)
  30816. const texel = this._invSize;
  30817. // kernel definition (in glsl matrices are filled in column-major order)
  30818. const Gx = mat3( - 1, - 2, - 1, 0, 0, 0, 1, 2, 1 ); // x direction kernel
  30819. const Gy = mat3( - 1, 0, 1, - 2, 0, 2, - 1, 0, 1 ); // y direction kernel
  30820. // fetch the 3x3 neighbourhood of a fragment
  30821. // first column
  30822. const tx0y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, - 1 ) ) ) ).xyz );
  30823. const tx0y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, 0 ) ) ) ).xyz );
  30824. const tx0y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, 1 ) ) ) ).xyz );
  30825. // second column
  30826. const tx1y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, - 1 ) ) ) ).xyz );
  30827. const tx1y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, 0 ) ) ) ).xyz );
  30828. const tx1y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, 1 ) ) ) ).xyz );
  30829. // third column
  30830. const tx2y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, - 1 ) ) ) ).xyz );
  30831. const tx2y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, 0 ) ) ) ).xyz );
  30832. const tx2y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, 1 ) ) ) ).xyz );
  30833. // gradient value in x direction
  30834. const valueGx = add(
  30835. Gx[ 0 ][ 0 ].mul( tx0y0 ),
  30836. Gx[ 1 ][ 0 ].mul( tx1y0 ),
  30837. Gx[ 2 ][ 0 ].mul( tx2y0 ),
  30838. Gx[ 0 ][ 1 ].mul( tx0y1 ),
  30839. Gx[ 1 ][ 1 ].mul( tx1y1 ),
  30840. Gx[ 2 ][ 1 ].mul( tx2y1 ),
  30841. Gx[ 0 ][ 2 ].mul( tx0y2 ),
  30842. Gx[ 1 ][ 2 ].mul( tx1y2 ),
  30843. Gx[ 2 ][ 2 ].mul( tx2y2 )
  30844. );
  30845. // gradient value in y direction
  30846. const valueGy = add(
  30847. Gy[ 0 ][ 0 ].mul( tx0y0 ),
  30848. Gy[ 1 ][ 0 ].mul( tx1y0 ),
  30849. Gy[ 2 ][ 0 ].mul( tx2y0 ),
  30850. Gy[ 0 ][ 1 ].mul( tx0y1 ),
  30851. Gy[ 1 ][ 1 ].mul( tx1y1 ),
  30852. Gy[ 2 ][ 1 ].mul( tx2y1 ),
  30853. Gy[ 0 ][ 2 ].mul( tx0y2 ),
  30854. Gy[ 1 ][ 2 ].mul( tx1y2 ),
  30855. Gy[ 2 ][ 2 ].mul( tx2y2 )
  30856. );
  30857. // magnitute of the total gradient
  30858. const G = valueGx.mul( valueGx ).add( valueGy.mul( valueGy ) ).sqrt();
  30859. return vec4( vec3( G ), 1 );
  30860. } );
  30861. const outputNode = sobel();
  30862. return outputNode;
  30863. }
  30864. }
  30865. const sobel = ( node ) => nodeObject( new SobelOperatorNode( nodeObject( node ).toTexture() ) );
  30866. addNodeElement( 'sobel', sobel );
  30867. class DepthOfFieldNode extends TempNode {
  30868. constructor( textureNode, viewZNode, focusNode, apertureNode, maxblurNode ) {
  30869. super();
  30870. this.textureNode = textureNode;
  30871. this.viewZNode = viewZNode;
  30872. this.focusNode = focusNode;
  30873. this.apertureNode = apertureNode;
  30874. this.maxblurNode = maxblurNode;
  30875. this._aspect = uniform( 0 );
  30876. this.updateBeforeType = NodeUpdateType.RENDER;
  30877. }
  30878. updateBefore() {
  30879. const map = this.textureNode.value;
  30880. this._aspect.value = map.image.width / map.image.height;
  30881. }
  30882. setup() {
  30883. const textureNode = this.textureNode;
  30884. const uvNode = textureNode.uvNode || uv();
  30885. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30886. const dof = tslFn( () => {
  30887. const aspectcorrect = vec2( 1.0, this._aspect );
  30888. const factor = this.focusNode.add( this.viewZNode );
  30889. const dofblur = vec2( clamp( factor.mul( this.apertureNode ), this.maxblurNode.negate(), this.maxblurNode ) );
  30890. const dofblur9 = dofblur.mul( 0.9 );
  30891. const dofblur7 = dofblur.mul( 0.7 );
  30892. const dofblur4 = dofblur.mul( 0.4 );
  30893. let col = vec4( 0.0 );
  30894. col = col.add( sampleTexture( uvNode ) );
  30895. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).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.29, 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30898. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30899. col = col.add( sampleTexture( uvNode.add( vec2( 0.40, 0.0 ).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.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30902. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30903. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).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.29, 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30906. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30907. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30908. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30909. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30910. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30911. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30912. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30913. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30914. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30915. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30916. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30917. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30918. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  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.40, 0.0 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30921. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30922. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30923. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30924. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30925. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30926. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  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.4, 0.0 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30929. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30930. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30931. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30932. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30933. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30934. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30935. col = col.div( 41 );
  30936. col.a = 1;
  30937. return vec4( col );
  30938. } );
  30939. const outputNode = dof();
  30940. return outputNode;
  30941. }
  30942. }
  30943. 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 ) ) );
  30944. addNodeElement( 'dof', dof );
  30945. class DotScreenNode extends TempNode {
  30946. constructor( inputNode, center = new Vector2( 0.5, 0.5 ), angle = 1.57, scale = 1 ) {
  30947. super( 'vec4' );
  30948. this.inputNode = inputNode;
  30949. this.center = uniform( center );
  30950. this.angle = uniform( angle );
  30951. this.scale = uniform( scale );
  30952. this._size = uniform( new Vector2() );
  30953. this.updateBeforeType = NodeUpdateType.RENDER;
  30954. }
  30955. updateBefore() {
  30956. const map = this.inputNode.value;
  30957. this._size.value.set( map.image.width, map.image.height );
  30958. }
  30959. setup() {
  30960. const inputNode = this.inputNode;
  30961. const pattern = tslFn( () => {
  30962. const s = sin( this.angle );
  30963. const c = cos( this.angle );
  30964. const tex = uv().mul( this._size ).sub( this.center );
  30965. const point = vec2( c.mul( tex.x ).sub( s.mul( tex.y ) ), s.mul( tex.x ).add( c.mul( tex.y ) ) ).mul( this.scale );
  30966. return sin( point.x ).mul( sin( point.y ) ).mul( 4 );
  30967. } );
  30968. const dotScreen = tslFn( () => {
  30969. const color = inputNode;
  30970. const average = add( color.r, color.g, color.b ).div( 3 );
  30971. return vec4( vec3( average.mul( 10 ).sub( 5 ).add( pattern() ) ), color.a );
  30972. } );
  30973. const outputNode = dotScreen();
  30974. return outputNode;
  30975. }
  30976. }
  30977. const dotScreen = ( node, center, angle, scale ) => nodeObject( new DotScreenNode( nodeObject( node ), center, angle, scale ) );
  30978. addNodeElement( 'dotScreen', dotScreen );
  30979. class RGBShiftNode extends TempNode {
  30980. constructor( textureNode, amount = 0.005, angle = 0 ) {
  30981. super( 'vec4' );
  30982. this.textureNode = textureNode;
  30983. this.amount = uniform( amount );
  30984. this.angle = uniform( angle );
  30985. }
  30986. setup() {
  30987. const { textureNode } = this;
  30988. const uvNode = textureNode.uvNode || uv();
  30989. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30990. const rgbShift = tslFn( () => {
  30991. const offset = vec2( cos( this.angle ), sin( this.angle ) ).mul( this.amount );
  30992. const cr = sampleTexture( uvNode.add( offset ) );
  30993. const cga = sampleTexture( uvNode );
  30994. const cb = sampleTexture( uvNode.sub( offset ) );
  30995. return vec4( cr.r, cga.g, cb.b, cga.a );
  30996. } );
  30997. return rgbShift();
  30998. }
  30999. }
  31000. const rgbShift = ( node, amount, angle ) => nodeObject( new RGBShiftNode( nodeObject( node ).toTexture(), amount, angle ) );
  31001. addNodeElement( 'rgbShift', rgbShift );
  31002. class FilmNode extends TempNode {
  31003. constructor( inputNode, intensityNode = null, uvNode = null ) {
  31004. super();
  31005. this.inputNode = inputNode;
  31006. this.intensityNode = intensityNode;
  31007. this.uvNode = uvNode;
  31008. }
  31009. setup() {
  31010. const uvNode = this.uvNode || uv();
  31011. const film = tslFn( () => {
  31012. const base = this.inputNode.rgb;
  31013. const noise = rand( fract( uvNode.add( timerLocal() ) ) );
  31014. let color = base.add( base.mul( clamp( noise.add( 0.1 ), 0, 1 ) ) );
  31015. if ( this.intensityNode !== null ) {
  31016. color = mix( base, color, this.intensityNode );
  31017. }
  31018. return vec4( color, this.inputNode.a );
  31019. } );
  31020. const outputNode = film();
  31021. return outputNode;
  31022. }
  31023. }
  31024. const film = nodeProxy( FilmNode );
  31025. addNodeElement( 'film', film );
  31026. class Lut3DNode extends TempNode {
  31027. constructor( inputNode, lutNode, size, intensityNode ) {
  31028. super();
  31029. this.inputNode = inputNode;
  31030. this.lutNode = lutNode;
  31031. this.size = uniform( size );
  31032. this.intensityNode = intensityNode;
  31033. }
  31034. setup() {
  31035. const { inputNode, lutNode } = this;
  31036. const sampleLut = ( uv ) => lutNode.uv( uv );
  31037. const lut3D = tslFn( () => {
  31038. const base = inputNode;
  31039. // pull the sample in by half a pixel so the sample begins at the center of the edge pixels.
  31040. const pixelWidth = float( 1.0 ).div( this.size );
  31041. const halfPixelWidth = float( 0.5 ).div( this.size );
  31042. const uvw = vec3( halfPixelWidth ).add( base.rgb.mul( float( 1.0 ).sub( pixelWidth ) ) );
  31043. const lutValue = vec4( sampleLut( uvw ).rgb, base.a );
  31044. return vec4( mix( base, lutValue, this.intensityNode ) );
  31045. } );
  31046. const outputNode = lut3D();
  31047. return outputNode;
  31048. }
  31049. }
  31050. const lut3D = ( node, lut, size, intensity ) => nodeObject( new Lut3DNode( nodeObject( node ), nodeObject( lut ), size, nodeObject( intensity ) ) );
  31051. addNodeElement( 'lut3D', lut3D );
  31052. class FunctionCallNode extends TempNode {
  31053. constructor( functionNode = null, parameters = {} ) {
  31054. super();
  31055. this.functionNode = functionNode;
  31056. this.parameters = parameters;
  31057. }
  31058. setParameters( parameters ) {
  31059. this.parameters = parameters;
  31060. return this;
  31061. }
  31062. getParameters() {
  31063. return this.parameters;
  31064. }
  31065. getNodeType( builder ) {
  31066. return this.functionNode.getNodeType( builder );
  31067. }
  31068. generate( builder ) {
  31069. const params = [];
  31070. const functionNode = this.functionNode;
  31071. const inputs = functionNode.getInputs( builder );
  31072. const parameters = this.parameters;
  31073. if ( Array.isArray( parameters ) ) {
  31074. for ( let i = 0; i < parameters.length; i ++ ) {
  31075. const inputNode = inputs[ i ];
  31076. const node = parameters[ i ];
  31077. params.push( node.build( builder, inputNode.type ) );
  31078. }
  31079. } else {
  31080. for ( const inputNode of inputs ) {
  31081. const node = parameters[ inputNode.name ];
  31082. if ( node !== undefined ) {
  31083. params.push( node.build( builder, inputNode.type ) );
  31084. } else {
  31085. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  31086. }
  31087. }
  31088. }
  31089. const functionName = functionNode.build( builder, 'property' );
  31090. return `${functionName}( ${params.join( ', ' )} )`;
  31091. }
  31092. }
  31093. const call = ( func, ...params ) => {
  31094. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  31095. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  31096. };
  31097. addNodeElement( 'call', call );
  31098. addNodeClass( 'FunctionCallNode', FunctionCallNode );
  31099. class ScriptableValueNode extends Node {
  31100. constructor( value = null ) {
  31101. super();
  31102. this._value = value;
  31103. this._cache = null;
  31104. this.inputType = null;
  31105. this.outpuType = null;
  31106. this.events = new EventDispatcher();
  31107. this.isScriptableValueNode = true;
  31108. }
  31109. get isScriptableOutputNode() {
  31110. return this.outputType !== null;
  31111. }
  31112. set value( val ) {
  31113. if ( this._value === val ) return;
  31114. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  31115. URL.revokeObjectURL( this._cache );
  31116. this._cache = null;
  31117. }
  31118. this._value = val;
  31119. this.events.dispatchEvent( { type: 'change' } );
  31120. this.refresh();
  31121. }
  31122. get value() {
  31123. return this._value;
  31124. }
  31125. refresh() {
  31126. this.events.dispatchEvent( { type: 'refresh' } );
  31127. }
  31128. getValue() {
  31129. const value = this.value;
  31130. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  31131. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  31132. } else if ( value && value.value !== null && value.value !== undefined && (
  31133. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  31134. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  31135. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  31136. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  31137. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  31138. ( this.inputType === 'Color' && value.value.isColor ) ||
  31139. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  31140. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  31141. ) ) {
  31142. return value.value;
  31143. }
  31144. return this._cache || value;
  31145. }
  31146. getNodeType( builder ) {
  31147. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  31148. }
  31149. setup() {
  31150. return this.value && this.value.isNode ? this.value : float();
  31151. }
  31152. serialize( data ) {
  31153. super.serialize( data );
  31154. if ( this.value !== null ) {
  31155. if ( this.inputType === 'ArrayBuffer' ) {
  31156. data.value = arrayBufferToBase64( this.value );
  31157. } else {
  31158. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  31159. }
  31160. } else {
  31161. data.value = null;
  31162. }
  31163. data.inputType = this.inputType;
  31164. data.outputType = this.outputType;
  31165. }
  31166. deserialize( data ) {
  31167. super.deserialize( data );
  31168. let value = null;
  31169. if ( data.value !== null ) {
  31170. if ( data.inputType === 'ArrayBuffer' ) {
  31171. value = base64ToArrayBuffer( data.value );
  31172. } else if ( data.inputType === 'Texture' ) {
  31173. value = data.meta.textures[ data.value ];
  31174. } else {
  31175. value = data.meta.nodes[ data.value ] || null;
  31176. }
  31177. }
  31178. this.value = value;
  31179. this.inputType = data.inputType;
  31180. this.outputType = data.outputType;
  31181. }
  31182. }
  31183. const scriptableValue = nodeProxy( ScriptableValueNode );
  31184. addNodeElement( 'scriptableValue', scriptableValue );
  31185. addNodeClass( 'ScriptableValueNode', ScriptableValueNode );
  31186. class Resources extends Map {
  31187. get( key, callback = null, ...params ) {
  31188. if ( this.has( key ) ) return super.get( key );
  31189. if ( callback !== null ) {
  31190. const value = callback( ...params );
  31191. this.set( key, value );
  31192. return value;
  31193. }
  31194. }
  31195. }
  31196. class Parameters {
  31197. constructor( scriptableNode ) {
  31198. this.scriptableNode = scriptableNode;
  31199. }
  31200. get parameters() {
  31201. return this.scriptableNode.parameters;
  31202. }
  31203. get layout() {
  31204. return this.scriptableNode.getLayout();
  31205. }
  31206. getInputLayout( id ) {
  31207. return this.scriptableNode.getInputLayout( id );
  31208. }
  31209. get( name ) {
  31210. const param = this.parameters[ name ];
  31211. const value = param ? param.getValue() : null;
  31212. return value;
  31213. }
  31214. }
  31215. const global = new Resources();
  31216. class ScriptableNode extends Node {
  31217. constructor( codeNode = null, parameters = {} ) {
  31218. super();
  31219. this.codeNode = codeNode;
  31220. this.parameters = parameters;
  31221. this._local = new Resources();
  31222. this._output = scriptableValue();
  31223. this._outputs = {};
  31224. this._source = this.source;
  31225. this._method = null;
  31226. this._object = null;
  31227. this._value = null;
  31228. this._needsOutputUpdate = true;
  31229. this.onRefresh = this.onRefresh.bind( this );
  31230. this.isScriptableNode = true;
  31231. }
  31232. get source() {
  31233. return this.codeNode ? this.codeNode.code : '';
  31234. }
  31235. setLocal( name, value ) {
  31236. return this._local.set( name, value );
  31237. }
  31238. getLocal( name ) {
  31239. return this._local.get( name );
  31240. }
  31241. onRefresh() {
  31242. this._refresh();
  31243. }
  31244. getInputLayout( id ) {
  31245. for ( const element of this.getLayout() ) {
  31246. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  31247. return element;
  31248. }
  31249. }
  31250. }
  31251. getOutputLayout( id ) {
  31252. for ( const element of this.getLayout() ) {
  31253. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  31254. return element;
  31255. }
  31256. }
  31257. }
  31258. setOutput( name, value ) {
  31259. const outputs = this._outputs;
  31260. if ( outputs[ name ] === undefined ) {
  31261. outputs[ name ] = scriptableValue( value );
  31262. } else {
  31263. outputs[ name ].value = value;
  31264. }
  31265. return this;
  31266. }
  31267. getOutput( name ) {
  31268. return this._outputs[ name ];
  31269. }
  31270. getParameter( name ) {
  31271. return this.parameters[ name ];
  31272. }
  31273. setParameter( name, value ) {
  31274. const parameters = this.parameters;
  31275. if ( value && value.isScriptableNode ) {
  31276. this.deleteParameter( name );
  31277. parameters[ name ] = value;
  31278. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  31279. } else if ( value && value.isScriptableValueNode ) {
  31280. this.deleteParameter( name );
  31281. parameters[ name ] = value;
  31282. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  31283. } else if ( parameters[ name ] === undefined ) {
  31284. parameters[ name ] = scriptableValue( value );
  31285. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  31286. } else {
  31287. parameters[ name ].value = value;
  31288. }
  31289. return this;
  31290. }
  31291. getValue() {
  31292. return this.getDefaultOutput().getValue();
  31293. }
  31294. deleteParameter( name ) {
  31295. let valueNode = this.parameters[ name ];
  31296. if ( valueNode ) {
  31297. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  31298. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  31299. }
  31300. return this;
  31301. }
  31302. clearParameters() {
  31303. for ( const name of Object.keys( this.parameters ) ) {
  31304. this.deleteParameter( name );
  31305. }
  31306. this.needsUpdate = true;
  31307. return this;
  31308. }
  31309. call( name, ...params ) {
  31310. const object = this.getObject();
  31311. const method = object[ name ];
  31312. if ( typeof method === 'function' ) {
  31313. return method( ...params );
  31314. }
  31315. }
  31316. async callAsync( name, ...params ) {
  31317. const object = this.getObject();
  31318. const method = object[ name ];
  31319. if ( typeof method === 'function' ) {
  31320. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  31321. }
  31322. }
  31323. getNodeType( builder ) {
  31324. return this.getDefaultOutputNode().getNodeType( builder );
  31325. }
  31326. refresh( output = null ) {
  31327. if ( output !== null ) {
  31328. this.getOutput( output ).refresh();
  31329. } else {
  31330. this._refresh();
  31331. }
  31332. }
  31333. getObject() {
  31334. if ( this.needsUpdate ) this.dispose();
  31335. if ( this._object !== null ) return this._object;
  31336. //
  31337. const refresh = () => this.refresh();
  31338. const setOutput = ( id, value ) => this.setOutput( id, value );
  31339. const parameters = new Parameters( this );
  31340. const THREE = global.get( 'THREE' );
  31341. const TSL = global.get( 'TSL' );
  31342. const method = this.getMethod( this.codeNode );
  31343. const params = [ parameters, this._local, global, refresh, setOutput, THREE, TSL ];
  31344. this._object = method( ...params );
  31345. const layout = this._object.layout;
  31346. if ( layout ) {
  31347. if ( layout.cache === false ) {
  31348. this._local.clear();
  31349. }
  31350. // default output
  31351. this._output.outputType = layout.outputType || null;
  31352. if ( Array.isArray( layout.elements ) ) {
  31353. for ( const element of layout.elements ) {
  31354. const id = element.id || element.name;
  31355. if ( element.inputType ) {
  31356. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  31357. this.getParameter( id ).inputType = element.inputType;
  31358. }
  31359. if ( element.outputType ) {
  31360. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  31361. this.getOutput( id ).outputType = element.outputType;
  31362. }
  31363. }
  31364. }
  31365. }
  31366. return this._object;
  31367. }
  31368. deserialize( data ) {
  31369. super.deserialize( data );
  31370. for ( const name in this.parameters ) {
  31371. let valueNode = this.parameters[ name ];
  31372. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  31373. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  31374. }
  31375. }
  31376. getLayout() {
  31377. return this.getObject().layout;
  31378. }
  31379. getDefaultOutputNode() {
  31380. const output = this.getDefaultOutput().value;
  31381. if ( output && output.isNode ) {
  31382. return output;
  31383. }
  31384. return float();
  31385. }
  31386. getDefaultOutput() {
  31387. return this._exec()._output;
  31388. }
  31389. getMethod() {
  31390. if ( this.needsUpdate ) this.dispose();
  31391. if ( this._method !== null ) return this._method;
  31392. //
  31393. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  31394. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  31395. const properties = interfaceProps.join( ', ' );
  31396. const declarations = 'var ' + properties + '; var output = {};\n';
  31397. const returns = '\nreturn { ...output, ' + properties + ' };';
  31398. const code = declarations + this.codeNode.code + returns;
  31399. //
  31400. this._method = new Function( ...parametersProps, code );
  31401. return this._method;
  31402. }
  31403. dispose() {
  31404. if ( this._method === null ) return;
  31405. if ( this._object && typeof this._object.dispose === 'function' ) {
  31406. this._object.dispose();
  31407. }
  31408. this._method = null;
  31409. this._object = null;
  31410. this._source = null;
  31411. this._value = null;
  31412. this._needsOutputUpdate = true;
  31413. this._output.value = null;
  31414. this._outputs = {};
  31415. }
  31416. setup() {
  31417. return this.getDefaultOutputNode();
  31418. }
  31419. set needsUpdate( value ) {
  31420. if ( value === true ) this.dispose();
  31421. }
  31422. get needsUpdate() {
  31423. return this.source !== this._source;
  31424. }
  31425. _exec() {
  31426. if ( this.codeNode === null ) return this;
  31427. if ( this._needsOutputUpdate === true ) {
  31428. this._value = this.call( 'main' );
  31429. this._needsOutputUpdate = false;
  31430. }
  31431. this._output.value = this._value;
  31432. return this;
  31433. }
  31434. _refresh() {
  31435. this.needsUpdate = true;
  31436. this._exec();
  31437. this._output.refresh();
  31438. }
  31439. }
  31440. const scriptable = nodeProxy( ScriptableNode );
  31441. addNodeElement( 'scriptable', scriptable );
  31442. addNodeClass( 'ScriptableNode', ScriptableNode );
  31443. class FogNode extends Node {
  31444. constructor( colorNode, factorNode ) {
  31445. super( 'float' );
  31446. this.isFogNode = true;
  31447. this.colorNode = colorNode;
  31448. this.factorNode = factorNode;
  31449. }
  31450. getViewZNode( builder ) {
  31451. let viewZ;
  31452. const getViewZ = builder.context.getViewZ;
  31453. if ( getViewZ !== undefined ) {
  31454. viewZ = getViewZ( this );
  31455. }
  31456. return ( viewZ || positionView.z ).negate();
  31457. }
  31458. setup() {
  31459. return this.factorNode;
  31460. }
  31461. }
  31462. const fog = nodeProxy( FogNode );
  31463. addNodeElement( 'fog', fog );
  31464. addNodeClass( 'FogNode', FogNode );
  31465. class FogRangeNode extends FogNode {
  31466. constructor( colorNode, nearNode, farNode ) {
  31467. super( colorNode );
  31468. this.isFogRangeNode = true;
  31469. this.nearNode = nearNode;
  31470. this.farNode = farNode;
  31471. }
  31472. setup( builder ) {
  31473. const viewZ = this.getViewZNode( builder );
  31474. return smoothstep( this.nearNode, this.farNode, viewZ );
  31475. }
  31476. }
  31477. const rangeFog = nodeProxy( FogRangeNode );
  31478. addNodeElement( 'rangeFog', rangeFog );
  31479. addNodeClass( 'FogRangeNode', FogRangeNode );
  31480. class FogExp2Node extends FogNode {
  31481. constructor( colorNode, densityNode ) {
  31482. super( colorNode );
  31483. this.isFogExp2Node = true;
  31484. this.densityNode = densityNode;
  31485. }
  31486. setup( builder ) {
  31487. const viewZ = this.getViewZNode( builder );
  31488. const density = this.densityNode;
  31489. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  31490. }
  31491. }
  31492. const densityFog = nodeProxy( FogExp2Node );
  31493. addNodeElement( 'densityFog', densityFog );
  31494. addNodeClass( 'FogExp2Node', FogExp2Node );
  31495. let min = null;
  31496. let max = null;
  31497. class RangeNode extends Node {
  31498. constructor( minNode = float(), maxNode = float() ) {
  31499. super();
  31500. this.minNode = minNode;
  31501. this.maxNode = maxNode;
  31502. }
  31503. getVectorLength( builder ) {
  31504. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  31505. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  31506. return minLength > maxLength ? minLength : maxLength;
  31507. }
  31508. getNodeType( builder ) {
  31509. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  31510. }
  31511. setup( builder ) {
  31512. const object = builder.object;
  31513. let output = null;
  31514. if ( object.count > 1 ) {
  31515. const minValue = this.minNode.value;
  31516. const maxValue = this.maxNode.value;
  31517. const minLength = builder.getTypeLength( getValueType( minValue ) );
  31518. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  31519. min = min || new Vector4();
  31520. max = max || new Vector4();
  31521. min.setScalar( 0 );
  31522. max.setScalar( 0 );
  31523. if ( minLength === 1 ) min.setScalar( minValue );
  31524. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  31525. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  31526. if ( maxLength === 1 ) max.setScalar( maxValue );
  31527. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  31528. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  31529. const stride = 4;
  31530. const length = stride * object.count;
  31531. const array = new Float32Array( length );
  31532. for ( let i = 0; i < length; i ++ ) {
  31533. const index = i % stride;
  31534. const minElementValue = min.getComponent( index );
  31535. const maxElementValue = max.getComponent( index );
  31536. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  31537. }
  31538. const nodeType = this.getNodeType( builder );
  31539. if ( object.count <= 4096 ) {
  31540. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  31541. } else {
  31542. // TODO: Improve anonymous buffer attribute creation removing this part
  31543. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  31544. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  31545. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  31546. }
  31547. } else {
  31548. output = float( 0 );
  31549. }
  31550. return output;
  31551. }
  31552. }
  31553. const range = nodeProxy( RangeNode );
  31554. addNodeClass( 'RangeNode', RangeNode );
  31555. class ComputeNode extends Node {
  31556. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  31557. super( 'void' );
  31558. this.isComputeNode = true;
  31559. this.computeNode = computeNode;
  31560. this.count = count;
  31561. this.workgroupSize = workgroupSize;
  31562. this.dispatchCount = 0;
  31563. this.version = 1;
  31564. this.updateBeforeType = NodeUpdateType.OBJECT;
  31565. this.updateDispatchCount();
  31566. }
  31567. dispose() {
  31568. this.dispatchEvent( { type: 'dispose' } );
  31569. }
  31570. set needsUpdate( value ) {
  31571. if ( value === true ) this.version ++;
  31572. }
  31573. updateDispatchCount() {
  31574. const { count, workgroupSize } = this;
  31575. let size = workgroupSize[ 0 ];
  31576. for ( let i = 1; i < workgroupSize.length; i ++ )
  31577. size *= workgroupSize[ i ];
  31578. this.dispatchCount = Math.ceil( count / size );
  31579. }
  31580. onInit() { }
  31581. updateBefore( { renderer } ) {
  31582. renderer.compute( this );
  31583. }
  31584. generate( builder ) {
  31585. const { shaderStage } = builder;
  31586. if ( shaderStage === 'compute' ) {
  31587. const snippet = this.computeNode.build( builder, 'void' );
  31588. if ( snippet !== '' ) {
  31589. builder.addLineFlowCode( snippet );
  31590. }
  31591. }
  31592. }
  31593. }
  31594. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  31595. addNodeElement( 'compute', compute );
  31596. addNodeClass( 'ComputeNode', ComputeNode );
  31597. class LightNode extends Node {
  31598. constructor( scope = LightNode.TARGET_DIRECTION, light = null ) {
  31599. super();
  31600. this.scope = scope;
  31601. this.light = light;
  31602. }
  31603. setup() {
  31604. const { scope, light } = this;
  31605. let output = null;
  31606. if ( scope === LightNode.TARGET_DIRECTION ) {
  31607. output = cameraViewMatrix.transformDirection( objectPosition( light ).sub( objectPosition( light.target ) ) );
  31608. }
  31609. return output;
  31610. }
  31611. serialize( data ) {
  31612. super.serialize( data );
  31613. data.scope = this.scope;
  31614. }
  31615. deserialize( data ) {
  31616. super.deserialize( data );
  31617. this.scope = data.scope;
  31618. }
  31619. }
  31620. LightNode.TARGET_DIRECTION = 'targetDirection';
  31621. const lightTargetDirection = nodeProxy( LightNode, LightNode.TARGET_DIRECTION );
  31622. addNodeClass( 'LightNode', LightNode );
  31623. const getDistanceAttenuation = tslFn( ( inputs ) => {
  31624. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  31625. // based upon Frostbite 3 Moving to Physically-based Rendering
  31626. // page 32, equation 26: E[window1]
  31627. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  31628. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  31629. return cutoffDistance.greaterThan( 0 ).cond(
  31630. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  31631. distanceFalloff
  31632. );
  31633. } ); // validated
  31634. class PointLightNode extends AnalyticLightNode {
  31635. constructor( light = null ) {
  31636. super( light );
  31637. this.cutoffDistanceNode = uniform( 0 );
  31638. this.decayExponentNode = uniform( 0 );
  31639. }
  31640. update( frame ) {
  31641. const { light } = this;
  31642. super.update( frame );
  31643. this.cutoffDistanceNode.value = light.distance;
  31644. this.decayExponentNode.value = light.decay;
  31645. }
  31646. setup( builder ) {
  31647. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  31648. const lightingModel = builder.context.lightingModel;
  31649. const lVector = objectViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  31650. const lightDirection = lVector.normalize();
  31651. const lightDistance = lVector.length();
  31652. const lightAttenuation = getDistanceAttenuation( {
  31653. lightDistance,
  31654. cutoffDistance: cutoffDistanceNode,
  31655. decayExponent: decayExponentNode
  31656. } );
  31657. const lightColor = colorNode.mul( lightAttenuation );
  31658. const reflectedLight = builder.context.reflectedLight;
  31659. lightingModel.direct( {
  31660. lightDirection,
  31661. lightColor,
  31662. reflectedLight,
  31663. shadowMask: this.shadowMaskNode
  31664. }, builder.stack, builder );
  31665. }
  31666. }
  31667. addNodeClass( 'PointLightNode', PointLightNode );
  31668. addLightNode( PointLight, PointLightNode );
  31669. class DirectionalLightNode extends AnalyticLightNode {
  31670. constructor( light = null ) {
  31671. super( light );
  31672. }
  31673. setup( builder ) {
  31674. super.setup( builder );
  31675. const lightingModel = builder.context.lightingModel;
  31676. const lightColor = this.colorNode;
  31677. const lightDirection = lightTargetDirection( this.light );
  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( 'DirectionalLightNode', DirectionalLightNode );
  31688. addLightNode( DirectionalLight, DirectionalLightNode );
  31689. const _matrix41 = new Matrix4();
  31690. const _matrix42 = new Matrix4();
  31691. let ltcLib = null;
  31692. class RectAreaLightNode extends AnalyticLightNode {
  31693. constructor( light = null ) {
  31694. super( light );
  31695. this.halfHeight = uniform( new Vector3() );
  31696. this.halfWidth = uniform( new Vector3() );
  31697. }
  31698. update( frame ) {
  31699. super.update( frame );
  31700. const { light } = this;
  31701. const viewMatrix = frame.camera.matrixWorldInverse;
  31702. _matrix42.identity();
  31703. _matrix41.copy( light.matrixWorld );
  31704. _matrix41.premultiply( viewMatrix );
  31705. _matrix42.extractRotation( _matrix41 );
  31706. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  31707. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  31708. this.halfWidth.value.applyMatrix4( _matrix42 );
  31709. this.halfHeight.value.applyMatrix4( _matrix42 );
  31710. }
  31711. setup( builder ) {
  31712. super.setup( builder );
  31713. let ltc_1, ltc_2;
  31714. if ( builder.isAvailable( 'float32Filterable' ) ) {
  31715. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  31716. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  31717. } else {
  31718. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  31719. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  31720. }
  31721. const { colorNode, light } = this;
  31722. const lightingModel = builder.context.lightingModel;
  31723. const lightPosition = objectViewPosition( light );
  31724. const reflectedLight = builder.context.reflectedLight;
  31725. lightingModel.directRectArea( {
  31726. lightColor: colorNode,
  31727. lightPosition,
  31728. halfWidth: this.halfWidth,
  31729. halfHeight: this.halfHeight,
  31730. reflectedLight,
  31731. ltc_1,
  31732. ltc_2
  31733. }, builder.stack, builder );
  31734. }
  31735. static setLTC( ltc ) {
  31736. ltcLib = ltc;
  31737. }
  31738. }
  31739. addNodeClass( 'RectAreaLightNode', RectAreaLightNode );
  31740. addLightNode( RectAreaLight, RectAreaLightNode );
  31741. class SpotLightNode extends AnalyticLightNode {
  31742. constructor( light = null ) {
  31743. super( light );
  31744. this.coneCosNode = uniform( 0 );
  31745. this.penumbraCosNode = uniform( 0 );
  31746. this.cutoffDistanceNode = uniform( 0 );
  31747. this.decayExponentNode = uniform( 0 );
  31748. }
  31749. update( frame ) {
  31750. super.update( frame );
  31751. const { light } = this;
  31752. this.coneCosNode.value = Math.cos( light.angle );
  31753. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  31754. this.cutoffDistanceNode.value = light.distance;
  31755. this.decayExponentNode.value = light.decay;
  31756. }
  31757. getSpotAttenuation( angleCosine ) {
  31758. const { coneCosNode, penumbraCosNode } = this;
  31759. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  31760. }
  31761. setup( builder ) {
  31762. super.setup( builder );
  31763. const lightingModel = builder.context.lightingModel;
  31764. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  31765. const lVector = objectViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  31766. const lightDirection = lVector.normalize();
  31767. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  31768. const spotAttenuation = this.getSpotAttenuation( angleCos );
  31769. const lightDistance = lVector.length();
  31770. const lightAttenuation = getDistanceAttenuation( {
  31771. lightDistance,
  31772. cutoffDistance: cutoffDistanceNode,
  31773. decayExponent: decayExponentNode
  31774. } );
  31775. const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  31776. const reflectedLight = builder.context.reflectedLight;
  31777. lightingModel.direct( {
  31778. lightDirection,
  31779. lightColor,
  31780. reflectedLight,
  31781. shadowMask: this.shadowMaskNode
  31782. }, builder.stack, builder );
  31783. }
  31784. }
  31785. addNodeClass( 'SpotLightNode', SpotLightNode );
  31786. addLightNode( SpotLight, SpotLightNode );
  31787. class IESSpotLight extends SpotLight {
  31788. constructor( color, intensity, distance, angle, penumbra, decay ) {
  31789. super( color, intensity, distance, angle, penumbra, decay );
  31790. this.iesMap = null;
  31791. }
  31792. copy( source, recursive ) {
  31793. super.copy( source, recursive );
  31794. this.iesMap = source.iesMap;
  31795. return this;
  31796. }
  31797. }
  31798. class IESSpotLightNode extends SpotLightNode {
  31799. getSpotAttenuation( angleCosine ) {
  31800. const iesMap = this.light.iesMap;
  31801. let spotAttenuation = null;
  31802. if ( iesMap && iesMap.isTexture === true ) {
  31803. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  31804. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  31805. } else {
  31806. spotAttenuation = super.getSpotAttenuation( angleCosine );
  31807. }
  31808. return spotAttenuation;
  31809. }
  31810. }
  31811. addNodeClass( 'IESSpotLightNode', IESSpotLightNode );
  31812. addLightNode( IESSpotLight, IESSpotLightNode );
  31813. class AmbientLightNode extends AnalyticLightNode {
  31814. constructor( light = null ) {
  31815. super( light );
  31816. }
  31817. setup( { context } ) {
  31818. context.irradiance.addAssign( this.colorNode );
  31819. }
  31820. }
  31821. addNodeClass( 'AmbientLightNode', AmbientLightNode );
  31822. addLightNode( AmbientLight, AmbientLightNode );
  31823. class HemisphereLightNode extends AnalyticLightNode {
  31824. constructor( light = null ) {
  31825. super( light );
  31826. this.lightPositionNode = objectPosition( light );
  31827. this.lightDirectionNode = this.lightPositionNode.normalize();
  31828. this.groundColorNode = uniform( new Color() );
  31829. }
  31830. update( frame ) {
  31831. const { light } = this;
  31832. super.update( frame );
  31833. this.lightPositionNode.object3d = light;
  31834. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  31835. }
  31836. setup( builder ) {
  31837. const { colorNode, groundColorNode, lightDirectionNode } = this;
  31838. const dotNL = normalView.dot( lightDirectionNode );
  31839. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  31840. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  31841. builder.context.irradiance.addAssign( irradiance );
  31842. }
  31843. }
  31844. addNodeClass( 'HemisphereLightNode', HemisphereLightNode );
  31845. addLightNode( HemisphereLight, HemisphereLightNode );
  31846. const checkerShaderNode = tslFn( ( inputs ) => {
  31847. const uv = inputs.uv.mul( 2.0 );
  31848. const cx = uv.x.floor();
  31849. const cy = uv.y.floor();
  31850. const result = cx.add( cy ).mod( 2.0 );
  31851. return result.sign();
  31852. } );
  31853. class CheckerNode extends TempNode {
  31854. constructor( uvNode = uv() ) {
  31855. super( 'float' );
  31856. this.uvNode = uvNode;
  31857. }
  31858. setup() {
  31859. return checkerShaderNode( { uv: this.uvNode } );
  31860. }
  31861. }
  31862. const checker = nodeProxy( CheckerNode );
  31863. addNodeElement( 'checker', checker );
  31864. addNodeClass( 'CheckerNode', CheckerNode );
  31865. class NodeLoader extends Loader {
  31866. constructor( manager ) {
  31867. super( manager );
  31868. this.textures = {};
  31869. }
  31870. load( url, onLoad, onProgress, onError ) {
  31871. const loader = new FileLoader( this.manager );
  31872. loader.setPath( this.path );
  31873. loader.setRequestHeader( this.requestHeader );
  31874. loader.setWithCredentials( this.withCredentials );
  31875. loader.load( url, ( text ) => {
  31876. try {
  31877. onLoad( this.parse( JSON.parse( text ) ) );
  31878. } catch ( e ) {
  31879. if ( onError ) {
  31880. onError( e );
  31881. } else {
  31882. console.error( e );
  31883. }
  31884. this.manager.itemError( url );
  31885. }
  31886. }, onProgress, onError );
  31887. }
  31888. parseNodes( json ) {
  31889. const nodes = {};
  31890. if ( json !== undefined ) {
  31891. for ( const nodeJSON of json ) {
  31892. const { uuid, type } = nodeJSON;
  31893. nodes[ uuid ] = nodeObject( createNodeFromType( type ) ); // @TODO: Maybe nodeObjectify the node in createNodeFromType?
  31894. nodes[ uuid ].uuid = uuid;
  31895. }
  31896. const meta = { nodes, textures: this.textures };
  31897. for ( const nodeJSON of json ) {
  31898. nodeJSON.meta = meta;
  31899. const node = nodes[ nodeJSON.uuid ];
  31900. node.deserialize( nodeJSON );
  31901. delete nodeJSON.meta;
  31902. }
  31903. }
  31904. return nodes;
  31905. }
  31906. parse( json ) {
  31907. const node = nodeObject( createNodeFromType( json.type ) );
  31908. node.uuid = json.uuid;
  31909. const nodes = this.parseNodes( json.nodes );
  31910. const meta = { nodes, textures: this.textures };
  31911. json.meta = meta;
  31912. node.deserialize( json );
  31913. delete json.meta;
  31914. return node;
  31915. }
  31916. setTextures( value ) {
  31917. this.textures = value;
  31918. return this;
  31919. }
  31920. }
  31921. const defaultValues$e = new PointsMaterial();
  31922. class InstancedPointsNodeMaterial extends NodeMaterial {
  31923. constructor( params = {} ) {
  31924. super();
  31925. this.normals = false;
  31926. this.lights = false;
  31927. this.useAlphaToCoverage = true;
  31928. this.useColor = params.vertexColors;
  31929. this.pointWidth = 1;
  31930. this.pointColorNode = null;
  31931. this.setDefaultValues( defaultValues$e );
  31932. this.setupShaders();
  31933. this.setValues( params );
  31934. }
  31935. setupShaders() {
  31936. const useAlphaToCoverage = this.alphaToCoverage;
  31937. const useColor = this.useColor;
  31938. this.vertexNode = tslFn( () => {
  31939. //vUv = uv;
  31940. varying( vec2(), 'vUv' ).assign( uv() ); // @TODO: Analyze other way to do this
  31941. const instancePosition = attribute( 'instancePosition' );
  31942. // camera space
  31943. const mvPos = property( 'vec4', 'mvPos' );
  31944. mvPos.assign( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  31945. const aspect = viewport.z.div( viewport.w );
  31946. // clip space
  31947. const clipPos = cameraProjectionMatrix.mul( mvPos );
  31948. // offset in ndc space
  31949. const offset = property( 'vec2', 'offset' );
  31950. offset.assign( positionGeometry.xy );
  31951. offset.assign( offset.mul( materialPointWidth ) );
  31952. offset.assign( offset.div( viewport.z ) );
  31953. offset.y.assign( offset.y.mul( aspect ) );
  31954. // back to clip space
  31955. offset.assign( offset.mul( clipPos.w ) );
  31956. //clipPos.xy += offset;
  31957. clipPos.assign( clipPos.add( vec4( offset, 0, 0 ) ) );
  31958. return clipPos;
  31959. //vec4 mvPosition = mvPos; // this was used for somethihng...
  31960. } )();
  31961. this.fragmentNode = tslFn( () => {
  31962. const vUv = varying( vec2(), 'vUv' );
  31963. // force assignment into correct place in flow
  31964. const alpha = property( 'float', 'alpha' );
  31965. alpha.assign( 1 );
  31966. const a = vUv.x;
  31967. const b = vUv.y;
  31968. const len2 = a.mul( a ).add( b.mul( b ) );
  31969. if ( useAlphaToCoverage ) {
  31970. // force assignment out of following 'if' statement - to avoid uniform control flow errors
  31971. const dlen = property( 'float', 'dlen' );
  31972. dlen.assign( len2.fwidth() );
  31973. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  31974. } else {
  31975. len2.greaterThan( 1.0 ).discard();
  31976. }
  31977. let pointColorNode;
  31978. if ( this.pointColorNode ) {
  31979. pointColorNode = this.pointColorNode;
  31980. } else {
  31981. if ( useColor ) {
  31982. const instanceColor = attribute( 'instanceColor' );
  31983. pointColorNode = instanceColor.mul( materialColor );
  31984. } else {
  31985. pointColorNode = materialColor;
  31986. }
  31987. }
  31988. return vec4( pointColorNode, alpha );
  31989. } )();
  31990. this.needsUpdate = true;
  31991. }
  31992. get alphaToCoverage() {
  31993. return this.useAlphaToCoverage;
  31994. }
  31995. set alphaToCoverage( value ) {
  31996. if ( this.useAlphaToCoverage !== value ) {
  31997. this.useAlphaToCoverage = value;
  31998. this.setupShaders();
  31999. }
  32000. }
  32001. }
  32002. addNodeMaterial( 'InstancedPointsNodeMaterial', InstancedPointsNodeMaterial );
  32003. const defaultValues$d = new LineBasicMaterial();
  32004. class LineBasicNodeMaterial extends NodeMaterial {
  32005. constructor( parameters ) {
  32006. super();
  32007. this.isLineBasicNodeMaterial = true;
  32008. this.lights = false;
  32009. this.normals = false;
  32010. this.setDefaultValues( defaultValues$d );
  32011. this.setValues( parameters );
  32012. }
  32013. }
  32014. addNodeMaterial( 'LineBasicNodeMaterial', LineBasicNodeMaterial );
  32015. const defaultValues$c = new LineDashedMaterial();
  32016. class LineDashedNodeMaterial extends NodeMaterial {
  32017. constructor( parameters ) {
  32018. super();
  32019. this.isLineDashedNodeMaterial = true;
  32020. this.lights = false;
  32021. this.normals = false;
  32022. this.setDefaultValues( defaultValues$c );
  32023. this.offsetNode = null;
  32024. this.dashScaleNode = null;
  32025. this.dashSizeNode = null;
  32026. this.gapSizeNode = null;
  32027. this.setValues( parameters );
  32028. }
  32029. setupVariants() {
  32030. const offsetNode = this.offsetNode;
  32031. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  32032. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  32033. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  32034. dashSize.assign( dashSizeNode );
  32035. gapSize.assign( gapSizeNode );
  32036. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  32037. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  32038. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  32039. }
  32040. }
  32041. addNodeMaterial( 'LineDashedNodeMaterial', LineDashedNodeMaterial );
  32042. const defaultValues$b = new LineDashedMaterial();
  32043. class Line2NodeMaterial extends NodeMaterial {
  32044. constructor( params = {} ) {
  32045. super();
  32046. this.normals = false;
  32047. this.lights = false;
  32048. this.setDefaultValues( defaultValues$b );
  32049. this.useAlphaToCoverage = true;
  32050. this.useColor = params.vertexColors;
  32051. this.useDash = params.dashed;
  32052. this.useWorldUnits = false;
  32053. this.dashOffset = 0;
  32054. this.lineWidth = 1;
  32055. this.lineColorNode = null;
  32056. this.offsetNode = null;
  32057. this.dashScaleNode = null;
  32058. this.dashSizeNode = null;
  32059. this.gapSizeNode = null;
  32060. this.setValues( params );
  32061. }
  32062. setup( builder ) {
  32063. this.setupShaders();
  32064. super.setup( builder );
  32065. }
  32066. setupShaders() {
  32067. const useAlphaToCoverage = this.alphaToCoverage;
  32068. const useColor = this.useColor;
  32069. const useDash = this.dashed;
  32070. const useWorldUnits = this.worldUnits;
  32071. const trimSegment = tslFn( ( { start, end } ) => {
  32072. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  32073. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  32074. const nearEstimate = b.mul( - 0.5 ).div( a );
  32075. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  32076. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  32077. } );
  32078. this.vertexNode = tslFn( () => {
  32079. varyingProperty( 'vec2', 'vUv' ).assign( uv() );
  32080. const instanceStart = attribute( 'instanceStart' );
  32081. const instanceEnd = attribute( 'instanceEnd' );
  32082. // camera space
  32083. const start = property( 'vec4', 'start' );
  32084. const end = property( 'vec4', 'end' );
  32085. start.assign( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ); // force assignment into correct place in flow
  32086. end.assign( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) );
  32087. if ( useWorldUnits ) {
  32088. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  32089. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  32090. }
  32091. const aspect = viewport.z.div( viewport.w );
  32092. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  32093. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  32094. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  32095. // perhaps there is a more elegant solution -- WestLangley
  32096. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  32097. If( perspective, () => {
  32098. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  32099. end.assign( trimSegment( { start: start, end: end } ) );
  32100. } ).elseif( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  32101. start.assign( trimSegment( { start: end, end: start } ) );
  32102. } );
  32103. } );
  32104. // clip space
  32105. const clipStart = cameraProjectionMatrix.mul( start );
  32106. const clipEnd = cameraProjectionMatrix.mul( end );
  32107. // ndc space
  32108. const ndcStart = clipStart.xyz.div( clipStart.w );
  32109. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  32110. // direction
  32111. const dir = ndcEnd.xy.sub( ndcStart.xy ).temp();
  32112. // account for clip-space aspect ratio
  32113. dir.x.assign( dir.x.mul( aspect ) );
  32114. dir.assign( dir.normalize() );
  32115. const clip = temp( vec4() );
  32116. if ( useWorldUnits ) {
  32117. // get the offset direction as perpendicular to the view vector
  32118. const worldDir = end.xyz.sub( start.xyz ).normalize();
  32119. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  32120. const worldUp = worldDir.cross( tmpFwd ).normalize();
  32121. const worldFwd = worldDir.cross( worldUp );
  32122. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  32123. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).cond( start, end ) );
  32124. // height offset
  32125. const hw = materialLineWidth.mul( 0.5 );
  32126. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).cond( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  32127. // don't extend the line if we're rendering dashes because we
  32128. // won't be rendering the endcaps
  32129. if ( ! useDash ) {
  32130. // cap extension
  32131. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).cond( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  32132. // add width to the box
  32133. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  32134. // endcaps
  32135. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  32136. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  32137. } );
  32138. }
  32139. // project the worldpos
  32140. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  32141. // shift the depth of the projected points so the line
  32142. // segments overlap neatly
  32143. const clipPose = temp( vec3() );
  32144. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).cond( ndcStart, ndcEnd ) );
  32145. clip.z.assign( clipPose.z.mul( clip.w ) );
  32146. } else {
  32147. const offset = property( 'vec2', 'offset' );
  32148. offset.assign( vec2( dir.y, dir.x.negate() ) );
  32149. // undo aspect ratio adjustment
  32150. dir.x.assign( dir.x.div( aspect ) );
  32151. offset.x.assign( offset.x.div( aspect ) );
  32152. // sign flip
  32153. offset.assign( positionGeometry.x.lessThan( 0.0 ).cond( offset.negate(), offset ) );
  32154. // endcaps
  32155. If( positionGeometry.y.lessThan( 0.0 ), () => {
  32156. offset.assign( offset.sub( dir ) );
  32157. } ).elseif( positionGeometry.y.greaterThan( 1.0 ), () => {
  32158. offset.assign( offset.add( dir ) );
  32159. } );
  32160. // adjust for linewidth
  32161. offset.assign( offset.mul( materialLineWidth ) );
  32162. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  32163. offset.assign( offset.div( viewport.w ) );
  32164. // select end
  32165. clip.assign( positionGeometry.y.lessThan( 0.5 ).cond( clipStart, clipEnd ) );
  32166. // back to clip space
  32167. offset.assign( offset.mul( clip.w ) );
  32168. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  32169. }
  32170. return clip;
  32171. } )();
  32172. const closestLineToLine = tslFn( ( { p1, p2, p3, p4 } ) => {
  32173. const p13 = p1.sub( p3 );
  32174. const p43 = p4.sub( p3 );
  32175. const p21 = p2.sub( p1 );
  32176. const d1343 = p13.dot( p43 );
  32177. const d4321 = p43.dot( p21 );
  32178. const d1321 = p13.dot( p21 );
  32179. const d4343 = p43.dot( p43 );
  32180. const d2121 = p21.dot( p21 );
  32181. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  32182. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  32183. const mua = numer.div( denom ).clamp();
  32184. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  32185. return vec2( mua, mub );
  32186. } );
  32187. this.fragmentNode = tslFn( () => {
  32188. const vUv = varyingProperty( 'vec2', 'vUv' );
  32189. if ( useDash ) {
  32190. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  32191. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  32192. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  32193. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  32194. dashSize.assign( dashSizeNode );
  32195. gapSize.assign( gapSizeNode );
  32196. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  32197. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  32198. const lineDistance = positionGeometry.y.lessThan( 0.5 ).cond( dashScaleNode.mul( instanceDistanceStart ), materialLineScale.mul( instanceDistanceEnd ) );
  32199. const vLineDistance = varying( lineDistance.add( materialLineDashOffset ) );
  32200. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  32201. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  32202. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  32203. }
  32204. // force assignment into correct place in flow
  32205. const alpha = property( 'float', 'alpha' );
  32206. alpha.assign( 1 );
  32207. if ( useWorldUnits ) {
  32208. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  32209. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  32210. // Find the closest points on the view ray and the line segment
  32211. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  32212. const lineDir = worldEnd.sub( worldStart );
  32213. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  32214. const p1 = worldStart.add( lineDir.mul( params.x ) );
  32215. const p2 = rayEnd.mul( params.y );
  32216. const delta = p1.sub( p2 );
  32217. const len = delta.length();
  32218. const norm = len.div( materialLineWidth );
  32219. if ( ! useDash ) {
  32220. if ( useAlphaToCoverage ) {
  32221. const dnorm = norm.fwidth();
  32222. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  32223. } else {
  32224. norm.greaterThan( 0.5 ).discard();
  32225. }
  32226. }
  32227. } else {
  32228. // round endcaps
  32229. if ( useAlphaToCoverage ) {
  32230. const a = vUv.x;
  32231. const b = vUv.y.greaterThan( 0.0 ).cond( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  32232. const len2 = a.mul( a ).add( b.mul( b ) );
  32233. // force assignment out of following 'if' statement - to avoid uniform control flow errors
  32234. const dlen = property( 'float', 'dlen' );
  32235. dlen.assign( len2.fwidth() );
  32236. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  32237. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  32238. } );
  32239. } else {
  32240. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  32241. const a = vUv.x;
  32242. const b = vUv.y.greaterThan( 0.0 ).cond( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  32243. const len2 = a.mul( a ).add( b.mul( b ) );
  32244. len2.greaterThan( 1.0 ).discard();
  32245. } );
  32246. }
  32247. }
  32248. let lineColorNode;
  32249. if ( this.lineColorNode ) {
  32250. lineColorNode = this.lineColorNode;
  32251. } else {
  32252. if ( useColor ) {
  32253. const instanceColorStart = attribute( 'instanceColorStart' );
  32254. const instanceColorEnd = attribute( 'instanceColorEnd' );
  32255. const instanceColor = positionGeometry.y.lessThan( 0.5 ).cond( instanceColorStart, instanceColorEnd );
  32256. lineColorNode = instanceColor.mul( materialColor );
  32257. } else {
  32258. lineColorNode = materialColor;
  32259. }
  32260. }
  32261. return vec4( lineColorNode, alpha );
  32262. } )();
  32263. }
  32264. get worldUnits() {
  32265. return this.useWorldUnits;
  32266. }
  32267. set worldUnits( value ) {
  32268. if ( this.useWorldUnits !== value ) {
  32269. this.useWorldUnits = value;
  32270. this.needsUpdate = true;
  32271. }
  32272. }
  32273. get dashed() {
  32274. return this.useDash;
  32275. }
  32276. set dashed( value ) {
  32277. if ( this.useDash !== value ) {
  32278. this.useDash = value;
  32279. this.needsUpdate = true;
  32280. }
  32281. }
  32282. get alphaToCoverage() {
  32283. return this.useAlphaToCoverage;
  32284. }
  32285. set alphaToCoverage( value ) {
  32286. if ( this.useAlphaToCoverage !== value ) {
  32287. this.useAlphaToCoverage = value;
  32288. this.needsUpdate = true;
  32289. }
  32290. }
  32291. }
  32292. addNodeMaterial( 'Line2NodeMaterial', Line2NodeMaterial );
  32293. const defaultValues$a = new MeshNormalMaterial();
  32294. class MeshNormalNodeMaterial extends NodeMaterial {
  32295. constructor( parameters ) {
  32296. super();
  32297. this.lights = false;
  32298. this.isMeshNormalNodeMaterial = true;
  32299. this.setDefaultValues( defaultValues$a );
  32300. this.setValues( parameters );
  32301. }
  32302. setupDiffuseColor() {
  32303. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  32304. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  32305. }
  32306. }
  32307. addNodeMaterial( 'MeshNormalNodeMaterial', MeshNormalNodeMaterial );
  32308. const defaultValues$9 = new MeshBasicMaterial();
  32309. class MeshBasicNodeMaterial extends NodeMaterial {
  32310. constructor( parameters ) {
  32311. super();
  32312. this.isMeshBasicNodeMaterial = true;
  32313. this.lights = false;
  32314. //this.normals = false; @TODO: normals usage by context
  32315. this.setDefaultValues( defaultValues$9 );
  32316. this.setValues( parameters );
  32317. }
  32318. }
  32319. addNodeMaterial( 'MeshBasicNodeMaterial', MeshBasicNodeMaterial );
  32320. const F_Schlick = tslFn( ( { f0, f90, dotVH } ) => {
  32321. // Original approximation by Christophe Schlick '94
  32322. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  32323. // Optimized variant (presented by Epic at SIGGRAPH '13)
  32324. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  32325. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  32326. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  32327. } ); // validated
  32328. const BRDF_Lambert = tslFn( ( inputs ) => {
  32329. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  32330. } ); // validated
  32331. const G_BlinnPhong_Implicit = () => float( 0.25 );
  32332. const D_BlinnPhong = tslFn( ( { dotNH } ) => {
  32333. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  32334. } );
  32335. const BRDF_BlinnPhong = tslFn( ( { lightDirection } ) => {
  32336. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  32337. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  32338. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  32339. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  32340. const G = G_BlinnPhong_Implicit();
  32341. const D = D_BlinnPhong( { dotNH } );
  32342. return F.mul( G ).mul( D );
  32343. } );
  32344. class PhongLightingModel extends LightingModel {
  32345. constructor( specular = true ) {
  32346. super();
  32347. this.specular = specular;
  32348. }
  32349. direct( { lightDirection, lightColor, reflectedLight } ) {
  32350. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  32351. const irradiance = dotNL.mul( lightColor );
  32352. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  32353. if ( this.specular === true ) {
  32354. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  32355. }
  32356. }
  32357. indirectDiffuse( { irradiance, reflectedLight } ) {
  32358. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  32359. }
  32360. }
  32361. const defaultValues$8 = new MeshLambertMaterial();
  32362. class MeshLambertNodeMaterial extends NodeMaterial {
  32363. constructor( parameters ) {
  32364. super();
  32365. this.isMeshLambertNodeMaterial = true;
  32366. this.lights = true;
  32367. this.setDefaultValues( defaultValues$8 );
  32368. this.setValues( parameters );
  32369. }
  32370. setupLightingModel( /*builder*/ ) {
  32371. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  32372. }
  32373. }
  32374. addNodeMaterial( 'MeshLambertNodeMaterial', MeshLambertNodeMaterial );
  32375. const defaultValues$7 = new MeshPhongMaterial();
  32376. class MeshPhongNodeMaterial extends NodeMaterial {
  32377. constructor( parameters ) {
  32378. super();
  32379. this.isMeshPhongNodeMaterial = true;
  32380. this.lights = true;
  32381. this.shininessNode = null;
  32382. this.specularNode = null;
  32383. this.setDefaultValues( defaultValues$7 );
  32384. this.setValues( parameters );
  32385. }
  32386. setupLightingModel( /*builder*/ ) {
  32387. return new PhongLightingModel();
  32388. }
  32389. setupVariants() {
  32390. // SHININESS
  32391. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  32392. shininess.assign( shininessNode );
  32393. // SPECULAR COLOR
  32394. const specularNode = this.specularNode || materialSpecular;
  32395. specularColor.assign( specularNode );
  32396. }
  32397. copy( source ) {
  32398. this.shininessNode = source.shininessNode;
  32399. this.specularNode = source.specularNode;
  32400. return super.copy( source );
  32401. }
  32402. }
  32403. addNodeMaterial( 'MeshPhongNodeMaterial', MeshPhongNodeMaterial );
  32404. const getGeometryRoughness = tslFn( () => {
  32405. const dxy = normalGeometry.dFdx().abs().max( normalGeometry.dFdy().abs() );
  32406. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  32407. return geometryRoughness;
  32408. } );
  32409. const getRoughness = tslFn( ( inputs ) => {
  32410. const { roughness } = inputs;
  32411. const geometryRoughness = getGeometryRoughness();
  32412. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  32413. roughnessFactor = roughnessFactor.add( geometryRoughness );
  32414. roughnessFactor = roughnessFactor.min( 1.0 );
  32415. return roughnessFactor;
  32416. } );
  32417. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  32418. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  32419. const V_GGX_SmithCorrelated = tslFn( ( { alpha, dotNL, dotNV } ) => {
  32420. const a2 = alpha.pow2();
  32421. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  32422. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  32423. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  32424. } ).setLayout( {
  32425. name: 'V_GGX_SmithCorrelated',
  32426. type: 'float',
  32427. inputs: [
  32428. { name: 'alpha', type: 'float' },
  32429. { name: 'dotNL', type: 'float' },
  32430. { name: 'dotNV', type: 'float' }
  32431. ]
  32432. } ); // validated
  32433. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  32434. const V_GGX_SmithCorrelated_Anisotropic = tslFn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  32435. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  32436. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  32437. const v = div( 0.5, gv.add( gl ) );
  32438. return v.saturate();
  32439. } ).setLayout( {
  32440. name: 'V_GGX_SmithCorrelated_Anisotropic',
  32441. type: 'float',
  32442. inputs: [
  32443. { name: 'alphaT', type: 'float', qualifier: 'in' },
  32444. { name: 'alphaB', type: 'float', qualifier: 'in' },
  32445. { name: 'dotTV', type: 'float', qualifier: 'in' },
  32446. { name: 'dotBV', type: 'float', qualifier: 'in' },
  32447. { name: 'dotTL', type: 'float', qualifier: 'in' },
  32448. { name: 'dotBL', type: 'float', qualifier: 'in' },
  32449. { name: 'dotNV', type: 'float', qualifier: 'in' },
  32450. { name: 'dotNL', type: 'float', qualifier: 'in' }
  32451. ]
  32452. } );
  32453. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  32454. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  32455. // alpha is "roughness squared" in Disney’s reparameterization
  32456. const D_GGX = tslFn( ( { alpha, dotNH } ) => {
  32457. const a2 = alpha.pow2();
  32458. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  32459. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  32460. } ).setLayout( {
  32461. name: 'D_GGX',
  32462. type: 'float',
  32463. inputs: [
  32464. { name: 'alpha', type: 'float' },
  32465. { name: 'dotNH', type: 'float' }
  32466. ]
  32467. } ); // validated
  32468. const RECIPROCAL_PI = float( 1 / Math.PI );
  32469. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  32470. const D_GGX_Anisotropic = tslFn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  32471. const a2 = alphaT.mul( alphaB );
  32472. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  32473. const v2 = v.dot( v );
  32474. const w2 = a2.div( v2 );
  32475. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  32476. } ).setLayout( {
  32477. name: 'D_GGX_Anisotropic',
  32478. type: 'float',
  32479. inputs: [
  32480. { name: 'alphaT', type: 'float', qualifier: 'in' },
  32481. { name: 'alphaB', type: 'float', qualifier: 'in' },
  32482. { name: 'dotNH', type: 'float', qualifier: 'in' },
  32483. { name: 'dotTH', type: 'float', qualifier: 'in' },
  32484. { name: 'dotBH', type: 'float', qualifier: 'in' }
  32485. ]
  32486. } );
  32487. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  32488. const BRDF_GGX = tslFn( ( inputs ) => {
  32489. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  32490. const normalView = inputs.normalView || transformedNormalView;
  32491. const alpha = roughness.pow2(); // UE4's roughness
  32492. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  32493. const dotNL = normalView.dot( lightDirection ).clamp();
  32494. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  32495. const dotNH = normalView.dot( halfDir ).clamp();
  32496. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  32497. let F = F_Schlick( { f0, f90, dotVH } );
  32498. let V, D;
  32499. if ( defined( USE_IRIDESCENCE ) ) {
  32500. F = iridescence.mix( F, f );
  32501. }
  32502. if ( defined( USE_ANISOTROPY ) ) {
  32503. const dotTL = anisotropyT.dot( lightDirection );
  32504. const dotTV = anisotropyT.dot( positionViewDirection );
  32505. const dotTH = anisotropyT.dot( halfDir );
  32506. const dotBL = anisotropyB.dot( lightDirection );
  32507. const dotBV = anisotropyB.dot( positionViewDirection );
  32508. const dotBH = anisotropyB.dot( halfDir );
  32509. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  32510. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  32511. } else {
  32512. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  32513. D = D_GGX( { alpha, dotNH } );
  32514. }
  32515. return F.mul( V ).mul( D );
  32516. } ); // validated
  32517. // Analytical approximation of the DFG LUT, one half of the
  32518. // split-sum approximation used in indirect specular lighting.
  32519. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  32520. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  32521. const DFGApprox = tslFn( ( { roughness, dotNV } ) => {
  32522. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  32523. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  32524. const r = roughness.mul( c0 ).add( c1 );
  32525. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  32526. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  32527. return fab;
  32528. } ).setLayout( {
  32529. name: 'DFGApprox',
  32530. type: 'vec2',
  32531. inputs: [
  32532. { name: 'roughness', type: 'float' },
  32533. { name: 'dotNV', type: 'vec3' }
  32534. ]
  32535. } );
  32536. const EnvironmentBRDF = tslFn( ( inputs ) => {
  32537. const { dotNV, specularColor, specularF90, roughness } = inputs;
  32538. const fab = DFGApprox( { dotNV, roughness } );
  32539. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  32540. } );
  32541. const Schlick_to_F0 = tslFn( ( { f, f90, dotVH } ) => {
  32542. const x = dotVH.oneMinus().saturate();
  32543. const x2 = x.mul( x );
  32544. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  32545. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  32546. } ).setLayout( {
  32547. name: 'Schlick_to_F0',
  32548. type: 'vec3',
  32549. inputs: [
  32550. { name: 'f', type: 'vec3' },
  32551. { name: 'f90', type: 'float' },
  32552. { name: 'dotVH', type: 'float' }
  32553. ]
  32554. } );
  32555. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  32556. const D_Charlie = tslFn( ( { roughness, dotNH } ) => {
  32557. const alpha = roughness.pow2();
  32558. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  32559. const invAlpha = float( 1.0 ).div( alpha );
  32560. const cos2h = dotNH.pow2();
  32561. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  32562. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  32563. } ).setLayout( {
  32564. name: 'D_Charlie',
  32565. type: 'float',
  32566. inputs: [
  32567. { name: 'roughness', type: 'float' },
  32568. { name: 'dotNH', type: 'float' }
  32569. ]
  32570. } );
  32571. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  32572. const V_Neubelt = tslFn( ( { dotNV, dotNL } ) => {
  32573. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  32574. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  32575. } ).setLayout( {
  32576. name: 'V_Neubelt',
  32577. type: 'float',
  32578. inputs: [
  32579. { name: 'dotNV', type: 'float' },
  32580. { name: 'dotNL', type: 'float' }
  32581. ]
  32582. } );
  32583. const BRDF_Sheen = tslFn( ( { lightDirection } ) => {
  32584. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  32585. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  32586. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  32587. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  32588. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  32589. const V = V_Neubelt( { dotNV, dotNL } );
  32590. return sheen.mul( D ).mul( V );
  32591. } );
  32592. // Rect Area Light
  32593. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  32594. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  32595. // code: https://github.com/selfshadow/ltc_code/
  32596. const LTC_Uv = tslFn( ( { N, V, roughness } ) => {
  32597. const LUT_SIZE = 64.0;
  32598. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  32599. const LUT_BIAS = 0.5 / LUT_SIZE;
  32600. const dotNV = N.dot( V ).saturate();
  32601. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  32602. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  32603. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  32604. return uv;
  32605. } ).setLayout( {
  32606. name: 'LTC_Uv',
  32607. type: 'vec2',
  32608. inputs: [
  32609. { name: 'N', type: 'vec3' },
  32610. { name: 'V', type: 'vec3' },
  32611. { name: 'roughness', type: 'float' }
  32612. ]
  32613. } );
  32614. const LTC_ClippedSphereFormFactor = tslFn( ( { f } ) => {
  32615. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  32616. // An approximation of the form factor of a horizon-clipped rectangle.
  32617. const l = f.length();
  32618. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  32619. } ).setLayout( {
  32620. name: 'LTC_ClippedSphereFormFactor',
  32621. type: 'float',
  32622. inputs: [
  32623. { name: 'f', type: 'vec3' }
  32624. ]
  32625. } );
  32626. const LTC_EdgeVectorFormFactor = tslFn( ( { v1, v2 } ) => {
  32627. const x = v1.dot( v2 );
  32628. const y = x.abs().toVar();
  32629. // rational polynomial approximation to theta / sin( theta ) / 2PI
  32630. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  32631. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  32632. const v = a.div( b );
  32633. const theta_sintheta = x.greaterThan( 0.0 ).cond( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  32634. return v1.cross( v2 ).mul( theta_sintheta );
  32635. } ).setLayout( {
  32636. name: 'LTC_EdgeVectorFormFactor',
  32637. type: 'vec3',
  32638. inputs: [
  32639. { name: 'v1', type: 'vec3' },
  32640. { name: 'v2', type: 'vec3' }
  32641. ]
  32642. } );
  32643. const LTC_Evaluate = tslFn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  32644. // bail if point is on back side of plane of light
  32645. // assumes ccw winding order of light vertices
  32646. const v1 = p1.sub( p0 ).toVar();
  32647. const v2 = p3.sub( p0 ).toVar();
  32648. const lightNormal = v1.cross( v2 );
  32649. const result = vec3().toVar();
  32650. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  32651. // construct orthonormal basis around N
  32652. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  32653. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  32654. // compute transform
  32655. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  32656. // transform rect
  32657. // & project rect onto sphere
  32658. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  32659. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  32660. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  32661. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  32662. // calculate vector form factor
  32663. const vectorFormFactor = vec3( 0 ).toVar();
  32664. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  32665. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  32666. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  32667. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  32668. // adjust for horizon clipping
  32669. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  32670. } );
  32671. return result;
  32672. } ).setLayout( {
  32673. name: 'LTC_Evaluate',
  32674. type: 'vec3',
  32675. inputs: [
  32676. { name: 'N', type: 'vec3' },
  32677. { name: 'V', type: 'vec3' },
  32678. { name: 'P', type: 'vec3' },
  32679. { name: 'mInv', type: 'mat3' },
  32680. { name: 'p0', type: 'vec3' },
  32681. { name: 'p1', type: 'vec3' },
  32682. { name: 'p2', type: 'vec3' },
  32683. { name: 'p3', type: 'vec3' }
  32684. ]
  32685. } );
  32686. //
  32687. // Transmission
  32688. //
  32689. const getVolumeTransmissionRay = tslFn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  32690. // Direction of refracted light.
  32691. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  32692. // Compute rotation-independant scaling of the model matrix.
  32693. const modelScale = vec3(
  32694. length( modelMatrix[ 0 ].xyz ),
  32695. length( modelMatrix[ 1 ].xyz ),
  32696. length( modelMatrix[ 2 ].xyz )
  32697. );
  32698. // The thickness is specified in local space.
  32699. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  32700. } ).setLayout( {
  32701. name: 'getVolumeTransmissionRay',
  32702. type: 'vec3',
  32703. inputs: [
  32704. { name: 'n', type: 'vec3' },
  32705. { name: 'v', type: 'vec3' },
  32706. { name: 'thickness', type: 'float' },
  32707. { name: 'ior', type: 'float' },
  32708. { name: 'modelMatrix', type: 'mat4' }
  32709. ]
  32710. } );
  32711. const applyIorToRoughness = tslFn( ( [ roughness, ior ] ) => {
  32712. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  32713. // an IOR of 1.5 results in the default amount of microfacet refraction.
  32714. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  32715. } ).setLayout( {
  32716. name: 'applyIorToRoughness',
  32717. type: 'float',
  32718. inputs: [
  32719. { name: 'roughness', type: 'float' },
  32720. { name: 'ior', type: 'float' }
  32721. ]
  32722. } );
  32723. const singleViewportMipTexture = viewportMipTexture();
  32724. const getTransmissionSample = tslFn( ( [ fragCoord, roughness, ior ] ) => {
  32725. const transmissionSample = singleViewportMipTexture.uv( fragCoord );
  32726. //const transmissionSample = viewportMipTexture( fragCoord );
  32727. const lod = log2( float( viewportResolution.x ) ).mul( applyIorToRoughness( roughness, ior ) );
  32728. return transmissionSample.bicubic( lod );
  32729. } );
  32730. const volumeAttenuation = tslFn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  32731. If( attenuationDistance.notEqual( 0 ), () => {
  32732. // Compute light attenuation using Beer's law.
  32733. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  32734. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  32735. return transmittance;
  32736. } );
  32737. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  32738. return vec3( 1.0 );
  32739. } ).setLayout( {
  32740. name: 'volumeAttenuation',
  32741. type: 'vec3',
  32742. inputs: [
  32743. { name: 'transmissionDistance', type: 'float' },
  32744. { name: 'attenuationColor', type: 'vec3' },
  32745. { name: 'attenuationDistance', type: 'float' }
  32746. ]
  32747. } );
  32748. const getIBLVolumeRefraction = tslFn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  32749. let transmittedLight, transmittance;
  32750. if ( dispersion ) {
  32751. transmittedLight = vec4().toVar();
  32752. transmittance = vec3().toVar();
  32753. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  32754. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  32755. loop( { start: 0, end: 3 }, ( { i } ) => {
  32756. const ior = iors.element( i );
  32757. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  32758. const refractedRayExit = position.add( transmissionRay );
  32759. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  32760. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  32761. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  32762. refractionCoords.addAssign( 1.0 );
  32763. refractionCoords.divAssign( 2.0 );
  32764. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  32765. // Sample framebuffer to get pixel the refracted ray hits.
  32766. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  32767. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  32768. transmittedLight.a.addAssign( transmissionSample.a );
  32769. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  32770. } );
  32771. transmittedLight.a.divAssign( 3.0 );
  32772. } else {
  32773. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  32774. const refractedRayExit = position.add( transmissionRay );
  32775. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  32776. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  32777. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  32778. refractionCoords.addAssign( 1.0 );
  32779. refractionCoords.divAssign( 2.0 );
  32780. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  32781. // Sample framebuffer to get pixel the refracted ray hits.
  32782. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  32783. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  32784. }
  32785. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  32786. const dotNV = n.dot( v ).clamp();
  32787. // Get the specular component.
  32788. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  32789. dotNV,
  32790. specularColor,
  32791. specularF90,
  32792. roughness
  32793. } ) );
  32794. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  32795. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  32796. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  32797. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  32798. } );
  32799. //
  32800. // Iridescence
  32801. //
  32802. // XYZ to linear-sRGB color space
  32803. const XYZ_TO_REC709 = mat3(
  32804. 3.2404542, - 0.9692660, 0.0556434,
  32805. - 1.5371385, 1.8760108, - 0.2040259,
  32806. - 0.4985314, 0.0415560, 1.0572252
  32807. );
  32808. // Assume air interface for top
  32809. // Note: We don't handle the case fresnel0 == 1
  32810. const Fresnel0ToIor = ( fresnel0 ) => {
  32811. const sqrtF0 = fresnel0.sqrt();
  32812. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  32813. };
  32814. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  32815. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  32816. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  32817. };
  32818. // Fresnel equations for dielectric/dielectric interfaces.
  32819. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  32820. // Evaluation XYZ sensitivity curves in Fourier space
  32821. const evalSensitivity = ( OPD, shift ) => {
  32822. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  32823. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  32824. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  32825. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  32826. 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() );
  32827. 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() );
  32828. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  32829. const rgb = XYZ_TO_REC709.mul( xyz );
  32830. return rgb;
  32831. };
  32832. const evalIridescence = tslFn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  32833. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  32834. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  32835. // Evaluate the cosTheta on the base layer (Snell law)
  32836. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( float( 1 ).sub( cosTheta1.pow2() ) );
  32837. // Handle TIR:
  32838. const cosTheta2Sq = float( 1 ).sub( sinTheta2Sq );
  32839. /*if ( cosTheta2Sq < 0.0 ) {
  32840. return vec3( 1.0 );
  32841. }*/
  32842. const cosTheta2 = cosTheta2Sq.sqrt();
  32843. // First interface
  32844. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  32845. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  32846. //const R21 = R12;
  32847. const T121 = R12.oneMinus();
  32848. const phi12 = iridescenceIOR.lessThan( outsideIOR ).cond( Math.PI, 0.0 );
  32849. const phi21 = float( Math.PI ).sub( phi12 );
  32850. // Second interface
  32851. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  32852. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  32853. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  32854. const phi23 = vec3(
  32855. baseIOR.x.lessThan( iridescenceIOR ).cond( Math.PI, 0.0 ),
  32856. baseIOR.y.lessThan( iridescenceIOR ).cond( Math.PI, 0.0 ),
  32857. baseIOR.z.lessThan( iridescenceIOR ).cond( Math.PI, 0.0 )
  32858. );
  32859. // Phase shift
  32860. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  32861. const phi = vec3( phi21 ).add( phi23 );
  32862. // Compound terms
  32863. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  32864. const r123 = R123.sqrt();
  32865. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  32866. // Reflectance term for m = 0 (DC term amplitude)
  32867. const C0 = R12.add( Rs );
  32868. let I = C0;
  32869. // Reflectance term for m > 0 (pairs of diracs)
  32870. let Cm = Rs.sub( T121 );
  32871. for ( let m = 1; m <= 2; ++ m ) {
  32872. Cm = Cm.mul( r123 );
  32873. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  32874. I = I.add( Cm.mul( Sm ) );
  32875. }
  32876. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  32877. return I.max( vec3( 0.0 ) );
  32878. } ).setLayout( {
  32879. name: 'evalIridescence',
  32880. type: 'vec3',
  32881. inputs: [
  32882. { name: 'outsideIOR', type: 'float' },
  32883. { name: 'eta2', type: 'float' },
  32884. { name: 'cosTheta1', type: 'float' },
  32885. { name: 'thinFilmThickness', type: 'float' },
  32886. { name: 'baseF0', type: 'vec3' }
  32887. ]
  32888. } );
  32889. //
  32890. // Sheen
  32891. //
  32892. // This is a curve-fit approxmation to the "Charlie sheen" BRDF integrated over the hemisphere from
  32893. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  32894. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  32895. const IBLSheenBRDF = tslFn( ( { normal, viewDir, roughness } ) => {
  32896. const dotNV = normal.dot( viewDir ).saturate();
  32897. const r2 = roughness.pow2();
  32898. const a = cond(
  32899. roughness.lessThan( 0.25 ),
  32900. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  32901. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  32902. );
  32903. const b = cond(
  32904. roughness.lessThan( 0.25 ),
  32905. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  32906. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  32907. );
  32908. const DG = cond( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  32909. return DG.mul( 1.0 / Math.PI ).saturate();
  32910. } );
  32911. const clearcoatF0 = vec3( 0.04 );
  32912. const clearcoatF90 = float( 1 );
  32913. //
  32914. class PhysicalLightingModel extends LightingModel {
  32915. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  32916. super();
  32917. this.clearcoat = clearcoat;
  32918. this.sheen = sheen;
  32919. this.iridescence = iridescence;
  32920. this.anisotropy = anisotropy;
  32921. this.transmission = transmission;
  32922. this.dispersion = dispersion;
  32923. this.clearcoatRadiance = null;
  32924. this.clearcoatSpecularDirect = null;
  32925. this.clearcoatSpecularIndirect = null;
  32926. this.sheenSpecularDirect = null;
  32927. this.sheenSpecularIndirect = null;
  32928. this.iridescenceFresnel = null;
  32929. this.iridescenceF0 = null;
  32930. }
  32931. start( context ) {
  32932. if ( this.clearcoat === true ) {
  32933. this.clearcoatRadiance = vec3().temp( 'clearcoatRadiance' );
  32934. this.clearcoatSpecularDirect = vec3().temp( 'clearcoatSpecularDirect' );
  32935. this.clearcoatSpecularIndirect = vec3().temp( 'clearcoatSpecularIndirect' );
  32936. }
  32937. if ( this.sheen === true ) {
  32938. this.sheenSpecularDirect = vec3().temp( 'sheenSpecularDirect' );
  32939. this.sheenSpecularIndirect = vec3().temp( 'sheenSpecularIndirect' );
  32940. }
  32941. if ( this.iridescence === true ) {
  32942. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  32943. this.iridescenceFresnel = evalIridescence( {
  32944. outsideIOR: float( 1.0 ),
  32945. eta2: iridescenceIOR,
  32946. cosTheta1: dotNVi,
  32947. thinFilmThickness: iridescenceThickness,
  32948. baseF0: specularColor
  32949. } );
  32950. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  32951. }
  32952. if ( this.transmission === true ) {
  32953. const position = positionWorld;
  32954. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  32955. const n = transformedNormalWorld;
  32956. context.backdrop = getIBLVolumeRefraction(
  32957. n,
  32958. v,
  32959. roughness,
  32960. diffuseColor,
  32961. specularColor,
  32962. specularF90, // specularF90
  32963. position, // positionWorld
  32964. modelWorldMatrix, // modelMatrix
  32965. cameraViewMatrix, // viewMatrix
  32966. cameraProjectionMatrix, // projMatrix
  32967. ior,
  32968. thickness,
  32969. attenuationColor,
  32970. attenuationDistance,
  32971. this.dispersion ? dispersion : null
  32972. );
  32973. context.backdropAlpha = transmission;
  32974. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  32975. }
  32976. }
  32977. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  32978. // Approximates multiscattering in order to preserve energy.
  32979. // http://www.jcgt.org/published/0008/01/03/
  32980. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  32981. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  32982. const fab = DFGApprox( { roughness, dotNV } );
  32983. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  32984. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  32985. const Ess = fab.x.add( fab.y );
  32986. const Ems = Ess.oneMinus();
  32987. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  32988. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  32989. singleScatter.addAssign( FssEss );
  32990. multiScatter.addAssign( Fms.mul( Ems ) );
  32991. }
  32992. direct( { lightDirection, lightColor, reflectedLight } ) {
  32993. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  32994. const irradiance = dotNL.mul( lightColor );
  32995. if ( this.sheen === true ) {
  32996. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  32997. }
  32998. if ( this.clearcoat === true ) {
  32999. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  33000. const ccIrradiance = dotNLcc.mul( lightColor );
  33001. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  33002. }
  33003. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  33004. 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 } ) ) );
  33005. }
  33006. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  33007. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  33008. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  33009. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  33010. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  33011. const N = transformedNormalView;
  33012. const V = positionViewDirection;
  33013. const P = positionView.toVar();
  33014. const uv = LTC_Uv( { N, V, roughness } );
  33015. const t1 = ltc_1.uv( uv ).toVar();
  33016. const t2 = ltc_2.uv( uv ).toVar();
  33017. const mInv = mat3(
  33018. vec3( t1.x, 0, t1.y ),
  33019. vec3( 0, 1, 0 ),
  33020. vec3( t1.z, 0, t1.w )
  33021. ).toVar();
  33022. // LTC Fresnel Approximation by Stephen Hill
  33023. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  33024. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  33025. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  33026. 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 } ) ) );
  33027. }
  33028. indirectDiffuse( { irradiance, reflectedLight } ) {
  33029. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  33030. }
  33031. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  33032. if ( this.sheen === true ) {
  33033. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  33034. sheen,
  33035. IBLSheenBRDF( {
  33036. normal: transformedNormalView,
  33037. viewDir: positionViewDirection,
  33038. roughness: sheenRoughness
  33039. } )
  33040. ) );
  33041. }
  33042. if ( this.clearcoat === true ) {
  33043. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  33044. const clearcoatEnv = EnvironmentBRDF( {
  33045. dotNV: dotNVcc,
  33046. specularColor: clearcoatF0,
  33047. specularF90: clearcoatF90,
  33048. roughness: clearcoatRoughness
  33049. } );
  33050. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  33051. }
  33052. // Both indirect specular and indirect diffuse light accumulate here
  33053. const singleScattering = vec3().temp( 'singleScattering' );
  33054. const multiScattering = vec3().temp( 'multiScattering' );
  33055. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  33056. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  33057. const totalScattering = singleScattering.add( multiScattering );
  33058. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  33059. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  33060. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  33061. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  33062. }
  33063. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  33064. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  33065. const aoNV = dotNV.add( ambientOcclusion );
  33066. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  33067. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  33068. if ( this.clearcoat === true ) {
  33069. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  33070. }
  33071. if ( this.sheen === true ) {
  33072. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  33073. }
  33074. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  33075. reflectedLight.indirectSpecular.mulAssign( aoNode );
  33076. }
  33077. finish( context ) {
  33078. const { outgoingLight } = context;
  33079. if ( this.clearcoat === true ) {
  33080. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  33081. const Fcc = F_Schlick( {
  33082. dotVH: dotNVcc,
  33083. f0: clearcoatF0,
  33084. f90: clearcoatF90
  33085. } );
  33086. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  33087. outgoingLight.assign( clearcoatLight );
  33088. }
  33089. if ( this.sheen === true ) {
  33090. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  33091. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  33092. outgoingLight.assign( sheenLight );
  33093. }
  33094. }
  33095. }
  33096. const defaultValues$6 = new MeshStandardMaterial();
  33097. class MeshStandardNodeMaterial extends NodeMaterial {
  33098. constructor( parameters ) {
  33099. super();
  33100. this.isMeshStandardNodeMaterial = true;
  33101. this.emissiveNode = null;
  33102. this.metalnessNode = null;
  33103. this.roughnessNode = null;
  33104. this.setDefaultValues( defaultValues$6 );
  33105. this.setValues( parameters );
  33106. }
  33107. setupLightingModel( /*builder*/ ) {
  33108. return new PhysicalLightingModel();
  33109. }
  33110. setupSpecular() {
  33111. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  33112. specularColor.assign( specularColorNode );
  33113. specularF90.assign( 1.0 );
  33114. }
  33115. setupVariants() {
  33116. // METALNESS
  33117. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  33118. metalness.assign( metalnessNode );
  33119. // ROUGHNESS
  33120. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  33121. roughnessNode = getRoughness( { roughness: roughnessNode } );
  33122. roughness.assign( roughnessNode );
  33123. // SPECULAR COLOR
  33124. this.setupSpecular();
  33125. // DIFFUSE COLOR
  33126. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  33127. }
  33128. copy( source ) {
  33129. this.emissiveNode = source.emissiveNode;
  33130. this.metalnessNode = source.metalnessNode;
  33131. this.roughnessNode = source.roughnessNode;
  33132. return super.copy( source );
  33133. }
  33134. }
  33135. addNodeMaterial( 'MeshStandardNodeMaterial', MeshStandardNodeMaterial );
  33136. const defaultValues$5 = new MeshPhysicalMaterial();
  33137. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  33138. constructor( parameters ) {
  33139. super();
  33140. this.isMeshPhysicalNodeMaterial = true;
  33141. this.clearcoatNode = null;
  33142. this.clearcoatRoughnessNode = null;
  33143. this.clearcoatNormalNode = null;
  33144. this.sheenNode = null;
  33145. this.sheenRoughnessNode = null;
  33146. this.iridescenceNode = null;
  33147. this.iridescenceIORNode = null;
  33148. this.iridescenceThicknessNode = null;
  33149. this.specularIntensityNode = null;
  33150. this.specularColorNode = null;
  33151. this.iorNode = null;
  33152. this.transmissionNode = null;
  33153. this.thicknessNode = null;
  33154. this.attenuationDistanceNode = null;
  33155. this.attenuationColorNode = null;
  33156. this.dispersionNode = null;
  33157. this.anisotropyNode = null;
  33158. this.setDefaultValues( defaultValues$5 );
  33159. this.setValues( parameters );
  33160. }
  33161. get useClearcoat() {
  33162. return this.clearcoat > 0 || this.clearcoatNode !== null;
  33163. }
  33164. get useIridescence() {
  33165. return this.iridescence > 0 || this.iridescenceNode !== null;
  33166. }
  33167. get useSheen() {
  33168. return this.sheen > 0 || this.sheenNode !== null;
  33169. }
  33170. get useAnisotropy() {
  33171. return this.anisotropy > 0 || this.anisotropyNode !== null;
  33172. }
  33173. get useTransmission() {
  33174. return this.transmission > 0 || this.transmissionNode !== null;
  33175. }
  33176. get useDispersion() {
  33177. return this.dispersion > 0 || this.dispersionNode !== null;
  33178. }
  33179. setupSpecular() {
  33180. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  33181. ior.assign( iorNode );
  33182. 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 ) );
  33183. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  33184. }
  33185. setupLightingModel( /*builder*/ ) {
  33186. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  33187. }
  33188. setupVariants( builder ) {
  33189. super.setupVariants( builder );
  33190. // CLEARCOAT
  33191. if ( this.useClearcoat ) {
  33192. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  33193. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  33194. clearcoat.assign( clearcoatNode );
  33195. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  33196. }
  33197. // SHEEN
  33198. if ( this.useSheen ) {
  33199. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  33200. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  33201. sheen.assign( sheenNode );
  33202. sheenRoughness.assign( sheenRoughnessNode );
  33203. }
  33204. // IRIDESCENCE
  33205. if ( this.useIridescence ) {
  33206. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  33207. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  33208. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  33209. iridescence.assign( iridescenceNode );
  33210. iridescenceIOR.assign( iridescenceIORNode );
  33211. iridescenceThickness.assign( iridescenceThicknessNode );
  33212. }
  33213. // ANISOTROPY
  33214. if ( this.useAnisotropy ) {
  33215. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  33216. anisotropy.assign( anisotropyV.length() );
  33217. If( anisotropy.equal( 0.0 ), () => {
  33218. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  33219. } ).else( () => {
  33220. anisotropyV.divAssign( vec2( anisotropy ) );
  33221. anisotropy.assign( anisotropy.saturate() );
  33222. } );
  33223. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  33224. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  33225. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  33226. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  33227. }
  33228. // TRANSMISSION
  33229. if ( this.useTransmission ) {
  33230. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  33231. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  33232. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  33233. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  33234. transmission.assign( transmissionNode );
  33235. thickness.assign( thicknessNode );
  33236. attenuationDistance.assign( attenuationDistanceNode );
  33237. attenuationColor.assign( attenuationColorNode );
  33238. if ( this.useDispersion ) {
  33239. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  33240. dispersion.assign( dispersionNode );
  33241. }
  33242. }
  33243. }
  33244. setupNormal( builder ) {
  33245. super.setupNormal( builder );
  33246. // CLEARCOAT NORMAL
  33247. const clearcoatNormalNode = this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  33248. transformedClearcoatNormalView.assign( clearcoatNormalNode );
  33249. }
  33250. copy( source ) {
  33251. this.clearcoatNode = source.clearcoatNode;
  33252. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  33253. this.clearcoatNormalNode = source.clearcoatNormalNode;
  33254. this.sheenNode = source.sheenNode;
  33255. this.sheenRoughnessNode = source.sheenRoughnessNode;
  33256. this.iridescenceNode = source.iridescenceNode;
  33257. this.iridescenceIORNode = source.iridescenceIORNode;
  33258. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  33259. this.specularIntensityNode = source.specularIntensityNode;
  33260. this.specularColorNode = source.specularColorNode;
  33261. this.transmissionNode = source.transmissionNode;
  33262. this.thicknessNode = source.thicknessNode;
  33263. this.attenuationDistanceNode = source.attenuationDistanceNode;
  33264. this.attenuationColorNode = source.attenuationColorNode;
  33265. this.dispersionNode = source.dispersionNode;
  33266. this.anisotropyNode = source.anisotropyNode;
  33267. return super.copy( source );
  33268. }
  33269. }
  33270. addNodeMaterial( 'MeshPhysicalNodeMaterial', MeshPhysicalNodeMaterial );
  33271. class SSSLightingModel extends PhysicalLightingModel {
  33272. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  33273. super( useClearcoat, useSheen, useIridescence );
  33274. this.useSSS = useSSS;
  33275. }
  33276. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  33277. if ( this.useSSS === true ) {
  33278. const material = builder.material;
  33279. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  33280. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  33281. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  33282. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  33283. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  33284. }
  33285. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  33286. }
  33287. }
  33288. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  33289. constructor( parameters ) {
  33290. super( parameters );
  33291. this.thicknessColorNode = null;
  33292. this.thicknessDistortionNode = float( 0.1 );
  33293. this.thicknessAmbientNode = float( 0.0 );
  33294. this.thicknessAttenuationNode = float( .1 );
  33295. this.thicknessPowerNode = float( 2.0 );
  33296. this.thicknessScaleNode = float( 10.0 );
  33297. }
  33298. get useSSS() {
  33299. return this.thicknessColorNode !== null;
  33300. }
  33301. setupLightingModel( /*builder*/ ) {
  33302. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  33303. }
  33304. copy( source ) {
  33305. this.thicknessColorNode = source.thicknessColorNode;
  33306. this.thicknessDistortionNode = source.thicknessDistortionNode;
  33307. this.thicknessAmbientNode = source.thicknessAmbientNode;
  33308. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  33309. this.thicknessPowerNode = source.thicknessPowerNode;
  33310. this.thicknessScaleNode = source.thicknessScaleNode;
  33311. return super.copy( source );
  33312. }
  33313. }
  33314. addNodeMaterial( 'MeshSSSNodeMaterial', MeshSSSNodeMaterial );
  33315. const getGradientIrradiance = tslFn( ( { normal, lightDirection, builder } ) => {
  33316. // dotNL will be from -1.0 to 1.0
  33317. const dotNL = normal.dot( lightDirection );
  33318. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  33319. if ( builder.material.gradientMap ) {
  33320. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  33321. return vec3( gradientMap.r );
  33322. } else {
  33323. const fw = coord.fwidth().mul( 0.5 );
  33324. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  33325. }
  33326. } );
  33327. class ToonLightingModel extends LightingModel {
  33328. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  33329. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  33330. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  33331. }
  33332. indirectDiffuse( { irradiance, reflectedLight } ) {
  33333. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  33334. }
  33335. }
  33336. const defaultValues$4 = new MeshToonMaterial();
  33337. class MeshToonNodeMaterial extends NodeMaterial {
  33338. constructor( parameters ) {
  33339. super();
  33340. this.isMeshToonNodeMaterial = true;
  33341. this.lights = true;
  33342. this.setDefaultValues( defaultValues$4 );
  33343. this.setValues( parameters );
  33344. }
  33345. setupLightingModel( /*builder*/ ) {
  33346. return new ToonLightingModel();
  33347. }
  33348. }
  33349. addNodeMaterial( 'MeshToonNodeMaterial', MeshToonNodeMaterial );
  33350. const defaultValues$3 = new MeshMatcapMaterial();
  33351. class MeshMatcapNodeMaterial extends NodeMaterial {
  33352. constructor( parameters ) {
  33353. super();
  33354. this.lights = false;
  33355. this.isMeshMatcapNodeMaterial = true;
  33356. this.setDefaultValues( defaultValues$3 );
  33357. this.setValues( parameters );
  33358. }
  33359. setupVariants( builder ) {
  33360. const uv = matcapUV;
  33361. let matcapColor;
  33362. if ( builder.material.matcap ) {
  33363. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  33364. } else {
  33365. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  33366. }
  33367. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  33368. }
  33369. }
  33370. addNodeMaterial( 'MeshMatcapNodeMaterial', MeshMatcapNodeMaterial );
  33371. const defaultValues$2 = new PointsMaterial();
  33372. class PointsNodeMaterial extends NodeMaterial {
  33373. constructor( parameters ) {
  33374. super();
  33375. this.isPointsNodeMaterial = true;
  33376. this.lights = false;
  33377. this.normals = false;
  33378. this.transparent = true;
  33379. this.sizeNode = null;
  33380. this.setDefaultValues( defaultValues$2 );
  33381. this.setValues( parameters );
  33382. }
  33383. copy( source ) {
  33384. this.sizeNode = source.sizeNode;
  33385. return super.copy( source );
  33386. }
  33387. }
  33388. addNodeMaterial( 'PointsNodeMaterial', PointsNodeMaterial );
  33389. const defaultValues$1 = new SpriteMaterial();
  33390. class SpriteNodeMaterial extends NodeMaterial {
  33391. constructor( parameters ) {
  33392. super();
  33393. this.isSpriteNodeMaterial = true;
  33394. this.lights = false;
  33395. this.normals = false;
  33396. this.positionNode = null;
  33397. this.rotationNode = null;
  33398. this.scaleNode = null;
  33399. this.setDefaultValues( defaultValues$1 );
  33400. this.setValues( parameters );
  33401. }
  33402. setupPosition( { object, context } ) {
  33403. // < VERTEX STAGE >
  33404. const { positionNode, rotationNode, scaleNode } = this;
  33405. const vertex = positionLocal;
  33406. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  33407. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  33408. if ( scaleNode !== null ) {
  33409. scale = scale.mul( scaleNode );
  33410. }
  33411. let alignedPosition = vertex.xy;
  33412. if ( object.center && object.center.isVector2 === true ) {
  33413. alignedPosition = alignedPosition.sub( uniform( object.center ).sub( 0.5 ) );
  33414. }
  33415. alignedPosition = alignedPosition.mul( scale );
  33416. const rotation = float( rotationNode || materialRotation );
  33417. const rotatedPosition = alignedPosition.rotate( rotation );
  33418. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  33419. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  33420. context.vertex = vertex;
  33421. return modelViewProjection;
  33422. }
  33423. copy( source ) {
  33424. this.positionNode = source.positionNode;
  33425. this.rotationNode = source.rotationNode;
  33426. this.scaleNode = source.scaleNode;
  33427. return super.copy( source );
  33428. }
  33429. }
  33430. addNodeMaterial( 'SpriteNodeMaterial', SpriteNodeMaterial );
  33431. class ShadowMaskModel extends LightingModel {
  33432. constructor() {
  33433. super();
  33434. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  33435. }
  33436. direct( { shadowMask } ) {
  33437. this.shadowNode.mulAssign( shadowMask );
  33438. }
  33439. finish( context ) {
  33440. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  33441. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  33442. }
  33443. }
  33444. const defaultValues = new ShadowMaterial();
  33445. class ShadowNodeMaterial extends NodeMaterial {
  33446. constructor( parameters ) {
  33447. super();
  33448. this.isShadowNodeMaterial = true;
  33449. this.lights = true;
  33450. this.setDefaultValues( defaultValues );
  33451. this.setValues( parameters );
  33452. }
  33453. setupLightingModel( /*builder*/ ) {
  33454. return new ShadowMaskModel();
  33455. }
  33456. }
  33457. addNodeMaterial( 'ShadowNodeMaterial', ShadowNodeMaterial );
  33458. class VolumeNodeMaterial extends NodeMaterial {
  33459. constructor( params = {} ) {
  33460. super();
  33461. this.normals = false;
  33462. this.lights = false;
  33463. this.isVolumeNodeMaterial = true;
  33464. this.testNode = null;
  33465. this.setValues( params );
  33466. }
  33467. setup( builder ) {
  33468. const map = texture3D( this.map, null, 0 );
  33469. const hitBox = tslFn( ( { orig, dir } ) => {
  33470. const box_min = vec3( - 0.5 );
  33471. const box_max = vec3( 0.5 );
  33472. const inv_dir = dir.reciprocal();
  33473. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  33474. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  33475. const tmin = min$1( tmin_tmp, tmax_tmp );
  33476. const tmax = max$1( tmin_tmp, tmax_tmp );
  33477. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  33478. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  33479. return vec2( t0, t1 );
  33480. } );
  33481. this.fragmentNode = tslFn( () => {
  33482. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  33483. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  33484. const rayDir = vDirection.normalize();
  33485. const bounds = property( 'vec2', 'bounds' ).assign( hitBox( { orig: vOrigin, dir: rayDir } ) );
  33486. bounds.x.greaterThan( bounds.y ).discard();
  33487. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  33488. const p = property( 'vec3', 'p' ).assign( vOrigin.add( bounds.x.mul( rayDir ) ) );
  33489. const inc = property( 'vec3', 'inc' ).assign( vec3( rayDir.abs().reciprocal() ) );
  33490. const delta = property( 'float', 'delta' ).assign( min$1( inc.x, min$1( inc.y, inc.z ) ) );
  33491. delta.divAssign( materialReference( 'steps', 'float' ) );
  33492. const ac = property( 'vec4', 'ac' ).assign( vec4( materialReference( 'base', 'color' ), 0.0 ) );
  33493. loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  33494. const d = property( 'float', 'd' ).assign( map.uv( p.add( 0.5 ) ).r );
  33495. if ( this.testNode !== null ) {
  33496. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  33497. } else {
  33498. // default to show surface of mesh
  33499. ac.a.assign( 1 );
  33500. Break();
  33501. }
  33502. p.addAssign( rayDir.mul( delta ) );
  33503. } );
  33504. ac.a.equal( 0 ).discard();
  33505. return vec4( ac );
  33506. } )();
  33507. super.setup( builder );
  33508. }
  33509. }
  33510. addNodeMaterial( 'VolumeNodeMaterial', VolumeNodeMaterial );
  33511. const superFromTypeFunction = MaterialLoader.createMaterialFromType;
  33512. MaterialLoader.createMaterialFromType = function ( type ) {
  33513. const material = createNodeMaterialFromType( type );
  33514. if ( material !== undefined ) {
  33515. return material;
  33516. }
  33517. return superFromTypeFunction.call( this, type );
  33518. };
  33519. class NodeMaterialLoader extends MaterialLoader {
  33520. constructor( manager ) {
  33521. super( manager );
  33522. this.nodes = {};
  33523. }
  33524. parse( json ) {
  33525. const material = super.parse( json );
  33526. const nodes = this.nodes;
  33527. const inputNodes = json.inputNodes;
  33528. for ( const property in inputNodes ) {
  33529. const uuid = inputNodes[ property ];
  33530. material[ property ] = nodes[ uuid ];
  33531. }
  33532. return material;
  33533. }
  33534. setNodes( value ) {
  33535. this.nodes = value;
  33536. return this;
  33537. }
  33538. }
  33539. class NodeObjectLoader extends ObjectLoader {
  33540. constructor( manager ) {
  33541. super( manager );
  33542. this._nodesJSON = null;
  33543. }
  33544. parse( json, onLoad ) {
  33545. this._nodesJSON = json.nodes;
  33546. const data = super.parse( json, onLoad );
  33547. this._nodesJSON = null; // dispose
  33548. return data;
  33549. }
  33550. parseNodes( json, textures ) {
  33551. if ( json !== undefined ) {
  33552. const loader = new NodeLoader();
  33553. loader.setTextures( textures );
  33554. return loader.parseNodes( json );
  33555. }
  33556. return {};
  33557. }
  33558. parseMaterials( json, textures ) {
  33559. const materials = {};
  33560. if ( json !== undefined ) {
  33561. const nodes = this.parseNodes( this._nodesJSON, textures );
  33562. const loader = new NodeMaterialLoader();
  33563. loader.setTextures( textures );
  33564. loader.setNodes( nodes );
  33565. for ( let i = 0, l = json.length; i < l; i ++ ) {
  33566. const data = json[ i ];
  33567. materials[ data.uuid ] = loader.parse( data );
  33568. }
  33569. }
  33570. return materials;
  33571. }
  33572. }
  33573. class NodeParser {
  33574. parseFunction( /*source*/ ) {
  33575. console.warn( 'Abstract function.' );
  33576. }
  33577. }
  33578. class NodeFunction {
  33579. constructor( type, inputs, name = '', precision = '' ) {
  33580. this.type = type;
  33581. this.inputs = inputs;
  33582. this.name = name;
  33583. this.precision = precision;
  33584. }
  33585. getCode( /*name = this.name*/ ) {
  33586. console.warn( 'Abstract function.' );
  33587. }
  33588. }
  33589. NodeFunction.isNodeFunction = true;
  33590. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  33591. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  33592. const pragmaMain = '#pragma main';
  33593. const parse$1 = ( source ) => {
  33594. source = source.trim();
  33595. const pragmaMainIndex = source.indexOf( pragmaMain );
  33596. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  33597. const declaration = mainCode.match( declarationRegexp$1 );
  33598. if ( declaration !== null && declaration.length === 5 ) {
  33599. // tokenizer
  33600. const inputsCode = declaration[ 4 ];
  33601. const propsMatches = [];
  33602. let nameMatch = null;
  33603. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  33604. propsMatches.push( nameMatch );
  33605. }
  33606. // parser
  33607. const inputs = [];
  33608. let i = 0;
  33609. while ( i < propsMatches.length ) {
  33610. const isConst = propsMatches[ i ][ 0 ] === 'const';
  33611. if ( isConst === true ) {
  33612. i ++;
  33613. }
  33614. let qualifier = propsMatches[ i ][ 0 ];
  33615. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  33616. i ++;
  33617. } else {
  33618. qualifier = '';
  33619. }
  33620. const type = propsMatches[ i ++ ][ 0 ];
  33621. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  33622. if ( Number.isNaN( count ) === false ) i ++;
  33623. else count = null;
  33624. const name = propsMatches[ i ++ ][ 0 ];
  33625. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  33626. }
  33627. //
  33628. const blockCode = mainCode.substring( declaration[ 0 ].length );
  33629. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  33630. const type = declaration[ 2 ];
  33631. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  33632. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  33633. return {
  33634. type,
  33635. inputs,
  33636. name,
  33637. precision,
  33638. inputsCode,
  33639. blockCode,
  33640. headerCode
  33641. };
  33642. } else {
  33643. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  33644. }
  33645. };
  33646. class GLSLNodeFunction extends NodeFunction {
  33647. constructor( source ) {
  33648. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  33649. super( type, inputs, name, precision );
  33650. this.inputsCode = inputsCode;
  33651. this.blockCode = blockCode;
  33652. this.headerCode = headerCode;
  33653. }
  33654. getCode( name = this.name ) {
  33655. let code;
  33656. const blockCode = this.blockCode;
  33657. if ( blockCode !== '' ) {
  33658. const { type, inputsCode, headerCode, precision } = this;
  33659. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  33660. if ( precision !== '' ) {
  33661. declarationCode = `${ precision } ${ declarationCode }`;
  33662. }
  33663. code = headerCode + declarationCode + blockCode;
  33664. } else {
  33665. // interface function
  33666. code = '';
  33667. }
  33668. return code;
  33669. }
  33670. }
  33671. class GLSLNodeParser extends NodeParser {
  33672. parseFunction( source ) {
  33673. return new GLSLNodeFunction( source );
  33674. }
  33675. }
  33676. // Three.js Transpiler
  33677. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  33678. const mx_select = /*#__PURE__*/ tslFn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  33679. const f = float( f_immutable ).toVar();
  33680. const t = float( t_immutable ).toVar();
  33681. const b = bool( b_immutable ).toVar();
  33682. return cond( b, t, f );
  33683. } ).setLayout( {
  33684. name: 'mx_select',
  33685. type: 'float',
  33686. inputs: [
  33687. { name: 'b', type: 'bool' },
  33688. { name: 't', type: 'float' },
  33689. { name: 'f', type: 'float' }
  33690. ]
  33691. } );
  33692. const mx_negate_if = /*#__PURE__*/ tslFn( ( [ val_immutable, b_immutable ] ) => {
  33693. const b = bool( b_immutable ).toVar();
  33694. const val = float( val_immutable ).toVar();
  33695. return cond( b, val.negate(), val );
  33696. } ).setLayout( {
  33697. name: 'mx_negate_if',
  33698. type: 'float',
  33699. inputs: [
  33700. { name: 'val', type: 'float' },
  33701. { name: 'b', type: 'bool' }
  33702. ]
  33703. } );
  33704. const mx_floor = /*#__PURE__*/ tslFn( ( [ x_immutable ] ) => {
  33705. const x = float( x_immutable ).toVar();
  33706. return int( floor( x ) );
  33707. } ).setLayout( {
  33708. name: 'mx_floor',
  33709. type: 'int',
  33710. inputs: [
  33711. { name: 'x', type: 'float' }
  33712. ]
  33713. } );
  33714. const mx_floorfrac = /*#__PURE__*/ tslFn( ( [ x_immutable, i ] ) => {
  33715. const x = float( x_immutable ).toVar();
  33716. i.assign( mx_floor( x ) );
  33717. return x.sub( float( i ) );
  33718. } );
  33719. const mx_bilerp_0 = /*#__PURE__*/ tslFn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  33720. const t = float( t_immutable ).toVar();
  33721. const s = float( s_immutable ).toVar();
  33722. const v3 = float( v3_immutable ).toVar();
  33723. const v2 = float( v2_immutable ).toVar();
  33724. const v1 = float( v1_immutable ).toVar();
  33725. const v0 = float( v0_immutable ).toVar();
  33726. const s1 = float( sub( 1.0, s ) ).toVar();
  33727. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  33728. } ).setLayout( {
  33729. name: 'mx_bilerp_0',
  33730. type: 'float',
  33731. inputs: [
  33732. { name: 'v0', type: 'float' },
  33733. { name: 'v1', type: 'float' },
  33734. { name: 'v2', type: 'float' },
  33735. { name: 'v3', type: 'float' },
  33736. { name: 's', type: 'float' },
  33737. { name: 't', type: 'float' }
  33738. ]
  33739. } );
  33740. const mx_bilerp_1 = /*#__PURE__*/ tslFn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  33741. const t = float( t_immutable ).toVar();
  33742. const s = float( s_immutable ).toVar();
  33743. const v3 = vec3( v3_immutable ).toVar();
  33744. const v2 = vec3( v2_immutable ).toVar();
  33745. const v1 = vec3( v1_immutable ).toVar();
  33746. const v0 = vec3( v0_immutable ).toVar();
  33747. const s1 = float( sub( 1.0, s ) ).toVar();
  33748. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  33749. } ).setLayout( {
  33750. name: 'mx_bilerp_1',
  33751. type: 'vec3',
  33752. inputs: [
  33753. { name: 'v0', type: 'vec3' },
  33754. { name: 'v1', type: 'vec3' },
  33755. { name: 'v2', type: 'vec3' },
  33756. { name: 'v3', type: 'vec3' },
  33757. { name: 's', type: 'float' },
  33758. { name: 't', type: 'float' }
  33759. ]
  33760. } );
  33761. const mx_bilerp = /*#__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  33762. 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 ] ) => {
  33763. const r = float( r_immutable ).toVar();
  33764. const t = float( t_immutable ).toVar();
  33765. const s = float( s_immutable ).toVar();
  33766. const v7 = float( v7_immutable ).toVar();
  33767. const v6 = float( v6_immutable ).toVar();
  33768. const v5 = float( v5_immutable ).toVar();
  33769. const v4 = float( v4_immutable ).toVar();
  33770. const v3 = float( v3_immutable ).toVar();
  33771. const v2 = float( v2_immutable ).toVar();
  33772. const v1 = float( v1_immutable ).toVar();
  33773. const v0 = float( v0_immutable ).toVar();
  33774. const s1 = float( sub( 1.0, s ) ).toVar();
  33775. const t1 = float( sub( 1.0, t ) ).toVar();
  33776. const r1 = float( sub( 1.0, r ) ).toVar();
  33777. 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 ) ) ) ) ) );
  33778. } ).setLayout( {
  33779. name: 'mx_trilerp_0',
  33780. type: 'float',
  33781. inputs: [
  33782. { name: 'v0', type: 'float' },
  33783. { name: 'v1', type: 'float' },
  33784. { name: 'v2', type: 'float' },
  33785. { name: 'v3', type: 'float' },
  33786. { name: 'v4', type: 'float' },
  33787. { name: 'v5', type: 'float' },
  33788. { name: 'v6', type: 'float' },
  33789. { name: 'v7', type: 'float' },
  33790. { name: 's', type: 'float' },
  33791. { name: 't', type: 'float' },
  33792. { name: 'r', type: 'float' }
  33793. ]
  33794. } );
  33795. 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 ] ) => {
  33796. const r = float( r_immutable ).toVar();
  33797. const t = float( t_immutable ).toVar();
  33798. const s = float( s_immutable ).toVar();
  33799. const v7 = vec3( v7_immutable ).toVar();
  33800. const v6 = vec3( v6_immutable ).toVar();
  33801. const v5 = vec3( v5_immutable ).toVar();
  33802. const v4 = vec3( v4_immutable ).toVar();
  33803. const v3 = vec3( v3_immutable ).toVar();
  33804. const v2 = vec3( v2_immutable ).toVar();
  33805. const v1 = vec3( v1_immutable ).toVar();
  33806. const v0 = vec3( v0_immutable ).toVar();
  33807. const s1 = float( sub( 1.0, s ) ).toVar();
  33808. const t1 = float( sub( 1.0, t ) ).toVar();
  33809. const r1 = float( sub( 1.0, r ) ).toVar();
  33810. 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 ) ) ) ) ) );
  33811. } ).setLayout( {
  33812. name: 'mx_trilerp_1',
  33813. type: 'vec3',
  33814. inputs: [
  33815. { name: 'v0', type: 'vec3' },
  33816. { name: 'v1', type: 'vec3' },
  33817. { name: 'v2', type: 'vec3' },
  33818. { name: 'v3', type: 'vec3' },
  33819. { name: 'v4', type: 'vec3' },
  33820. { name: 'v5', type: 'vec3' },
  33821. { name: 'v6', type: 'vec3' },
  33822. { name: 'v7', type: 'vec3' },
  33823. { name: 's', type: 'float' },
  33824. { name: 't', type: 'float' },
  33825. { name: 'r', type: 'float' }
  33826. ]
  33827. } );
  33828. const mx_trilerp = /*#__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  33829. const mx_gradient_float_0 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  33830. const y = float( y_immutable ).toVar();
  33831. const x = float( x_immutable ).toVar();
  33832. const hash = uint( hash_immutable ).toVar();
  33833. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  33834. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  33835. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  33836. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  33837. } ).setLayout( {
  33838. name: 'mx_gradient_float_0',
  33839. type: 'float',
  33840. inputs: [
  33841. { name: 'hash', type: 'uint' },
  33842. { name: 'x', type: 'float' },
  33843. { name: 'y', type: 'float' }
  33844. ]
  33845. } );
  33846. const mx_gradient_float_1 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  33847. const z = float( z_immutable ).toVar();
  33848. const y = float( y_immutable ).toVar();
  33849. const x = float( x_immutable ).toVar();
  33850. const hash = uint( hash_immutable ).toVar();
  33851. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  33852. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  33853. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  33854. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  33855. } ).setLayout( {
  33856. name: 'mx_gradient_float_1',
  33857. type: 'float',
  33858. inputs: [
  33859. { name: 'hash', type: 'uint' },
  33860. { name: 'x', type: 'float' },
  33861. { name: 'y', type: 'float' },
  33862. { name: 'z', type: 'float' }
  33863. ]
  33864. } );
  33865. const mx_gradient_float = /*#__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  33866. const mx_gradient_vec3_0 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  33867. const y = float( y_immutable ).toVar();
  33868. const x = float( x_immutable ).toVar();
  33869. const hash = uvec3( hash_immutable ).toVar();
  33870. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  33871. } ).setLayout( {
  33872. name: 'mx_gradient_vec3_0',
  33873. type: 'vec3',
  33874. inputs: [
  33875. { name: 'hash', type: 'uvec3' },
  33876. { name: 'x', type: 'float' },
  33877. { name: 'y', type: 'float' }
  33878. ]
  33879. } );
  33880. const mx_gradient_vec3_1 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  33881. const z = float( z_immutable ).toVar();
  33882. const y = float( y_immutable ).toVar();
  33883. const x = float( x_immutable ).toVar();
  33884. const hash = uvec3( hash_immutable ).toVar();
  33885. 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 ) );
  33886. } ).setLayout( {
  33887. name: 'mx_gradient_vec3_1',
  33888. type: 'vec3',
  33889. inputs: [
  33890. { name: 'hash', type: 'uvec3' },
  33891. { name: 'x', type: 'float' },
  33892. { name: 'y', type: 'float' },
  33893. { name: 'z', type: 'float' }
  33894. ]
  33895. } );
  33896. const mx_gradient_vec3 = /*#__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  33897. const mx_gradient_scale2d_0 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  33898. const v = float( v_immutable ).toVar();
  33899. return mul( 0.6616, v );
  33900. } ).setLayout( {
  33901. name: 'mx_gradient_scale2d_0',
  33902. type: 'float',
  33903. inputs: [
  33904. { name: 'v', type: 'float' }
  33905. ]
  33906. } );
  33907. const mx_gradient_scale3d_0 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  33908. const v = float( v_immutable ).toVar();
  33909. return mul( 0.9820, v );
  33910. } ).setLayout( {
  33911. name: 'mx_gradient_scale3d_0',
  33912. type: 'float',
  33913. inputs: [
  33914. { name: 'v', type: 'float' }
  33915. ]
  33916. } );
  33917. const mx_gradient_scale2d_1 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  33918. const v = vec3( v_immutable ).toVar();
  33919. return mul( 0.6616, v );
  33920. } ).setLayout( {
  33921. name: 'mx_gradient_scale2d_1',
  33922. type: 'vec3',
  33923. inputs: [
  33924. { name: 'v', type: 'vec3' }
  33925. ]
  33926. } );
  33927. const mx_gradient_scale2d = /*#__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  33928. const mx_gradient_scale3d_1 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  33929. const v = vec3( v_immutable ).toVar();
  33930. return mul( 0.9820, v );
  33931. } ).setLayout( {
  33932. name: 'mx_gradient_scale3d_1',
  33933. type: 'vec3',
  33934. inputs: [
  33935. { name: 'v', type: 'vec3' }
  33936. ]
  33937. } );
  33938. const mx_gradient_scale3d = /*#__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  33939. const mx_rotl32 = /*#__PURE__*/ tslFn( ( [ x_immutable, k_immutable ] ) => {
  33940. const k = int( k_immutable ).toVar();
  33941. const x = uint( x_immutable ).toVar();
  33942. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  33943. } ).setLayout( {
  33944. name: 'mx_rotl32',
  33945. type: 'uint',
  33946. inputs: [
  33947. { name: 'x', type: 'uint' },
  33948. { name: 'k', type: 'int' }
  33949. ]
  33950. } );
  33951. const mx_bjmix = /*#__PURE__*/ tslFn( ( [ a, b, c ] ) => {
  33952. a.subAssign( c );
  33953. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  33954. c.addAssign( b );
  33955. b.subAssign( a );
  33956. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  33957. a.addAssign( c );
  33958. c.subAssign( b );
  33959. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  33960. b.addAssign( a );
  33961. a.subAssign( c );
  33962. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  33963. c.addAssign( b );
  33964. b.subAssign( a );
  33965. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  33966. a.addAssign( c );
  33967. c.subAssign( b );
  33968. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  33969. b.addAssign( a );
  33970. } );
  33971. const mx_bjfinal = /*#__PURE__*/ tslFn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  33972. const c = uint( c_immutable ).toVar();
  33973. const b = uint( b_immutable ).toVar();
  33974. const a = uint( a_immutable ).toVar();
  33975. c.bitXorAssign( b );
  33976. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  33977. a.bitXorAssign( c );
  33978. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  33979. b.bitXorAssign( a );
  33980. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  33981. c.bitXorAssign( b );
  33982. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  33983. a.bitXorAssign( c );
  33984. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  33985. b.bitXorAssign( a );
  33986. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  33987. c.bitXorAssign( b );
  33988. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  33989. return c;
  33990. } ).setLayout( {
  33991. name: 'mx_bjfinal',
  33992. type: 'uint',
  33993. inputs: [
  33994. { name: 'a', type: 'uint' },
  33995. { name: 'b', type: 'uint' },
  33996. { name: 'c', type: 'uint' }
  33997. ]
  33998. } );
  33999. const mx_bits_to_01 = /*#__PURE__*/ tslFn( ( [ bits_immutable ] ) => {
  34000. const bits = uint( bits_immutable ).toVar();
  34001. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  34002. } ).setLayout( {
  34003. name: 'mx_bits_to_01',
  34004. type: 'float',
  34005. inputs: [
  34006. { name: 'bits', type: 'uint' }
  34007. ]
  34008. } );
  34009. const mx_fade = /*#__PURE__*/ tslFn( ( [ t_immutable ] ) => {
  34010. const t = float( t_immutable ).toVar();
  34011. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  34012. } ).setLayout( {
  34013. name: 'mx_fade',
  34014. type: 'float',
  34015. inputs: [
  34016. { name: 't', type: 'float' }
  34017. ]
  34018. } );
  34019. const mx_hash_int_0 = /*#__PURE__*/ tslFn( ( [ x_immutable ] ) => {
  34020. const x = int( x_immutable ).toVar();
  34021. const len = uint( uint( 1 ) ).toVar();
  34022. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  34023. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  34024. } ).setLayout( {
  34025. name: 'mx_hash_int_0',
  34026. type: 'uint',
  34027. inputs: [
  34028. { name: 'x', type: 'int' }
  34029. ]
  34030. } );
  34031. const mx_hash_int_1 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable ] ) => {
  34032. const y = int( y_immutable ).toVar();
  34033. const x = int( x_immutable ).toVar();
  34034. const len = uint( uint( 2 ) ).toVar();
  34035. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34036. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34037. a.addAssign( uint( x ) );
  34038. b.addAssign( uint( y ) );
  34039. return mx_bjfinal( a, b, c );
  34040. } ).setLayout( {
  34041. name: 'mx_hash_int_1',
  34042. type: 'uint',
  34043. inputs: [
  34044. { name: 'x', type: 'int' },
  34045. { name: 'y', type: 'int' }
  34046. ]
  34047. } );
  34048. const mx_hash_int_2 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  34049. const z = int( z_immutable ).toVar();
  34050. const y = int( y_immutable ).toVar();
  34051. const x = int( x_immutable ).toVar();
  34052. const len = uint( uint( 3 ) ).toVar();
  34053. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34054. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34055. a.addAssign( uint( x ) );
  34056. b.addAssign( uint( y ) );
  34057. c.addAssign( uint( z ) );
  34058. return mx_bjfinal( a, b, c );
  34059. } ).setLayout( {
  34060. name: 'mx_hash_int_2',
  34061. type: 'uint',
  34062. inputs: [
  34063. { name: 'x', type: 'int' },
  34064. { name: 'y', type: 'int' },
  34065. { name: 'z', type: 'int' }
  34066. ]
  34067. } );
  34068. const mx_hash_int_3 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  34069. const xx = int( xx_immutable ).toVar();
  34070. const z = int( z_immutable ).toVar();
  34071. const y = int( y_immutable ).toVar();
  34072. const x = int( x_immutable ).toVar();
  34073. const len = uint( uint( 4 ) ).toVar();
  34074. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34075. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34076. a.addAssign( uint( x ) );
  34077. b.addAssign( uint( y ) );
  34078. c.addAssign( uint( z ) );
  34079. mx_bjmix( a, b, c );
  34080. a.addAssign( uint( xx ) );
  34081. return mx_bjfinal( a, b, c );
  34082. } ).setLayout( {
  34083. name: 'mx_hash_int_3',
  34084. type: 'uint',
  34085. inputs: [
  34086. { name: 'x', type: 'int' },
  34087. { name: 'y', type: 'int' },
  34088. { name: 'z', type: 'int' },
  34089. { name: 'xx', type: 'int' }
  34090. ]
  34091. } );
  34092. const mx_hash_int_4 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  34093. const yy = int( yy_immutable ).toVar();
  34094. const xx = int( xx_immutable ).toVar();
  34095. const z = int( z_immutable ).toVar();
  34096. const y = int( y_immutable ).toVar();
  34097. const x = int( x_immutable ).toVar();
  34098. const len = uint( uint( 5 ) ).toVar();
  34099. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34100. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34101. a.addAssign( uint( x ) );
  34102. b.addAssign( uint( y ) );
  34103. c.addAssign( uint( z ) );
  34104. mx_bjmix( a, b, c );
  34105. a.addAssign( uint( xx ) );
  34106. b.addAssign( uint( yy ) );
  34107. return mx_bjfinal( a, b, c );
  34108. } ).setLayout( {
  34109. name: 'mx_hash_int_4',
  34110. type: 'uint',
  34111. inputs: [
  34112. { name: 'x', type: 'int' },
  34113. { name: 'y', type: 'int' },
  34114. { name: 'z', type: 'int' },
  34115. { name: 'xx', type: 'int' },
  34116. { name: 'yy', type: 'int' }
  34117. ]
  34118. } );
  34119. 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 ] );
  34120. const mx_hash_vec3_0 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable ] ) => {
  34121. const y = int( y_immutable ).toVar();
  34122. const x = int( x_immutable ).toVar();
  34123. const h = uint( mx_hash_int( x, y ) ).toVar();
  34124. const result = uvec3().toVar();
  34125. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  34126. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  34127. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  34128. return result;
  34129. } ).setLayout( {
  34130. name: 'mx_hash_vec3_0',
  34131. type: 'uvec3',
  34132. inputs: [
  34133. { name: 'x', type: 'int' },
  34134. { name: 'y', type: 'int' }
  34135. ]
  34136. } );
  34137. const mx_hash_vec3_1 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  34138. const z = int( z_immutable ).toVar();
  34139. const y = int( y_immutable ).toVar();
  34140. const x = int( x_immutable ).toVar();
  34141. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  34142. const result = uvec3().toVar();
  34143. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  34144. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  34145. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  34146. return result;
  34147. } ).setLayout( {
  34148. name: 'mx_hash_vec3_1',
  34149. type: 'uvec3',
  34150. inputs: [
  34151. { name: 'x', type: 'int' },
  34152. { name: 'y', type: 'int' },
  34153. { name: 'z', type: 'int' }
  34154. ]
  34155. } );
  34156. const mx_hash_vec3 = /*#__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  34157. const mx_perlin_noise_float_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34158. const p = vec2( p_immutable ).toVar();
  34159. const X = int().toVar(), Y = int().toVar();
  34160. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34161. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34162. const u = float( mx_fade( fx ) ).toVar();
  34163. const v = float( mx_fade( fy ) ).toVar();
  34164. 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();
  34165. return mx_gradient_scale2d( result );
  34166. } ).setLayout( {
  34167. name: 'mx_perlin_noise_float_0',
  34168. type: 'float',
  34169. inputs: [
  34170. { name: 'p', type: 'vec2' }
  34171. ]
  34172. } );
  34173. const mx_perlin_noise_float_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34174. const p = vec3( p_immutable ).toVar();
  34175. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34176. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34177. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34178. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  34179. const u = float( mx_fade( fx ) ).toVar();
  34180. const v = float( mx_fade( fy ) ).toVar();
  34181. const w = float( mx_fade( fz ) ).toVar();
  34182. 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();
  34183. return mx_gradient_scale3d( result );
  34184. } ).setLayout( {
  34185. name: 'mx_perlin_noise_float_1',
  34186. type: 'float',
  34187. inputs: [
  34188. { name: 'p', type: 'vec3' }
  34189. ]
  34190. } );
  34191. const mx_perlin_noise_float = /*#__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  34192. const mx_perlin_noise_vec3_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34193. const p = vec2( p_immutable ).toVar();
  34194. const X = int().toVar(), Y = int().toVar();
  34195. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34196. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34197. const u = float( mx_fade( fx ) ).toVar();
  34198. const v = float( mx_fade( fy ) ).toVar();
  34199. 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();
  34200. return mx_gradient_scale2d( result );
  34201. } ).setLayout( {
  34202. name: 'mx_perlin_noise_vec3_0',
  34203. type: 'vec3',
  34204. inputs: [
  34205. { name: 'p', type: 'vec2' }
  34206. ]
  34207. } );
  34208. const mx_perlin_noise_vec3_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34209. const p = vec3( p_immutable ).toVar();
  34210. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34211. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34212. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34213. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  34214. const u = float( mx_fade( fx ) ).toVar();
  34215. const v = float( mx_fade( fy ) ).toVar();
  34216. const w = float( mx_fade( fz ) ).toVar();
  34217. 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();
  34218. return mx_gradient_scale3d( result );
  34219. } ).setLayout( {
  34220. name: 'mx_perlin_noise_vec3_1',
  34221. type: 'vec3',
  34222. inputs: [
  34223. { name: 'p', type: 'vec3' }
  34224. ]
  34225. } );
  34226. const mx_perlin_noise_vec3 = /*#__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  34227. const mx_cell_noise_float_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34228. const p = float( p_immutable ).toVar();
  34229. const ix = int( mx_floor( p ) ).toVar();
  34230. return mx_bits_to_01( mx_hash_int( ix ) );
  34231. } ).setLayout( {
  34232. name: 'mx_cell_noise_float_0',
  34233. type: 'float',
  34234. inputs: [
  34235. { name: 'p', type: 'float' }
  34236. ]
  34237. } );
  34238. const mx_cell_noise_float_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34239. const p = vec2( p_immutable ).toVar();
  34240. const ix = int( mx_floor( p.x ) ).toVar();
  34241. const iy = int( mx_floor( p.y ) ).toVar();
  34242. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  34243. } ).setLayout( {
  34244. name: 'mx_cell_noise_float_1',
  34245. type: 'float',
  34246. inputs: [
  34247. { name: 'p', type: 'vec2' }
  34248. ]
  34249. } );
  34250. const mx_cell_noise_float_2 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34251. const p = vec3( p_immutable ).toVar();
  34252. const ix = int( mx_floor( p.x ) ).toVar();
  34253. const iy = int( mx_floor( p.y ) ).toVar();
  34254. const iz = int( mx_floor( p.z ) ).toVar();
  34255. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  34256. } ).setLayout( {
  34257. name: 'mx_cell_noise_float_2',
  34258. type: 'float',
  34259. inputs: [
  34260. { name: 'p', type: 'vec3' }
  34261. ]
  34262. } );
  34263. const mx_cell_noise_float_3 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34264. const p = vec4( p_immutable ).toVar();
  34265. const ix = int( mx_floor( p.x ) ).toVar();
  34266. const iy = int( mx_floor( p.y ) ).toVar();
  34267. const iz = int( mx_floor( p.z ) ).toVar();
  34268. const iw = int( mx_floor( p.w ) ).toVar();
  34269. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  34270. } ).setLayout( {
  34271. name: 'mx_cell_noise_float_3',
  34272. type: 'float',
  34273. inputs: [
  34274. { name: 'p', type: 'vec4' }
  34275. ]
  34276. } );
  34277. 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 ] );
  34278. const mx_cell_noise_vec3_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34279. const p = float( p_immutable ).toVar();
  34280. const ix = int( mx_floor( p ) ).toVar();
  34281. 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 ) ) ) );
  34282. } ).setLayout( {
  34283. name: 'mx_cell_noise_vec3_0',
  34284. type: 'vec3',
  34285. inputs: [
  34286. { name: 'p', type: 'float' }
  34287. ]
  34288. } );
  34289. const mx_cell_noise_vec3_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34290. const p = vec2( p_immutable ).toVar();
  34291. const ix = int( mx_floor( p.x ) ).toVar();
  34292. const iy = int( mx_floor( p.y ) ).toVar();
  34293. 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 ) ) ) );
  34294. } ).setLayout( {
  34295. name: 'mx_cell_noise_vec3_1',
  34296. type: 'vec3',
  34297. inputs: [
  34298. { name: 'p', type: 'vec2' }
  34299. ]
  34300. } );
  34301. const mx_cell_noise_vec3_2 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34302. const p = vec3( p_immutable ).toVar();
  34303. const ix = int( mx_floor( p.x ) ).toVar();
  34304. const iy = int( mx_floor( p.y ) ).toVar();
  34305. const iz = int( mx_floor( p.z ) ).toVar();
  34306. 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 ) ) ) );
  34307. } ).setLayout( {
  34308. name: 'mx_cell_noise_vec3_2',
  34309. type: 'vec3',
  34310. inputs: [
  34311. { name: 'p', type: 'vec3' }
  34312. ]
  34313. } );
  34314. const mx_cell_noise_vec3_3 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34315. const p = vec4( p_immutable ).toVar();
  34316. const ix = int( mx_floor( p.x ) ).toVar();
  34317. const iy = int( mx_floor( p.y ) ).toVar();
  34318. const iz = int( mx_floor( p.z ) ).toVar();
  34319. const iw = int( mx_floor( p.w ) ).toVar();
  34320. 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 ) ) ) );
  34321. } ).setLayout( {
  34322. name: 'mx_cell_noise_vec3_3',
  34323. type: 'vec3',
  34324. inputs: [
  34325. { name: 'p', type: 'vec4' }
  34326. ]
  34327. } );
  34328. 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 ] );
  34329. const mx_fractal_noise_float$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34330. const diminish = float( diminish_immutable ).toVar();
  34331. const lacunarity = float( lacunarity_immutable ).toVar();
  34332. const octaves = int( octaves_immutable ).toVar();
  34333. const p = vec3( p_immutable ).toVar();
  34334. const result = float( 0.0 ).toVar();
  34335. const amplitude = float( 1.0 ).toVar();
  34336. loop( octaves, () => {
  34337. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  34338. amplitude.mulAssign( diminish );
  34339. p.mulAssign( lacunarity );
  34340. } );
  34341. return result;
  34342. } ).setLayout( {
  34343. name: 'mx_fractal_noise_float',
  34344. type: 'float',
  34345. inputs: [
  34346. { name: 'p', type: 'vec3' },
  34347. { name: 'octaves', type: 'int' },
  34348. { name: 'lacunarity', type: 'float' },
  34349. { name: 'diminish', type: 'float' }
  34350. ]
  34351. } );
  34352. const mx_fractal_noise_vec3$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34353. const diminish = float( diminish_immutable ).toVar();
  34354. const lacunarity = float( lacunarity_immutable ).toVar();
  34355. const octaves = int( octaves_immutable ).toVar();
  34356. const p = vec3( p_immutable ).toVar();
  34357. const result = vec3( 0.0 ).toVar();
  34358. const amplitude = float( 1.0 ).toVar();
  34359. loop( octaves, () => {
  34360. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  34361. amplitude.mulAssign( diminish );
  34362. p.mulAssign( lacunarity );
  34363. } );
  34364. return result;
  34365. } ).setLayout( {
  34366. name: 'mx_fractal_noise_vec3',
  34367. type: 'vec3',
  34368. inputs: [
  34369. { name: 'p', type: 'vec3' },
  34370. { name: 'octaves', type: 'int' },
  34371. { name: 'lacunarity', type: 'float' },
  34372. { name: 'diminish', type: 'float' }
  34373. ]
  34374. } );
  34375. const mx_fractal_noise_vec2$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34376. const diminish = float( diminish_immutable ).toVar();
  34377. const lacunarity = float( lacunarity_immutable ).toVar();
  34378. const octaves = int( octaves_immutable ).toVar();
  34379. const p = vec3( p_immutable ).toVar();
  34380. 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 ) );
  34381. } ).setLayout( {
  34382. name: 'mx_fractal_noise_vec2',
  34383. type: 'vec2',
  34384. inputs: [
  34385. { name: 'p', type: 'vec3' },
  34386. { name: 'octaves', type: 'int' },
  34387. { name: 'lacunarity', type: 'float' },
  34388. { name: 'diminish', type: 'float' }
  34389. ]
  34390. } );
  34391. const mx_fractal_noise_vec4$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34392. const diminish = float( diminish_immutable ).toVar();
  34393. const lacunarity = float( lacunarity_immutable ).toVar();
  34394. const octaves = int( octaves_immutable ).toVar();
  34395. const p = vec3( p_immutable ).toVar();
  34396. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  34397. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  34398. return vec4( c, f );
  34399. } ).setLayout( {
  34400. name: 'mx_fractal_noise_vec4',
  34401. type: 'vec4',
  34402. inputs: [
  34403. { name: 'p', type: 'vec3' },
  34404. { name: 'octaves', type: 'int' },
  34405. { name: 'lacunarity', type: 'float' },
  34406. { name: 'diminish', type: 'float' }
  34407. ]
  34408. } );
  34409. const mx_worley_distance_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  34410. const metric = int( metric_immutable ).toVar();
  34411. const jitter = float( jitter_immutable ).toVar();
  34412. const yoff = int( yoff_immutable ).toVar();
  34413. const xoff = int( xoff_immutable ).toVar();
  34414. const y = int( y_immutable ).toVar();
  34415. const x = int( x_immutable ).toVar();
  34416. const p = vec2( p_immutable ).toVar();
  34417. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  34418. const off = vec2( tmp.x, tmp.y ).toVar();
  34419. off.subAssign( 0.5 );
  34420. off.mulAssign( jitter );
  34421. off.addAssign( 0.5 );
  34422. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  34423. const diff = vec2( cellpos.sub( p ) ).toVar();
  34424. If( metric.equal( int( 2 ) ), () => {
  34425. return abs( diff.x ).add( abs( diff.y ) );
  34426. } );
  34427. If( metric.equal( int( 3 ) ), () => {
  34428. return max$1( abs( diff.x ), abs( diff.y ) );
  34429. } );
  34430. return dot( diff, diff );
  34431. } ).setLayout( {
  34432. name: 'mx_worley_distance_0',
  34433. type: 'float',
  34434. inputs: [
  34435. { name: 'p', type: 'vec2' },
  34436. { name: 'x', type: 'int' },
  34437. { name: 'y', type: 'int' },
  34438. { name: 'xoff', type: 'int' },
  34439. { name: 'yoff', type: 'int' },
  34440. { name: 'jitter', type: 'float' },
  34441. { name: 'metric', type: 'int' }
  34442. ]
  34443. } );
  34444. 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 ] ) => {
  34445. const metric = int( metric_immutable ).toVar();
  34446. const jitter = float( jitter_immutable ).toVar();
  34447. const zoff = int( zoff_immutable ).toVar();
  34448. const yoff = int( yoff_immutable ).toVar();
  34449. const xoff = int( xoff_immutable ).toVar();
  34450. const z = int( z_immutable ).toVar();
  34451. const y = int( y_immutable ).toVar();
  34452. const x = int( x_immutable ).toVar();
  34453. const p = vec3( p_immutable ).toVar();
  34454. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  34455. off.subAssign( 0.5 );
  34456. off.mulAssign( jitter );
  34457. off.addAssign( 0.5 );
  34458. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  34459. const diff = vec3( cellpos.sub( p ) ).toVar();
  34460. If( metric.equal( int( 2 ) ), () => {
  34461. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  34462. } );
  34463. If( metric.equal( int( 3 ) ), () => {
  34464. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  34465. } );
  34466. return dot( diff, diff );
  34467. } ).setLayout( {
  34468. name: 'mx_worley_distance_1',
  34469. type: 'float',
  34470. inputs: [
  34471. { name: 'p', type: 'vec3' },
  34472. { name: 'x', type: 'int' },
  34473. { name: 'y', type: 'int' },
  34474. { name: 'z', type: 'int' },
  34475. { name: 'xoff', type: 'int' },
  34476. { name: 'yoff', type: 'int' },
  34477. { name: 'zoff', type: 'int' },
  34478. { name: 'jitter', type: 'float' },
  34479. { name: 'metric', type: 'int' }
  34480. ]
  34481. } );
  34482. const mx_worley_distance = /*#__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  34483. const mx_worley_noise_float_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34484. const metric = int( metric_immutable ).toVar();
  34485. const jitter = float( jitter_immutable ).toVar();
  34486. const p = vec2( p_immutable ).toVar();
  34487. const X = int().toVar(), Y = int().toVar();
  34488. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34489. const sqdist = float( 1e6 ).toVar();
  34490. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34491. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34492. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34493. sqdist.assign( min$1( sqdist, dist ) );
  34494. } );
  34495. } );
  34496. If( metric.equal( int( 0 ) ), () => {
  34497. sqdist.assign( sqrt( sqdist ) );
  34498. } );
  34499. return sqdist;
  34500. } ).setLayout( {
  34501. name: 'mx_worley_noise_float_0',
  34502. type: 'float',
  34503. inputs: [
  34504. { name: 'p', type: 'vec2' },
  34505. { name: 'jitter', type: 'float' },
  34506. { name: 'metric', type: 'int' }
  34507. ]
  34508. } );
  34509. const mx_worley_noise_vec2_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34510. const metric = int( metric_immutable ).toVar();
  34511. const jitter = float( jitter_immutable ).toVar();
  34512. const p = vec2( p_immutable ).toVar();
  34513. const X = int().toVar(), Y = int().toVar();
  34514. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34515. const sqdist = vec2( 1e6, 1e6 ).toVar();
  34516. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34517. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34518. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34519. If( dist.lessThan( sqdist.x ), () => {
  34520. sqdist.y.assign( sqdist.x );
  34521. sqdist.x.assign( dist );
  34522. } ).elseif( dist.lessThan( sqdist.y ), () => {
  34523. sqdist.y.assign( dist );
  34524. } );
  34525. } );
  34526. } );
  34527. If( metric.equal( int( 0 ) ), () => {
  34528. sqdist.assign( sqrt( sqdist ) );
  34529. } );
  34530. return sqdist;
  34531. } ).setLayout( {
  34532. name: 'mx_worley_noise_vec2_0',
  34533. type: 'vec2',
  34534. inputs: [
  34535. { name: 'p', type: 'vec2' },
  34536. { name: 'jitter', type: 'float' },
  34537. { name: 'metric', type: 'int' }
  34538. ]
  34539. } );
  34540. const mx_worley_noise_vec3_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34541. const metric = int( metric_immutable ).toVar();
  34542. const jitter = float( jitter_immutable ).toVar();
  34543. const p = vec2( p_immutable ).toVar();
  34544. const X = int().toVar(), Y = int().toVar();
  34545. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34546. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  34547. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34548. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34549. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34550. If( dist.lessThan( sqdist.x ), () => {
  34551. sqdist.z.assign( sqdist.y );
  34552. sqdist.y.assign( sqdist.x );
  34553. sqdist.x.assign( dist );
  34554. } ).elseif( dist.lessThan( sqdist.y ), () => {
  34555. sqdist.z.assign( sqdist.y );
  34556. sqdist.y.assign( dist );
  34557. } ).elseif( dist.lessThan( sqdist.z ), () => {
  34558. sqdist.z.assign( dist );
  34559. } );
  34560. } );
  34561. } );
  34562. If( metric.equal( int( 0 ) ), () => {
  34563. sqdist.assign( sqrt( sqdist ) );
  34564. } );
  34565. return sqdist;
  34566. } ).setLayout( {
  34567. name: 'mx_worley_noise_vec3_0',
  34568. type: 'vec3',
  34569. inputs: [
  34570. { name: 'p', type: 'vec2' },
  34571. { name: 'jitter', type: 'float' },
  34572. { name: 'metric', type: 'int' }
  34573. ]
  34574. } );
  34575. const mx_worley_noise_float_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34576. const metric = int( metric_immutable ).toVar();
  34577. const jitter = float( jitter_immutable ).toVar();
  34578. const p = vec3( p_immutable ).toVar();
  34579. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34580. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34581. const sqdist = float( 1e6 ).toVar();
  34582. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34583. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34584. loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34585. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34586. sqdist.assign( min$1( sqdist, dist ) );
  34587. } );
  34588. } );
  34589. } );
  34590. If( metric.equal( int( 0 ) ), () => {
  34591. sqdist.assign( sqrt( sqdist ) );
  34592. } );
  34593. return sqdist;
  34594. } ).setLayout( {
  34595. name: 'mx_worley_noise_float_1',
  34596. type: 'float',
  34597. inputs: [
  34598. { name: 'p', type: 'vec3' },
  34599. { name: 'jitter', type: 'float' },
  34600. { name: 'metric', type: 'int' }
  34601. ]
  34602. } );
  34603. const mx_worley_noise_float$1 = /*#__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  34604. const mx_worley_noise_vec2_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34605. const metric = int( metric_immutable ).toVar();
  34606. const jitter = float( jitter_immutable ).toVar();
  34607. const p = vec3( p_immutable ).toVar();
  34608. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34609. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34610. const sqdist = vec2( 1e6, 1e6 ).toVar();
  34611. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34612. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34613. loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34614. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34615. If( dist.lessThan( sqdist.x ), () => {
  34616. sqdist.y.assign( sqdist.x );
  34617. sqdist.x.assign( dist );
  34618. } ).elseif( dist.lessThan( sqdist.y ), () => {
  34619. sqdist.y.assign( dist );
  34620. } );
  34621. } );
  34622. } );
  34623. } );
  34624. If( metric.equal( int( 0 ) ), () => {
  34625. sqdist.assign( sqrt( sqdist ) );
  34626. } );
  34627. return sqdist;
  34628. } ).setLayout( {
  34629. name: 'mx_worley_noise_vec2_1',
  34630. type: 'vec2',
  34631. inputs: [
  34632. { name: 'p', type: 'vec3' },
  34633. { name: 'jitter', type: 'float' },
  34634. { name: 'metric', type: 'int' }
  34635. ]
  34636. } );
  34637. const mx_worley_noise_vec2$1 = /*#__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  34638. const mx_worley_noise_vec3_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34639. const metric = int( metric_immutable ).toVar();
  34640. const jitter = float( jitter_immutable ).toVar();
  34641. const p = vec3( p_immutable ).toVar();
  34642. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34643. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34644. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  34645. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34646. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34647. loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34648. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34649. If( dist.lessThan( sqdist.x ), () => {
  34650. sqdist.z.assign( sqdist.y );
  34651. sqdist.y.assign( sqdist.x );
  34652. sqdist.x.assign( dist );
  34653. } ).elseif( dist.lessThan( sqdist.y ), () => {
  34654. sqdist.z.assign( sqdist.y );
  34655. sqdist.y.assign( dist );
  34656. } ).elseif( dist.lessThan( sqdist.z ), () => {
  34657. sqdist.z.assign( dist );
  34658. } );
  34659. } );
  34660. } );
  34661. } );
  34662. If( metric.equal( int( 0 ) ), () => {
  34663. sqdist.assign( sqrt( sqdist ) );
  34664. } );
  34665. return sqdist;
  34666. } ).setLayout( {
  34667. name: 'mx_worley_noise_vec3_1',
  34668. type: 'vec3',
  34669. inputs: [
  34670. { name: 'p', type: 'vec3' },
  34671. { name: 'jitter', type: 'float' },
  34672. { name: 'metric', type: 'int' }
  34673. ]
  34674. } );
  34675. const mx_worley_noise_vec3$1 = /*#__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  34676. // Three.js Transpiler
  34677. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  34678. const mx_hsvtorgb = /*#__PURE__*/ tslFn( ( [ hsv_immutable ] ) => {
  34679. const hsv = vec3( hsv_immutable ).toVar();
  34680. const h = float( hsv.x ).toVar();
  34681. const s = float( hsv.y ).toVar();
  34682. const v = float( hsv.z ).toVar();
  34683. If( s.lessThan( 0.0001 ), () => {
  34684. return vec3( v, v, v );
  34685. } ).else( () => {
  34686. h.assign( mul( 6.0, h.sub( floor( h ) ) ) );
  34687. const hi = int( trunc( h ) ).toVar();
  34688. const f = float( h.sub( float( hi ) ) ).toVar();
  34689. const p = float( v.mul( sub( 1.0, s ) ) ).toVar();
  34690. const q = float( v.mul( sub( 1.0, s.mul( f ) ) ) ).toVar();
  34691. const t = float( v.mul( sub( 1.0, s.mul( sub( 1.0, f ) ) ) ) ).toVar();
  34692. If( hi.equal( int( 0 ) ), () => {
  34693. return vec3( v, t, p );
  34694. } ).elseif( hi.equal( int( 1 ) ), () => {
  34695. return vec3( q, v, p );
  34696. } ).elseif( hi.equal( int( 2 ) ), () => {
  34697. return vec3( p, v, t );
  34698. } ).elseif( hi.equal( int( 3 ) ), () => {
  34699. return vec3( p, q, v );
  34700. } ).elseif( hi.equal( int( 4 ) ), () => {
  34701. return vec3( t, p, v );
  34702. } );
  34703. return vec3( v, p, q );
  34704. } );
  34705. } ).setLayout( {
  34706. name: 'mx_hsvtorgb',
  34707. type: 'vec3',
  34708. inputs: [
  34709. { name: 'hsv', type: 'vec3' }
  34710. ]
  34711. } );
  34712. const mx_rgbtohsv = /*#__PURE__*/ tslFn( ( [ c_immutable ] ) => {
  34713. const c = vec3( c_immutable ).toVar();
  34714. const r = float( c.x ).toVar();
  34715. const g = float( c.y ).toVar();
  34716. const b = float( c.z ).toVar();
  34717. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  34718. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  34719. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  34720. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  34721. v.assign( maxcomp );
  34722. If( maxcomp.greaterThan( 0.0 ), () => {
  34723. s.assign( delta.div( maxcomp ) );
  34724. } ).else( () => {
  34725. s.assign( 0.0 );
  34726. } );
  34727. If( s.lessThanEqual( 0.0 ), () => {
  34728. h.assign( 0.0 );
  34729. } ).else( () => {
  34730. If( r.greaterThanEqual( maxcomp ), () => {
  34731. h.assign( g.sub( b ).div( delta ) );
  34732. } ).elseif( g.greaterThanEqual( maxcomp ), () => {
  34733. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  34734. } ).else( () => {
  34735. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  34736. } );
  34737. h.mulAssign( 1.0 / 6.0 );
  34738. If( h.lessThan( 0.0 ), () => {
  34739. h.addAssign( 1.0 );
  34740. } );
  34741. } );
  34742. return vec3( h, s, v );
  34743. } ).setLayout( {
  34744. name: 'mx_rgbtohsv',
  34745. type: 'vec3',
  34746. inputs: [
  34747. { name: 'c', type: 'vec3' }
  34748. ]
  34749. } );
  34750. // Three.js Transpiler
  34751. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  34752. const mx_srgb_texture_to_lin_rec709 = /*#__PURE__*/ tslFn( ( [ color_immutable ] ) => {
  34753. const color = vec3( color_immutable ).toVar();
  34754. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  34755. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  34756. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  34757. return mix( linSeg, powSeg, isAbove );
  34758. } ).setLayout( {
  34759. name: 'mx_srgb_texture_to_lin_rec709',
  34760. type: 'vec3',
  34761. inputs: [
  34762. { name: 'color', type: 'vec3' }
  34763. ]
  34764. } );
  34765. const mx_aastep = ( threshold, value ) => {
  34766. threshold = float( threshold );
  34767. value = float( value );
  34768. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  34769. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  34770. };
  34771. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  34772. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  34773. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  34774. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  34775. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  34776. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  34777. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  34778. const mx_safepower = ( in1, in2 = 1 ) => {
  34779. in1 = float( in1 );
  34780. return in1.abs().pow( in2 ).mul( in1.sign() );
  34781. };
  34782. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  34783. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  34784. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  34785. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  34786. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  34787. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  34788. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  34789. return noise_vec4.mul( amplitude ).add( pivot );
  34790. };
  34791. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  34792. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  34793. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  34794. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  34795. 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 );
  34796. 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 );
  34797. 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 );
  34798. 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 );
  34799. function painterSortStable( a, b ) {
  34800. if ( a.groupOrder !== b.groupOrder ) {
  34801. return a.groupOrder - b.groupOrder;
  34802. } else if ( a.renderOrder !== b.renderOrder ) {
  34803. return a.renderOrder - b.renderOrder;
  34804. } else if ( a.material.id !== b.material.id ) {
  34805. return a.material.id - b.material.id;
  34806. } else if ( a.z !== b.z ) {
  34807. return a.z - b.z;
  34808. } else {
  34809. return a.id - b.id;
  34810. }
  34811. }
  34812. function reversePainterSortStable( a, b ) {
  34813. if ( a.groupOrder !== b.groupOrder ) {
  34814. return a.groupOrder - b.groupOrder;
  34815. } else if ( a.renderOrder !== b.renderOrder ) {
  34816. return a.renderOrder - b.renderOrder;
  34817. } else if ( a.z !== b.z ) {
  34818. return b.z - a.z;
  34819. } else {
  34820. return a.id - b.id;
  34821. }
  34822. }
  34823. class RenderList {
  34824. constructor() {
  34825. this.renderItems = [];
  34826. this.renderItemsIndex = 0;
  34827. this.opaque = [];
  34828. this.transparent = [];
  34829. this.bundles = [];
  34830. this.lightsNode = new LightsNode( [] );
  34831. this.lightsArray = [];
  34832. this.occlusionQueryCount = 0;
  34833. }
  34834. begin() {
  34835. this.renderItemsIndex = 0;
  34836. this.opaque.length = 0;
  34837. this.transparent.length = 0;
  34838. this.bundles.length = 0;
  34839. this.lightsArray.length = 0;
  34840. this.occlusionQueryCount = 0;
  34841. return this;
  34842. }
  34843. getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  34844. let renderItem = this.renderItems[ this.renderItemsIndex ];
  34845. if ( renderItem === undefined ) {
  34846. renderItem = {
  34847. id: object.id,
  34848. object: object,
  34849. geometry: geometry,
  34850. material: material,
  34851. groupOrder: groupOrder,
  34852. renderOrder: object.renderOrder,
  34853. z: z,
  34854. group: group
  34855. };
  34856. this.renderItems[ this.renderItemsIndex ] = renderItem;
  34857. } else {
  34858. renderItem.id = object.id;
  34859. renderItem.object = object;
  34860. renderItem.geometry = geometry;
  34861. renderItem.material = material;
  34862. renderItem.groupOrder = groupOrder;
  34863. renderItem.renderOrder = object.renderOrder;
  34864. renderItem.z = z;
  34865. renderItem.group = group;
  34866. }
  34867. this.renderItemsIndex ++;
  34868. return renderItem;
  34869. }
  34870. push( object, geometry, material, groupOrder, z, group ) {
  34871. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  34872. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  34873. ( material.transparent === true || material.transmission > 0 ? this.transparent : this.opaque ).push( renderItem );
  34874. }
  34875. unshift( object, geometry, material, groupOrder, z, group ) {
  34876. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  34877. ( material.transparent === true ? this.transparent : this.opaque ).unshift( renderItem );
  34878. }
  34879. pushBundle( group ) {
  34880. this.bundles.push( group );
  34881. }
  34882. pushLight( light ) {
  34883. this.lightsArray.push( light );
  34884. }
  34885. getLightsNode() {
  34886. return this.lightsNode.fromLights( this.lightsArray );
  34887. }
  34888. sort( customOpaqueSort, customTransparentSort ) {
  34889. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  34890. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  34891. }
  34892. finish() {
  34893. // update lights
  34894. this.lightsNode.fromLights( this.lightsArray );
  34895. // Clear references from inactive renderItems in the list
  34896. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  34897. const renderItem = this.renderItems[ i ];
  34898. if ( renderItem.id === null ) break;
  34899. renderItem.id = null;
  34900. renderItem.object = null;
  34901. renderItem.geometry = null;
  34902. renderItem.material = null;
  34903. renderItem.groupOrder = null;
  34904. renderItem.renderOrder = null;
  34905. renderItem.z = null;
  34906. renderItem.group = null;
  34907. }
  34908. }
  34909. }
  34910. class RenderLists {
  34911. constructor() {
  34912. this.lists = new ChainMap();
  34913. }
  34914. get( scene, camera ) {
  34915. const lists = this.lists;
  34916. const keys = [ scene, camera ];
  34917. let list = lists.get( keys );
  34918. if ( list === undefined ) {
  34919. list = new RenderList();
  34920. lists.set( keys, list );
  34921. }
  34922. return list;
  34923. }
  34924. dispose() {
  34925. this.lists = new ChainMap();
  34926. }
  34927. }
  34928. let id$2 = 0;
  34929. class RenderContext {
  34930. constructor() {
  34931. this.id = id$2 ++;
  34932. this.color = true;
  34933. this.clearColor = true;
  34934. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  34935. this.depth = true;
  34936. this.clearDepth = true;
  34937. this.clearDepthValue = 1;
  34938. this.stencil = false;
  34939. this.clearStencil = true;
  34940. this.clearStencilValue = 1;
  34941. this.viewport = false;
  34942. this.viewportValue = new Vector4();
  34943. this.scissor = false;
  34944. this.scissorValue = new Vector4();
  34945. this.textures = null;
  34946. this.depthTexture = null;
  34947. this.activeCubeFace = 0;
  34948. this.sampleCount = 1;
  34949. this.width = 0;
  34950. this.height = 0;
  34951. this.isRenderContext = true;
  34952. }
  34953. }
  34954. class RenderContexts {
  34955. constructor() {
  34956. this.chainMaps = {};
  34957. }
  34958. get( scene, camera, renderTarget = null ) {
  34959. const chainKey = [ scene, camera ];
  34960. let attachmentState;
  34961. if ( renderTarget === null ) {
  34962. attachmentState = 'default';
  34963. } else {
  34964. const format = renderTarget.texture.format;
  34965. const count = renderTarget.count;
  34966. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  34967. }
  34968. const chainMap = this.getChainMap( attachmentState );
  34969. let renderState = chainMap.get( chainKey );
  34970. if ( renderState === undefined ) {
  34971. renderState = new RenderContext();
  34972. chainMap.set( chainKey, renderState );
  34973. }
  34974. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  34975. return renderState;
  34976. }
  34977. getChainMap( attachmentState ) {
  34978. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  34979. }
  34980. dispose() {
  34981. this.chainMaps = {};
  34982. }
  34983. }
  34984. const _size = new Vector3();
  34985. class Textures extends DataMap {
  34986. constructor( renderer, backend, info ) {
  34987. super();
  34988. this.renderer = renderer;
  34989. this.backend = backend;
  34990. this.info = info;
  34991. }
  34992. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  34993. const renderTargetData = this.get( renderTarget );
  34994. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  34995. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  34996. const texture = renderTarget.texture;
  34997. const textures = renderTarget.textures;
  34998. const size = this.getSize( texture );
  34999. const mipWidth = size.width >> activeMipmapLevel;
  35000. const mipHeight = size.height >> activeMipmapLevel;
  35001. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  35002. let textureNeedsUpdate = false;
  35003. if ( depthTexture === undefined ) {
  35004. depthTexture = new DepthTexture();
  35005. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  35006. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  35007. depthTexture.image.width = mipWidth;
  35008. depthTexture.image.height = mipHeight;
  35009. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  35010. }
  35011. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  35012. textureNeedsUpdate = true;
  35013. depthTexture.needsUpdate = true;
  35014. depthTexture.image.width = mipWidth;
  35015. depthTexture.image.height = mipHeight;
  35016. }
  35017. renderTargetData.width = size.width;
  35018. renderTargetData.height = size.height;
  35019. renderTargetData.textures = textures;
  35020. renderTargetData.depthTexture = depthTexture;
  35021. renderTargetData.depth = renderTarget.depthBuffer;
  35022. renderTargetData.stencil = renderTarget.stencilBuffer;
  35023. renderTargetData.renderTarget = renderTarget;
  35024. if ( renderTargetData.sampleCount !== sampleCount ) {
  35025. textureNeedsUpdate = true;
  35026. depthTexture.needsUpdate = true;
  35027. renderTargetData.sampleCount = sampleCount;
  35028. }
  35029. //
  35030. const options = { sampleCount };
  35031. for ( let i = 0; i < textures.length; i ++ ) {
  35032. const texture = textures[ i ];
  35033. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  35034. this.updateTexture( texture, options );
  35035. }
  35036. this.updateTexture( depthTexture, options );
  35037. // dispose handler
  35038. if ( renderTargetData.initialized !== true ) {
  35039. renderTargetData.initialized = true;
  35040. // dispose
  35041. const onDispose = () => {
  35042. renderTarget.removeEventListener( 'dispose', onDispose );
  35043. if ( textures !== undefined ) {
  35044. for ( let i = 0; i < textures.length; i ++ ) {
  35045. this._destroyTexture( textures[ i ] );
  35046. }
  35047. } else {
  35048. this._destroyTexture( texture );
  35049. }
  35050. this._destroyTexture( depthTexture );
  35051. };
  35052. renderTarget.addEventListener( 'dispose', onDispose );
  35053. }
  35054. }
  35055. updateTexture( texture, options = {} ) {
  35056. const textureData = this.get( texture );
  35057. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  35058. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  35059. const backend = this.backend;
  35060. if ( isRenderTarget && textureData.initialized === true ) {
  35061. // it's an update
  35062. backend.destroySampler( texture );
  35063. backend.destroyTexture( texture );
  35064. }
  35065. //
  35066. if ( texture.isFramebufferTexture ) {
  35067. const renderer = this.renderer;
  35068. const renderTarget = renderer.getRenderTarget();
  35069. if ( renderTarget ) {
  35070. texture.type = renderTarget.texture.type;
  35071. } else {
  35072. texture.type = UnsignedByteType;
  35073. }
  35074. }
  35075. //
  35076. const { width, height, depth } = this.getSize( texture );
  35077. options.width = width;
  35078. options.height = height;
  35079. options.depth = depth;
  35080. options.needsMipmaps = this.needsMipmaps( texture );
  35081. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  35082. //
  35083. if ( isRenderTarget || texture.isStorageTexture === true ) {
  35084. backend.createSampler( texture );
  35085. backend.createTexture( texture, options );
  35086. } else {
  35087. const needsCreate = textureData.initialized !== true;
  35088. if ( needsCreate ) backend.createSampler( texture );
  35089. if ( texture.version > 0 ) {
  35090. const image = texture.image;
  35091. if ( image === undefined ) {
  35092. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  35093. } else if ( image.complete === false ) {
  35094. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  35095. } else {
  35096. if ( texture.images ) {
  35097. const images = [];
  35098. for ( const image of texture.images ) {
  35099. images.push( image );
  35100. }
  35101. options.images = images;
  35102. } else {
  35103. options.image = image;
  35104. }
  35105. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  35106. backend.createTexture( texture, options );
  35107. textureData.isDefaultTexture = false;
  35108. }
  35109. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  35110. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  35111. }
  35112. } else {
  35113. // async update
  35114. backend.createDefaultTexture( texture );
  35115. textureData.isDefaultTexture = true;
  35116. }
  35117. }
  35118. // dispose handler
  35119. if ( textureData.initialized !== true ) {
  35120. textureData.initialized = true;
  35121. //
  35122. this.info.memory.textures ++;
  35123. // dispose
  35124. const onDispose = () => {
  35125. texture.removeEventListener( 'dispose', onDispose );
  35126. this._destroyTexture( texture );
  35127. this.info.memory.textures --;
  35128. };
  35129. texture.addEventListener( 'dispose', onDispose );
  35130. }
  35131. //
  35132. textureData.version = texture.version;
  35133. }
  35134. getSize( texture, target = _size ) {
  35135. let image = texture.images ? texture.images[ 0 ] : texture.image;
  35136. if ( image ) {
  35137. if ( image.image !== undefined ) image = image.image;
  35138. target.width = image.width;
  35139. target.height = image.height;
  35140. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  35141. } else {
  35142. target.width = target.height = target.depth = 1;
  35143. }
  35144. return target;
  35145. }
  35146. getMipLevels( texture, width, height ) {
  35147. let mipLevelCount;
  35148. if ( texture.isCompressedTexture ) {
  35149. mipLevelCount = texture.mipmaps.length;
  35150. } else {
  35151. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  35152. }
  35153. return mipLevelCount;
  35154. }
  35155. needsMipmaps( texture ) {
  35156. if ( this.isEnvironmentTexture( texture ) ) return true;
  35157. return ( texture.isCompressedTexture === true ) || ( ( texture.minFilter !== NearestFilter ) && ( texture.minFilter !== LinearFilter ) );
  35158. }
  35159. isEnvironmentTexture( texture ) {
  35160. const mapping = texture.mapping;
  35161. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  35162. }
  35163. _destroyTexture( texture ) {
  35164. this.backend.destroySampler( texture );
  35165. this.backend.destroyTexture( texture );
  35166. this.delete( texture );
  35167. }
  35168. }
  35169. class Color4 extends Color {
  35170. constructor( r, g, b, a = 1 ) {
  35171. super( r, g, b );
  35172. this.a = a;
  35173. }
  35174. set( r, g, b, a = 1 ) {
  35175. this.a = a;
  35176. return super.set( r, g, b );
  35177. }
  35178. copy( color ) {
  35179. if ( color.a !== undefined ) this.a = color.a;
  35180. return super.copy( color );
  35181. }
  35182. clone() {
  35183. return new this.constructor( this.r, this.g, this.b, this.a );
  35184. }
  35185. }
  35186. const _clearColor = new Color4();
  35187. class Background extends DataMap {
  35188. constructor( renderer, nodes ) {
  35189. super();
  35190. this.renderer = renderer;
  35191. this.nodes = nodes;
  35192. }
  35193. update( scene, renderList, renderContext ) {
  35194. const renderer = this.renderer;
  35195. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  35196. let forceClear = false;
  35197. if ( background === null ) {
  35198. // no background settings, use clear color configuration from the renderer
  35199. renderer._clearColor.getRGB( _clearColor, LinearSRGBColorSpace );
  35200. _clearColor.a = renderer._clearColor.a;
  35201. } else if ( background.isColor === true ) {
  35202. // background is an opaque color
  35203. background.getRGB( _clearColor, LinearSRGBColorSpace );
  35204. _clearColor.a = 1;
  35205. forceClear = true;
  35206. } else if ( background.isNode === true ) {
  35207. const sceneData = this.get( scene );
  35208. const backgroundNode = background;
  35209. _clearColor.copy( renderer._clearColor );
  35210. let backgroundMesh = sceneData.backgroundMesh;
  35211. if ( backgroundMesh === undefined ) {
  35212. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  35213. // @TODO: Add Texture2D support using node context
  35214. getUV: () => normalWorld,
  35215. getTextureLevel: () => backgroundBlurriness
  35216. } );
  35217. let viewProj = modelViewProjection();
  35218. viewProj = viewProj.setZ( viewProj.w );
  35219. const nodeMaterial = new NodeMaterial();
  35220. nodeMaterial.side = BackSide;
  35221. nodeMaterial.depthTest = false;
  35222. nodeMaterial.depthWrite = false;
  35223. nodeMaterial.fog = false;
  35224. nodeMaterial.vertexNode = viewProj;
  35225. nodeMaterial.fragmentNode = backgroundMeshNode;
  35226. sceneData.backgroundMeshNode = backgroundMeshNode;
  35227. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  35228. backgroundMesh.frustumCulled = false;
  35229. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  35230. this.matrixWorld.copyPosition( camera.matrixWorld );
  35231. };
  35232. }
  35233. const backgroundCacheKey = backgroundNode.getCacheKey();
  35234. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  35235. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  35236. backgroundMesh.material.needsUpdate = true;
  35237. sceneData.backgroundCacheKey = backgroundCacheKey;
  35238. }
  35239. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null );
  35240. } else {
  35241. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  35242. }
  35243. //
  35244. if ( renderer.autoClear === true || forceClear === true ) {
  35245. _clearColor.multiplyScalar( _clearColor.a );
  35246. const clearColorValue = renderContext.clearColorValue;
  35247. clearColorValue.r = _clearColor.r;
  35248. clearColorValue.g = _clearColor.g;
  35249. clearColorValue.b = _clearColor.b;
  35250. clearColorValue.a = _clearColor.a;
  35251. renderContext.depthClearValue = renderer._clearDepth;
  35252. renderContext.stencilClearValue = renderer._clearStencil;
  35253. renderContext.clearColor = renderer.autoClearColor === true;
  35254. renderContext.clearDepth = renderer.autoClearDepth === true;
  35255. renderContext.clearStencil = renderer.autoClearStencil === true;
  35256. } else {
  35257. renderContext.clearColor = false;
  35258. renderContext.clearDepth = false;
  35259. renderContext.clearStencil = false;
  35260. }
  35261. }
  35262. }
  35263. class NodeBuilderState {
  35264. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, instanceBindGroups = true, transforms = [] ) {
  35265. this.vertexShader = vertexShader;
  35266. this.fragmentShader = fragmentShader;
  35267. this.computeShader = computeShader;
  35268. this.transforms = transforms;
  35269. this.nodeAttributes = nodeAttributes;
  35270. this.bindings = bindings;
  35271. this.updateNodes = updateNodes;
  35272. this.updateBeforeNodes = updateBeforeNodes;
  35273. this.updateAfterNodes = updateAfterNodes;
  35274. this.instanceBindGroups = instanceBindGroups;
  35275. this.usedTimes = 0;
  35276. }
  35277. createBindings() {
  35278. const bindings = [];
  35279. for ( const instanceGroup of this.bindings ) {
  35280. const shared = this.instanceBindGroups && instanceGroup.bindings[ 0 ].groupNode.shared;
  35281. if ( shared !== true ) {
  35282. const bindingsGroup = new BindGroup( instanceGroup.name );
  35283. bindings.push( bindingsGroup );
  35284. for ( const instanceBinding of instanceGroup.bindings ) {
  35285. bindingsGroup.bindings.push( instanceBinding.clone() );
  35286. }
  35287. } else {
  35288. bindings.push( instanceGroup );
  35289. }
  35290. }
  35291. return bindings;
  35292. }
  35293. }
  35294. class Nodes extends DataMap {
  35295. constructor( renderer, backend ) {
  35296. super();
  35297. this.renderer = renderer;
  35298. this.backend = backend;
  35299. this.nodeFrame = new NodeFrame();
  35300. this.nodeBuilderCache = new Map();
  35301. this.callHashCache = new ChainMap();
  35302. this.groupsData = new ChainMap();
  35303. }
  35304. updateGroup( nodeUniformsGroup ) {
  35305. const groupNode = nodeUniformsGroup.groupNode;
  35306. const name = groupNode.name;
  35307. // objectGroup is every updated
  35308. if ( name === objectGroup.name ) return true;
  35309. // renderGroup is updated once per render/compute call
  35310. if ( name === renderGroup.name ) {
  35311. const uniformsGroupData = this.get( nodeUniformsGroup );
  35312. const renderId = this.nodeFrame.renderId;
  35313. if ( uniformsGroupData.renderId !== renderId ) {
  35314. uniformsGroupData.renderId = renderId;
  35315. return true;
  35316. }
  35317. return false;
  35318. }
  35319. // frameGroup is updated once per frame
  35320. if ( name === frameGroup.name ) {
  35321. const uniformsGroupData = this.get( nodeUniformsGroup );
  35322. const frameId = this.nodeFrame.frameId;
  35323. if ( uniformsGroupData.frameId !== frameId ) {
  35324. uniformsGroupData.frameId = frameId;
  35325. return true;
  35326. }
  35327. return false;
  35328. }
  35329. // other groups are updated just when groupNode.needsUpdate is true
  35330. const groupChain = [ groupNode, nodeUniformsGroup ];
  35331. let groupData = this.groupsData.get( groupChain );
  35332. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  35333. if ( groupData.version !== groupNode.version ) {
  35334. groupData.version = groupNode.version;
  35335. return true;
  35336. }
  35337. return false;
  35338. }
  35339. getForRenderCacheKey( renderObject ) {
  35340. return renderObject.initialCacheKey;
  35341. }
  35342. getForRender( renderObject ) {
  35343. const renderObjectData = this.get( renderObject );
  35344. let nodeBuilderState = renderObjectData.nodeBuilderState;
  35345. if ( nodeBuilderState === undefined ) {
  35346. const { nodeBuilderCache } = this;
  35347. const cacheKey = this.getForRenderCacheKey( renderObject );
  35348. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  35349. if ( nodeBuilderState === undefined ) {
  35350. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  35351. nodeBuilder.scene = renderObject.scene;
  35352. nodeBuilder.material = renderObject.material;
  35353. nodeBuilder.camera = renderObject.camera;
  35354. nodeBuilder.context.material = renderObject.material;
  35355. nodeBuilder.lightsNode = renderObject.lightsNode;
  35356. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  35357. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  35358. nodeBuilder.clippingContext = renderObject.clippingContext;
  35359. nodeBuilder.build();
  35360. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  35361. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  35362. }
  35363. nodeBuilderState.usedTimes ++;
  35364. renderObjectData.nodeBuilderState = nodeBuilderState;
  35365. }
  35366. return nodeBuilderState;
  35367. }
  35368. delete( object ) {
  35369. if ( object.isRenderObject ) {
  35370. const nodeBuilderState = this.get( object ).nodeBuilderState;
  35371. nodeBuilderState.usedTimes --;
  35372. if ( nodeBuilderState.usedTimes === 0 ) {
  35373. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  35374. }
  35375. }
  35376. return super.delete( object );
  35377. }
  35378. getForCompute( computeNode ) {
  35379. const computeData = this.get( computeNode );
  35380. let nodeBuilderState = computeData.nodeBuilderState;
  35381. if ( nodeBuilderState === undefined ) {
  35382. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  35383. nodeBuilder.build();
  35384. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  35385. computeData.nodeBuilderState = nodeBuilderState;
  35386. }
  35387. return nodeBuilderState;
  35388. }
  35389. _createNodeBuilderState( nodeBuilder ) {
  35390. return new NodeBuilderState(
  35391. nodeBuilder.vertexShader,
  35392. nodeBuilder.fragmentShader,
  35393. nodeBuilder.computeShader,
  35394. nodeBuilder.getAttributesArray(),
  35395. nodeBuilder.getBindings(),
  35396. nodeBuilder.updateNodes,
  35397. nodeBuilder.updateBeforeNodes,
  35398. nodeBuilder.updateAfterNodes,
  35399. nodeBuilder.instanceBindGroups,
  35400. nodeBuilder.transforms
  35401. );
  35402. }
  35403. getEnvironmentNode( scene ) {
  35404. return scene.environmentNode || this.get( scene ).environmentNode || null;
  35405. }
  35406. getBackgroundNode( scene ) {
  35407. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  35408. }
  35409. getFogNode( scene ) {
  35410. return scene.fogNode || this.get( scene ).fogNode || null;
  35411. }
  35412. getCacheKey( scene, lightsNode ) {
  35413. const chain = [ scene, lightsNode ];
  35414. const callId = this.renderer.info.calls;
  35415. let cacheKeyData = this.callHashCache.get( chain );
  35416. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  35417. const environmentNode = this.getEnvironmentNode( scene );
  35418. const fogNode = this.getFogNode( scene );
  35419. const cacheKey = [];
  35420. if ( lightsNode ) cacheKey.push( lightsNode.getCacheKey() );
  35421. if ( environmentNode ) cacheKey.push( environmentNode.getCacheKey() );
  35422. if ( fogNode ) cacheKey.push( fogNode.getCacheKey() );
  35423. cacheKeyData = {
  35424. callId,
  35425. cacheKey: cacheKey.join( ',' )
  35426. };
  35427. this.callHashCache.set( chain, cacheKeyData );
  35428. }
  35429. return cacheKeyData.cacheKey;
  35430. }
  35431. updateScene( scene ) {
  35432. this.updateEnvironment( scene );
  35433. this.updateFog( scene );
  35434. this.updateBackground( scene );
  35435. }
  35436. get isToneMappingState() {
  35437. return this.renderer.getRenderTarget() ? false : true;
  35438. }
  35439. updateBackground( scene ) {
  35440. const sceneData = this.get( scene );
  35441. const background = scene.background;
  35442. if ( background ) {
  35443. if ( sceneData.background !== background ) {
  35444. let backgroundNode = null;
  35445. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping ) ) {
  35446. backgroundNode = pmremTexture( background, normalWorld );
  35447. } else if ( background.isTexture === true ) {
  35448. backgroundNode = texture( background, viewportBottomLeft ).setUpdateMatrix( true );
  35449. } else if ( background.isColor !== true ) {
  35450. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  35451. }
  35452. sceneData.backgroundNode = backgroundNode;
  35453. sceneData.background = background;
  35454. }
  35455. } else if ( sceneData.backgroundNode ) {
  35456. delete sceneData.backgroundNode;
  35457. delete sceneData.background;
  35458. }
  35459. }
  35460. updateFog( scene ) {
  35461. const sceneData = this.get( scene );
  35462. const fog = scene.fog;
  35463. if ( fog ) {
  35464. if ( sceneData.fog !== fog ) {
  35465. let fogNode = null;
  35466. if ( fog.isFogExp2 ) {
  35467. fogNode = densityFog( reference( 'color', 'color', fog ), reference( 'density', 'float', fog ) );
  35468. } else if ( fog.isFog ) {
  35469. fogNode = rangeFog( reference( 'color', 'color', fog ), reference( 'near', 'float', fog ), reference( 'far', 'float', fog ) );
  35470. } else {
  35471. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  35472. }
  35473. sceneData.fogNode = fogNode;
  35474. sceneData.fog = fog;
  35475. }
  35476. } else {
  35477. delete sceneData.fogNode;
  35478. delete sceneData.fog;
  35479. }
  35480. }
  35481. updateEnvironment( scene ) {
  35482. const sceneData = this.get( scene );
  35483. const environment = scene.environment;
  35484. if ( environment ) {
  35485. if ( sceneData.environment !== environment ) {
  35486. let environmentNode = null;
  35487. if ( environment.isCubeTexture === true ) {
  35488. environmentNode = cubeTexture( environment );
  35489. } else if ( environment.isTexture === true ) {
  35490. environmentNode = texture( environment );
  35491. } else {
  35492. console.error( 'Nodes: Unsupported environment configuration.', environment );
  35493. }
  35494. sceneData.environmentNode = environmentNode;
  35495. sceneData.environment = environment;
  35496. }
  35497. } else if ( sceneData.environmentNode ) {
  35498. delete sceneData.environmentNode;
  35499. delete sceneData.environment;
  35500. }
  35501. }
  35502. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  35503. const nodeFrame = this.nodeFrame;
  35504. nodeFrame.renderer = renderer;
  35505. nodeFrame.scene = scene;
  35506. nodeFrame.object = object;
  35507. nodeFrame.camera = camera;
  35508. nodeFrame.material = material;
  35509. return nodeFrame;
  35510. }
  35511. getNodeFrameForRender( renderObject ) {
  35512. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  35513. }
  35514. getOutputNode( outputTexture ) {
  35515. let output = texture( outputTexture, viewportTopLeft );
  35516. if ( this.isToneMappingState ) {
  35517. if ( this.renderer.toneMappingNode ) {
  35518. output = vec4( this.renderer.toneMappingNode.context( { color: output.rgb } ), output.a );
  35519. } else if ( this.renderer.toneMapping !== NoToneMapping ) {
  35520. output = output.toneMapping( this.renderer.toneMapping );
  35521. }
  35522. }
  35523. if ( this.renderer.currentColorSpace === SRGBColorSpace ) {
  35524. output = output.linearToColorSpace( this.renderer.currentColorSpace );
  35525. }
  35526. return output;
  35527. }
  35528. updateBefore( renderObject ) {
  35529. const nodeFrame = this.getNodeFrameForRender( renderObject );
  35530. const nodeBuilder = renderObject.getNodeBuilderState();
  35531. for ( const node of nodeBuilder.updateBeforeNodes ) {
  35532. nodeFrame.updateBeforeNode( node );
  35533. }
  35534. }
  35535. updateAfter( renderObject ) {
  35536. const nodeFrame = this.getNodeFrameForRender( renderObject );
  35537. const nodeBuilder = renderObject.getNodeBuilderState();
  35538. for ( const node of nodeBuilder.updateAfterNodes ) {
  35539. nodeFrame.updateAfterNode( node );
  35540. }
  35541. }
  35542. updateForCompute( computeNode ) {
  35543. const nodeFrame = this.getNodeFrame();
  35544. const nodeBuilder = this.getForCompute( computeNode );
  35545. for ( const node of nodeBuilder.updateNodes ) {
  35546. nodeFrame.updateNode( node );
  35547. }
  35548. }
  35549. updateForRender( renderObject ) {
  35550. const nodeFrame = this.getNodeFrameForRender( renderObject );
  35551. const nodeBuilder = renderObject.getNodeBuilderState();
  35552. for ( const node of nodeBuilder.updateNodes ) {
  35553. nodeFrame.updateNode( node );
  35554. }
  35555. }
  35556. dispose() {
  35557. super.dispose();
  35558. this.nodeFrame = new NodeFrame();
  35559. this.nodeBuilderCache = new Map();
  35560. }
  35561. }
  35562. class RenderBundle {
  35563. constructor( scene, camera ) {
  35564. this.scene = scene;
  35565. this.camera = camera;
  35566. }
  35567. clone() {
  35568. return Object.assign( new this.constructor(), this );
  35569. }
  35570. }
  35571. class RenderBundles {
  35572. constructor() {
  35573. this.lists = new ChainMap();
  35574. }
  35575. get( scene, camera ) {
  35576. const lists = this.lists;
  35577. const keys = [ scene, camera ];
  35578. let list = lists.get( keys );
  35579. if ( list === undefined ) {
  35580. list = new RenderBundle( scene, camera );
  35581. lists.set( keys, list );
  35582. }
  35583. return list;
  35584. }
  35585. dispose() {
  35586. this.lists = new ChainMap();
  35587. }
  35588. }
  35589. const _scene = new Scene();
  35590. const _drawingBufferSize = new Vector2();
  35591. const _screen = new Vector4();
  35592. const _frustum = new Frustum();
  35593. const _projScreenMatrix = new Matrix4();
  35594. const _vector3 = new Vector3();
  35595. const _quad = new QuadMesh( new NodeMaterial() );
  35596. class Renderer {
  35597. constructor( backend, parameters = {} ) {
  35598. this.isRenderer = true;
  35599. //
  35600. const {
  35601. logarithmicDepthBuffer = false,
  35602. alpha = true
  35603. } = parameters;
  35604. // public
  35605. this.domElement = backend.getDomElement();
  35606. this.backend = backend;
  35607. this.autoClear = true;
  35608. this.autoClearColor = true;
  35609. this.autoClearDepth = true;
  35610. this.autoClearStencil = true;
  35611. this.alpha = alpha;
  35612. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  35613. this.outputColorSpace = SRGBColorSpace;
  35614. this.toneMapping = NoToneMapping;
  35615. this.toneMappingExposure = 1.0;
  35616. this.sortObjects = true;
  35617. this.depth = true;
  35618. this.stencil = false;
  35619. this.clippingPlanes = [];
  35620. this.info = new Info();
  35621. // nodes
  35622. this.toneMappingNode = null;
  35623. // internals
  35624. this._pixelRatio = 1;
  35625. this._width = this.domElement.width;
  35626. this._height = this.domElement.height;
  35627. this._viewport = new Vector4( 0, 0, this._width, this._height );
  35628. this._scissor = new Vector4( 0, 0, this._width, this._height );
  35629. this._scissorTest = false;
  35630. this._attributes = null;
  35631. this._geometries = null;
  35632. this._nodes = null;
  35633. this._animation = null;
  35634. this._bindings = null;
  35635. this._objects = null;
  35636. this._pipelines = null;
  35637. this._bundles = null;
  35638. this._renderLists = null;
  35639. this._renderContexts = null;
  35640. this._textures = null;
  35641. this._background = null;
  35642. this._currentRenderContext = null;
  35643. this._opaqueSort = null;
  35644. this._transparentSort = null;
  35645. this._frameBufferTarget = null;
  35646. const alphaClear = this.alpha === true ? 0 : 1;
  35647. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  35648. this._clearDepth = 1;
  35649. this._clearStencil = 0;
  35650. this._renderTarget = null;
  35651. this._activeCubeFace = 0;
  35652. this._activeMipmapLevel = 0;
  35653. this._renderObjectFunction = null;
  35654. this._currentRenderObjectFunction = null;
  35655. this._currentRenderBundle = null;
  35656. this._handleObjectFunction = this._renderObjectDirect;
  35657. this._initialized = false;
  35658. this._initPromise = null;
  35659. this._compilationPromises = null;
  35660. // backwards compatibility
  35661. this.shadowMap = {
  35662. enabled: false,
  35663. type: null
  35664. };
  35665. this.xr = {
  35666. enabled: false
  35667. };
  35668. this.debug = {
  35669. checkShaderErrors: true,
  35670. onShaderError: null
  35671. };
  35672. }
  35673. async init() {
  35674. if ( this._initialized ) {
  35675. throw new Error( 'Renderer: Backend has already been initialized.' );
  35676. }
  35677. if ( this._initPromise !== null ) {
  35678. return this._initPromise;
  35679. }
  35680. this._initPromise = new Promise( async ( resolve, reject ) => {
  35681. const backend = this.backend;
  35682. try {
  35683. await backend.init( this );
  35684. } catch ( error ) {
  35685. reject( error );
  35686. return;
  35687. }
  35688. this._nodes = new Nodes( this, backend );
  35689. this._animation = new Animation( this._nodes, this.info );
  35690. this._attributes = new Attributes( backend );
  35691. this._background = new Background( this, this._nodes );
  35692. this._geometries = new Geometries( this._attributes, this.info );
  35693. this._textures = new Textures( this, backend, this.info );
  35694. this._pipelines = new Pipelines( backend, this._nodes );
  35695. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  35696. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  35697. this._renderLists = new RenderLists();
  35698. this._bundles = new RenderBundles();
  35699. this._renderContexts = new RenderContexts();
  35700. //
  35701. this._initialized = true;
  35702. resolve();
  35703. } );
  35704. return this._initPromise;
  35705. }
  35706. get coordinateSystem() {
  35707. return this.backend.coordinateSystem;
  35708. }
  35709. async compileAsync( scene, camera, targetScene = null ) {
  35710. if ( this._initialized === false ) await this.init();
  35711. // preserve render tree
  35712. const nodeFrame = this._nodes.nodeFrame;
  35713. const previousRenderId = nodeFrame.renderId;
  35714. const previousRenderContext = this._currentRenderContext;
  35715. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  35716. const previousCompilationPromises = this._compilationPromises;
  35717. //
  35718. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  35719. if ( targetScene === null ) targetScene = scene;
  35720. const renderTarget = this._renderTarget;
  35721. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  35722. const activeMipmapLevel = this._activeMipmapLevel;
  35723. const compilationPromises = [];
  35724. this._currentRenderContext = renderContext;
  35725. this._currentRenderObjectFunction = this.renderObject;
  35726. this._handleObjectFunction = this._createObjectPipeline;
  35727. this._compilationPromises = compilationPromises;
  35728. nodeFrame.renderId ++;
  35729. //
  35730. nodeFrame.update();
  35731. //
  35732. renderContext.depth = this.depth;
  35733. renderContext.stencil = this.stencil;
  35734. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  35735. renderContext.clippingContext.updateGlobal( this, camera );
  35736. //
  35737. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  35738. //
  35739. const renderList = this._renderLists.get( scene, camera );
  35740. renderList.begin();
  35741. this._projectObject( scene, camera, 0, renderList );
  35742. // include lights from target scene
  35743. if ( targetScene !== scene ) {
  35744. targetScene.traverseVisible( function ( object ) {
  35745. if ( object.isLight && object.layers.test( camera.layers ) ) {
  35746. renderList.pushLight( object );
  35747. }
  35748. } );
  35749. }
  35750. renderList.finish();
  35751. //
  35752. if ( renderTarget !== null ) {
  35753. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  35754. const renderTargetData = this._textures.get( renderTarget );
  35755. renderContext.textures = renderTargetData.textures;
  35756. renderContext.depthTexture = renderTargetData.depthTexture;
  35757. } else {
  35758. renderContext.textures = null;
  35759. renderContext.depthTexture = null;
  35760. }
  35761. //
  35762. this._nodes.updateScene( sceneRef );
  35763. //
  35764. this._background.update( sceneRef, renderList, renderContext );
  35765. // process render lists
  35766. const opaqueObjects = renderList.opaque;
  35767. const transparentObjects = renderList.transparent;
  35768. const lightsNode = renderList.lightsNode;
  35769. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  35770. if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  35771. // restore render tree
  35772. nodeFrame.renderId = previousRenderId;
  35773. this._currentRenderContext = previousRenderContext;
  35774. this._currentRenderObjectFunction = previousRenderObjectFunction;
  35775. this._compilationPromises = previousCompilationPromises;
  35776. this._handleObjectFunction = this._renderObjectDirect;
  35777. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  35778. await Promise.all( compilationPromises );
  35779. }
  35780. async renderAsync( scene, camera ) {
  35781. if ( this._initialized === false ) await this.init();
  35782. const renderContext = this._renderScene( scene, camera );
  35783. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  35784. }
  35785. _renderBundle( bundle, sceneRef, lightsNode ) {
  35786. const { object, camera, renderList } = bundle;
  35787. const renderContext = this._currentRenderContext;
  35788. const renderContextData = this.backend.get( renderContext );
  35789. //
  35790. const renderBundle = this._bundles.get( object, camera );
  35791. const renderBundleData = this.backend.get( renderBundle );
  35792. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  35793. //
  35794. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || object.needsUpdate === true;
  35795. renderBundleData.renderContexts.add( renderContext );
  35796. if ( renderBundleNeedsUpdate ) {
  35797. if ( renderContextData.renderObjects === undefined || object.needsUpdate === true ) {
  35798. const nodeFrame = this._nodes.nodeFrame;
  35799. renderContextData.renderObjects = [];
  35800. renderContextData.renderBundles = [];
  35801. renderContextData.scene = sceneRef;
  35802. renderContextData.camera = camera;
  35803. renderContextData.renderId = nodeFrame.renderId;
  35804. renderContextData.registerBundlesPhase = true;
  35805. }
  35806. this._currentRenderBundle = renderBundle;
  35807. const opaqueObjects = renderList.opaque;
  35808. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  35809. this._currentRenderBundle = null;
  35810. //
  35811. object.needsUpdate = false;
  35812. } else {
  35813. const renderContext = this._currentRenderContext;
  35814. const renderContextData = this.backend.get( renderContext );
  35815. for ( let i = 0, l = renderContextData.renderObjects.length; i < l; i ++ ) {
  35816. const renderObject = renderContextData.renderObjects[ i ];
  35817. this._nodes.updateBefore( renderObject );
  35818. //
  35819. renderObject.object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, renderObject.object.matrixWorld );
  35820. renderObject.object.normalMatrix.getNormalMatrix( renderObject.object.modelViewMatrix );
  35821. this._nodes.updateForRender( renderObject );
  35822. this._bindings.updateForRender( renderObject );
  35823. this.backend.draw( renderObject, this.info );
  35824. this._nodes.updateAfter( renderObject );
  35825. }
  35826. }
  35827. }
  35828. render( scene, camera ) {
  35829. if ( this._initialized === false ) {
  35830. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  35831. return this.renderAsync( scene, camera );
  35832. }
  35833. this._renderScene( scene, camera );
  35834. }
  35835. _getFrameBufferTarget() {
  35836. const { currentColorSpace } = this;
  35837. const useToneMapping = this._renderTarget === null && ( this.toneMapping !== NoToneMapping || this.toneMappingNode !== null );
  35838. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace && currentColorSpace !== NoColorSpace;
  35839. if ( useToneMapping === false && useColorSpace === false ) return null;
  35840. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  35841. const { depth, stencil } = this;
  35842. let frameBufferTarget = this._frameBufferTarget;
  35843. if ( frameBufferTarget === null ) {
  35844. frameBufferTarget = new RenderTarget( width, height, {
  35845. depthBuffer: depth,
  35846. stencilBuffer: stencil,
  35847. type: HalfFloatType, // FloatType
  35848. format: RGBAFormat,
  35849. colorSpace: LinearSRGBColorSpace,
  35850. generateMipmaps: false,
  35851. minFilter: LinearFilter,
  35852. magFilter: LinearFilter,
  35853. samples: this.backend.parameters.antialias ? 4 : 0
  35854. } );
  35855. frameBufferTarget.isPostProcessingRenderTarget = true;
  35856. this._frameBufferTarget = frameBufferTarget;
  35857. }
  35858. frameBufferTarget.depthBuffer = depth;
  35859. frameBufferTarget.stencilBuffer = stencil;
  35860. frameBufferTarget.setSize( width, height );
  35861. frameBufferTarget.viewport.copy( this._viewport );
  35862. frameBufferTarget.scissor.copy( this._scissor );
  35863. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  35864. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  35865. frameBufferTarget.scissorTest = this._scissorTest;
  35866. return frameBufferTarget;
  35867. }
  35868. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  35869. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  35870. // preserve render tree
  35871. const nodeFrame = this._nodes.nodeFrame;
  35872. const previousRenderId = nodeFrame.renderId;
  35873. const previousRenderContext = this._currentRenderContext;
  35874. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  35875. //
  35876. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  35877. const outputRenderTarget = this._renderTarget;
  35878. const activeCubeFace = this._activeCubeFace;
  35879. const activeMipmapLevel = this._activeMipmapLevel;
  35880. //
  35881. let renderTarget;
  35882. if ( frameBufferTarget !== null ) {
  35883. renderTarget = frameBufferTarget;
  35884. this.setRenderTarget( renderTarget );
  35885. } else {
  35886. renderTarget = outputRenderTarget;
  35887. }
  35888. //
  35889. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  35890. this._currentRenderContext = renderContext;
  35891. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  35892. //
  35893. this.info.calls ++;
  35894. this.info.render.calls ++;
  35895. this.info.render.frameCalls ++;
  35896. nodeFrame.renderId = this.info.calls;
  35897. //
  35898. const coordinateSystem = this.coordinateSystem;
  35899. if ( camera.coordinateSystem !== coordinateSystem ) {
  35900. camera.coordinateSystem = coordinateSystem;
  35901. camera.updateProjectionMatrix();
  35902. }
  35903. //
  35904. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  35905. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  35906. //
  35907. let viewport = this._viewport;
  35908. let scissor = this._scissor;
  35909. let pixelRatio = this._pixelRatio;
  35910. if ( renderTarget !== null ) {
  35911. viewport = renderTarget.viewport;
  35912. scissor = renderTarget.scissor;
  35913. pixelRatio = 1;
  35914. }
  35915. this.getDrawingBufferSize( _drawingBufferSize );
  35916. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  35917. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  35918. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  35919. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  35920. renderContext.viewportValue.width >>= activeMipmapLevel;
  35921. renderContext.viewportValue.height >>= activeMipmapLevel;
  35922. renderContext.viewportValue.minDepth = minDepth;
  35923. renderContext.viewportValue.maxDepth = maxDepth;
  35924. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  35925. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  35926. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  35927. renderContext.scissorValue.width >>= activeMipmapLevel;
  35928. renderContext.scissorValue.height >>= activeMipmapLevel;
  35929. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  35930. renderContext.clippingContext.updateGlobal( this, camera );
  35931. //
  35932. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  35933. //
  35934. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  35935. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  35936. const renderList = this._renderLists.get( scene, camera );
  35937. renderList.begin();
  35938. this._projectObject( scene, camera, 0, renderList );
  35939. renderList.finish();
  35940. if ( this.sortObjects === true ) {
  35941. renderList.sort( this._opaqueSort, this._transparentSort );
  35942. }
  35943. //
  35944. if ( renderTarget !== null ) {
  35945. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  35946. const renderTargetData = this._textures.get( renderTarget );
  35947. renderContext.textures = renderTargetData.textures;
  35948. renderContext.depthTexture = renderTargetData.depthTexture;
  35949. renderContext.width = renderTargetData.width;
  35950. renderContext.height = renderTargetData.height;
  35951. renderContext.renderTarget = renderTarget;
  35952. renderContext.depth = renderTarget.depthBuffer;
  35953. renderContext.stencil = renderTarget.stencilBuffer;
  35954. } else {
  35955. renderContext.textures = null;
  35956. renderContext.depthTexture = null;
  35957. renderContext.width = this.domElement.width;
  35958. renderContext.height = this.domElement.height;
  35959. renderContext.depth = this.depth;
  35960. renderContext.stencil = this.stencil;
  35961. }
  35962. renderContext.width >>= activeMipmapLevel;
  35963. renderContext.height >>= activeMipmapLevel;
  35964. renderContext.activeCubeFace = activeCubeFace;
  35965. renderContext.activeMipmapLevel = activeMipmapLevel;
  35966. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  35967. //
  35968. this._nodes.updateScene( sceneRef );
  35969. //
  35970. this._background.update( sceneRef, renderList, renderContext );
  35971. //
  35972. this.backend.beginRender( renderContext );
  35973. // process render lists
  35974. const opaqueObjects = renderList.opaque;
  35975. const transparentObjects = renderList.transparent;
  35976. const bundles = renderList.bundles;
  35977. const lightsNode = renderList.lightsNode;
  35978. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  35979. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  35980. if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  35981. // finish render pass
  35982. this.backend.finishRender( renderContext );
  35983. // restore render tree
  35984. nodeFrame.renderId = previousRenderId;
  35985. this._currentRenderContext = previousRenderContext;
  35986. this._currentRenderObjectFunction = previousRenderObjectFunction;
  35987. //
  35988. if ( frameBufferTarget !== null ) {
  35989. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  35990. _quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  35991. this._renderScene( _quad, _quad.camera, false );
  35992. }
  35993. //
  35994. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  35995. //
  35996. return renderContext;
  35997. }
  35998. getMaxAnisotropy() {
  35999. return this.backend.getMaxAnisotropy();
  36000. }
  36001. getActiveCubeFace() {
  36002. return this._activeCubeFace;
  36003. }
  36004. getActiveMipmapLevel() {
  36005. return this._activeMipmapLevel;
  36006. }
  36007. async setAnimationLoop( callback ) {
  36008. if ( this._initialized === false ) await this.init();
  36009. this._animation.setAnimationLoop( callback );
  36010. }
  36011. async getArrayBufferAsync( attribute ) {
  36012. return await this.backend.getArrayBufferAsync( attribute );
  36013. }
  36014. getContext() {
  36015. return this.backend.getContext();
  36016. }
  36017. getPixelRatio() {
  36018. return this._pixelRatio;
  36019. }
  36020. getDrawingBufferSize( target ) {
  36021. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  36022. }
  36023. getSize( target ) {
  36024. return target.set( this._width, this._height );
  36025. }
  36026. setPixelRatio( value = 1 ) {
  36027. this._pixelRatio = value;
  36028. this.setSize( this._width, this._height, false );
  36029. }
  36030. setDrawingBufferSize( width, height, pixelRatio ) {
  36031. this._width = width;
  36032. this._height = height;
  36033. this._pixelRatio = pixelRatio;
  36034. this.domElement.width = Math.floor( width * pixelRatio );
  36035. this.domElement.height = Math.floor( height * pixelRatio );
  36036. this.setViewport( 0, 0, width, height );
  36037. if ( this._initialized ) this.backend.updateSize();
  36038. }
  36039. setSize( width, height, updateStyle = true ) {
  36040. this._width = width;
  36041. this._height = height;
  36042. this.domElement.width = Math.floor( width * this._pixelRatio );
  36043. this.domElement.height = Math.floor( height * this._pixelRatio );
  36044. if ( updateStyle === true ) {
  36045. this.domElement.style.width = width + 'px';
  36046. this.domElement.style.height = height + 'px';
  36047. }
  36048. this.setViewport( 0, 0, width, height );
  36049. if ( this._initialized ) this.backend.updateSize();
  36050. }
  36051. setOpaqueSort( method ) {
  36052. this._opaqueSort = method;
  36053. }
  36054. setTransparentSort( method ) {
  36055. this._transparentSort = method;
  36056. }
  36057. getScissor( target ) {
  36058. const scissor = this._scissor;
  36059. target.x = scissor.x;
  36060. target.y = scissor.y;
  36061. target.width = scissor.width;
  36062. target.height = scissor.height;
  36063. return target;
  36064. }
  36065. setScissor( x, y, width, height ) {
  36066. const scissor = this._scissor;
  36067. if ( x.isVector4 ) {
  36068. scissor.copy( x );
  36069. } else {
  36070. scissor.set( x, y, width, height );
  36071. }
  36072. }
  36073. getScissorTest() {
  36074. return this._scissorTest;
  36075. }
  36076. setScissorTest( boolean ) {
  36077. this._scissorTest = boolean;
  36078. this.backend.setScissorTest( boolean );
  36079. }
  36080. getViewport( target ) {
  36081. return target.copy( this._viewport );
  36082. }
  36083. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  36084. const viewport = this._viewport;
  36085. if ( x.isVector4 ) {
  36086. viewport.copy( x );
  36087. } else {
  36088. viewport.set( x, y, width, height );
  36089. }
  36090. viewport.minDepth = minDepth;
  36091. viewport.maxDepth = maxDepth;
  36092. }
  36093. getClearColor( target ) {
  36094. return target.copy( this._clearColor );
  36095. }
  36096. setClearColor( color, alpha = 1 ) {
  36097. this._clearColor.set( color );
  36098. this._clearColor.a = alpha;
  36099. }
  36100. getClearAlpha() {
  36101. return this._clearColor.a;
  36102. }
  36103. setClearAlpha( alpha ) {
  36104. this._clearColor.a = alpha;
  36105. }
  36106. getClearDepth() {
  36107. return this._clearDepth;
  36108. }
  36109. setClearDepth( depth ) {
  36110. this._clearDepth = depth;
  36111. }
  36112. getClearStencil() {
  36113. return this._clearStencil;
  36114. }
  36115. setClearStencil( stencil ) {
  36116. this._clearStencil = stencil;
  36117. }
  36118. isOccluded( object ) {
  36119. const renderContext = this._currentRenderContext;
  36120. return renderContext && this.backend.isOccluded( renderContext, object );
  36121. }
  36122. clear( color = true, depth = true, stencil = true ) {
  36123. if ( this._initialized === false ) {
  36124. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  36125. return this.clearAsync( color, depth, stencil );
  36126. }
  36127. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  36128. let renderTargetData = null;
  36129. if ( renderTarget !== null ) {
  36130. this._textures.updateRenderTarget( renderTarget );
  36131. renderTargetData = this._textures.get( renderTarget );
  36132. }
  36133. this.backend.clear( color, depth, stencil, renderTargetData );
  36134. if ( renderTarget !== null && this._renderTarget === null ) {
  36135. // If a color space transform or tone mapping is required,
  36136. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  36137. _quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  36138. this._renderScene( _quad, _quad.camera, false );
  36139. }
  36140. }
  36141. clearColor() {
  36142. return this.clear( true, false, false );
  36143. }
  36144. clearDepth() {
  36145. return this.clear( false, true, false );
  36146. }
  36147. clearStencil() {
  36148. return this.clear( false, false, true );
  36149. }
  36150. async clearAsync( color = true, depth = true, stencil = true ) {
  36151. if ( this._initialized === false ) await this.init();
  36152. this.clear( color, depth, stencil );
  36153. }
  36154. clearColorAsync() {
  36155. return this.clearAsync( true, false, false );
  36156. }
  36157. clearDepthAsync() {
  36158. return this.clearAsync( false, true, false );
  36159. }
  36160. clearStencilAsync() {
  36161. return this.clearAsync( false, false, true );
  36162. }
  36163. get currentColorSpace() {
  36164. const renderTarget = this._renderTarget;
  36165. if ( renderTarget !== null ) {
  36166. const texture = renderTarget.texture;
  36167. return ( Array.isArray( texture ) ? texture[ 0 ] : texture ).colorSpace;
  36168. }
  36169. return this.outputColorSpace;
  36170. }
  36171. dispose() {
  36172. this.info.dispose();
  36173. this._animation.dispose();
  36174. this._objects.dispose();
  36175. this._pipelines.dispose();
  36176. this._nodes.dispose();
  36177. this._bindings.dispose();
  36178. this._renderLists.dispose();
  36179. this._renderContexts.dispose();
  36180. this._textures.dispose();
  36181. this.setRenderTarget( null );
  36182. this.setAnimationLoop( null );
  36183. }
  36184. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  36185. this._renderTarget = renderTarget;
  36186. this._activeCubeFace = activeCubeFace;
  36187. this._activeMipmapLevel = activeMipmapLevel;
  36188. }
  36189. getRenderTarget() {
  36190. return this._renderTarget;
  36191. }
  36192. setRenderObjectFunction( renderObjectFunction ) {
  36193. this._renderObjectFunction = renderObjectFunction;
  36194. }
  36195. getRenderObjectFunction() {
  36196. return this._renderObjectFunction;
  36197. }
  36198. async computeAsync( computeNodes ) {
  36199. if ( this._initialized === false ) await this.init();
  36200. const nodeFrame = this._nodes.nodeFrame;
  36201. const previousRenderId = nodeFrame.renderId;
  36202. //
  36203. this.info.calls ++;
  36204. this.info.compute.calls ++;
  36205. this.info.compute.frameCalls ++;
  36206. nodeFrame.renderId = this.info.calls;
  36207. //
  36208. const backend = this.backend;
  36209. const pipelines = this._pipelines;
  36210. const bindings = this._bindings;
  36211. const nodes = this._nodes;
  36212. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  36213. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  36214. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  36215. }
  36216. backend.beginCompute( computeNodes );
  36217. for ( const computeNode of computeList ) {
  36218. // onInit
  36219. if ( pipelines.has( computeNode ) === false ) {
  36220. const dispose = () => {
  36221. computeNode.removeEventListener( 'dispose', dispose );
  36222. pipelines.delete( computeNode );
  36223. bindings.delete( computeNode );
  36224. nodes.delete( computeNode );
  36225. };
  36226. computeNode.addEventListener( 'dispose', dispose );
  36227. //
  36228. computeNode.onInit( { renderer: this } );
  36229. }
  36230. nodes.updateForCompute( computeNode );
  36231. bindings.updateForCompute( computeNode );
  36232. const computeBindings = bindings.getForCompute( computeNode );
  36233. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  36234. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  36235. }
  36236. backend.finishCompute( computeNodes );
  36237. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  36238. //
  36239. nodeFrame.renderId = previousRenderId;
  36240. }
  36241. async hasFeatureAsync( name ) {
  36242. if ( this._initialized === false ) await this.init();
  36243. return this.backend.hasFeature( name );
  36244. }
  36245. hasFeature( name ) {
  36246. if ( this._initialized === false ) {
  36247. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  36248. return false;
  36249. }
  36250. return this.backend.hasFeature( name );
  36251. }
  36252. copyFramebufferToTexture( framebufferTexture ) {
  36253. const renderContext = this._currentRenderContext;
  36254. this._textures.updateTexture( framebufferTexture );
  36255. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext );
  36256. }
  36257. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  36258. this._textures.updateTexture( srcTexture );
  36259. this._textures.updateTexture( dstTexture );
  36260. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  36261. }
  36262. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0 ) {
  36263. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height );
  36264. }
  36265. _projectObject( object, camera, groupOrder, renderList ) {
  36266. if ( object.visible === false ) return;
  36267. const visible = object.layers.test( camera.layers );
  36268. if ( visible ) {
  36269. if ( object.isGroup ) {
  36270. groupOrder = object.renderOrder;
  36271. } else if ( object.isLOD ) {
  36272. if ( object.autoUpdate === true ) object.update( camera );
  36273. } else if ( object.isLight ) {
  36274. renderList.pushLight( object );
  36275. } else if ( object.isSprite ) {
  36276. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  36277. if ( this.sortObjects === true ) {
  36278. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  36279. }
  36280. const geometry = object.geometry;
  36281. const material = object.material;
  36282. if ( material.visible ) {
  36283. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  36284. }
  36285. }
  36286. } else if ( object.isLineLoop ) {
  36287. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  36288. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  36289. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  36290. const geometry = object.geometry;
  36291. const material = object.material;
  36292. if ( this.sortObjects === true ) {
  36293. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  36294. _vector3
  36295. .copy( geometry.boundingSphere.center )
  36296. .applyMatrix4( object.matrixWorld )
  36297. .applyMatrix4( _projScreenMatrix );
  36298. }
  36299. if ( Array.isArray( material ) ) {
  36300. const groups = geometry.groups;
  36301. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  36302. const group = groups[ i ];
  36303. const groupMaterial = material[ group.materialIndex ];
  36304. if ( groupMaterial && groupMaterial.visible ) {
  36305. renderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  36306. }
  36307. }
  36308. } else if ( material.visible ) {
  36309. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  36310. }
  36311. }
  36312. }
  36313. }
  36314. if ( object.static === true ) {
  36315. const baseRenderList = renderList;
  36316. // replace render list
  36317. renderList = this._renderLists.get( object, camera );
  36318. renderList.begin();
  36319. baseRenderList.pushBundle( {
  36320. object,
  36321. camera,
  36322. renderList,
  36323. } );
  36324. renderList.finish();
  36325. }
  36326. const children = object.children;
  36327. for ( let i = 0, l = children.length; i < l; i ++ ) {
  36328. this._projectObject( children[ i ], camera, groupOrder, renderList );
  36329. }
  36330. }
  36331. _renderBundles( bundles, sceneRef, lightsNode ) {
  36332. for ( const bundle of bundles ) {
  36333. this._renderBundle( bundle, sceneRef, lightsNode );
  36334. }
  36335. }
  36336. _renderObjects( renderList, camera, scene, lightsNode ) {
  36337. // process renderable objects
  36338. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  36339. const renderItem = renderList[ i ];
  36340. // @TODO: Add support for multiple materials per object. This will require to extract
  36341. // the material from the renderItem object and pass it with its group data to renderObject().
  36342. const { object, geometry, material, group } = renderItem;
  36343. if ( camera.isArrayCamera ) {
  36344. const cameras = camera.cameras;
  36345. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  36346. const camera2 = cameras[ j ];
  36347. if ( object.layers.test( camera2.layers ) ) {
  36348. const vp = camera2.viewport;
  36349. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  36350. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  36351. const viewportValue = this._currentRenderContext.viewportValue;
  36352. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  36353. viewportValue.minDepth = minDepth;
  36354. viewportValue.maxDepth = maxDepth;
  36355. this.backend.updateViewport( this._currentRenderContext );
  36356. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode );
  36357. }
  36358. }
  36359. } else {
  36360. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode );
  36361. }
  36362. }
  36363. }
  36364. renderObject( object, scene, camera, geometry, material, group, lightsNode ) {
  36365. let overridePositionNode;
  36366. let overrideFragmentNode;
  36367. let overrideDepthNode;
  36368. //
  36369. object.onBeforeRender( this, scene, camera, geometry, material, group );
  36370. //
  36371. if ( scene.overrideMaterial !== null ) {
  36372. const overrideMaterial = scene.overrideMaterial;
  36373. if ( material.positionNode && material.positionNode.isNode ) {
  36374. overridePositionNode = overrideMaterial.positionNode;
  36375. overrideMaterial.positionNode = material.positionNode;
  36376. }
  36377. if ( overrideMaterial.isShadowNodeMaterial ) {
  36378. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  36379. if ( material.depthNode && material.depthNode.isNode ) {
  36380. overrideDepthNode = overrideMaterial.depthNode;
  36381. overrideMaterial.depthNode = material.depthNode;
  36382. }
  36383. if ( material.shadowNode && material.shadowNode.isNode ) {
  36384. overrideFragmentNode = overrideMaterial.fragmentNode;
  36385. overrideMaterial.fragmentNode = material.shadowNode;
  36386. }
  36387. if ( this.localClippingEnabled ) {
  36388. if ( material.clipShadows ) {
  36389. if ( overrideMaterial.clippingPlanes !== material.clippingPlanes ) {
  36390. overrideMaterial.clippingPlanes = material.clippingPlanes;
  36391. overrideMaterial.needsUpdate = true;
  36392. }
  36393. if ( overrideMaterial.clipIntersection !== material.clipIntersection ) {
  36394. overrideMaterial.clipIntersection = material.clipIntersection;
  36395. }
  36396. } else if ( Array.isArray( overrideMaterial.clippingPlanes ) ) {
  36397. overrideMaterial.clippingPlanes = null;
  36398. overrideMaterial.needsUpdate = true;
  36399. }
  36400. }
  36401. }
  36402. material = overrideMaterial;
  36403. }
  36404. //
  36405. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  36406. material.side = BackSide;
  36407. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, 'backSide' ); // create backSide pass id
  36408. material.side = FrontSide;
  36409. this._handleObjectFunction( object, material, scene, camera, lightsNode, group ); // use default pass id
  36410. material.side = DoubleSide;
  36411. } else {
  36412. this._handleObjectFunction( object, material, scene, camera, lightsNode, group );
  36413. }
  36414. //
  36415. if ( overridePositionNode !== undefined ) {
  36416. scene.overrideMaterial.positionNode = overridePositionNode;
  36417. }
  36418. if ( overrideDepthNode !== undefined ) {
  36419. scene.overrideMaterial.depthNode = overrideDepthNode;
  36420. }
  36421. if ( overrideFragmentNode !== undefined ) {
  36422. scene.overrideMaterial.fragmentNode = overrideFragmentNode;
  36423. }
  36424. //
  36425. object.onAfterRender( this, scene, camera, geometry, material, group );
  36426. }
  36427. _renderObjectDirect( object, material, scene, camera, lightsNode, group, passId ) {
  36428. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  36429. renderObject.drawRange = group || object.geometry.drawRange;
  36430. //
  36431. this._nodes.updateBefore( renderObject );
  36432. //
  36433. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  36434. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  36435. //
  36436. this._nodes.updateForRender( renderObject );
  36437. this._geometries.updateForRender( renderObject );
  36438. this._bindings.updateForRender( renderObject );
  36439. this._pipelines.updateForRender( renderObject );
  36440. //
  36441. if ( this._currentRenderBundle !== null && this._currentRenderBundle.needsUpdate === true ) {
  36442. const renderObjectData = this.backend.get( renderObject );
  36443. renderObjectData.bundleEncoder = undefined;
  36444. renderObjectData.lastPipelineGPU = undefined;
  36445. }
  36446. this.backend.draw( renderObject, this.info );
  36447. if ( this._currentRenderBundle !== null ) {
  36448. const renderContextData = this.backend.get( this._currentRenderContext );
  36449. renderContextData.renderObjects.push( renderObject );
  36450. }
  36451. this._nodes.updateAfter( renderObject );
  36452. }
  36453. _createObjectPipeline( object, material, scene, camera, lightsNode, passId ) {
  36454. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  36455. //
  36456. this._nodes.updateBefore( renderObject );
  36457. //
  36458. this._nodes.updateForRender( renderObject );
  36459. this._geometries.updateForRender( renderObject );
  36460. this._bindings.updateForRender( renderObject );
  36461. this._pipelines.getForRender( renderObject, this._compilationPromises );
  36462. this._nodes.updateAfter( renderObject );
  36463. }
  36464. get compute() {
  36465. return this.computeAsync;
  36466. }
  36467. get compile() {
  36468. return this.compileAsync;
  36469. }
  36470. }
  36471. class Binding {
  36472. constructor( name = '' ) {
  36473. this.name = name;
  36474. this.visibility = 0;
  36475. }
  36476. setVisibility( visibility ) {
  36477. this.visibility |= visibility;
  36478. }
  36479. clone() {
  36480. return Object.assign( new this.constructor(), this );
  36481. }
  36482. }
  36483. function getFloatLength( floatLength ) {
  36484. // ensure chunk size alignment (STD140 layout)
  36485. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  36486. }
  36487. class Buffer extends Binding {
  36488. constructor( name, buffer = null ) {
  36489. super( name );
  36490. this.isBuffer = true;
  36491. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  36492. this._buffer = buffer;
  36493. }
  36494. get byteLength() {
  36495. return getFloatLength( this._buffer.byteLength );
  36496. }
  36497. get buffer() {
  36498. return this._buffer;
  36499. }
  36500. update() {
  36501. return true;
  36502. }
  36503. }
  36504. class UniformBuffer extends Buffer {
  36505. constructor( name, buffer = null ) {
  36506. super( name, buffer );
  36507. this.isUniformBuffer = true;
  36508. }
  36509. }
  36510. let _id$2 = 0;
  36511. class NodeUniformBuffer extends UniformBuffer {
  36512. constructor( nodeUniform, groupNode ) {
  36513. super( 'UniformBuffer_' + _id$2 ++, nodeUniform ? nodeUniform.value : null );
  36514. this.nodeUniform = nodeUniform;
  36515. this.groupNode = groupNode;
  36516. }
  36517. get buffer() {
  36518. return this.nodeUniform.value;
  36519. }
  36520. }
  36521. class UniformsGroup extends UniformBuffer {
  36522. constructor( name ) {
  36523. super( name );
  36524. this.isUniformsGroup = true;
  36525. this._values = null;
  36526. // the order of uniforms in this array must match the order of uniforms in the shader
  36527. this.uniforms = [];
  36528. }
  36529. addUniform( uniform ) {
  36530. this.uniforms.push( uniform );
  36531. return this;
  36532. }
  36533. removeUniform( uniform ) {
  36534. const index = this.uniforms.indexOf( uniform );
  36535. if ( index !== - 1 ) {
  36536. this.uniforms.splice( index, 1 );
  36537. }
  36538. return this;
  36539. }
  36540. get values() {
  36541. if ( this._values === null ) {
  36542. this._values = Array.from( this.buffer );
  36543. }
  36544. return this._values;
  36545. }
  36546. get buffer() {
  36547. let buffer = this._buffer;
  36548. if ( buffer === null ) {
  36549. const byteLength = this.byteLength;
  36550. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  36551. this._buffer = buffer;
  36552. }
  36553. return buffer;
  36554. }
  36555. get byteLength() {
  36556. let offset = 0; // global buffer offset in bytes
  36557. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  36558. const uniform = this.uniforms[ i ];
  36559. const { boundary, itemSize } = uniform;
  36560. // offset within a single chunk in bytes
  36561. const chunkOffset = offset % GPU_CHUNK_BYTES;
  36562. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  36563. // conformance tests
  36564. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  36565. // check for chunk overflow
  36566. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  36567. } else if ( chunkOffset % boundary !== 0 ) {
  36568. // check for correct alignment
  36569. offset += ( chunkOffset % boundary );
  36570. }
  36571. uniform.offset = ( offset / this.bytesPerElement );
  36572. offset += ( itemSize * this.bytesPerElement );
  36573. }
  36574. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  36575. }
  36576. update() {
  36577. let updated = false;
  36578. for ( const uniform of this.uniforms ) {
  36579. if ( this.updateByType( uniform ) === true ) {
  36580. updated = true;
  36581. }
  36582. }
  36583. return updated;
  36584. }
  36585. updateByType( uniform ) {
  36586. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  36587. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  36588. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  36589. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  36590. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  36591. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  36592. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  36593. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  36594. }
  36595. updateNumber( uniform ) {
  36596. let updated = false;
  36597. const a = this.values;
  36598. const v = uniform.getValue();
  36599. const offset = uniform.offset;
  36600. if ( a[ offset ] !== v ) {
  36601. const b = this.buffer;
  36602. b[ offset ] = a[ offset ] = v;
  36603. updated = true;
  36604. }
  36605. return updated;
  36606. }
  36607. updateVector2( uniform ) {
  36608. let updated = false;
  36609. const a = this.values;
  36610. const v = uniform.getValue();
  36611. const offset = uniform.offset;
  36612. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  36613. const b = this.buffer;
  36614. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36615. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36616. updated = true;
  36617. }
  36618. return updated;
  36619. }
  36620. updateVector3( uniform ) {
  36621. let updated = false;
  36622. const a = this.values;
  36623. const v = uniform.getValue();
  36624. const offset = uniform.offset;
  36625. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  36626. const b = this.buffer;
  36627. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36628. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36629. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  36630. updated = true;
  36631. }
  36632. return updated;
  36633. }
  36634. updateVector4( uniform ) {
  36635. let updated = false;
  36636. const a = this.values;
  36637. const v = uniform.getValue();
  36638. const offset = uniform.offset;
  36639. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  36640. const b = this.buffer;
  36641. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36642. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36643. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  36644. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  36645. updated = true;
  36646. }
  36647. return updated;
  36648. }
  36649. updateColor( uniform ) {
  36650. let updated = false;
  36651. const a = this.values;
  36652. const c = uniform.getValue();
  36653. const offset = uniform.offset;
  36654. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  36655. const b = this.buffer;
  36656. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  36657. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  36658. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  36659. updated = true;
  36660. }
  36661. return updated;
  36662. }
  36663. updateMatrix3( uniform ) {
  36664. let updated = false;
  36665. const a = this.values;
  36666. const e = uniform.getValue().elements;
  36667. const offset = uniform.offset;
  36668. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  36669. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  36670. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  36671. const b = this.buffer;
  36672. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  36673. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  36674. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  36675. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  36676. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  36677. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  36678. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  36679. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  36680. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  36681. updated = true;
  36682. }
  36683. return updated;
  36684. }
  36685. updateMatrix4( uniform ) {
  36686. let updated = false;
  36687. const a = this.values;
  36688. const e = uniform.getValue().elements;
  36689. const offset = uniform.offset;
  36690. if ( arraysEqual( a, e, offset ) === false ) {
  36691. const b = this.buffer;
  36692. b.set( e, offset );
  36693. setArray( a, e, offset );
  36694. updated = true;
  36695. }
  36696. return updated;
  36697. }
  36698. }
  36699. function setArray( a, b, offset ) {
  36700. for ( let i = 0, l = b.length; i < l; i ++ ) {
  36701. a[ offset + i ] = b[ i ];
  36702. }
  36703. }
  36704. function arraysEqual( a, b, offset ) {
  36705. for ( let i = 0, l = b.length; i < l; i ++ ) {
  36706. if ( a[ offset + i ] !== b[ i ] ) return false;
  36707. }
  36708. return true;
  36709. }
  36710. let id$1 = 0;
  36711. class NodeUniformsGroup extends UniformsGroup {
  36712. constructor( name, groupNode ) {
  36713. super( name );
  36714. this.id = id$1 ++;
  36715. this.groupNode = groupNode;
  36716. this.isNodeUniformsGroup = true;
  36717. }
  36718. getNodes() {
  36719. const nodes = [];
  36720. for ( const uniform of this.uniforms ) {
  36721. const node = uniform.nodeUniform.node;
  36722. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  36723. nodes.push( node );
  36724. }
  36725. return nodes;
  36726. }
  36727. }
  36728. let id = 0;
  36729. class SampledTexture extends Binding {
  36730. constructor( name, texture ) {
  36731. super( name );
  36732. this.id = id ++;
  36733. this.texture = texture;
  36734. this.version = texture ? texture.version : 0;
  36735. this.store = false;
  36736. this.isSampledTexture = true;
  36737. }
  36738. get needsBindingsUpdate() {
  36739. const { texture, version } = this;
  36740. return texture.isVideoTexture ? true : version !== texture.version; // @TODO: version === 0 && texture.version > 0 ( add it just to External Textures like PNG,JPG )
  36741. }
  36742. update() {
  36743. const { texture, version } = this;
  36744. if ( version !== texture.version ) {
  36745. this.version = texture.version;
  36746. return true;
  36747. }
  36748. return false;
  36749. }
  36750. }
  36751. class NodeSampledTexture extends SampledTexture {
  36752. constructor( name, textureNode, groupNode, access = null ) {
  36753. super( name, textureNode ? textureNode.value : null );
  36754. this.textureNode = textureNode;
  36755. this.groupNode = groupNode;
  36756. this.access = access;
  36757. }
  36758. get needsBindingsUpdate() {
  36759. return this.textureNode.value !== this.texture || super.needsBindingsUpdate;
  36760. }
  36761. update() {
  36762. const { textureNode } = this;
  36763. if ( this.texture !== textureNode.value ) {
  36764. this.texture = textureNode.value;
  36765. return true;
  36766. }
  36767. return super.update();
  36768. }
  36769. }
  36770. class NodeSampledCubeTexture extends NodeSampledTexture {
  36771. constructor( name, textureNode, groupNode, access ) {
  36772. super( name, textureNode, groupNode, access );
  36773. this.isSampledCubeTexture = true;
  36774. }
  36775. }
  36776. class NodeSampledTexture3D extends NodeSampledTexture {
  36777. constructor( name, textureNode, groupNode, access ) {
  36778. super( name, textureNode, groupNode, access );
  36779. this.isSampledTexture3D = true;
  36780. }
  36781. }
  36782. const glslMethods = {
  36783. [ MathNode.ATAN2 ]: 'atan',
  36784. textureDimensions: 'textureSize',
  36785. equals: 'equal'
  36786. };
  36787. const precisionLib = {
  36788. low: 'lowp',
  36789. medium: 'mediump',
  36790. high: 'highp'
  36791. };
  36792. const supports$1 = {
  36793. swizzleAssign: true,
  36794. storageBuffer: false
  36795. };
  36796. const defaultPrecisions = `
  36797. precision highp float;
  36798. precision highp int;
  36799. precision highp sampler2D;
  36800. precision highp sampler3D;
  36801. precision highp samplerCube;
  36802. precision highp sampler2DArray;
  36803. precision highp usampler2D;
  36804. precision highp usampler3D;
  36805. precision highp usamplerCube;
  36806. precision highp usampler2DArray;
  36807. precision highp isampler2D;
  36808. precision highp isampler3D;
  36809. precision highp isamplerCube;
  36810. precision highp isampler2DArray;
  36811. precision lowp sampler2DShadow;
  36812. `;
  36813. class GLSLNodeBuilder extends NodeBuilder {
  36814. constructor( object, renderer ) {
  36815. super( object, renderer, new GLSLNodeParser() );
  36816. this.uniformGroups = {};
  36817. this.transforms = [];
  36818. this.instanceBindGroups = false;
  36819. }
  36820. getMethod( method ) {
  36821. return glslMethods[ method ] || method;
  36822. }
  36823. getOutputStructName() {
  36824. return '';
  36825. }
  36826. buildFunctionCode( shaderNode ) {
  36827. const layout = shaderNode.layout;
  36828. const flowData = this.flowShaderNode( shaderNode );
  36829. const parameters = [];
  36830. for ( const input of layout.inputs ) {
  36831. parameters.push( this.getType( input.type ) + ' ' + input.name );
  36832. }
  36833. //
  36834. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  36835. ${ flowData.vars }
  36836. ${ flowData.code }
  36837. return ${ flowData.result };
  36838. }`;
  36839. //
  36840. return code;
  36841. }
  36842. setupPBO( storageBufferNode ) {
  36843. const attribute = storageBufferNode.value;
  36844. if ( attribute.pbo === undefined ) {
  36845. const originalArray = attribute.array;
  36846. const numElements = attribute.count * attribute.itemSize;
  36847. const { itemSize } = attribute;
  36848. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  36849. let format = isInteger ? RedIntegerFormat : RedFormat;
  36850. if ( itemSize === 2 ) {
  36851. format = isInteger ? RGIntegerFormat : RGFormat;
  36852. } else if ( itemSize === 3 ) {
  36853. format = isInteger ? RGBIntegerFormat : RGBFormat;
  36854. } else if ( itemSize === 4 ) {
  36855. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  36856. }
  36857. const typeMap = {
  36858. Float32Array: FloatType,
  36859. Uint8Array: UnsignedByteType,
  36860. Uint16Array: UnsignedShortType,
  36861. Uint32Array: UnsignedIntType,
  36862. Int8Array: ByteType,
  36863. Int16Array: ShortType,
  36864. Int32Array: IntType,
  36865. Uint8ClampedArray: UnsignedByteType,
  36866. };
  36867. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  36868. let height = Math.ceil( ( numElements / itemSize ) / width );
  36869. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  36870. const newSize = width * height * itemSize;
  36871. const newArray = new originalArray.constructor( newSize );
  36872. newArray.set( originalArray, 0 );
  36873. attribute.array = newArray;
  36874. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  36875. pboTexture.needsUpdate = true;
  36876. pboTexture.isPBOTexture = true;
  36877. const pbo = new TextureNode( pboTexture, null, null );
  36878. pbo.setPrecision( 'high' );
  36879. attribute.pboNode = pbo;
  36880. attribute.pbo = pbo.value;
  36881. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  36882. }
  36883. }
  36884. getPropertyName( node, shaderStage = this.shaderStage ) {
  36885. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  36886. return shaderStage.charAt( 0 ) + '_' + node.name;
  36887. }
  36888. return super.getPropertyName( node, shaderStage );
  36889. }
  36890. generatePBO( storageArrayElementNode ) {
  36891. const { node, indexNode } = storageArrayElementNode;
  36892. const attribute = node.value;
  36893. if ( this.renderer.backend.has( attribute ) ) {
  36894. const attributeData = this.renderer.backend.get( attribute );
  36895. attributeData.pbo = attribute.pbo;
  36896. }
  36897. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  36898. const textureName = this.getPropertyName( nodeUniform );
  36899. indexNode.increaseUsage( this ); // force cache generate to be used as index in x,y
  36900. const indexSnippet = indexNode.build( this, 'uint' );
  36901. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  36902. let propertyName = elementNodeData.propertyName;
  36903. if ( propertyName === undefined ) {
  36904. // property element
  36905. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  36906. propertyName = this.getPropertyName( nodeVar );
  36907. // property size
  36908. const bufferNodeData = this.getDataFromNode( node );
  36909. let propertySizeName = bufferNodeData.propertySizeName;
  36910. if ( propertySizeName === undefined ) {
  36911. propertySizeName = propertyName + 'Size';
  36912. this.getVarFromNode( node, propertySizeName, 'uint' );
  36913. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )` );
  36914. bufferNodeData.propertySizeName = propertySizeName;
  36915. }
  36916. //
  36917. const { itemSize } = attribute;
  36918. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  36919. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  36920. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  36921. //
  36922. let prefix = 'vec4';
  36923. if ( attribute.pbo.type === UnsignedIntType ) {
  36924. prefix = 'uvec4';
  36925. } else if ( attribute.pbo.type === IntType ) {
  36926. prefix = 'ivec4';
  36927. }
  36928. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}` );
  36929. elementNodeData.propertyName = propertyName;
  36930. }
  36931. return propertyName;
  36932. }
  36933. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  36934. if ( depthSnippet ) {
  36935. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  36936. } else {
  36937. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  36938. }
  36939. }
  36940. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  36941. if ( texture.isDepthTexture ) {
  36942. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  36943. } else {
  36944. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  36945. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  36946. }
  36947. }
  36948. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  36949. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  36950. }
  36951. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  36952. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  36953. }
  36954. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  36955. if ( shaderStage === 'fragment' ) {
  36956. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  36957. } else {
  36958. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  36959. }
  36960. }
  36961. getVars( shaderStage ) {
  36962. const snippets = [];
  36963. const vars = this.vars[ shaderStage ];
  36964. if ( vars !== undefined ) {
  36965. for ( const variable of vars ) {
  36966. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  36967. }
  36968. }
  36969. return snippets.join( '\n\t' );
  36970. }
  36971. getUniforms( shaderStage ) {
  36972. const uniforms = this.uniforms[ shaderStage ];
  36973. const bindingSnippets = [];
  36974. const uniformGroups = {};
  36975. for ( const uniform of uniforms ) {
  36976. let snippet = null;
  36977. let group = false;
  36978. if ( uniform.type === 'texture' ) {
  36979. const texture = uniform.node.value;
  36980. let typePrefix = '';
  36981. if ( texture.isDataTexture === true ) {
  36982. if ( texture.type === UnsignedIntType ) {
  36983. typePrefix = 'u';
  36984. } else if ( texture.type === IntType ) {
  36985. typePrefix = 'i';
  36986. }
  36987. }
  36988. if ( texture.compareFunction ) {
  36989. snippet = `sampler2DShadow ${ uniform.name };`;
  36990. } else if ( texture.isDataArrayTexture === true ) {
  36991. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  36992. } else {
  36993. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  36994. }
  36995. } else if ( uniform.type === 'cubeTexture' ) {
  36996. snippet = `samplerCube ${ uniform.name };`;
  36997. } else if ( uniform.type === 'texture3D' ) {
  36998. snippet = `sampler3D ${ uniform.name };`;
  36999. } else if ( uniform.type === 'buffer' ) {
  37000. const bufferNode = uniform.node;
  37001. const bufferType = this.getType( bufferNode.bufferType );
  37002. const bufferCount = bufferNode.bufferCount;
  37003. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  37004. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  37005. } else {
  37006. const vectorType = this.getVectorType( uniform.type );
  37007. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  37008. group = true;
  37009. }
  37010. const precision = uniform.node.precision;
  37011. if ( precision !== null ) {
  37012. snippet = precisionLib[ precision ] + ' ' + snippet;
  37013. }
  37014. if ( group ) {
  37015. snippet = '\t' + snippet;
  37016. const groupName = uniform.groupNode.name;
  37017. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  37018. groupSnippets.push( snippet );
  37019. } else {
  37020. snippet = 'uniform ' + snippet;
  37021. bindingSnippets.push( snippet );
  37022. }
  37023. }
  37024. let output = '';
  37025. for ( const name in uniformGroups ) {
  37026. const groupSnippets = uniformGroups[ name ];
  37027. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  37028. }
  37029. output += bindingSnippets.join( '\n' );
  37030. return output;
  37031. }
  37032. getTypeFromAttribute( attribute ) {
  37033. let nodeType = super.getTypeFromAttribute( attribute );
  37034. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  37035. let dataAttribute = attribute;
  37036. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  37037. const array = dataAttribute.array;
  37038. if ( ( array instanceof Uint32Array || array instanceof Int32Array || array instanceof Uint16Array || array instanceof Int16Array ) === false ) {
  37039. nodeType = nodeType.slice( 1 );
  37040. }
  37041. }
  37042. return nodeType;
  37043. }
  37044. getAttributes( shaderStage ) {
  37045. let snippet = '';
  37046. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  37047. const attributes = this.getAttributesArray();
  37048. let location = 0;
  37049. for ( const attribute of attributes ) {
  37050. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  37051. }
  37052. }
  37053. return snippet;
  37054. }
  37055. getStructMembers( struct ) {
  37056. const snippets = [];
  37057. const members = struct.getMemberTypes();
  37058. for ( let i = 0; i < members.length; i ++ ) {
  37059. const member = members[ i ];
  37060. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  37061. }
  37062. return snippets.join( '\n' );
  37063. }
  37064. getStructs( shaderStage ) {
  37065. const snippets = [];
  37066. const structs = this.structs[ shaderStage ];
  37067. if ( structs.length === 0 ) {
  37068. return 'layout( location = 0 ) out vec4 fragColor;\n';
  37069. }
  37070. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  37071. const struct = structs[ index ];
  37072. let snippet = '\n';
  37073. snippet += this.getStructMembers( struct );
  37074. snippet += '\n';
  37075. snippets.push( snippet );
  37076. }
  37077. return snippets.join( '\n\n' );
  37078. }
  37079. getVaryings( shaderStage ) {
  37080. let snippet = '';
  37081. const varyings = this.varyings;
  37082. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  37083. for ( const varying of varyings ) {
  37084. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  37085. const type = varying.type;
  37086. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  37087. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  37088. }
  37089. } else if ( shaderStage === 'fragment' ) {
  37090. for ( const varying of varyings ) {
  37091. if ( varying.needsInterpolation ) {
  37092. const type = varying.type;
  37093. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  37094. snippet += `${flat}in ${type} ${varying.name};\n`;
  37095. }
  37096. }
  37097. }
  37098. return snippet;
  37099. }
  37100. getVertexIndex() {
  37101. return 'uint( gl_VertexID )';
  37102. }
  37103. getInstanceIndex() {
  37104. return 'uint( gl_InstanceID )';
  37105. }
  37106. getDrawIndex() {
  37107. const extensions = this.renderer.backend.extensions;
  37108. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  37109. return 'uint( gl_DrawID )';
  37110. }
  37111. return null;
  37112. }
  37113. getFrontFacing() {
  37114. return 'gl_FrontFacing';
  37115. }
  37116. getFragCoord() {
  37117. return 'gl_FragCoord';
  37118. }
  37119. getFragDepth() {
  37120. return 'gl_FragDepth';
  37121. }
  37122. getExtensions( shaderStage ) {
  37123. let extensions = '';
  37124. if ( shaderStage === 'vertex' ) {
  37125. const ext = this.renderer.backend.extensions;
  37126. const isBatchedMesh = this.object.isBatchedMesh;
  37127. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  37128. extensions += '#extension GL_ANGLE_multi_draw : require\n';
  37129. }
  37130. }
  37131. return extensions;
  37132. }
  37133. isAvailable( name ) {
  37134. let result = supports$1[ name ];
  37135. if ( result === undefined ) {
  37136. if ( name === 'float32Filterable' ) {
  37137. const extensions = this.renderer.backend.extensions;
  37138. if ( extensions.has( 'OES_texture_float_linear' ) ) {
  37139. extensions.get( 'OES_texture_float_linear' );
  37140. result = true;
  37141. } else {
  37142. result = false;
  37143. }
  37144. }
  37145. supports$1[ name ] = result;
  37146. }
  37147. return result;
  37148. }
  37149. isFlipY() {
  37150. return true;
  37151. }
  37152. registerTransform( varyingName, attributeNode ) {
  37153. this.transforms.push( { varyingName, attributeNode } );
  37154. }
  37155. getTransforms( /* shaderStage */ ) {
  37156. const transforms = this.transforms;
  37157. let snippet = '';
  37158. for ( let i = 0; i < transforms.length; i ++ ) {
  37159. const transform = transforms[ i ];
  37160. const attributeName = this.getPropertyName( transform.attributeNode );
  37161. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  37162. }
  37163. return snippet;
  37164. }
  37165. _getGLSLUniformStruct( name, vars ) {
  37166. return `
  37167. layout( std140 ) uniform ${name} {
  37168. ${vars}
  37169. };`;
  37170. }
  37171. _getGLSLVertexCode( shaderData ) {
  37172. return `#version 300 es
  37173. // extensions
  37174. ${shaderData.extensions}
  37175. // precision
  37176. ${ defaultPrecisions }
  37177. // uniforms
  37178. ${shaderData.uniforms}
  37179. // varyings
  37180. ${shaderData.varyings}
  37181. // attributes
  37182. ${shaderData.attributes}
  37183. // codes
  37184. ${shaderData.codes}
  37185. void main() {
  37186. // vars
  37187. ${shaderData.vars}
  37188. // transforms
  37189. ${shaderData.transforms}
  37190. // flow
  37191. ${shaderData.flow}
  37192. gl_PointSize = 1.0;
  37193. }
  37194. `;
  37195. }
  37196. _getGLSLFragmentCode( shaderData ) {
  37197. return `#version 300 es
  37198. ${ this.getSignature() }
  37199. // precision
  37200. ${ defaultPrecisions }
  37201. // uniforms
  37202. ${shaderData.uniforms}
  37203. // varyings
  37204. ${shaderData.varyings}
  37205. // codes
  37206. ${shaderData.codes}
  37207. ${shaderData.structs}
  37208. void main() {
  37209. // vars
  37210. ${shaderData.vars}
  37211. // flow
  37212. ${shaderData.flow}
  37213. }
  37214. `;
  37215. }
  37216. buildCode() {
  37217. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  37218. for ( const shaderStage in shadersData ) {
  37219. let flow = '// code\n\n';
  37220. flow += this.flowCode[ shaderStage ];
  37221. const flowNodes = this.flowNodes[ shaderStage ];
  37222. const mainNode = flowNodes[ flowNodes.length - 1 ];
  37223. for ( const node of flowNodes ) {
  37224. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  37225. const slotName = node.name;
  37226. if ( slotName ) {
  37227. if ( flow.length > 0 ) flow += '\n';
  37228. flow += `\t// flow -> ${ slotName }\n\t`;
  37229. }
  37230. flow += `${ flowSlotData.code }\n\t`;
  37231. if ( node === mainNode && shaderStage !== 'compute' ) {
  37232. flow += '// result\n\t';
  37233. if ( shaderStage === 'vertex' ) {
  37234. flow += 'gl_Position = ';
  37235. flow += `${ flowSlotData.result };`;
  37236. } else if ( shaderStage === 'fragment' ) {
  37237. if ( ! node.outputNode.isOutputStructNode ) {
  37238. flow += 'fragColor = ';
  37239. flow += `${ flowSlotData.result };`;
  37240. }
  37241. }
  37242. }
  37243. }
  37244. const stageData = shadersData[ shaderStage ];
  37245. stageData.extensions = this.getExtensions( shaderStage );
  37246. stageData.uniforms = this.getUniforms( shaderStage );
  37247. stageData.attributes = this.getAttributes( shaderStage );
  37248. stageData.varyings = this.getVaryings( shaderStage );
  37249. stageData.vars = this.getVars( shaderStage );
  37250. stageData.structs = this.getStructs( shaderStage );
  37251. stageData.codes = this.getCodes( shaderStage );
  37252. stageData.transforms = this.getTransforms( shaderStage );
  37253. stageData.flow = flow;
  37254. }
  37255. if ( this.material !== null ) {
  37256. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  37257. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  37258. } else {
  37259. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  37260. }
  37261. }
  37262. getUniformFromNode( node, type, shaderStage, name = null ) {
  37263. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  37264. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  37265. let uniformGPU = nodeData.uniformGPU;
  37266. if ( uniformGPU === undefined ) {
  37267. const group = node.groupNode;
  37268. const groupName = group.name;
  37269. const bindings = this.getBindGroupArray( groupName, shaderStage );
  37270. if ( type === 'texture' ) {
  37271. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  37272. bindings.push( uniformGPU );
  37273. } else if ( type === 'cubeTexture' ) {
  37274. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  37275. bindings.push( uniformGPU );
  37276. } else if ( type === 'texture3D' ) {
  37277. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  37278. bindings.push( uniformGPU );
  37279. } else if ( type === 'buffer' ) {
  37280. node.name = `NodeBuffer_${ node.id }`;
  37281. uniformNode.name = `buffer${ node.id }`;
  37282. const buffer = new NodeUniformBuffer( node, group );
  37283. buffer.name = node.name;
  37284. bindings.push( buffer );
  37285. uniformGPU = buffer;
  37286. } else {
  37287. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  37288. let uniformsGroup = uniformsStage[ groupName ];
  37289. if ( uniformsGroup === undefined ) {
  37290. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  37291. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  37292. uniformsStage[ groupName ] = uniformsGroup;
  37293. bindings.push( uniformsGroup );
  37294. }
  37295. uniformGPU = this.getNodeUniform( uniformNode, type );
  37296. uniformsGroup.addUniform( uniformGPU );
  37297. }
  37298. nodeData.uniformGPU = uniformGPU;
  37299. }
  37300. return uniformNode;
  37301. }
  37302. }
  37303. let vector2 = null;
  37304. let vector4 = null;
  37305. let color4 = null;
  37306. class Backend {
  37307. constructor( parameters = {} ) {
  37308. this.parameters = Object.assign( {}, parameters );
  37309. this.data = new WeakMap();
  37310. this.renderer = null;
  37311. this.domElement = null;
  37312. }
  37313. async init( renderer ) {
  37314. this.renderer = renderer;
  37315. }
  37316. // render context
  37317. begin( /*renderContext*/ ) { }
  37318. finish( /*renderContext*/ ) { }
  37319. // render object
  37320. draw( /*renderObject, info*/ ) { }
  37321. // program
  37322. createProgram( /*program*/ ) { }
  37323. destroyProgram( /*program*/ ) { }
  37324. // bindings
  37325. createBindings( /*renderObject*/ ) { }
  37326. updateBindings( /*renderObject*/ ) { }
  37327. // pipeline
  37328. createRenderPipeline( /*renderObject*/ ) { }
  37329. createComputePipeline( /*computeNode, pipeline*/ ) { }
  37330. destroyPipeline( /*pipeline*/ ) { }
  37331. // cache key
  37332. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  37333. getRenderCacheKey( /*renderObject*/ ) { } // return String
  37334. // node builder
  37335. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  37336. // textures
  37337. createSampler( /*texture*/ ) { }
  37338. createDefaultTexture( /*texture*/ ) { }
  37339. createTexture( /*texture*/ ) { }
  37340. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  37341. // attributes
  37342. createAttribute( /*attribute*/ ) { }
  37343. createIndexAttribute( /*attribute*/ ) { }
  37344. updateAttribute( /*attribute*/ ) { }
  37345. destroyAttribute( /*attribute*/ ) { }
  37346. // canvas
  37347. getContext() { }
  37348. updateSize() { }
  37349. // utils
  37350. resolveTimestampAsync( /*renderContext, type*/ ) { }
  37351. hasFeatureAsync( /*name*/ ) { } // return Boolean
  37352. hasFeature( /*name*/ ) { } // return Boolean
  37353. getInstanceCount( renderObject ) {
  37354. const { object, geometry } = renderObject;
  37355. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  37356. }
  37357. getDrawingBufferSize() {
  37358. vector2 = vector2 || new Vector2();
  37359. return this.renderer.getDrawingBufferSize( vector2 );
  37360. }
  37361. getScissor() {
  37362. vector4 = vector4 || new Vector4();
  37363. return this.renderer.getScissor( vector4 );
  37364. }
  37365. setScissorTest( /*boolean*/ ) { }
  37366. getClearColor() {
  37367. const renderer = this.renderer;
  37368. color4 = color4 || new Color4();
  37369. renderer.getClearColor( color4 );
  37370. color4.getRGB( color4, this.renderer.currentColorSpace );
  37371. return color4;
  37372. }
  37373. getDomElement() {
  37374. let domElement = this.domElement;
  37375. if ( domElement === null ) {
  37376. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  37377. // OffscreenCanvas does not have setAttribute, see #22811
  37378. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  37379. this.domElement = domElement;
  37380. }
  37381. return domElement;
  37382. }
  37383. // resource properties
  37384. set( object, value ) {
  37385. this.data.set( object, value );
  37386. }
  37387. get( object ) {
  37388. let map = this.data.get( object );
  37389. if ( map === undefined ) {
  37390. map = {};
  37391. this.data.set( object, map );
  37392. }
  37393. return map;
  37394. }
  37395. has( object ) {
  37396. return this.data.has( object );
  37397. }
  37398. delete( object ) {
  37399. this.data.delete( object );
  37400. }
  37401. }
  37402. let _id$1 = 0;
  37403. class DualAttributeData {
  37404. constructor( attributeData, dualBuffer ) {
  37405. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  37406. this.type = attributeData.type;
  37407. this.bufferType = attributeData.bufferType;
  37408. this.pbo = attributeData.pbo;
  37409. this.byteLength = attributeData.byteLength;
  37410. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  37411. this.version = attributeData.version;
  37412. this.isInteger = attributeData.isInteger;
  37413. this.activeBufferIndex = 0;
  37414. this.baseId = attributeData.id;
  37415. }
  37416. get id() {
  37417. return `${ this.baseId }|${ this.activeBufferIndex }`;
  37418. }
  37419. get bufferGPU() {
  37420. return this.buffers[ this.activeBufferIndex ];
  37421. }
  37422. get transformBuffer() {
  37423. return this.buffers[ this.activeBufferIndex ^ 1 ];
  37424. }
  37425. switchBuffers() {
  37426. this.activeBufferIndex ^= 1;
  37427. }
  37428. }
  37429. class WebGLAttributeUtils {
  37430. constructor( backend ) {
  37431. this.backend = backend;
  37432. }
  37433. createAttribute( attribute, bufferType ) {
  37434. const backend = this.backend;
  37435. const { gl } = backend;
  37436. const array = attribute.array;
  37437. const usage = attribute.usage || gl.STATIC_DRAW;
  37438. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  37439. const bufferData = backend.get( bufferAttribute );
  37440. let bufferGPU = bufferData.bufferGPU;
  37441. if ( bufferGPU === undefined ) {
  37442. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  37443. bufferData.bufferGPU = bufferGPU;
  37444. bufferData.bufferType = bufferType;
  37445. bufferData.version = bufferAttribute.version;
  37446. }
  37447. //attribute.onUploadCallback();
  37448. let type;
  37449. if ( array instanceof Float32Array ) {
  37450. type = gl.FLOAT;
  37451. } else if ( array instanceof Uint16Array ) {
  37452. if ( attribute.isFloat16BufferAttribute ) {
  37453. type = gl.HALF_FLOAT;
  37454. } else {
  37455. type = gl.UNSIGNED_SHORT;
  37456. }
  37457. } else if ( array instanceof Int16Array ) {
  37458. type = gl.SHORT;
  37459. } else if ( array instanceof Uint32Array ) {
  37460. type = gl.UNSIGNED_INT;
  37461. } else if ( array instanceof Int32Array ) {
  37462. type = gl.INT;
  37463. } else if ( array instanceof Int8Array ) {
  37464. type = gl.BYTE;
  37465. } else if ( array instanceof Uint8Array ) {
  37466. type = gl.UNSIGNED_BYTE;
  37467. } else if ( array instanceof Uint8ClampedArray ) {
  37468. type = gl.UNSIGNED_BYTE;
  37469. } else {
  37470. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  37471. }
  37472. let attributeData = {
  37473. bufferGPU,
  37474. bufferType,
  37475. type,
  37476. byteLength: array.byteLength,
  37477. bytesPerElement: array.BYTES_PER_ELEMENT,
  37478. version: attribute.version,
  37479. pbo: attribute.pbo,
  37480. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || type === gl.UNSIGNED_SHORT || attribute.gpuType === IntType,
  37481. id: _id$1 ++
  37482. };
  37483. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  37484. // create buffer for tranform feedback use
  37485. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  37486. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  37487. }
  37488. backend.set( attribute, attributeData );
  37489. }
  37490. updateAttribute( attribute ) {
  37491. const backend = this.backend;
  37492. const { gl } = backend;
  37493. const array = attribute.array;
  37494. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  37495. const bufferData = backend.get( bufferAttribute );
  37496. const bufferType = bufferData.bufferType;
  37497. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  37498. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  37499. if ( updateRanges.length === 0 ) {
  37500. // Not using update ranges
  37501. gl.bufferSubData( bufferType, 0, array );
  37502. } else {
  37503. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  37504. const range = updateRanges[ i ];
  37505. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  37506. array, range.start, range.count );
  37507. }
  37508. bufferAttribute.clearUpdateRanges();
  37509. }
  37510. gl.bindBuffer( bufferType, null );
  37511. bufferData.version = bufferAttribute.version;
  37512. }
  37513. destroyAttribute( attribute ) {
  37514. const backend = this.backend;
  37515. const { gl } = backend;
  37516. if ( attribute.isInterleavedBufferAttribute ) {
  37517. backend.delete( attribute.data );
  37518. }
  37519. const attributeData = backend.get( attribute );
  37520. gl.deleteBuffer( attributeData.bufferGPU );
  37521. backend.delete( attribute );
  37522. }
  37523. async getArrayBufferAsync( attribute ) {
  37524. const backend = this.backend;
  37525. const { gl } = backend;
  37526. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  37527. const { bufferGPU } = backend.get( bufferAttribute );
  37528. const array = attribute.array;
  37529. const byteLength = array.byteLength;
  37530. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  37531. const writeBuffer = gl.createBuffer();
  37532. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  37533. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  37534. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  37535. await backend.utils._clientWaitAsync();
  37536. const dstBuffer = new attribute.array.constructor( array.length );
  37537. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  37538. gl.deleteBuffer( writeBuffer );
  37539. return dstBuffer.buffer;
  37540. }
  37541. _createBuffer( gl, bufferType, array, usage ) {
  37542. const bufferGPU = gl.createBuffer();
  37543. gl.bindBuffer( bufferType, bufferGPU );
  37544. gl.bufferData( bufferType, array, usage );
  37545. gl.bindBuffer( bufferType, null );
  37546. return bufferGPU;
  37547. }
  37548. }
  37549. let initialized$1 = false, equationToGL, factorToGL;
  37550. class WebGLState {
  37551. constructor( backend ) {
  37552. this.backend = backend;
  37553. this.gl = this.backend.gl;
  37554. this.enabled = {};
  37555. this.currentFlipSided = null;
  37556. this.currentCullFace = null;
  37557. this.currentProgram = null;
  37558. this.currentBlendingEnabled = false;
  37559. this.currentBlending = null;
  37560. this.currentBlendSrc = null;
  37561. this.currentBlendDst = null;
  37562. this.currentBlendSrcAlpha = null;
  37563. this.currentBlendDstAlpha = null;
  37564. this.currentPremultipledAlpha = null;
  37565. this.currentPolygonOffsetFactor = null;
  37566. this.currentPolygonOffsetUnits = null;
  37567. this.currentColorMask = null;
  37568. this.currentDepthFunc = null;
  37569. this.currentDepthMask = null;
  37570. this.currentStencilFunc = null;
  37571. this.currentStencilRef = null;
  37572. this.currentStencilFuncMask = null;
  37573. this.currentStencilFail = null;
  37574. this.currentStencilZFail = null;
  37575. this.currentStencilZPass = null;
  37576. this.currentStencilMask = null;
  37577. this.currentLineWidth = null;
  37578. this.currentBoundFramebuffers = {};
  37579. this.currentDrawbuffers = new WeakMap();
  37580. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  37581. this.currentTextureSlot = null;
  37582. this.currentBoundTextures = {};
  37583. if ( initialized$1 === false ) {
  37584. this._init( this.gl );
  37585. initialized$1 = true;
  37586. }
  37587. }
  37588. _init( gl ) {
  37589. // Store only WebGL constants here.
  37590. equationToGL = {
  37591. [ AddEquation ]: gl.FUNC_ADD,
  37592. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  37593. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  37594. };
  37595. factorToGL = {
  37596. [ ZeroFactor ]: gl.ZERO,
  37597. [ OneFactor ]: gl.ONE,
  37598. [ SrcColorFactor ]: gl.SRC_COLOR,
  37599. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  37600. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  37601. [ DstColorFactor ]: gl.DST_COLOR,
  37602. [ DstAlphaFactor ]: gl.DST_ALPHA,
  37603. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  37604. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  37605. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  37606. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  37607. };
  37608. }
  37609. enable( id ) {
  37610. const { enabled } = this;
  37611. if ( enabled[ id ] !== true ) {
  37612. this.gl.enable( id );
  37613. enabled[ id ] = true;
  37614. }
  37615. }
  37616. disable( id ) {
  37617. const { enabled } = this;
  37618. if ( enabled[ id ] !== false ) {
  37619. this.gl.disable( id );
  37620. enabled[ id ] = false;
  37621. }
  37622. }
  37623. setFlipSided( flipSided ) {
  37624. if ( this.currentFlipSided !== flipSided ) {
  37625. const { gl } = this;
  37626. if ( flipSided ) {
  37627. gl.frontFace( gl.CW );
  37628. } else {
  37629. gl.frontFace( gl.CCW );
  37630. }
  37631. this.currentFlipSided = flipSided;
  37632. }
  37633. }
  37634. setCullFace( cullFace ) {
  37635. const { gl } = this;
  37636. if ( cullFace !== CullFaceNone ) {
  37637. this.enable( gl.CULL_FACE );
  37638. if ( cullFace !== this.currentCullFace ) {
  37639. if ( cullFace === CullFaceBack ) {
  37640. gl.cullFace( gl.BACK );
  37641. } else if ( cullFace === CullFaceFront ) {
  37642. gl.cullFace( gl.FRONT );
  37643. } else {
  37644. gl.cullFace( gl.FRONT_AND_BACK );
  37645. }
  37646. }
  37647. } else {
  37648. this.disable( gl.CULL_FACE );
  37649. }
  37650. this.currentCullFace = cullFace;
  37651. }
  37652. setLineWidth( width ) {
  37653. const { currentLineWidth, gl } = this;
  37654. if ( width !== currentLineWidth ) {
  37655. gl.lineWidth( width );
  37656. this.currentLineWidth = width;
  37657. }
  37658. }
  37659. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  37660. const { gl } = this;
  37661. if ( blending === NoBlending ) {
  37662. if ( this.currentBlendingEnabled === true ) {
  37663. this.disable( gl.BLEND );
  37664. this.currentBlendingEnabled = false;
  37665. }
  37666. return;
  37667. }
  37668. if ( this.currentBlendingEnabled === false ) {
  37669. this.enable( gl.BLEND );
  37670. this.currentBlendingEnabled = true;
  37671. }
  37672. if ( blending !== CustomBlending ) {
  37673. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  37674. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  37675. gl.blendEquation( gl.FUNC_ADD );
  37676. this.currentBlendEquation = AddEquation;
  37677. this.currentBlendEquationAlpha = AddEquation;
  37678. }
  37679. if ( premultipliedAlpha ) {
  37680. switch ( blending ) {
  37681. case NormalBlending:
  37682. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  37683. break;
  37684. case AdditiveBlending:
  37685. gl.blendFunc( gl.ONE, gl.ONE );
  37686. break;
  37687. case SubtractiveBlending:
  37688. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  37689. break;
  37690. case MultiplyBlending:
  37691. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  37692. break;
  37693. default:
  37694. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  37695. break;
  37696. }
  37697. } else {
  37698. switch ( blending ) {
  37699. case NormalBlending:
  37700. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  37701. break;
  37702. case AdditiveBlending:
  37703. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  37704. break;
  37705. case SubtractiveBlending:
  37706. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  37707. break;
  37708. case MultiplyBlending:
  37709. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  37710. break;
  37711. default:
  37712. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  37713. break;
  37714. }
  37715. }
  37716. this.currentBlendSrc = null;
  37717. this.currentBlendDst = null;
  37718. this.currentBlendSrcAlpha = null;
  37719. this.currentBlendDstAlpha = null;
  37720. this.currentBlending = blending;
  37721. this.currentPremultipledAlpha = premultipliedAlpha;
  37722. }
  37723. return;
  37724. }
  37725. // custom blending
  37726. blendEquationAlpha = blendEquationAlpha || blendEquation;
  37727. blendSrcAlpha = blendSrcAlpha || blendSrc;
  37728. blendDstAlpha = blendDstAlpha || blendDst;
  37729. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  37730. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  37731. this.currentBlendEquation = blendEquation;
  37732. this.currentBlendEquationAlpha = blendEquationAlpha;
  37733. }
  37734. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  37735. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  37736. this.currentBlendSrc = blendSrc;
  37737. this.currentBlendDst = blendDst;
  37738. this.currentBlendSrcAlpha = blendSrcAlpha;
  37739. this.currentBlendDstAlpha = blendDstAlpha;
  37740. }
  37741. this.currentBlending = blending;
  37742. this.currentPremultipledAlpha = false;
  37743. }
  37744. setColorMask( colorMask ) {
  37745. if ( this.currentColorMask !== colorMask ) {
  37746. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  37747. this.currentColorMask = colorMask;
  37748. }
  37749. }
  37750. setDepthTest( depthTest ) {
  37751. const { gl } = this;
  37752. if ( depthTest ) {
  37753. this.enable( gl.DEPTH_TEST );
  37754. } else {
  37755. this.disable( gl.DEPTH_TEST );
  37756. }
  37757. }
  37758. setDepthMask( depthMask ) {
  37759. if ( this.currentDepthMask !== depthMask ) {
  37760. this.gl.depthMask( depthMask );
  37761. this.currentDepthMask = depthMask;
  37762. }
  37763. }
  37764. setDepthFunc( depthFunc ) {
  37765. if ( this.currentDepthFunc !== depthFunc ) {
  37766. const { gl } = this;
  37767. switch ( depthFunc ) {
  37768. case NeverDepth:
  37769. gl.depthFunc( gl.NEVER );
  37770. break;
  37771. case AlwaysDepth:
  37772. gl.depthFunc( gl.ALWAYS );
  37773. break;
  37774. case LessDepth:
  37775. gl.depthFunc( gl.LESS );
  37776. break;
  37777. case LessEqualDepth:
  37778. gl.depthFunc( gl.LEQUAL );
  37779. break;
  37780. case EqualDepth:
  37781. gl.depthFunc( gl.EQUAL );
  37782. break;
  37783. case GreaterEqualDepth:
  37784. gl.depthFunc( gl.GEQUAL );
  37785. break;
  37786. case GreaterDepth:
  37787. gl.depthFunc( gl.GREATER );
  37788. break;
  37789. case NotEqualDepth:
  37790. gl.depthFunc( gl.NOTEQUAL );
  37791. break;
  37792. default:
  37793. gl.depthFunc( gl.LEQUAL );
  37794. }
  37795. this.currentDepthFunc = depthFunc;
  37796. }
  37797. }
  37798. setStencilTest( stencilTest ) {
  37799. const { gl } = this;
  37800. if ( stencilTest ) {
  37801. this.enable( gl.STENCIL_TEST );
  37802. } else {
  37803. this.disable( gl.STENCIL_TEST );
  37804. }
  37805. }
  37806. setStencilMask( stencilMask ) {
  37807. if ( this.currentStencilMask !== stencilMask ) {
  37808. this.gl.stencilMask( stencilMask );
  37809. this.currentStencilMask = stencilMask;
  37810. }
  37811. }
  37812. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  37813. if ( this.currentStencilFunc !== stencilFunc ||
  37814. this.currentStencilRef !== stencilRef ||
  37815. this.currentStencilFuncMask !== stencilMask ) {
  37816. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  37817. this.currentStencilFunc = stencilFunc;
  37818. this.currentStencilRef = stencilRef;
  37819. this.currentStencilFuncMask = stencilMask;
  37820. }
  37821. }
  37822. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  37823. if ( this.currentStencilFail !== stencilFail ||
  37824. this.currentStencilZFail !== stencilZFail ||
  37825. this.currentStencilZPass !== stencilZPass ) {
  37826. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  37827. this.currentStencilFail = stencilFail;
  37828. this.currentStencilZFail = stencilZFail;
  37829. this.currentStencilZPass = stencilZPass;
  37830. }
  37831. }
  37832. setMaterial( material, frontFaceCW ) {
  37833. const { gl } = this;
  37834. material.side === DoubleSide
  37835. ? this.disable( gl.CULL_FACE )
  37836. : this.enable( gl.CULL_FACE );
  37837. let flipSided = ( material.side === BackSide );
  37838. if ( frontFaceCW ) flipSided = ! flipSided;
  37839. this.setFlipSided( flipSided );
  37840. ( material.blending === NormalBlending && material.transparent === false )
  37841. ? this.setBlending( NoBlending )
  37842. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  37843. this.setDepthFunc( material.depthFunc );
  37844. this.setDepthTest( material.depthTest );
  37845. this.setDepthMask( material.depthWrite );
  37846. this.setColorMask( material.colorWrite );
  37847. const stencilWrite = material.stencilWrite;
  37848. this.setStencilTest( stencilWrite );
  37849. if ( stencilWrite ) {
  37850. this.setStencilMask( material.stencilWriteMask );
  37851. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  37852. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  37853. }
  37854. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  37855. material.alphaToCoverage === true
  37856. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  37857. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  37858. }
  37859. setPolygonOffset( polygonOffset, factor, units ) {
  37860. const { gl } = this;
  37861. if ( polygonOffset ) {
  37862. this.enable( gl.POLYGON_OFFSET_FILL );
  37863. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  37864. gl.polygonOffset( factor, units );
  37865. this.currentPolygonOffsetFactor = factor;
  37866. this.currentPolygonOffsetUnits = units;
  37867. }
  37868. } else {
  37869. this.disable( gl.POLYGON_OFFSET_FILL );
  37870. }
  37871. }
  37872. useProgram( program ) {
  37873. if ( this.currentProgram !== program ) {
  37874. this.gl.useProgram( program );
  37875. this.currentProgram = program;
  37876. return true;
  37877. }
  37878. return false;
  37879. }
  37880. // framebuffer
  37881. bindFramebuffer( target, framebuffer ) {
  37882. const { gl, currentBoundFramebuffers } = this;
  37883. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  37884. gl.bindFramebuffer( target, framebuffer );
  37885. currentBoundFramebuffers[ target ] = framebuffer;
  37886. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  37887. if ( target === gl.DRAW_FRAMEBUFFER ) {
  37888. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  37889. }
  37890. if ( target === gl.FRAMEBUFFER ) {
  37891. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  37892. }
  37893. return true;
  37894. }
  37895. return false;
  37896. }
  37897. drawBuffers( renderContext, framebuffer ) {
  37898. const { gl } = this;
  37899. let drawBuffers = [];
  37900. let needsUpdate = false;
  37901. if ( renderContext.textures !== null ) {
  37902. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  37903. if ( drawBuffers === undefined ) {
  37904. drawBuffers = [];
  37905. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  37906. }
  37907. const textures = renderContext.textures;
  37908. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  37909. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  37910. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  37911. }
  37912. drawBuffers.length = textures.length;
  37913. needsUpdate = true;
  37914. }
  37915. } else {
  37916. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  37917. drawBuffers[ 0 ] = gl.BACK;
  37918. needsUpdate = true;
  37919. }
  37920. }
  37921. if ( needsUpdate ) {
  37922. gl.drawBuffers( drawBuffers );
  37923. }
  37924. }
  37925. // texture
  37926. activeTexture( webglSlot ) {
  37927. const { gl, currentTextureSlot, maxTextures } = this;
  37928. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  37929. if ( currentTextureSlot !== webglSlot ) {
  37930. gl.activeTexture( webglSlot );
  37931. this.currentTextureSlot = webglSlot;
  37932. }
  37933. }
  37934. bindTexture( webglType, webglTexture, webglSlot ) {
  37935. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  37936. if ( webglSlot === undefined ) {
  37937. if ( currentTextureSlot === null ) {
  37938. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  37939. } else {
  37940. webglSlot = currentTextureSlot;
  37941. }
  37942. }
  37943. let boundTexture = currentBoundTextures[ webglSlot ];
  37944. if ( boundTexture === undefined ) {
  37945. boundTexture = { type: undefined, texture: undefined };
  37946. currentBoundTextures[ webglSlot ] = boundTexture;
  37947. }
  37948. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  37949. if ( currentTextureSlot !== webglSlot ) {
  37950. gl.activeTexture( webglSlot );
  37951. this.currentTextureSlot = webglSlot;
  37952. }
  37953. gl.bindTexture( webglType, webglTexture );
  37954. boundTexture.type = webglType;
  37955. boundTexture.texture = webglTexture;
  37956. }
  37957. }
  37958. unbindTexture() {
  37959. const { gl, currentTextureSlot, currentBoundTextures } = this;
  37960. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  37961. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  37962. gl.bindTexture( boundTexture.type, null );
  37963. boundTexture.type = undefined;
  37964. boundTexture.texture = undefined;
  37965. }
  37966. }
  37967. }
  37968. class WebGLUtils {
  37969. constructor( backend ) {
  37970. this.backend = backend;
  37971. this.gl = this.backend.gl;
  37972. this.extensions = backend.extensions;
  37973. }
  37974. convert( p, colorSpace = NoColorSpace ) {
  37975. const { gl, extensions } = this;
  37976. let extension;
  37977. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  37978. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  37979. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  37980. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  37981. if ( p === ByteType ) return gl.BYTE;
  37982. if ( p === ShortType ) return gl.SHORT;
  37983. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  37984. if ( p === IntType ) return gl.INT;
  37985. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  37986. if ( p === FloatType ) return gl.FLOAT;
  37987. if ( p === HalfFloatType ) {
  37988. return gl.HALF_FLOAT;
  37989. }
  37990. if ( p === AlphaFormat ) return gl.ALPHA;
  37991. if ( p === RGBFormat ) return gl.RGB;
  37992. if ( p === RGBAFormat ) return gl.RGBA;
  37993. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  37994. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  37995. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  37996. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  37997. // WebGL2 formats.
  37998. if ( p === RedFormat ) return gl.RED;
  37999. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  38000. if ( p === RGFormat ) return gl.RG;
  38001. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  38002. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  38003. // S3TC
  38004. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  38005. if ( colorSpace === SRGBColorSpace ) {
  38006. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  38007. if ( extension !== null ) {
  38008. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  38009. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  38010. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  38011. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  38012. } else {
  38013. return null;
  38014. }
  38015. } else {
  38016. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  38017. if ( extension !== null ) {
  38018. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  38019. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  38020. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  38021. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  38022. } else {
  38023. return null;
  38024. }
  38025. }
  38026. }
  38027. // PVRTC
  38028. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  38029. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  38030. if ( extension !== null ) {
  38031. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  38032. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  38033. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  38034. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  38035. } else {
  38036. return null;
  38037. }
  38038. }
  38039. // ETC
  38040. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  38041. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  38042. if ( extension !== null ) {
  38043. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  38044. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  38045. } else {
  38046. return null;
  38047. }
  38048. }
  38049. // ASTC
  38050. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  38051. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  38052. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  38053. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  38054. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  38055. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  38056. if ( extension !== null ) {
  38057. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  38058. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  38059. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  38060. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  38061. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  38062. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  38063. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  38064. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  38065. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  38066. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  38067. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  38068. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  38069. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  38070. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  38071. } else {
  38072. return null;
  38073. }
  38074. }
  38075. // BPTC
  38076. if ( p === RGBA_BPTC_Format ) {
  38077. extension = extensions.get( 'EXT_texture_compression_bptc' );
  38078. if ( extension !== null ) {
  38079. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  38080. } else {
  38081. return null;
  38082. }
  38083. }
  38084. // RGTC
  38085. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  38086. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  38087. if ( extension !== null ) {
  38088. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  38089. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  38090. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  38091. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  38092. } else {
  38093. return null;
  38094. }
  38095. }
  38096. //
  38097. if ( p === UnsignedInt248Type ) {
  38098. return gl.UNSIGNED_INT_24_8;
  38099. }
  38100. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  38101. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  38102. }
  38103. _clientWaitAsync() {
  38104. const { gl } = this;
  38105. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  38106. gl.flush();
  38107. return new Promise( ( resolve, reject ) => {
  38108. function test() {
  38109. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  38110. if ( res === gl.WAIT_FAILED ) {
  38111. gl.deleteSync( sync );
  38112. reject();
  38113. return;
  38114. }
  38115. if ( res === gl.TIMEOUT_EXPIRED ) {
  38116. requestAnimationFrame( test );
  38117. return;
  38118. }
  38119. gl.deleteSync( sync );
  38120. resolve();
  38121. }
  38122. test();
  38123. } );
  38124. }
  38125. }
  38126. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  38127. class WebGLTextureUtils {
  38128. constructor( backend ) {
  38129. this.backend = backend;
  38130. this.gl = backend.gl;
  38131. this.extensions = backend.extensions;
  38132. this.defaultTextures = {};
  38133. if ( initialized === false ) {
  38134. this._init( this.gl );
  38135. initialized = true;
  38136. }
  38137. }
  38138. _init( gl ) {
  38139. // Store only WebGL constants here.
  38140. wrappingToGL = {
  38141. [ RepeatWrapping ]: gl.REPEAT,
  38142. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  38143. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  38144. };
  38145. filterToGL = {
  38146. [ NearestFilter ]: gl.NEAREST,
  38147. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  38148. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  38149. [ LinearFilter ]: gl.LINEAR,
  38150. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  38151. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  38152. };
  38153. compareToGL = {
  38154. [ NeverCompare ]: gl.NEVER,
  38155. [ AlwaysCompare ]: gl.ALWAYS,
  38156. [ LessCompare ]: gl.LESS,
  38157. [ LessEqualCompare ]: gl.LEQUAL,
  38158. [ EqualCompare ]: gl.EQUAL,
  38159. [ GreaterEqualCompare ]: gl.GEQUAL,
  38160. [ GreaterCompare ]: gl.GREATER,
  38161. [ NotEqualCompare ]: gl.NOTEQUAL
  38162. };
  38163. }
  38164. filterFallback( f ) {
  38165. const { gl } = this;
  38166. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  38167. return gl.NEAREST;
  38168. }
  38169. return gl.LINEAR;
  38170. }
  38171. getGLTextureType( texture ) {
  38172. const { gl } = this;
  38173. let glTextureType;
  38174. if ( texture.isCubeTexture === true ) {
  38175. glTextureType = gl.TEXTURE_CUBE_MAP;
  38176. } else if ( texture.isDataArrayTexture === true ) {
  38177. glTextureType = gl.TEXTURE_2D_ARRAY;
  38178. } else if ( texture.isData3DTexture === true ) {
  38179. glTextureType = gl.TEXTURE_3D;
  38180. } else {
  38181. glTextureType = gl.TEXTURE_2D;
  38182. }
  38183. return glTextureType;
  38184. }
  38185. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  38186. const { gl, extensions } = this;
  38187. if ( internalFormatName !== null ) {
  38188. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  38189. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  38190. }
  38191. let internalFormat = glFormat;
  38192. if ( glFormat === gl.RED ) {
  38193. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  38194. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  38195. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  38196. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  38197. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  38198. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  38199. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  38200. if ( glType === gl.INT ) internalFormat = gl.R32I;
  38201. }
  38202. if ( glFormat === gl.RED_INTEGER ) {
  38203. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  38204. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  38205. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  38206. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  38207. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  38208. if ( glType === gl.INT ) internalFormat = gl.R32I;
  38209. }
  38210. if ( glFormat === gl.RG ) {
  38211. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  38212. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  38213. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  38214. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  38215. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  38216. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  38217. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  38218. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  38219. }
  38220. if ( glFormat === gl.RG_INTEGER ) {
  38221. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  38222. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  38223. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  38224. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  38225. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  38226. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  38227. }
  38228. if ( glFormat === gl.RGB ) {
  38229. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  38230. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  38231. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  38232. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  38233. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  38234. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  38235. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  38236. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  38237. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  38238. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  38239. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  38240. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  38241. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  38242. }
  38243. if ( glFormat === gl.RGB_INTEGER ) {
  38244. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  38245. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  38246. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  38247. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  38248. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  38249. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  38250. }
  38251. if ( glFormat === gl.RGBA ) {
  38252. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  38253. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  38254. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  38255. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  38256. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  38257. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  38258. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  38259. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  38260. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  38261. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  38262. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  38263. }
  38264. if ( glFormat === gl.RGBA_INTEGER ) {
  38265. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  38266. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  38267. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  38268. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  38269. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  38270. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  38271. }
  38272. if ( glFormat === gl.DEPTH_COMPONENT ) {
  38273. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  38274. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  38275. }
  38276. if ( glFormat === gl.DEPTH_STENCIL ) {
  38277. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  38278. }
  38279. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  38280. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  38281. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  38282. extensions.get( 'EXT_color_buffer_float' );
  38283. }
  38284. return internalFormat;
  38285. }
  38286. setTextureParameters( textureType, texture ) {
  38287. const { gl, extensions, backend } = this;
  38288. const { currentAnisotropy } = backend.get( texture );
  38289. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  38290. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  38291. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  38292. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  38293. }
  38294. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  38295. // follow WebGPU backend mapping for texture filtering
  38296. const minFilter = ! texture.isVideoTexture && texture.minFilter === LinearFilter ? LinearMipmapLinearFilter : texture.minFilter;
  38297. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  38298. if ( texture.compareFunction ) {
  38299. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  38300. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  38301. }
  38302. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  38303. if ( texture.magFilter === NearestFilter ) return;
  38304. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  38305. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  38306. if ( texture.anisotropy > 1 || currentAnisotropy !== texture.anisotropy ) {
  38307. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  38308. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  38309. backend.get( texture ).currentAnisotropy = texture.anisotropy;
  38310. }
  38311. }
  38312. }
  38313. createDefaultTexture( texture ) {
  38314. const { gl, backend, defaultTextures } = this;
  38315. const glTextureType = this.getGLTextureType( texture );
  38316. let textureGPU = defaultTextures[ glTextureType ];
  38317. if ( textureGPU === undefined ) {
  38318. textureGPU = gl.createTexture();
  38319. backend.state.bindTexture( glTextureType, textureGPU );
  38320. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  38321. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  38322. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  38323. defaultTextures[ glTextureType ] = textureGPU;
  38324. }
  38325. backend.set( texture, {
  38326. textureGPU,
  38327. glTextureType,
  38328. isDefault: true
  38329. } );
  38330. }
  38331. createTexture( texture, options ) {
  38332. const { gl, backend } = this;
  38333. const { levels, width, height, depth } = options;
  38334. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  38335. const glType = backend.utils.convert( texture.type );
  38336. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  38337. const textureGPU = gl.createTexture();
  38338. const glTextureType = this.getGLTextureType( texture );
  38339. backend.state.bindTexture( glTextureType, textureGPU );
  38340. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  38341. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  38342. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  38343. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  38344. this.setTextureParameters( glTextureType, texture );
  38345. if ( texture.isDataArrayTexture ) {
  38346. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  38347. } else if ( texture.isData3DTexture ) {
  38348. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  38349. } else if ( ! texture.isVideoTexture ) {
  38350. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  38351. }
  38352. backend.set( texture, {
  38353. textureGPU,
  38354. glTextureType,
  38355. glFormat,
  38356. glType,
  38357. glInternalFormat
  38358. } );
  38359. }
  38360. copyBufferToTexture( buffer, texture ) {
  38361. const { gl, backend } = this;
  38362. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  38363. const { width, height } = texture.source.data;
  38364. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  38365. backend.state.bindTexture( glTextureType, textureGPU );
  38366. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  38367. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  38368. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  38369. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  38370. backend.state.unbindTexture();
  38371. // debug
  38372. // const framebuffer = gl.createFramebuffer();
  38373. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  38374. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  38375. // const readout = new Float32Array( width * height * 4 );
  38376. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  38377. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  38378. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  38379. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  38380. // console.log( readout );
  38381. }
  38382. updateTexture( texture, options ) {
  38383. const { gl } = this;
  38384. const { width, height } = options;
  38385. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  38386. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  38387. return;
  38388. const getImage = ( source ) => {
  38389. if ( source.isDataTexture ) {
  38390. return source.image.data;
  38391. } else if ( source instanceof ImageBitmap || source instanceof OffscreenCanvas || source instanceof HTMLImageElement || source instanceof HTMLCanvasElement ) {
  38392. return source;
  38393. }
  38394. return source.data;
  38395. };
  38396. this.backend.state.bindTexture( glTextureType, textureGPU );
  38397. if ( texture.isCompressedTexture ) {
  38398. const mipmaps = texture.mipmaps;
  38399. for ( let i = 0; i < mipmaps.length; i ++ ) {
  38400. const mipmap = mipmaps[ i ];
  38401. if ( texture.isCompressedArrayTexture ) {
  38402. const image = options.image;
  38403. if ( texture.format !== gl.RGBA ) {
  38404. if ( glFormat !== null ) {
  38405. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  38406. } else {
  38407. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  38408. }
  38409. } else {
  38410. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  38411. }
  38412. } else {
  38413. if ( glFormat !== null ) {
  38414. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  38415. } else {
  38416. console.warn( 'Unsupported compressed texture format' );
  38417. }
  38418. }
  38419. }
  38420. } else if ( texture.isCubeTexture ) {
  38421. const images = options.images;
  38422. for ( let i = 0; i < 6; i ++ ) {
  38423. const image = getImage( images[ i ] );
  38424. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  38425. }
  38426. } else if ( texture.isDataArrayTexture ) {
  38427. const image = options.image;
  38428. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  38429. } else if ( texture.isData3DTexture ) {
  38430. const image = options.image;
  38431. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  38432. } else if ( texture.isVideoTexture ) {
  38433. texture.update();
  38434. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  38435. } else {
  38436. const image = getImage( options.image );
  38437. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  38438. }
  38439. }
  38440. generateMipmaps( texture ) {
  38441. const { gl, backend } = this;
  38442. const { textureGPU, glTextureType } = backend.get( texture );
  38443. backend.state.bindTexture( glTextureType, textureGPU );
  38444. gl.generateMipmap( glTextureType );
  38445. }
  38446. deallocateRenderBuffers( renderTarget ) {
  38447. const { gl, backend } = this;
  38448. // remove framebuffer reference
  38449. if ( renderTarget ) {
  38450. const renderContextData = backend.get( renderTarget );
  38451. renderContextData.renderBufferStorageSetup = undefined;
  38452. if ( renderContextData.framebuffer ) {
  38453. gl.deleteFramebuffer( renderContextData.framebuffer );
  38454. renderContextData.framebuffer = undefined;
  38455. }
  38456. if ( renderContextData.depthRenderbuffer ) {
  38457. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  38458. renderContextData.depthRenderbuffer = undefined;
  38459. }
  38460. if ( renderContextData.stencilRenderbuffer ) {
  38461. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  38462. renderContextData.stencilRenderbuffer = undefined;
  38463. }
  38464. if ( renderContextData.msaaFrameBuffer ) {
  38465. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  38466. renderContextData.msaaFrameBuffer = undefined;
  38467. }
  38468. if ( renderContextData.msaaRenderbuffers ) {
  38469. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  38470. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  38471. }
  38472. renderContextData.msaaRenderbuffers = undefined;
  38473. }
  38474. }
  38475. }
  38476. destroyTexture( texture ) {
  38477. const { gl, backend } = this;
  38478. const { textureGPU, renderTarget } = backend.get( texture );
  38479. this.deallocateRenderBuffers( renderTarget );
  38480. gl.deleteTexture( textureGPU );
  38481. backend.delete( texture );
  38482. }
  38483. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  38484. const { gl, backend } = this;
  38485. const { state } = this.backend;
  38486. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  38487. let width, height, minX, minY;
  38488. let dstX, dstY;
  38489. if ( srcRegion !== null ) {
  38490. width = srcRegion.max.x - srcRegion.min.x;
  38491. height = srcRegion.max.y - srcRegion.min.y;
  38492. minX = srcRegion.min.x;
  38493. minY = srcRegion.min.y;
  38494. } else {
  38495. width = srcTexture.image.width;
  38496. height = srcTexture.image.height;
  38497. minX = 0;
  38498. minY = 0;
  38499. }
  38500. if ( dstPosition !== null ) {
  38501. dstX = dstPosition.x;
  38502. dstY = dstPosition.y;
  38503. } else {
  38504. dstX = 0;
  38505. dstY = 0;
  38506. }
  38507. state.bindTexture( glTextureType, dstTextureGPU );
  38508. // As another texture upload may have changed pixelStorei
  38509. // parameters, make sure they are correct for the dstTexture
  38510. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  38511. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  38512. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  38513. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  38514. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  38515. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  38516. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  38517. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  38518. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  38519. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  38520. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  38521. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  38522. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  38523. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  38524. if ( srcTexture.isDataTexture ) {
  38525. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  38526. } else {
  38527. if ( srcTexture.isCompressedTexture ) {
  38528. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  38529. } else {
  38530. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  38531. }
  38532. }
  38533. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  38534. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  38535. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  38536. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  38537. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  38538. // Generate mipmaps only when copying level 0
  38539. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  38540. state.unbindTexture();
  38541. }
  38542. copyFramebufferToTexture( texture, renderContext ) {
  38543. const { gl } = this;
  38544. const { state } = this.backend;
  38545. const { textureGPU } = this.backend.get( texture );
  38546. const width = texture.image.width;
  38547. const height = texture.image.height;
  38548. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  38549. if ( requireDrawFrameBuffer ) {
  38550. let mask;
  38551. let attachment;
  38552. if ( texture.isDepthTexture === true ) {
  38553. mask = gl.DEPTH_BUFFER_BIT;
  38554. attachment = gl.DEPTH_ATTACHMENT;
  38555. if ( renderContext.stencil ) {
  38556. mask |= gl.STENCIL_BUFFER_BIT;
  38557. }
  38558. } else {
  38559. mask = gl.COLOR_BUFFER_BIT;
  38560. attachment = gl.COLOR_ATTACHMENT0;
  38561. }
  38562. const fb = gl.createFramebuffer();
  38563. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  38564. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  38565. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  38566. gl.deleteFramebuffer( fb );
  38567. } else {
  38568. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  38569. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, 0, 0, width, height );
  38570. state.unbindTexture();
  38571. }
  38572. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  38573. this.backend._setFramebuffer( renderContext );
  38574. }
  38575. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  38576. setupRenderBufferStorage( renderbuffer, renderContext ) {
  38577. const { gl } = this;
  38578. const renderTarget = renderContext.renderTarget;
  38579. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  38580. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  38581. if ( depthBuffer && ! stencilBuffer ) {
  38582. let glInternalFormat = gl.DEPTH_COMPONENT24;
  38583. if ( samples > 0 ) {
  38584. if ( depthTexture && depthTexture.isDepthTexture ) {
  38585. if ( depthTexture.type === gl.FLOAT ) {
  38586. glInternalFormat = gl.DEPTH_COMPONENT32F;
  38587. }
  38588. }
  38589. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  38590. } else {
  38591. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  38592. }
  38593. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  38594. } else if ( depthBuffer && stencilBuffer ) {
  38595. if ( samples > 0 ) {
  38596. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  38597. } else {
  38598. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  38599. }
  38600. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  38601. }
  38602. }
  38603. async copyTextureToBuffer( texture, x, y, width, height ) {
  38604. const { backend, gl } = this;
  38605. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  38606. const fb = gl.createFramebuffer();
  38607. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  38608. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  38609. const typedArrayType = this._getTypedArrayType( glType );
  38610. const bytesPerTexel = this._getBytesPerTexel( glFormat );
  38611. const elementCount = width * height;
  38612. const byteLength = elementCount * bytesPerTexel;
  38613. const buffer = gl.createBuffer();
  38614. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  38615. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  38616. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  38617. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  38618. await backend.utils._clientWaitAsync();
  38619. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  38620. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  38621. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  38622. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  38623. gl.deleteFramebuffer( fb );
  38624. return dstBuffer;
  38625. }
  38626. _getTypedArrayType( glType ) {
  38627. const { gl } = this;
  38628. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  38629. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  38630. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  38631. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  38632. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  38633. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  38634. if ( glType === gl.FLOAT ) return Float32Array;
  38635. throw new Error( `Unsupported WebGL type: ${glType}` );
  38636. }
  38637. _getBytesPerTexel( glFormat ) {
  38638. const { gl } = this;
  38639. if ( glFormat === gl.RGBA ) return 4;
  38640. if ( glFormat === gl.RGB ) return 3;
  38641. if ( glFormat === gl.ALPHA ) return 1;
  38642. }
  38643. }
  38644. class WebGLExtensions {
  38645. constructor( backend ) {
  38646. this.backend = backend;
  38647. this.gl = this.backend.gl;
  38648. this.availableExtensions = this.gl.getSupportedExtensions();
  38649. this.extensions = {};
  38650. }
  38651. get( name ) {
  38652. let extension = this.extensions[ name ];
  38653. if ( extension === undefined ) {
  38654. extension = this.gl.getExtension( name );
  38655. this.extensions[ name ] = extension;
  38656. }
  38657. return extension;
  38658. }
  38659. has( name ) {
  38660. return this.availableExtensions.includes( name );
  38661. }
  38662. }
  38663. class WebGLCapabilities {
  38664. constructor( backend ) {
  38665. this.backend = backend;
  38666. this.maxAnisotropy = null;
  38667. }
  38668. getMaxAnisotropy() {
  38669. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  38670. const gl = this.backend.gl;
  38671. const extensions = this.backend.extensions;
  38672. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  38673. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  38674. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  38675. } else {
  38676. this.maxAnisotropy = 0;
  38677. }
  38678. return this.maxAnisotropy;
  38679. }
  38680. }
  38681. const GLFeatureName = {
  38682. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  38683. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  38684. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  38685. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  38686. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  38687. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  38688. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  38689. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  38690. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  38691. };
  38692. class WebGLBufferRenderer {
  38693. constructor( backend ) {
  38694. this.gl = backend.gl;
  38695. this.extensions = backend.extensions;
  38696. this.info = backend.renderer.info;
  38697. this.mode = null;
  38698. this.index = 0;
  38699. this.type = null;
  38700. this.object = null;
  38701. }
  38702. render( start, count ) {
  38703. const { gl, mode, object, type, info, index } = this;
  38704. if ( index !== 0 ) {
  38705. gl.drawElements( mode, count, type, start );
  38706. } else {
  38707. gl.drawArrays( mode, start, count );
  38708. }
  38709. info.update( object, count, mode, 1 );
  38710. }
  38711. renderInstances( start, count, primcount ) {
  38712. const { gl, mode, type, index, object, info } = this;
  38713. if ( primcount === 0 ) return;
  38714. if ( index !== 0 ) {
  38715. gl.drawElementsInstanced( mode, count, type, start, primcount );
  38716. } else {
  38717. gl.drawArraysInstanced( mode, start, count, primcount );
  38718. }
  38719. info.update( object, count, mode, primcount );
  38720. }
  38721. renderMultiDraw( starts, counts, drawCount ) {
  38722. const { extensions, mode, object, info } = this;
  38723. if ( drawCount === 0 ) return;
  38724. const extension = extensions.get( 'WEBGL_multi_draw' );
  38725. if ( extension === null ) {
  38726. for ( let i = 0; i < drawCount; i ++ ) {
  38727. this.render( starts[ i ], counts[ i ] );
  38728. }
  38729. } else {
  38730. if ( this.index !== 0 ) {
  38731. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  38732. } else {
  38733. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  38734. }
  38735. let elementCount = 0;
  38736. for ( let i = 0; i < drawCount; i ++ ) {
  38737. elementCount += counts[ i ];
  38738. }
  38739. info.update( object, elementCount, mode, 1 );
  38740. }
  38741. }
  38742. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  38743. const { extensions, mode, object, info } = this;
  38744. if ( drawCount === 0 ) return;
  38745. const extension = extensions.get( 'WEBGL_multi_draw' );
  38746. if ( extension === null ) {
  38747. for ( let i = 0; i < drawCount; i ++ ) {
  38748. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  38749. }
  38750. } else {
  38751. if ( this.index !== 0 ) {
  38752. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  38753. } else {
  38754. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  38755. }
  38756. let elementCount = 0;
  38757. for ( let i = 0; i < drawCount; i ++ ) {
  38758. elementCount += counts[ i ];
  38759. }
  38760. for ( let i = 0; i < primcount.length; i ++ ) {
  38761. info.update( object, elementCount, mode, primcount[ i ] );
  38762. }
  38763. }
  38764. }
  38765. //
  38766. }
  38767. //
  38768. class WebGLBackend extends Backend {
  38769. constructor( parameters = {} ) {
  38770. super( parameters );
  38771. this.isWebGLBackend = true;
  38772. }
  38773. init( renderer ) {
  38774. super.init( renderer );
  38775. //
  38776. const parameters = this.parameters;
  38777. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  38778. this.gl = glContext;
  38779. this.extensions = new WebGLExtensions( this );
  38780. this.capabilities = new WebGLCapabilities( this );
  38781. this.attributeUtils = new WebGLAttributeUtils( this );
  38782. this.textureUtils = new WebGLTextureUtils( this );
  38783. this.bufferRenderer = new WebGLBufferRenderer( this );
  38784. this.state = new WebGLState( this );
  38785. this.utils = new WebGLUtils( this );
  38786. this.vaoCache = {};
  38787. this.transformFeedbackCache = {};
  38788. this.discard = false;
  38789. this.trackTimestamp = ( parameters.trackTimestamp === true );
  38790. this.extensions.get( 'EXT_color_buffer_float' );
  38791. this.extensions.get( 'WEBGL_multi_draw' );
  38792. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  38793. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  38794. this._currentContext = null;
  38795. }
  38796. get coordinateSystem() {
  38797. return WebGLCoordinateSystem;
  38798. }
  38799. async getArrayBufferAsync( attribute ) {
  38800. return await this.attributeUtils.getArrayBufferAsync( attribute );
  38801. }
  38802. initTimestampQuery( renderContext ) {
  38803. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  38804. const renderContextData = this.get( renderContext );
  38805. if ( this.queryRunning ) {
  38806. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  38807. renderContextData.queryQueue.push( renderContext );
  38808. return;
  38809. }
  38810. if ( renderContextData.activeQuery ) {
  38811. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  38812. renderContextData.activeQuery = null;
  38813. }
  38814. renderContextData.activeQuery = this.gl.createQuery();
  38815. if ( renderContextData.activeQuery !== null ) {
  38816. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  38817. this.queryRunning = true;
  38818. }
  38819. }
  38820. // timestamp utils
  38821. prepareTimestampBuffer( renderContext ) {
  38822. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  38823. const renderContextData = this.get( renderContext );
  38824. if ( renderContextData.activeQuery ) {
  38825. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  38826. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  38827. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  38828. renderContextData.activeQuery = null;
  38829. this.queryRunning = false;
  38830. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  38831. const nextRenderContext = renderContextData.queryQueue.shift();
  38832. this.initTimestampQuery( nextRenderContext );
  38833. }
  38834. }
  38835. }
  38836. async resolveTimestampAsync( renderContext, type = 'render' ) {
  38837. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  38838. const renderContextData = this.get( renderContext );
  38839. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  38840. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  38841. const queryInfo = renderContextData.gpuQueries[ i ];
  38842. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  38843. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  38844. if ( available && ! disjoint ) {
  38845. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  38846. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  38847. this.gl.deleteQuery( queryInfo.query );
  38848. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  38849. i --;
  38850. this.renderer.info.updateTimestamp( type, duration );
  38851. }
  38852. }
  38853. }
  38854. getContext() {
  38855. return this.gl;
  38856. }
  38857. beginRender( renderContext ) {
  38858. const { gl } = this;
  38859. const renderContextData = this.get( renderContext );
  38860. //
  38861. //
  38862. this.initTimestampQuery( renderContext );
  38863. renderContextData.previousContext = this._currentContext;
  38864. this._currentContext = renderContext;
  38865. this._setFramebuffer( renderContext );
  38866. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  38867. //
  38868. if ( renderContext.viewport ) {
  38869. this.updateViewport( renderContext );
  38870. } else {
  38871. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  38872. }
  38873. if ( renderContext.scissor ) {
  38874. const { x, y, width, height } = renderContext.scissorValue;
  38875. gl.scissor( x, y, width, height );
  38876. }
  38877. const occlusionQueryCount = renderContext.occlusionQueryCount;
  38878. if ( occlusionQueryCount > 0 ) {
  38879. // Get a reference to the array of objects with queries. The renderContextData property
  38880. // can be changed by another render pass before the async reading of all previous queries complete
  38881. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  38882. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  38883. renderContextData.lastOcclusionObject = null;
  38884. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  38885. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  38886. renderContextData.occlusionQueryIndex = 0;
  38887. }
  38888. }
  38889. finishRender( renderContext ) {
  38890. const { gl, state } = this;
  38891. const renderContextData = this.get( renderContext );
  38892. const previousContext = renderContextData.previousContext;
  38893. const textures = renderContext.textures;
  38894. if ( textures !== null ) {
  38895. for ( let i = 0; i < textures.length; i ++ ) {
  38896. const texture = textures[ i ];
  38897. if ( texture.generateMipmaps ) {
  38898. this.generateMipmaps( texture );
  38899. }
  38900. }
  38901. }
  38902. this._currentContext = previousContext;
  38903. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  38904. const renderTargetContextData = this.get( renderContext.renderTarget );
  38905. const { samples } = renderContext.renderTarget;
  38906. const fb = renderTargetContextData.framebuffer;
  38907. const mask = gl.COLOR_BUFFER_BIT;
  38908. if ( samples > 0 ) {
  38909. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  38910. const textures = renderContext.textures;
  38911. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  38912. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  38913. for ( let i = 0; i < textures.length; i ++ ) {
  38914. // TODO Add support for MRT
  38915. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  38916. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  38917. }
  38918. }
  38919. }
  38920. if ( previousContext !== null ) {
  38921. this._setFramebuffer( previousContext );
  38922. if ( previousContext.viewport ) {
  38923. this.updateViewport( previousContext );
  38924. } else {
  38925. const gl = this.gl;
  38926. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  38927. }
  38928. }
  38929. const occlusionQueryCount = renderContext.occlusionQueryCount;
  38930. if ( occlusionQueryCount > 0 ) {
  38931. const renderContextData = this.get( renderContext );
  38932. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  38933. const { gl } = this;
  38934. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  38935. }
  38936. this.resolveOccludedAsync( renderContext );
  38937. }
  38938. this.prepareTimestampBuffer( renderContext );
  38939. }
  38940. resolveOccludedAsync( renderContext ) {
  38941. const renderContextData = this.get( renderContext );
  38942. // handle occlusion query results
  38943. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  38944. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  38945. const occluded = new WeakSet();
  38946. const { gl } = this;
  38947. renderContextData.currentOcclusionQueryObjects = null;
  38948. renderContextData.currentOcclusionQueries = null;
  38949. const check = () => {
  38950. let completed = 0;
  38951. // check all queries and requeue as appropriate
  38952. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  38953. const query = currentOcclusionQueries[ i ];
  38954. if ( query === null ) continue;
  38955. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  38956. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  38957. currentOcclusionQueries[ i ] = null;
  38958. gl.deleteQuery( query );
  38959. completed ++;
  38960. }
  38961. }
  38962. if ( completed < currentOcclusionQueries.length ) {
  38963. requestAnimationFrame( check );
  38964. } else {
  38965. renderContextData.occluded = occluded;
  38966. }
  38967. };
  38968. check();
  38969. }
  38970. }
  38971. isOccluded( renderContext, object ) {
  38972. const renderContextData = this.get( renderContext );
  38973. return renderContextData.occluded && renderContextData.occluded.has( object );
  38974. }
  38975. updateViewport( renderContext ) {
  38976. const gl = this.gl;
  38977. const { x, y, width, height } = renderContext.viewportValue;
  38978. gl.viewport( x, y, width, height );
  38979. }
  38980. setScissorTest( boolean ) {
  38981. const gl = this.gl;
  38982. if ( boolean ) {
  38983. gl.enable( gl.SCISSOR_TEST );
  38984. } else {
  38985. gl.disable( gl.SCISSOR_TEST );
  38986. }
  38987. }
  38988. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  38989. const { gl } = this;
  38990. if ( descriptor === null ) {
  38991. descriptor = {
  38992. textures: null,
  38993. clearColorValue: this.getClearColor()
  38994. };
  38995. }
  38996. //
  38997. let clear = 0;
  38998. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  38999. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  39000. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  39001. if ( clear !== 0 ) {
  39002. const clearColor = descriptor.clearColorValue || this.getClearColor();
  39003. if ( depth ) this.state.setDepthMask( true );
  39004. if ( descriptor.textures === null ) {
  39005. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  39006. gl.clear( clear );
  39007. } else {
  39008. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  39009. if ( color ) {
  39010. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  39011. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  39012. }
  39013. }
  39014. if ( depth && stencil ) {
  39015. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  39016. } else if ( depth ) {
  39017. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  39018. } else if ( stencil ) {
  39019. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  39020. }
  39021. }
  39022. }
  39023. }
  39024. beginCompute( computeGroup ) {
  39025. const gl = this.gl;
  39026. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  39027. this.initTimestampQuery( computeGroup );
  39028. }
  39029. compute( computeGroup, computeNode, bindings, pipeline ) {
  39030. const gl = this.gl;
  39031. if ( ! this.discard ) {
  39032. // required here to handle async behaviour of render.compute()
  39033. gl.enable( gl.RASTERIZER_DISCARD );
  39034. this.discard = true;
  39035. }
  39036. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  39037. const vaoKey = this._getVaoKey( null, attributes );
  39038. const vaoGPU = this.vaoCache[ vaoKey ];
  39039. if ( vaoGPU === undefined ) {
  39040. this._createVao( null, attributes );
  39041. } else {
  39042. gl.bindVertexArray( vaoGPU );
  39043. }
  39044. gl.useProgram( programGPU );
  39045. this._bindUniforms( bindings );
  39046. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  39047. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  39048. gl.beginTransformFeedback( gl.POINTS );
  39049. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  39050. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  39051. } else {
  39052. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  39053. }
  39054. gl.endTransformFeedback();
  39055. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  39056. // switch active buffers
  39057. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  39058. const dualAttributeData = transformBuffers[ i ];
  39059. if ( dualAttributeData.pbo ) {
  39060. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  39061. }
  39062. dualAttributeData.switchBuffers();
  39063. }
  39064. }
  39065. finishCompute( computeGroup ) {
  39066. const gl = this.gl;
  39067. this.discard = false;
  39068. gl.disable( gl.RASTERIZER_DISCARD );
  39069. this.prepareTimestampBuffer( computeGroup );
  39070. }
  39071. draw( renderObject/*, info*/ ) {
  39072. const { object, pipeline, material, context } = renderObject;
  39073. const { programGPU } = this.get( pipeline );
  39074. const { gl, state } = this;
  39075. const contextData = this.get( context );
  39076. //
  39077. this._bindUniforms( renderObject.getBindings() );
  39078. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  39079. state.setMaterial( material, frontFaceCW );
  39080. gl.useProgram( programGPU );
  39081. //
  39082. let vaoGPU = renderObject.staticVao;
  39083. if ( vaoGPU === undefined ) {
  39084. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  39085. vaoGPU = this.vaoCache[ vaoKey ];
  39086. if ( vaoGPU === undefined ) {
  39087. let staticVao;
  39088. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  39089. if ( staticVao ) renderObject.staticVao = vaoGPU;
  39090. }
  39091. }
  39092. gl.bindVertexArray( vaoGPU );
  39093. //
  39094. const index = renderObject.getIndex();
  39095. const geometry = renderObject.geometry;
  39096. const drawRange = renderObject.drawRange;
  39097. const firstVertex = drawRange.start;
  39098. //
  39099. const lastObject = contextData.lastOcclusionObject;
  39100. if ( lastObject !== object && lastObject !== undefined ) {
  39101. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  39102. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  39103. contextData.occlusionQueryIndex ++;
  39104. }
  39105. if ( object.occlusionTest === true ) {
  39106. const query = gl.createQuery();
  39107. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  39108. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  39109. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  39110. }
  39111. contextData.lastOcclusionObject = object;
  39112. }
  39113. //
  39114. const renderer = this.bufferRenderer;
  39115. if ( object.isPoints ) renderer.mode = gl.POINTS;
  39116. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  39117. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  39118. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  39119. else {
  39120. if ( material.wireframe === true ) {
  39121. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  39122. renderer.mode = gl.LINES;
  39123. } else {
  39124. renderer.mode = gl.TRIANGLES;
  39125. }
  39126. }
  39127. //
  39128. let count;
  39129. renderer.object = object;
  39130. if ( index !== null ) {
  39131. const indexData = this.get( index );
  39132. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  39133. renderer.index = index.count;
  39134. renderer.type = indexData.type;
  39135. count = indexCount;
  39136. } else {
  39137. renderer.index = 0;
  39138. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : geometry.attributes.position.count;
  39139. count = vertexCount;
  39140. }
  39141. const instanceCount = this.getInstanceCount( renderObject );
  39142. if ( object.isBatchedMesh ) {
  39143. if ( object._multiDrawInstances !== null ) {
  39144. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  39145. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  39146. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  39147. } else {
  39148. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  39149. }
  39150. } else if ( instanceCount > 1 ) {
  39151. renderer.renderInstances( firstVertex, count, instanceCount );
  39152. } else {
  39153. renderer.render( firstVertex, count );
  39154. }
  39155. //
  39156. gl.bindVertexArray( null );
  39157. }
  39158. needsRenderUpdate( /*renderObject*/ ) {
  39159. return false;
  39160. }
  39161. getRenderCacheKey( renderObject ) {
  39162. return renderObject.id;
  39163. }
  39164. // textures
  39165. createDefaultTexture( texture ) {
  39166. this.textureUtils.createDefaultTexture( texture );
  39167. }
  39168. createTexture( texture, options ) {
  39169. this.textureUtils.createTexture( texture, options );
  39170. }
  39171. updateTexture( texture, options ) {
  39172. this.textureUtils.updateTexture( texture, options );
  39173. }
  39174. generateMipmaps( texture ) {
  39175. this.textureUtils.generateMipmaps( texture );
  39176. }
  39177. destroyTexture( texture ) {
  39178. this.textureUtils.destroyTexture( texture );
  39179. }
  39180. copyTextureToBuffer( texture, x, y, width, height ) {
  39181. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  39182. }
  39183. createSampler( /*texture*/ ) {
  39184. //console.warn( 'Abstract class.' );
  39185. }
  39186. destroySampler() {}
  39187. // node builder
  39188. createNodeBuilder( object, renderer ) {
  39189. return new GLSLNodeBuilder( object, renderer );
  39190. }
  39191. // program
  39192. createProgram( program ) {
  39193. const gl = this.gl;
  39194. const { stage, code } = program;
  39195. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  39196. gl.shaderSource( shader, code );
  39197. gl.compileShader( shader );
  39198. this.set( program, {
  39199. shaderGPU: shader
  39200. } );
  39201. }
  39202. destroyProgram( /*program*/ ) {
  39203. console.warn( 'Abstract class.' );
  39204. }
  39205. createRenderPipeline( renderObject, promises ) {
  39206. const gl = this.gl;
  39207. const pipeline = renderObject.pipeline;
  39208. // Program
  39209. const { fragmentProgram, vertexProgram } = pipeline;
  39210. const programGPU = gl.createProgram();
  39211. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  39212. const vertexShader = this.get( vertexProgram ).shaderGPU;
  39213. gl.attachShader( programGPU, fragmentShader );
  39214. gl.attachShader( programGPU, vertexShader );
  39215. gl.linkProgram( programGPU );
  39216. this.set( pipeline, {
  39217. programGPU,
  39218. fragmentShader,
  39219. vertexShader
  39220. } );
  39221. if ( promises !== null && this.parallel ) {
  39222. const p = new Promise( ( resolve /*, reject*/ ) => {
  39223. const parallel = this.parallel;
  39224. const checkStatus = () => {
  39225. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  39226. this._completeCompile( renderObject, pipeline );
  39227. resolve();
  39228. } else {
  39229. requestAnimationFrame( checkStatus );
  39230. }
  39231. };
  39232. checkStatus();
  39233. } );
  39234. promises.push( p );
  39235. return;
  39236. }
  39237. this._completeCompile( renderObject, pipeline );
  39238. }
  39239. _handleSource( string, errorLine ) {
  39240. const lines = string.split( '\n' );
  39241. const lines2 = [];
  39242. const from = Math.max( errorLine - 6, 0 );
  39243. const to = Math.min( errorLine + 6, lines.length );
  39244. for ( let i = from; i < to; i ++ ) {
  39245. const line = i + 1;
  39246. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  39247. }
  39248. return lines2.join( '\n' );
  39249. }
  39250. _getShaderErrors( gl, shader, type ) {
  39251. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  39252. const errors = gl.getShaderInfoLog( shader ).trim();
  39253. if ( status && errors === '' ) return '';
  39254. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  39255. if ( errorMatches ) {
  39256. const errorLine = parseInt( errorMatches[ 1 ] );
  39257. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  39258. } else {
  39259. return errors;
  39260. }
  39261. }
  39262. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  39263. if ( this.renderer.debug.checkShaderErrors ) {
  39264. const gl = this.gl;
  39265. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  39266. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  39267. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  39268. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  39269. } else {
  39270. // default error reporting
  39271. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  39272. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  39273. console.error(
  39274. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  39275. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  39276. 'Program Info Log: ' + programLog + '\n' +
  39277. vertexErrors + '\n' +
  39278. fragmentErrors
  39279. );
  39280. }
  39281. } else if ( programLog !== '' ) {
  39282. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  39283. }
  39284. }
  39285. }
  39286. _completeCompile( renderObject, pipeline ) {
  39287. const gl = this.gl;
  39288. const pipelineData = this.get( pipeline );
  39289. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  39290. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  39291. this._logProgramError( programGPU, fragmentShader, vertexShader );
  39292. }
  39293. gl.useProgram( programGPU );
  39294. // Bindings
  39295. const bindings = renderObject.getBindings();
  39296. this._setupBindings( bindings, programGPU );
  39297. //
  39298. this.set( pipeline, {
  39299. programGPU
  39300. } );
  39301. }
  39302. createComputePipeline( computePipeline, bindings ) {
  39303. const gl = this.gl;
  39304. // Program
  39305. const fragmentProgram = {
  39306. stage: 'fragment',
  39307. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  39308. };
  39309. this.createProgram( fragmentProgram );
  39310. const { computeProgram } = computePipeline;
  39311. const programGPU = gl.createProgram();
  39312. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  39313. const vertexShader = this.get( computeProgram ).shaderGPU;
  39314. const transforms = computeProgram.transforms;
  39315. const transformVaryingNames = [];
  39316. const transformAttributeNodes = [];
  39317. for ( let i = 0; i < transforms.length; i ++ ) {
  39318. const transform = transforms[ i ];
  39319. transformVaryingNames.push( transform.varyingName );
  39320. transformAttributeNodes.push( transform.attributeNode );
  39321. }
  39322. gl.attachShader( programGPU, fragmentShader );
  39323. gl.attachShader( programGPU, vertexShader );
  39324. gl.transformFeedbackVaryings(
  39325. programGPU,
  39326. transformVaryingNames,
  39327. gl.SEPARATE_ATTRIBS
  39328. );
  39329. gl.linkProgram( programGPU );
  39330. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  39331. this._logProgramError( programGPU, fragmentShader, vertexShader );
  39332. }
  39333. gl.useProgram( programGPU );
  39334. // Bindings
  39335. this.createBindings( null, bindings );
  39336. this._setupBindings( bindings, programGPU );
  39337. const attributeNodes = computeProgram.attributes;
  39338. const attributes = [];
  39339. const transformBuffers = [];
  39340. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  39341. const attribute = attributeNodes[ i ].node.attribute;
  39342. attributes.push( attribute );
  39343. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  39344. }
  39345. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  39346. const attribute = transformAttributeNodes[ i ].attribute;
  39347. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  39348. const attributeData = this.get( attribute );
  39349. transformBuffers.push( attributeData );
  39350. }
  39351. //
  39352. this.set( computePipeline, {
  39353. programGPU,
  39354. transformBuffers,
  39355. attributes
  39356. } );
  39357. }
  39358. createBindings( bindGroup, bindings ) {
  39359. this.updateBindings( bindGroup, bindings );
  39360. }
  39361. updateBindings( bindGroup, bindings ) {
  39362. const { gl } = this;
  39363. let groupIndex = 0;
  39364. let textureIndex = 0;
  39365. for ( const bindGroup of bindings ) {
  39366. for ( const binding of bindGroup.bindings ) {
  39367. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39368. const bufferGPU = gl.createBuffer();
  39369. const data = binding.buffer;
  39370. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  39371. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  39372. gl.bindBufferBase( gl.UNIFORM_BUFFER, groupIndex, bufferGPU );
  39373. this.set( binding, {
  39374. index: groupIndex ++,
  39375. bufferGPU
  39376. } );
  39377. } else if ( binding.isSampledTexture ) {
  39378. const { textureGPU, glTextureType } = this.get( binding.texture );
  39379. this.set( binding, {
  39380. index: textureIndex ++,
  39381. textureGPU,
  39382. glTextureType
  39383. } );
  39384. }
  39385. }
  39386. }
  39387. }
  39388. updateBinding( binding ) {
  39389. const gl = this.gl;
  39390. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39391. const bindingData = this.get( binding );
  39392. const bufferGPU = bindingData.bufferGPU;
  39393. const data = binding.buffer;
  39394. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  39395. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  39396. }
  39397. }
  39398. // attributes
  39399. createIndexAttribute( attribute ) {
  39400. const gl = this.gl;
  39401. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  39402. }
  39403. createAttribute( attribute ) {
  39404. if ( this.has( attribute ) ) return;
  39405. const gl = this.gl;
  39406. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  39407. }
  39408. createStorageAttribute( attribute ) {
  39409. if ( this.has( attribute ) ) return;
  39410. const gl = this.gl;
  39411. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  39412. }
  39413. updateAttribute( attribute ) {
  39414. this.attributeUtils.updateAttribute( attribute );
  39415. }
  39416. destroyAttribute( attribute ) {
  39417. this.attributeUtils.destroyAttribute( attribute );
  39418. }
  39419. updateSize() {
  39420. //console.warn( 'Abstract class.' );
  39421. }
  39422. hasFeature( name ) {
  39423. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  39424. const extensions = this.extensions;
  39425. for ( let i = 0; i < keysMatching.length; i ++ ) {
  39426. if ( extensions.has( keysMatching[ i ] ) ) return true;
  39427. }
  39428. return false;
  39429. }
  39430. getMaxAnisotropy() {
  39431. return this.capabilities.getMaxAnisotropy();
  39432. }
  39433. copyTextureToTexture( position, srcTexture, dstTexture, level ) {
  39434. this.textureUtils.copyTextureToTexture( position, srcTexture, dstTexture, level );
  39435. }
  39436. copyFramebufferToTexture( texture, renderContext ) {
  39437. this.textureUtils.copyFramebufferToTexture( texture, renderContext );
  39438. }
  39439. _setFramebuffer( renderContext ) {
  39440. const { gl, state } = this;
  39441. let currentFrameBuffer = null;
  39442. if ( renderContext.textures !== null ) {
  39443. const renderTarget = renderContext.renderTarget;
  39444. const renderTargetContextData = this.get( renderTarget );
  39445. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  39446. const cubeFace = this.renderer._activeCubeFace;
  39447. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  39448. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  39449. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  39450. let fb;
  39451. if ( isCube ) {
  39452. if ( renderTargetContextData.cubeFramebuffers === undefined ) {
  39453. renderTargetContextData.cubeFramebuffers = [];
  39454. }
  39455. fb = renderTargetContextData.cubeFramebuffers[ cubeFace ];
  39456. } else {
  39457. fb = renderTargetContextData.framebuffer;
  39458. }
  39459. if ( fb === undefined ) {
  39460. fb = gl.createFramebuffer();
  39461. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  39462. const textures = renderContext.textures;
  39463. if ( isCube ) {
  39464. renderTargetContextData.cubeFramebuffers[ cubeFace ] = fb;
  39465. const { textureGPU } = this.get( textures[ 0 ] );
  39466. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  39467. } else {
  39468. for ( let i = 0; i < textures.length; i ++ ) {
  39469. const texture = textures[ i ];
  39470. const textureData = this.get( texture );
  39471. textureData.renderTarget = renderContext.renderTarget;
  39472. const attachment = gl.COLOR_ATTACHMENT0 + i;
  39473. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  39474. }
  39475. renderTargetContextData.framebuffer = fb;
  39476. state.drawBuffers( renderContext, fb );
  39477. }
  39478. if ( renderContext.depthTexture !== null ) {
  39479. const textureData = this.get( renderContext.depthTexture );
  39480. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  39481. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  39482. }
  39483. }
  39484. if ( samples > 0 ) {
  39485. if ( msaaFb === undefined ) {
  39486. const invalidationArray = [];
  39487. msaaFb = gl.createFramebuffer();
  39488. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  39489. const msaaRenderbuffers = [];
  39490. const textures = renderContext.textures;
  39491. for ( let i = 0; i < textures.length; i ++ ) {
  39492. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  39493. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  39494. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  39495. if ( depthBuffer ) {
  39496. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  39497. invalidationArray.push( depthStyle );
  39498. }
  39499. const texture = renderContext.textures[ i ];
  39500. const textureData = this.get( texture );
  39501. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, renderContext.width, renderContext.height );
  39502. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  39503. }
  39504. renderTargetContextData.msaaFrameBuffer = msaaFb;
  39505. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  39506. if ( depthRenderbuffer === undefined ) {
  39507. depthRenderbuffer = gl.createRenderbuffer();
  39508. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, renderContext );
  39509. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  39510. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  39511. invalidationArray.push( depthStyle );
  39512. }
  39513. renderTargetContextData.invalidationArray = invalidationArray;
  39514. }
  39515. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  39516. } else {
  39517. currentFrameBuffer = fb;
  39518. }
  39519. }
  39520. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  39521. }
  39522. _getVaoKey( index, attributes ) {
  39523. let key = [];
  39524. if ( index !== null ) {
  39525. const indexData = this.get( index );
  39526. key += ':' + indexData.id;
  39527. }
  39528. for ( let i = 0; i < attributes.length; i ++ ) {
  39529. const attributeData = this.get( attributes[ i ] );
  39530. key += ':' + attributeData.id;
  39531. }
  39532. return key;
  39533. }
  39534. _createVao( index, attributes ) {
  39535. const { gl } = this;
  39536. const vaoGPU = gl.createVertexArray();
  39537. let key = '';
  39538. let staticVao = true;
  39539. gl.bindVertexArray( vaoGPU );
  39540. if ( index !== null ) {
  39541. const indexData = this.get( index );
  39542. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  39543. key += ':' + indexData.id;
  39544. }
  39545. for ( let i = 0; i < attributes.length; i ++ ) {
  39546. const attribute = attributes[ i ];
  39547. const attributeData = this.get( attribute );
  39548. key += ':' + attributeData.id;
  39549. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  39550. gl.enableVertexAttribArray( i );
  39551. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  39552. let stride, offset;
  39553. if ( attribute.isInterleavedBufferAttribute === true ) {
  39554. stride = attribute.data.stride * attributeData.bytesPerElement;
  39555. offset = attribute.offset * attributeData.bytesPerElement;
  39556. } else {
  39557. stride = 0;
  39558. offset = 0;
  39559. }
  39560. if ( attributeData.isInteger ) {
  39561. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  39562. } else {
  39563. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  39564. }
  39565. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  39566. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  39567. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  39568. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  39569. }
  39570. }
  39571. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  39572. this.vaoCache[ key ] = vaoGPU;
  39573. return { vaoGPU, staticVao };
  39574. }
  39575. _getTransformFeedback( transformBuffers ) {
  39576. let key = '';
  39577. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  39578. key += ':' + transformBuffers[ i ].id;
  39579. }
  39580. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  39581. if ( transformFeedbackGPU !== undefined ) {
  39582. return transformFeedbackGPU;
  39583. }
  39584. const gl = this.gl;
  39585. transformFeedbackGPU = gl.createTransformFeedback();
  39586. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  39587. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  39588. const attributeData = transformBuffers[ i ];
  39589. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  39590. }
  39591. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  39592. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  39593. return transformFeedbackGPU;
  39594. }
  39595. _setupBindings( bindings, programGPU ) {
  39596. const gl = this.gl;
  39597. for ( const bindGroup of bindings ) {
  39598. for ( const binding of bindGroup.bindings ) {
  39599. const bindingData = this.get( binding );
  39600. const index = bindingData.index;
  39601. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39602. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  39603. gl.uniformBlockBinding( programGPU, location, index );
  39604. } else if ( binding.isSampledTexture ) {
  39605. const location = gl.getUniformLocation( programGPU, binding.name );
  39606. gl.uniform1i( location, index );
  39607. }
  39608. }
  39609. }
  39610. }
  39611. _bindUniforms( bindings ) {
  39612. const { gl, state } = this;
  39613. for ( const bindGroup of bindings ) {
  39614. for ( const binding of bindGroup.bindings ) {
  39615. const bindingData = this.get( binding );
  39616. const index = bindingData.index;
  39617. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39618. gl.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  39619. } else if ( binding.isSampledTexture ) {
  39620. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  39621. }
  39622. }
  39623. }
  39624. }
  39625. }
  39626. class Sampler extends Binding {
  39627. constructor( name, texture ) {
  39628. super( name );
  39629. this.texture = texture;
  39630. this.version = texture ? texture.version : 0;
  39631. this.isSampler = true;
  39632. }
  39633. }
  39634. class NodeSampler extends Sampler {
  39635. constructor( name, textureNode, groupNode ) {
  39636. super( name, textureNode ? textureNode.value : null );
  39637. this.textureNode = textureNode;
  39638. this.groupNode = groupNode;
  39639. }
  39640. update() {
  39641. this.texture = this.textureNode.value;
  39642. }
  39643. }
  39644. class StorageBuffer extends Buffer {
  39645. constructor( name, attribute ) {
  39646. super( name, attribute ? attribute.array : null );
  39647. this.attribute = attribute;
  39648. this.isStorageBuffer = true;
  39649. }
  39650. }
  39651. let _id = 0;
  39652. class NodeStorageBuffer extends StorageBuffer {
  39653. constructor( nodeUniform, groupNode ) {
  39654. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  39655. this.nodeUniform = nodeUniform;
  39656. this.access = nodeUniform ? nodeUniform.access : GPUBufferBindingType.Storage;
  39657. this.groupNode = groupNode;
  39658. }
  39659. get buffer() {
  39660. return this.nodeUniform.value;
  39661. }
  39662. }
  39663. class WebGPUTexturePassUtils {
  39664. constructor( device ) {
  39665. this.device = device;
  39666. const mipmapVertexSource = `
  39667. struct VarysStruct {
  39668. @builtin( position ) Position: vec4<f32>,
  39669. @location( 0 ) vTex : vec2<f32>
  39670. };
  39671. @vertex
  39672. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  39673. var Varys : VarysStruct;
  39674. var pos = array< vec2<f32>, 4 >(
  39675. vec2<f32>( -1.0, 1.0 ),
  39676. vec2<f32>( 1.0, 1.0 ),
  39677. vec2<f32>( -1.0, -1.0 ),
  39678. vec2<f32>( 1.0, -1.0 )
  39679. );
  39680. var tex = array< vec2<f32>, 4 >(
  39681. vec2<f32>( 0.0, 0.0 ),
  39682. vec2<f32>( 1.0, 0.0 ),
  39683. vec2<f32>( 0.0, 1.0 ),
  39684. vec2<f32>( 1.0, 1.0 )
  39685. );
  39686. Varys.vTex = tex[ vertexIndex ];
  39687. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  39688. return Varys;
  39689. }
  39690. `;
  39691. const mipmapFragmentSource = `
  39692. @group( 0 ) @binding( 0 )
  39693. var imgSampler : sampler;
  39694. @group( 0 ) @binding( 1 )
  39695. var img : texture_2d<f32>;
  39696. @fragment
  39697. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  39698. return textureSample( img, imgSampler, vTex );
  39699. }
  39700. `;
  39701. const flipYFragmentSource = `
  39702. @group( 0 ) @binding( 0 )
  39703. var imgSampler : sampler;
  39704. @group( 0 ) @binding( 1 )
  39705. var img : texture_2d<f32>;
  39706. @fragment
  39707. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  39708. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  39709. }
  39710. `;
  39711. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  39712. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  39713. // We'll need a new pipeline for every texture format used.
  39714. this.transferPipelines = {};
  39715. this.flipYPipelines = {};
  39716. this.mipmapVertexShaderModule = device.createShaderModule( {
  39717. label: 'mipmapVertex',
  39718. code: mipmapVertexSource
  39719. } );
  39720. this.mipmapFragmentShaderModule = device.createShaderModule( {
  39721. label: 'mipmapFragment',
  39722. code: mipmapFragmentSource
  39723. } );
  39724. this.flipYFragmentShaderModule = device.createShaderModule( {
  39725. label: 'flipYFragment',
  39726. code: flipYFragmentSource
  39727. } );
  39728. }
  39729. getTransferPipeline( format ) {
  39730. let pipeline = this.transferPipelines[ format ];
  39731. if ( pipeline === undefined ) {
  39732. pipeline = this.device.createRenderPipeline( {
  39733. vertex: {
  39734. module: this.mipmapVertexShaderModule,
  39735. entryPoint: 'main'
  39736. },
  39737. fragment: {
  39738. module: this.mipmapFragmentShaderModule,
  39739. entryPoint: 'main',
  39740. targets: [ { format } ]
  39741. },
  39742. primitive: {
  39743. topology: GPUPrimitiveTopology.TriangleStrip,
  39744. stripIndexFormat: GPUIndexFormat.Uint32
  39745. },
  39746. layout: 'auto'
  39747. } );
  39748. this.transferPipelines[ format ] = pipeline;
  39749. }
  39750. return pipeline;
  39751. }
  39752. getFlipYPipeline( format ) {
  39753. let pipeline = this.flipYPipelines[ format ];
  39754. if ( pipeline === undefined ) {
  39755. pipeline = this.device.createRenderPipeline( {
  39756. vertex: {
  39757. module: this.mipmapVertexShaderModule,
  39758. entryPoint: 'main'
  39759. },
  39760. fragment: {
  39761. module: this.flipYFragmentShaderModule,
  39762. entryPoint: 'main',
  39763. targets: [ { format } ]
  39764. },
  39765. primitive: {
  39766. topology: GPUPrimitiveTopology.TriangleStrip,
  39767. stripIndexFormat: GPUIndexFormat.Uint32
  39768. },
  39769. layout: 'auto'
  39770. } );
  39771. this.flipYPipelines[ format ] = pipeline;
  39772. }
  39773. return pipeline;
  39774. }
  39775. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  39776. const format = textureGPUDescriptor.format;
  39777. const { width, height } = textureGPUDescriptor.size;
  39778. const transferPipeline = this.getTransferPipeline( format );
  39779. const flipYPipeline = this.getFlipYPipeline( format );
  39780. const tempTexture = this.device.createTexture( {
  39781. size: { width, height, depthOrArrayLayers: 1 },
  39782. format,
  39783. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  39784. } );
  39785. const srcView = textureGPU.createView( {
  39786. baseMipLevel: 0,
  39787. mipLevelCount: 1,
  39788. dimension: GPUTextureViewDimension.TwoD,
  39789. baseArrayLayer
  39790. } );
  39791. const dstView = tempTexture.createView( {
  39792. baseMipLevel: 0,
  39793. mipLevelCount: 1,
  39794. dimension: GPUTextureViewDimension.TwoD,
  39795. baseArrayLayer: 0
  39796. } );
  39797. const commandEncoder = this.device.createCommandEncoder( {} );
  39798. const pass = ( pipeline, sourceView, destinationView ) => {
  39799. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  39800. const bindGroup = this.device.createBindGroup( {
  39801. layout: bindGroupLayout,
  39802. entries: [ {
  39803. binding: 0,
  39804. resource: this.flipYSampler
  39805. }, {
  39806. binding: 1,
  39807. resource: sourceView
  39808. } ]
  39809. } );
  39810. const passEncoder = commandEncoder.beginRenderPass( {
  39811. colorAttachments: [ {
  39812. view: destinationView,
  39813. loadOp: GPULoadOp.Clear,
  39814. storeOp: GPUStoreOp.Store,
  39815. clearValue: [ 0, 0, 0, 0 ]
  39816. } ]
  39817. } );
  39818. passEncoder.setPipeline( pipeline );
  39819. passEncoder.setBindGroup( 0, bindGroup );
  39820. passEncoder.draw( 4, 1, 0, 0 );
  39821. passEncoder.end();
  39822. };
  39823. pass( transferPipeline, srcView, dstView );
  39824. pass( flipYPipeline, dstView, srcView );
  39825. this.device.queue.submit( [ commandEncoder.finish() ] );
  39826. tempTexture.destroy();
  39827. }
  39828. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  39829. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  39830. const commandEncoder = this.device.createCommandEncoder( {} );
  39831. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  39832. let srcView = textureGPU.createView( {
  39833. baseMipLevel: 0,
  39834. mipLevelCount: 1,
  39835. dimension: GPUTextureViewDimension.TwoD,
  39836. baseArrayLayer
  39837. } );
  39838. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  39839. const bindGroup = this.device.createBindGroup( {
  39840. layout: bindGroupLayout,
  39841. entries: [ {
  39842. binding: 0,
  39843. resource: this.mipmapSampler
  39844. }, {
  39845. binding: 1,
  39846. resource: srcView
  39847. } ]
  39848. } );
  39849. const dstView = textureGPU.createView( {
  39850. baseMipLevel: i,
  39851. mipLevelCount: 1,
  39852. dimension: GPUTextureViewDimension.TwoD,
  39853. baseArrayLayer
  39854. } );
  39855. const passEncoder = commandEncoder.beginRenderPass( {
  39856. colorAttachments: [ {
  39857. view: dstView,
  39858. loadOp: GPULoadOp.Clear,
  39859. storeOp: GPUStoreOp.Store,
  39860. clearValue: [ 0, 0, 0, 0 ]
  39861. } ]
  39862. } );
  39863. passEncoder.setPipeline( pipeline );
  39864. passEncoder.setBindGroup( 0, bindGroup );
  39865. passEncoder.draw( 4, 1, 0, 0 );
  39866. passEncoder.end();
  39867. srcView = dstView;
  39868. }
  39869. this.device.queue.submit( [ commandEncoder.finish() ] );
  39870. }
  39871. }
  39872. const _compareToWebGPU = {
  39873. [ NeverCompare ]: 'never',
  39874. [ LessCompare ]: 'less',
  39875. [ EqualCompare ]: 'equal',
  39876. [ LessEqualCompare ]: 'less-equal',
  39877. [ GreaterCompare ]: 'greater',
  39878. [ GreaterEqualCompare ]: 'greater-equal',
  39879. [ AlwaysCompare ]: 'always',
  39880. [ NotEqualCompare ]: 'not-equal'
  39881. };
  39882. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  39883. class WebGPUTextureUtils {
  39884. constructor( backend ) {
  39885. this.backend = backend;
  39886. this._passUtils = null;
  39887. this.defaultTexture = {};
  39888. this.defaultCubeTexture = {};
  39889. this.colorBuffer = null;
  39890. this.depthTexture = new DepthTexture();
  39891. this.depthTexture.name = 'depthBuffer';
  39892. }
  39893. createSampler( texture ) {
  39894. const backend = this.backend;
  39895. const device = backend.device;
  39896. const textureGPU = backend.get( texture );
  39897. const samplerDescriptorGPU = {
  39898. addressModeU: this._convertAddressMode( texture.wrapS ),
  39899. addressModeV: this._convertAddressMode( texture.wrapT ),
  39900. addressModeW: this._convertAddressMode( texture.wrapR ),
  39901. magFilter: this._convertFilterMode( texture.magFilter ),
  39902. minFilter: this._convertFilterMode( texture.minFilter ),
  39903. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  39904. maxAnisotropy: texture.anisotropy
  39905. };
  39906. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  39907. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  39908. }
  39909. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  39910. }
  39911. createDefaultTexture( texture ) {
  39912. let textureGPU;
  39913. const format = getFormat( texture );
  39914. if ( texture.isCubeTexture ) {
  39915. textureGPU = this._getDefaultCubeTextureGPU( format );
  39916. } else {
  39917. textureGPU = this._getDefaultTextureGPU( format );
  39918. }
  39919. this.backend.get( texture ).texture = textureGPU;
  39920. }
  39921. createTexture( texture, options = {} ) {
  39922. const backend = this.backend;
  39923. const textureData = backend.get( texture );
  39924. if ( textureData.initialized ) {
  39925. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  39926. }
  39927. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  39928. if ( options.levels === undefined ) options.levels = 1;
  39929. if ( options.depth === undefined ) options.depth = 1;
  39930. const { width, height, depth, levels } = options;
  39931. const dimension = this._getDimension( texture );
  39932. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  39933. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  39934. if ( sampleCount > 1 ) {
  39935. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  39936. sampleCount = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  39937. if ( sampleCount === 2 ) {
  39938. sampleCount = 4;
  39939. }
  39940. }
  39941. const primarySampleCount = texture.isRenderTargetTexture ? 1 : sampleCount;
  39942. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  39943. if ( texture.isStorageTexture === true ) {
  39944. usage |= GPUTextureUsage.STORAGE_BINDING;
  39945. }
  39946. if ( texture.isCompressedTexture !== true ) {
  39947. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  39948. }
  39949. const textureDescriptorGPU = {
  39950. label: texture.name,
  39951. size: {
  39952. width: width,
  39953. height: height,
  39954. depthOrArrayLayers: depth,
  39955. },
  39956. mipLevelCount: levels,
  39957. sampleCount: primarySampleCount,
  39958. dimension: dimension,
  39959. format: format,
  39960. usage: usage
  39961. };
  39962. // texture creation
  39963. if ( texture.isVideoTexture ) {
  39964. const video = texture.source.data;
  39965. const videoFrame = new VideoFrame( video );
  39966. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  39967. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  39968. videoFrame.close();
  39969. textureData.externalTexture = video;
  39970. } else {
  39971. if ( format === undefined ) {
  39972. console.warn( 'WebGPURenderer: Texture format not supported.' );
  39973. return this.createDefaultTexture( texture );
  39974. }
  39975. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  39976. }
  39977. if ( texture.isRenderTargetTexture && sampleCount > 1 ) {
  39978. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  39979. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  39980. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  39981. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  39982. }
  39983. textureData.initialized = true;
  39984. textureData.textureDescriptorGPU = textureDescriptorGPU;
  39985. }
  39986. destroyTexture( texture ) {
  39987. const backend = this.backend;
  39988. const textureData = backend.get( texture );
  39989. textureData.texture.destroy();
  39990. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  39991. backend.delete( texture );
  39992. }
  39993. destroySampler( texture ) {
  39994. const backend = this.backend;
  39995. const textureData = backend.get( texture );
  39996. delete textureData.sampler;
  39997. }
  39998. generateMipmaps( texture ) {
  39999. const textureData = this.backend.get( texture );
  40000. if ( texture.isCubeTexture ) {
  40001. for ( let i = 0; i < 6; i ++ ) {
  40002. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  40003. }
  40004. } else {
  40005. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU );
  40006. }
  40007. }
  40008. getColorBuffer() {
  40009. if ( this.colorBuffer ) this.colorBuffer.destroy();
  40010. const backend = this.backend;
  40011. const { width, height } = backend.getDrawingBufferSize();
  40012. this.colorBuffer = backend.device.createTexture( {
  40013. label: 'colorBuffer',
  40014. size: {
  40015. width: width,
  40016. height: height,
  40017. depthOrArrayLayers: 1
  40018. },
  40019. sampleCount: backend.parameters.sampleCount,
  40020. format: GPUTextureFormat.BGRA8Unorm,
  40021. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  40022. } );
  40023. return this.colorBuffer;
  40024. }
  40025. getDepthBuffer( depth = true, stencil = false ) {
  40026. const backend = this.backend;
  40027. const { width, height } = backend.getDrawingBufferSize();
  40028. const depthTexture = this.depthTexture;
  40029. const depthTextureGPU = backend.get( depthTexture ).texture;
  40030. let format, type;
  40031. if ( stencil ) {
  40032. format = DepthStencilFormat;
  40033. type = UnsignedInt248Type;
  40034. } else if ( depth ) {
  40035. format = DepthFormat;
  40036. type = UnsignedIntType;
  40037. }
  40038. if ( depthTextureGPU !== undefined ) {
  40039. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  40040. return depthTextureGPU;
  40041. }
  40042. this.destroyTexture( depthTexture );
  40043. }
  40044. depthTexture.name = 'depthBuffer';
  40045. depthTexture.format = format;
  40046. depthTexture.type = type;
  40047. depthTexture.image.width = width;
  40048. depthTexture.image.height = height;
  40049. this.createTexture( depthTexture, { sampleCount: backend.parameters.sampleCount, width, height } );
  40050. return backend.get( depthTexture ).texture;
  40051. }
  40052. updateTexture( texture, options ) {
  40053. const textureData = this.backend.get( texture );
  40054. const { textureDescriptorGPU } = textureData;
  40055. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  40056. return;
  40057. // transfer texture data
  40058. if ( texture.isDataTexture ) {
  40059. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  40060. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  40061. for ( let i = 0; i < options.image.depth; i ++ ) {
  40062. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  40063. }
  40064. } else if ( texture.isCompressedTexture ) {
  40065. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  40066. } else if ( texture.isCubeTexture ) {
  40067. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  40068. } else if ( texture.isVideoTexture ) {
  40069. const video = texture.source.data;
  40070. textureData.externalTexture = video;
  40071. } else {
  40072. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  40073. }
  40074. //
  40075. textureData.version = texture.version;
  40076. if ( texture.onUpdate ) texture.onUpdate( texture );
  40077. }
  40078. async copyTextureToBuffer( texture, x, y, width, height ) {
  40079. const device = this.backend.device;
  40080. const textureData = this.backend.get( texture );
  40081. const textureGPU = textureData.texture;
  40082. const format = textureData.textureDescriptorGPU.format;
  40083. const bytesPerTexel = this._getBytesPerTexel( format );
  40084. let bytesPerRow = width * bytesPerTexel;
  40085. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  40086. const readBuffer = device.createBuffer(
  40087. {
  40088. size: width * height * bytesPerTexel,
  40089. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  40090. }
  40091. );
  40092. const encoder = device.createCommandEncoder();
  40093. encoder.copyTextureToBuffer(
  40094. {
  40095. texture: textureGPU,
  40096. origin: { x, y },
  40097. },
  40098. {
  40099. buffer: readBuffer,
  40100. bytesPerRow: bytesPerRow
  40101. },
  40102. {
  40103. width: width,
  40104. height: height
  40105. }
  40106. );
  40107. const typedArrayType = this._getTypedArrayType( format );
  40108. device.queue.submit( [ encoder.finish() ] );
  40109. await readBuffer.mapAsync( GPUMapMode.READ );
  40110. const buffer = readBuffer.getMappedRange();
  40111. return new typedArrayType( buffer );
  40112. }
  40113. _isEnvironmentTexture( texture ) {
  40114. const mapping = texture.mapping;
  40115. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  40116. }
  40117. _getDefaultTextureGPU( format ) {
  40118. let defaultTexture = this.defaultTexture[ format ];
  40119. if ( defaultTexture === undefined ) {
  40120. const texture = new Texture();
  40121. texture.minFilter = NearestFilter;
  40122. texture.magFilter = NearestFilter;
  40123. this.createTexture( texture, { width: 1, height: 1, format } );
  40124. this.defaultTexture[ format ] = defaultTexture = texture;
  40125. }
  40126. return this.backend.get( defaultTexture ).texture;
  40127. }
  40128. _getDefaultCubeTextureGPU( format ) {
  40129. let defaultCubeTexture = this.defaultTexture[ format ];
  40130. if ( defaultCubeTexture === undefined ) {
  40131. const texture = new CubeTexture();
  40132. texture.minFilter = NearestFilter;
  40133. texture.magFilter = NearestFilter;
  40134. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  40135. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  40136. }
  40137. return this.backend.get( defaultCubeTexture ).texture;
  40138. }
  40139. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  40140. for ( let i = 0; i < 6; i ++ ) {
  40141. const image = images[ i ];
  40142. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  40143. if ( image.isDataTexture ) {
  40144. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  40145. } else {
  40146. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  40147. }
  40148. }
  40149. }
  40150. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  40151. const device = this.backend.device;
  40152. device.queue.copyExternalImageToTexture(
  40153. {
  40154. source: image
  40155. }, {
  40156. texture: textureGPU,
  40157. mipLevel: 0,
  40158. origin: { x: 0, y: 0, z: originDepth }
  40159. }, {
  40160. width: image.width,
  40161. height: image.height,
  40162. depthOrArrayLayers: 1
  40163. }
  40164. );
  40165. if ( flipY === true ) {
  40166. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  40167. }
  40168. }
  40169. _getPassUtils() {
  40170. let passUtils = this._passUtils;
  40171. if ( passUtils === null ) {
  40172. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  40173. }
  40174. return passUtils;
  40175. }
  40176. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  40177. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  40178. }
  40179. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  40180. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  40181. }
  40182. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  40183. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  40184. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  40185. const device = this.backend.device;
  40186. const data = image.data;
  40187. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  40188. const bytesPerRow = image.width * bytesPerTexel;
  40189. device.queue.writeTexture(
  40190. {
  40191. texture: textureGPU,
  40192. mipLevel: 0,
  40193. origin: { x: 0, y: 0, z: originDepth }
  40194. },
  40195. data,
  40196. {
  40197. offset: image.width * image.height * bytesPerTexel * depth,
  40198. bytesPerRow
  40199. },
  40200. {
  40201. width: image.width,
  40202. height: image.height,
  40203. depthOrArrayLayers: 1
  40204. } );
  40205. if ( flipY === true ) {
  40206. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  40207. }
  40208. }
  40209. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  40210. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  40211. const device = this.backend.device;
  40212. const blockData = this._getBlockData( textureDescriptorGPU.format );
  40213. for ( let i = 0; i < mipmaps.length; i ++ ) {
  40214. const mipmap = mipmaps[ i ];
  40215. const width = mipmap.width;
  40216. const height = mipmap.height;
  40217. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  40218. device.queue.writeTexture(
  40219. {
  40220. texture: textureGPU,
  40221. mipLevel: i
  40222. },
  40223. mipmap.data,
  40224. {
  40225. offset: 0,
  40226. bytesPerRow
  40227. },
  40228. {
  40229. width: Math.ceil( width / blockData.width ) * blockData.width,
  40230. height: Math.ceil( height / blockData.width ) * blockData.width,
  40231. depthOrArrayLayers: 1
  40232. }
  40233. );
  40234. }
  40235. }
  40236. _getBlockData( format ) {
  40237. // this method is only relevant for compressed texture formats
  40238. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  40239. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  40240. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  40241. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  40242. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  40243. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  40244. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  40245. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  40246. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  40247. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  40248. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  40249. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  40250. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  40251. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  40252. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  40253. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  40254. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  40255. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  40256. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  40257. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  40258. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  40259. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  40260. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  40261. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  40262. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  40263. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  40264. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  40265. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  40266. }
  40267. _convertAddressMode( value ) {
  40268. let addressMode = GPUAddressMode.ClampToEdge;
  40269. if ( value === RepeatWrapping ) {
  40270. addressMode = GPUAddressMode.Repeat;
  40271. } else if ( value === MirroredRepeatWrapping ) {
  40272. addressMode = GPUAddressMode.MirrorRepeat;
  40273. }
  40274. return addressMode;
  40275. }
  40276. _convertFilterMode( value ) {
  40277. let filterMode = GPUFilterMode.Linear;
  40278. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  40279. filterMode = GPUFilterMode.Nearest;
  40280. }
  40281. return filterMode;
  40282. }
  40283. _getBytesPerTexel( format ) {
  40284. // 8-bit formats
  40285. if ( format === GPUTextureFormat.R8Unorm ||
  40286. format === GPUTextureFormat.R8Snorm ||
  40287. format === GPUTextureFormat.R8Uint ||
  40288. format === GPUTextureFormat.R8Sint ) return 1;
  40289. // 16-bit formats
  40290. if ( format === GPUTextureFormat.R16Uint ||
  40291. format === GPUTextureFormat.R16Sint ||
  40292. format === GPUTextureFormat.R16Float ||
  40293. format === GPUTextureFormat.RG8Unorm ||
  40294. format === GPUTextureFormat.RG8Snorm ||
  40295. format === GPUTextureFormat.RG8Uint ||
  40296. format === GPUTextureFormat.RG8Sint ) return 2;
  40297. // 32-bit formats
  40298. if ( format === GPUTextureFormat.R32Uint ||
  40299. format === GPUTextureFormat.R32Sint ||
  40300. format === GPUTextureFormat.R32Float ||
  40301. format === GPUTextureFormat.RG16Uint ||
  40302. format === GPUTextureFormat.RG16Sint ||
  40303. format === GPUTextureFormat.RG16Float ||
  40304. format === GPUTextureFormat.RGBA8Unorm ||
  40305. format === GPUTextureFormat.RGBA8UnormSRGB ||
  40306. format === GPUTextureFormat.RGBA8Snorm ||
  40307. format === GPUTextureFormat.RGBA8Uint ||
  40308. format === GPUTextureFormat.RGBA8Sint ||
  40309. format === GPUTextureFormat.BGRA8Unorm ||
  40310. format === GPUTextureFormat.BGRA8UnormSRGB ||
  40311. // Packed 32-bit formats
  40312. format === GPUTextureFormat.RGB9E5UFloat ||
  40313. format === GPUTextureFormat.RGB10A2Unorm ||
  40314. format === GPUTextureFormat.RG11B10UFloat ||
  40315. format === GPUTextureFormat.Depth32Float ||
  40316. format === GPUTextureFormat.Depth24Plus ||
  40317. format === GPUTextureFormat.Depth24PlusStencil8 ||
  40318. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  40319. // 64-bit formats
  40320. if ( format === GPUTextureFormat.RG32Uint ||
  40321. format === GPUTextureFormat.RG32Sint ||
  40322. format === GPUTextureFormat.RG32Float ||
  40323. format === GPUTextureFormat.RGBA16Uint ||
  40324. format === GPUTextureFormat.RGBA16Sint ||
  40325. format === GPUTextureFormat.RGBA16Float ) return 8;
  40326. // 128-bit formats
  40327. if ( format === GPUTextureFormat.RGBA32Uint ||
  40328. format === GPUTextureFormat.RGBA32Sint ||
  40329. format === GPUTextureFormat.RGBA32Float ) return 16;
  40330. }
  40331. _getTypedArrayType( format ) {
  40332. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  40333. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  40334. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  40335. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  40336. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  40337. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  40338. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  40339. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  40340. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  40341. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  40342. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  40343. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  40344. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  40345. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  40346. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  40347. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  40348. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  40349. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  40350. if ( format === GPUTextureFormat.R16Float ) return Float32Array;
  40351. if ( format === GPUTextureFormat.RG16Float ) return Float32Array;
  40352. if ( format === GPUTextureFormat.RGBA16Float ) return Float32Array;
  40353. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  40354. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  40355. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  40356. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  40357. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  40358. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  40359. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  40360. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  40361. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  40362. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  40363. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  40364. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  40365. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  40366. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  40367. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  40368. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  40369. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  40370. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  40371. }
  40372. _getDimension( texture ) {
  40373. let dimension;
  40374. if ( texture.isData3DTexture ) {
  40375. dimension = GPUTextureDimension.ThreeD;
  40376. } else {
  40377. dimension = GPUTextureDimension.TwoD;
  40378. }
  40379. return dimension;
  40380. }
  40381. }
  40382. function getFormat( texture, device = null ) {
  40383. const format = texture.format;
  40384. const type = texture.type;
  40385. const colorSpace = texture.colorSpace;
  40386. let formatGPU;
  40387. if ( texture.isFramebufferTexture === true && texture.type === UnsignedByteType ) {
  40388. formatGPU = GPUTextureFormat.BGRA8Unorm;
  40389. } else if ( texture.isCompressedTexture === true ) {
  40390. switch ( format ) {
  40391. case RGBA_S3TC_DXT1_Format:
  40392. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  40393. break;
  40394. case RGBA_S3TC_DXT3_Format:
  40395. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  40396. break;
  40397. case RGBA_S3TC_DXT5_Format:
  40398. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  40399. break;
  40400. case RGB_ETC2_Format:
  40401. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  40402. break;
  40403. case RGBA_ETC2_EAC_Format:
  40404. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  40405. break;
  40406. case RGBA_ASTC_4x4_Format:
  40407. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  40408. break;
  40409. case RGBA_ASTC_5x4_Format:
  40410. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  40411. break;
  40412. case RGBA_ASTC_5x5_Format:
  40413. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  40414. break;
  40415. case RGBA_ASTC_6x5_Format:
  40416. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  40417. break;
  40418. case RGBA_ASTC_6x6_Format:
  40419. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  40420. break;
  40421. case RGBA_ASTC_8x5_Format:
  40422. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  40423. break;
  40424. case RGBA_ASTC_8x6_Format:
  40425. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  40426. break;
  40427. case RGBA_ASTC_8x8_Format:
  40428. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  40429. break;
  40430. case RGBA_ASTC_10x5_Format:
  40431. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  40432. break;
  40433. case RGBA_ASTC_10x6_Format:
  40434. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  40435. break;
  40436. case RGBA_ASTC_10x8_Format:
  40437. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  40438. break;
  40439. case RGBA_ASTC_10x10_Format:
  40440. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  40441. break;
  40442. case RGBA_ASTC_12x10_Format:
  40443. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  40444. break;
  40445. case RGBA_ASTC_12x12_Format:
  40446. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  40447. break;
  40448. default:
  40449. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  40450. }
  40451. } else {
  40452. switch ( format ) {
  40453. case RGBAFormat:
  40454. switch ( type ) {
  40455. case ByteType:
  40456. formatGPU = GPUTextureFormat.RGBA8Snorm;
  40457. break;
  40458. case ShortType:
  40459. formatGPU = GPUTextureFormat.RGBA16Sint;
  40460. break;
  40461. case UnsignedShortType:
  40462. formatGPU = GPUTextureFormat.RGBA16Uint;
  40463. break;
  40464. case UnsignedIntType:
  40465. formatGPU = GPUTextureFormat.RGBA32Uint;
  40466. break;
  40467. case IntType:
  40468. formatGPU = GPUTextureFormat.RGBA32Sint;
  40469. break;
  40470. case UnsignedByteType:
  40471. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  40472. break;
  40473. case HalfFloatType:
  40474. formatGPU = GPUTextureFormat.RGBA16Float;
  40475. break;
  40476. case FloatType:
  40477. formatGPU = GPUTextureFormat.RGBA32Float;
  40478. break;
  40479. default:
  40480. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  40481. }
  40482. break;
  40483. case RGBFormat:
  40484. switch ( type ) {
  40485. case UnsignedInt5999Type:
  40486. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  40487. break;
  40488. default:
  40489. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  40490. }
  40491. break;
  40492. case RedFormat:
  40493. switch ( type ) {
  40494. case ByteType:
  40495. formatGPU = GPUTextureFormat.R8Snorm;
  40496. break;
  40497. case ShortType:
  40498. formatGPU = GPUTextureFormat.R16Sint;
  40499. break;
  40500. case UnsignedShortType:
  40501. formatGPU = GPUTextureFormat.R16Uint;
  40502. break;
  40503. case UnsignedIntType:
  40504. formatGPU = GPUTextureFormat.R32Uint;
  40505. break;
  40506. case IntType:
  40507. formatGPU = GPUTextureFormat.R32Sint;
  40508. break;
  40509. case UnsignedByteType:
  40510. formatGPU = GPUTextureFormat.R8Unorm;
  40511. break;
  40512. case HalfFloatType:
  40513. formatGPU = GPUTextureFormat.R16Float;
  40514. break;
  40515. case FloatType:
  40516. formatGPU = GPUTextureFormat.R32Float;
  40517. break;
  40518. default:
  40519. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  40520. }
  40521. break;
  40522. case RGFormat:
  40523. switch ( type ) {
  40524. case ByteType:
  40525. formatGPU = GPUTextureFormat.RG8Snorm;
  40526. break;
  40527. case ShortType:
  40528. formatGPU = GPUTextureFormat.RG16Sint;
  40529. break;
  40530. case UnsignedShortType:
  40531. formatGPU = GPUTextureFormat.RG16Uint;
  40532. break;
  40533. case UnsignedIntType:
  40534. formatGPU = GPUTextureFormat.RG32Uint;
  40535. break;
  40536. case IntType:
  40537. formatGPU = GPUTextureFormat.RG32Sint;
  40538. break;
  40539. case UnsignedByteType:
  40540. formatGPU = GPUTextureFormat.RG8Unorm;
  40541. break;
  40542. case HalfFloatType:
  40543. formatGPU = GPUTextureFormat.RG16Float;
  40544. break;
  40545. case FloatType:
  40546. formatGPU = GPUTextureFormat.RG32Float;
  40547. break;
  40548. default:
  40549. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  40550. }
  40551. break;
  40552. case DepthFormat:
  40553. switch ( type ) {
  40554. case UnsignedShortType:
  40555. formatGPU = GPUTextureFormat.Depth16Unorm;
  40556. break;
  40557. case UnsignedIntType:
  40558. formatGPU = GPUTextureFormat.Depth24Plus;
  40559. break;
  40560. case FloatType:
  40561. formatGPU = GPUTextureFormat.Depth32Float;
  40562. break;
  40563. default:
  40564. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  40565. }
  40566. break;
  40567. case DepthStencilFormat:
  40568. switch ( type ) {
  40569. case UnsignedInt248Type:
  40570. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  40571. break;
  40572. case FloatType:
  40573. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  40574. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  40575. }
  40576. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  40577. break;
  40578. default:
  40579. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  40580. }
  40581. break;
  40582. case RedIntegerFormat:
  40583. switch ( type ) {
  40584. case IntType:
  40585. formatGPU = GPUTextureFormat.R32Sint;
  40586. break;
  40587. case UnsignedIntType:
  40588. formatGPU = GPUTextureFormat.R32Uint;
  40589. break;
  40590. default:
  40591. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  40592. }
  40593. break;
  40594. case RGIntegerFormat:
  40595. switch ( type ) {
  40596. case IntType:
  40597. formatGPU = GPUTextureFormat.RG32Sint;
  40598. break;
  40599. case UnsignedIntType:
  40600. formatGPU = GPUTextureFormat.RG32Uint;
  40601. break;
  40602. default:
  40603. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  40604. }
  40605. break;
  40606. case RGBAIntegerFormat:
  40607. switch ( type ) {
  40608. case IntType:
  40609. formatGPU = GPUTextureFormat.RGBA32Sint;
  40610. break;
  40611. case UnsignedIntType:
  40612. formatGPU = GPUTextureFormat.RGBA32Uint;
  40613. break;
  40614. default:
  40615. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  40616. }
  40617. break;
  40618. default:
  40619. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  40620. }
  40621. }
  40622. return formatGPU;
  40623. }
  40624. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  40625. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  40626. const wgslTypeLib$1 = {
  40627. 'f32': 'float',
  40628. 'i32': 'int',
  40629. 'u32': 'uint',
  40630. 'bool': 'bool',
  40631. 'vec2<f32>': 'vec2',
  40632. 'vec2<i32>': 'ivec2',
  40633. 'vec2<u32>': 'uvec2',
  40634. 'vec2<bool>': 'bvec2',
  40635. 'vec2f': 'vec2',
  40636. 'vec2i': 'ivec2',
  40637. 'vec2u': 'uvec2',
  40638. 'vec2b': 'bvec2',
  40639. 'vec3<f32>': 'vec3',
  40640. 'vec3<i32>': 'ivec3',
  40641. 'vec3<u32>': 'uvec3',
  40642. 'vec3<bool>': 'bvec3',
  40643. 'vec3f': 'vec3',
  40644. 'vec3i': 'ivec3',
  40645. 'vec3u': 'uvec3',
  40646. 'vec3b': 'bvec3',
  40647. 'vec4<f32>': 'vec4',
  40648. 'vec4<i32>': 'ivec4',
  40649. 'vec4<u32>': 'uvec4',
  40650. 'vec4<bool>': 'bvec4',
  40651. 'vec4f': 'vec4',
  40652. 'vec4i': 'ivec4',
  40653. 'vec4u': 'uvec4',
  40654. 'vec4b': 'bvec4',
  40655. 'mat2x2<f32>': 'mat2',
  40656. 'mat2x2f': 'mat2',
  40657. 'mat3x3<f32>': 'mat3',
  40658. 'mat3x3f': 'mat3',
  40659. 'mat4x4<f32>': 'mat4',
  40660. 'mat4x4f': 'mat4',
  40661. 'sampler': 'sampler',
  40662. 'texture_2d': 'texture',
  40663. 'texture_cube': 'cubeTexture',
  40664. 'texture_depth_2d': 'depthTexture',
  40665. 'texture_storage_2d': 'storageTexture',
  40666. 'texture_3d': 'texture3D'
  40667. };
  40668. const parse = ( source ) => {
  40669. source = source.trim();
  40670. const declaration = source.match( declarationRegexp );
  40671. if ( declaration !== null && declaration.length === 4 ) {
  40672. const inputsCode = declaration[ 2 ];
  40673. const propsMatches = [];
  40674. let match = null;
  40675. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  40676. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  40677. }
  40678. // Process matches to correctly pair names and types
  40679. const inputs = [];
  40680. for ( let i = 0; i < propsMatches.length; i ++ ) {
  40681. const { name, type } = propsMatches[ i ];
  40682. let resolvedType = type;
  40683. if ( resolvedType.startsWith( 'texture' ) ) {
  40684. resolvedType = type.split( '<' )[ 0 ];
  40685. }
  40686. resolvedType = wgslTypeLib$1[ resolvedType ] || resolvedType;
  40687. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  40688. }
  40689. const blockCode = source.substring( declaration[ 0 ].length );
  40690. const outputType = declaration[ 3 ] || 'void';
  40691. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  40692. const type = wgslTypeLib$1[ outputType ] || outputType;
  40693. return {
  40694. type,
  40695. inputs,
  40696. name,
  40697. inputsCode,
  40698. blockCode,
  40699. outputType
  40700. };
  40701. } else {
  40702. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  40703. }
  40704. };
  40705. class WGSLNodeFunction extends NodeFunction {
  40706. constructor( source ) {
  40707. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  40708. super( type, inputs, name );
  40709. this.inputsCode = inputsCode;
  40710. this.blockCode = blockCode;
  40711. this.outputType = outputType;
  40712. }
  40713. getCode( name = this.name ) {
  40714. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  40715. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  40716. }
  40717. }
  40718. class WGSLNodeParser extends NodeParser {
  40719. parseFunction( source ) {
  40720. return new WGSLNodeFunction( source );
  40721. }
  40722. }
  40723. // GPUShaderStage is not defined in browsers not supporting WebGPU
  40724. const GPUShaderStage = self.GPUShaderStage;
  40725. const gpuShaderStageLib = {
  40726. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  40727. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  40728. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  40729. };
  40730. const supports = {
  40731. instance: true,
  40732. swizzleAssign: false,
  40733. storageBuffer: true
  40734. };
  40735. const wgslFnOpLib = {
  40736. '^^': 'threejs_xor'
  40737. };
  40738. const wgslTypeLib = {
  40739. float: 'f32',
  40740. int: 'i32',
  40741. uint: 'u32',
  40742. bool: 'bool',
  40743. color: 'vec3<f32>',
  40744. vec2: 'vec2<f32>',
  40745. ivec2: 'vec2<i32>',
  40746. uvec2: 'vec2<u32>',
  40747. bvec2: 'vec2<bool>',
  40748. vec3: 'vec3<f32>',
  40749. ivec3: 'vec3<i32>',
  40750. uvec3: 'vec3<u32>',
  40751. bvec3: 'vec3<bool>',
  40752. vec4: 'vec4<f32>',
  40753. ivec4: 'vec4<i32>',
  40754. uvec4: 'vec4<u32>',
  40755. bvec4: 'vec4<bool>',
  40756. mat2: 'mat2x2<f32>',
  40757. imat2: 'mat2x2<i32>',
  40758. umat2: 'mat2x2<u32>',
  40759. bmat2: 'mat2x2<bool>',
  40760. mat3: 'mat3x3<f32>',
  40761. imat3: 'mat3x3<i32>',
  40762. umat3: 'mat3x3<u32>',
  40763. bmat3: 'mat3x3<bool>',
  40764. mat4: 'mat4x4<f32>',
  40765. imat4: 'mat4x4<i32>',
  40766. umat4: 'mat4x4<u32>',
  40767. bmat4: 'mat4x4<bool>'
  40768. };
  40769. const wgslMethods = {
  40770. dFdx: 'dpdx',
  40771. dFdy: '- dpdy',
  40772. mod_float: 'threejs_mod_float',
  40773. mod_vec2: 'threejs_mod_vec2',
  40774. mod_vec3: 'threejs_mod_vec3',
  40775. mod_vec4: 'threejs_mod_vec4',
  40776. equals_bool: 'threejs_equals_bool',
  40777. equals_bvec2: 'threejs_equals_bvec2',
  40778. equals_bvec3: 'threejs_equals_bvec3',
  40779. equals_bvec4: 'threejs_equals_bvec4',
  40780. lessThanEqual: 'threejs_lessThanEqual',
  40781. greaterThan: 'threejs_greaterThan',
  40782. inversesqrt: 'inverseSqrt',
  40783. bitcast: 'bitcast<f32>'
  40784. };
  40785. const wgslPolyfill = {
  40786. threejs_xor: new CodeNode( `
  40787. fn threejs_xor( a : bool, b : bool ) -> bool {
  40788. return ( a || b ) && !( a && b );
  40789. }
  40790. ` ),
  40791. lessThanEqual: new CodeNode( `
  40792. fn threejs_lessThanEqual( a : vec3<f32>, b : vec3<f32> ) -> vec3<bool> {
  40793. return vec3<bool>( a.x <= b.x, a.y <= b.y, a.z <= b.z );
  40794. }
  40795. ` ),
  40796. greaterThan: new CodeNode( `
  40797. fn threejs_greaterThan( a : vec3<f32>, b : vec3<f32> ) -> vec3<bool> {
  40798. return vec3<bool>( a.x > b.x, a.y > b.y, a.z > b.z );
  40799. }
  40800. ` ),
  40801. mod_float: new CodeNode( 'fn threejs_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  40802. mod_vec2: new CodeNode( 'fn threejs_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  40803. mod_vec3: new CodeNode( 'fn threejs_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  40804. mod_vec4: new CodeNode( 'fn threejs_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  40805. equals_bool: new CodeNode( 'fn threejs_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  40806. 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 ); }' ),
  40807. 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 ); }' ),
  40808. 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 ); }' ),
  40809. repeatWrapping: new CodeNode( `
  40810. fn threejs_repeatWrapping( uv : vec2<f32>, dimension : vec2<u32> ) -> vec2<u32> {
  40811. let uvScaled = vec2<u32>( uv * vec2<f32>( dimension ) );
  40812. return ( ( uvScaled % dimension ) + dimension ) % dimension;
  40813. }
  40814. ` ),
  40815. biquadraticTexture: new CodeNode( `
  40816. fn threejs_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, level : i32 ) -> vec4f {
  40817. let res = vec2f( textureDimensions( map, level ) );
  40818. let uvScaled = coord * res;
  40819. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  40820. // https://www.shadertoy.com/view/WtyXRy
  40821. let uv = uvWrapping - 0.5;
  40822. let iuv = floor( uv );
  40823. let f = fract( uv );
  40824. let rg1 = textureLoad( map, vec2i( iuv + vec2( 0.5, 0.5 ) ), level );
  40825. let rg2 = textureLoad( map, vec2i( iuv + vec2( 1.5, 0.5 ) ), level );
  40826. let rg3 = textureLoad( map, vec2i( iuv + vec2( 0.5, 1.5 ) ), level );
  40827. let rg4 = textureLoad( map, vec2i( iuv + vec2( 1.5, 1.5 ) ), level );
  40828. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  40829. }
  40830. ` )
  40831. };
  40832. class WGSLNodeBuilder extends NodeBuilder {
  40833. constructor( object, renderer ) {
  40834. super( object, renderer, new WGSLNodeParser() );
  40835. this.uniformGroups = {};
  40836. this.builtins = {};
  40837. }
  40838. needsColorSpaceToLinear( texture ) {
  40839. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  40840. }
  40841. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40842. if ( shaderStage === 'fragment' ) {
  40843. if ( depthSnippet ) {
  40844. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  40845. } else {
  40846. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  40847. }
  40848. } else if ( this.isFilteredTexture( texture ) ) {
  40849. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  40850. } else {
  40851. return this.generateTextureLod( texture, textureProperty, uvSnippet, '0' );
  40852. }
  40853. }
  40854. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  40855. if ( shaderStage === 'fragment' ) {
  40856. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  40857. } else {
  40858. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  40859. }
  40860. }
  40861. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40862. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  40863. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  40864. } else if ( this.isFilteredTexture( texture ) ) {
  40865. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  40866. } else {
  40867. return this.generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet );
  40868. }
  40869. }
  40870. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  40871. this._include( 'biquadraticTexture' );
  40872. return `threejs_biquadraticTexture( ${ textureProperty }, ${ uvSnippet }, i32( ${ levelSnippet } ) )`;
  40873. }
  40874. generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  40875. this._include( 'repeatWrapping' );
  40876. const dimension = `textureDimensions( ${ textureProperty }, 0 )`;
  40877. return `textureLoad( ${ textureProperty }, threejs_repeatWrapping( ${ uvSnippet }, ${ dimension } ), i32( ${ levelSnippet } ) )`;
  40878. }
  40879. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  40880. if ( depthSnippet ) {
  40881. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  40882. } else {
  40883. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  40884. }
  40885. }
  40886. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  40887. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  40888. }
  40889. isUnfilterable( texture ) {
  40890. return this.getComponentTypeFromTexture( texture ) !== 'float' || ( texture.isDataTexture === true && texture.type === FloatType );
  40891. }
  40892. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40893. let snippet = null;
  40894. if ( texture.isVideoTexture === true ) {
  40895. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  40896. } else if ( this.isUnfilterable( texture ) ) {
  40897. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, '0', depthSnippet, shaderStage );
  40898. } else {
  40899. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  40900. }
  40901. return snippet;
  40902. }
  40903. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40904. if ( shaderStage === 'fragment' ) {
  40905. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  40906. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  40907. } else {
  40908. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  40909. }
  40910. }
  40911. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40912. if ( shaderStage === 'fragment' ) {
  40913. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  40914. } else {
  40915. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  40916. }
  40917. }
  40918. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40919. let snippet = null;
  40920. if ( texture.isVideoTexture === true ) {
  40921. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  40922. } else {
  40923. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  40924. }
  40925. return snippet;
  40926. }
  40927. getPropertyName( node, shaderStage = this.shaderStage ) {
  40928. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  40929. if ( shaderStage === 'vertex' ) {
  40930. return `varyings.${ node.name }`;
  40931. }
  40932. } else if ( node.isNodeUniform === true ) {
  40933. const name = node.name;
  40934. const type = node.type;
  40935. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  40936. return name;
  40937. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  40938. return `NodeBuffer_${ node.id }.${name}`;
  40939. } else {
  40940. return node.groupNode.name + '.' + name;
  40941. }
  40942. }
  40943. return super.getPropertyName( node );
  40944. }
  40945. getOutputStructName() {
  40946. return 'output';
  40947. }
  40948. _getUniformGroupCount( shaderStage ) {
  40949. return Object.keys( this.uniforms[ shaderStage ] ).length;
  40950. }
  40951. getFunctionOperator( op ) {
  40952. const fnOp = wgslFnOpLib[ op ];
  40953. if ( fnOp !== undefined ) {
  40954. this._include( fnOp );
  40955. return fnOp;
  40956. }
  40957. return null;
  40958. }
  40959. getStorageAccess( node ) {
  40960. if ( node.isStorageTextureNode ) {
  40961. switch ( node.access ) {
  40962. case GPUStorageTextureAccess.ReadOnly:
  40963. return 'read';
  40964. case GPUStorageTextureAccess.WriteOnly:
  40965. return 'write';
  40966. default:
  40967. return 'read_write';
  40968. }
  40969. } else {
  40970. switch ( node.access ) {
  40971. case GPUBufferBindingType.Storage:
  40972. return 'read_write';
  40973. case GPUBufferBindingType.ReadOnlyStorage:
  40974. return 'read';
  40975. default:
  40976. return 'write';
  40977. }
  40978. }
  40979. }
  40980. getUniformFromNode( node, type, shaderStage, name = null ) {
  40981. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  40982. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  40983. if ( nodeData.uniformGPU === undefined ) {
  40984. let uniformGPU;
  40985. const group = node.groupNode;
  40986. const groupName = group.name;
  40987. const bindings = this.getBindGroupArray( groupName, shaderStage );
  40988. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  40989. let texture = null;
  40990. if ( type === 'texture' || type === 'storageTexture' ) {
  40991. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  40992. } else if ( type === 'cubeTexture' ) {
  40993. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  40994. } else if ( type === 'texture3D' ) {
  40995. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  40996. }
  40997. texture.store = node.isStorageTextureNode === true;
  40998. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  40999. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  41000. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  41001. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41002. bindings.push( sampler, texture );
  41003. uniformGPU = [ sampler, texture ];
  41004. } else {
  41005. bindings.push( texture );
  41006. uniformGPU = [ texture ];
  41007. }
  41008. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  41009. const bufferClass = type === 'storageBuffer' ? NodeStorageBuffer : NodeUniformBuffer;
  41010. const buffer = new bufferClass( node, group );
  41011. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41012. bindings.push( buffer );
  41013. uniformGPU = buffer;
  41014. } else {
  41015. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  41016. let uniformsGroup = uniformsStage[ groupName ];
  41017. if ( uniformsGroup === undefined ) {
  41018. uniformsGroup = new NodeUniformsGroup( groupName, group );
  41019. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41020. uniformsStage[ groupName ] = uniformsGroup;
  41021. bindings.push( uniformsGroup );
  41022. }
  41023. uniformGPU = this.getNodeUniform( uniformNode, type );
  41024. uniformsGroup.addUniform( uniformGPU );
  41025. }
  41026. nodeData.uniformGPU = uniformGPU;
  41027. }
  41028. return uniformNode;
  41029. }
  41030. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  41031. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  41032. if ( map.has( name ) === false ) {
  41033. map.set( name, {
  41034. name,
  41035. property,
  41036. type
  41037. } );
  41038. }
  41039. return property;
  41040. }
  41041. getVertexIndex() {
  41042. if ( this.shaderStage === 'vertex' ) {
  41043. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  41044. }
  41045. return 'vertexIndex';
  41046. }
  41047. buildFunctionCode( shaderNode ) {
  41048. const layout = shaderNode.layout;
  41049. const flowData = this.flowShaderNode( shaderNode );
  41050. const parameters = [];
  41051. for ( const input of layout.inputs ) {
  41052. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  41053. }
  41054. //
  41055. const code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  41056. ${ flowData.vars }
  41057. ${ flowData.code }
  41058. return ${ flowData.result };
  41059. }`;
  41060. //
  41061. return code;
  41062. }
  41063. getInstanceIndex() {
  41064. if ( this.shaderStage === 'vertex' ) {
  41065. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  41066. }
  41067. return 'instanceIndex';
  41068. }
  41069. getDrawIndex() {
  41070. return null;
  41071. }
  41072. getFrontFacing() {
  41073. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  41074. }
  41075. getFragCoord() {
  41076. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xyz';
  41077. }
  41078. getFragDepth() {
  41079. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  41080. }
  41081. isFlipY() {
  41082. return false;
  41083. }
  41084. getBuiltins( shaderStage ) {
  41085. const snippets = [];
  41086. const builtins = this.builtins[ shaderStage ];
  41087. if ( builtins !== undefined ) {
  41088. for ( const { name, property, type } of builtins.values() ) {
  41089. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  41090. }
  41091. }
  41092. return snippets.join( ',\n\t' );
  41093. }
  41094. getAttributes( shaderStage ) {
  41095. const snippets = [];
  41096. if ( shaderStage === 'compute' ) {
  41097. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  41098. }
  41099. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  41100. const builtins = this.getBuiltins( 'attribute' );
  41101. if ( builtins ) snippets.push( builtins );
  41102. const attributes = this.getAttributesArray();
  41103. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  41104. const attribute = attributes[ index ];
  41105. const name = attribute.name;
  41106. const type = this.getType( attribute.type );
  41107. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  41108. }
  41109. }
  41110. return snippets.join( ',\n\t' );
  41111. }
  41112. getStructMembers( struct ) {
  41113. const snippets = [];
  41114. const members = struct.getMemberTypes();
  41115. for ( let i = 0; i < members.length; i ++ ) {
  41116. const member = members[ i ];
  41117. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  41118. }
  41119. const builtins = this.getBuiltins( 'output' );
  41120. if ( builtins ) snippets.push( builtins );
  41121. return snippets.join( ',\n' );
  41122. }
  41123. getStructs( shaderStage ) {
  41124. const snippets = [];
  41125. const structs = this.structs[ shaderStage ];
  41126. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  41127. const struct = structs[ index ];
  41128. const name = struct.name;
  41129. let snippet = `\struct ${ name } {\n`;
  41130. snippet += this.getStructMembers( struct );
  41131. snippet += '\n}';
  41132. snippets.push( snippet );
  41133. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  41134. }
  41135. return snippets.join( '\n\n' );
  41136. }
  41137. getVar( type, name ) {
  41138. return `var ${ name } : ${ this.getType( type ) }`;
  41139. }
  41140. getVars( shaderStage ) {
  41141. const snippets = [];
  41142. const vars = this.vars[ shaderStage ];
  41143. if ( vars !== undefined ) {
  41144. for ( const variable of vars ) {
  41145. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  41146. }
  41147. }
  41148. return `\n${ snippets.join( '\n' ) }\n`;
  41149. }
  41150. getVaryings( shaderStage ) {
  41151. const snippets = [];
  41152. if ( shaderStage === 'vertex' ) {
  41153. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  41154. }
  41155. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  41156. const varyings = this.varyings;
  41157. const vars = this.vars[ shaderStage ];
  41158. for ( let index = 0; index < varyings.length; index ++ ) {
  41159. const varying = varyings[ index ];
  41160. if ( varying.needsInterpolation ) {
  41161. let attributesSnippet = `@location( ${index} )`;
  41162. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  41163. attributesSnippet += ' @interpolate( flat )';
  41164. }
  41165. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  41166. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  41167. vars.push( varying );
  41168. }
  41169. }
  41170. }
  41171. const builtins = this.getBuiltins( shaderStage );
  41172. if ( builtins ) snippets.push( builtins );
  41173. const code = snippets.join( ',\n\t' );
  41174. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  41175. }
  41176. getUniforms( shaderStage ) {
  41177. const uniforms = this.uniforms[ shaderStage ];
  41178. const bindingSnippets = [];
  41179. const bufferSnippets = [];
  41180. const structSnippets = [];
  41181. const uniformGroups = {};
  41182. for ( const uniform of uniforms ) {
  41183. const groundName = uniform.groupNode.name;
  41184. const uniformIndexes = this.bindingsIndexes[ groundName ];
  41185. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  41186. const texture = uniform.node.value;
  41187. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  41188. if ( texture.isDepthTexture === true && texture.compareFunction !== null ) {
  41189. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  41190. } else {
  41191. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  41192. }
  41193. }
  41194. let textureType;
  41195. if ( texture.isCubeTexture === true ) {
  41196. textureType = 'texture_cube<f32>';
  41197. } else if ( texture.isDataArrayTexture === true ) {
  41198. textureType = 'texture_2d_array<f32>';
  41199. } else if ( texture.isDepthTexture === true ) {
  41200. textureType = 'texture_depth_2d';
  41201. } else if ( texture.isVideoTexture === true ) {
  41202. textureType = 'texture_external';
  41203. } else if ( texture.isData3DTexture === true ) {
  41204. textureType = 'texture_3d<f32>';
  41205. } else if ( uniform.node.isStorageTextureNode === true ) {
  41206. const format = getFormat( texture );
  41207. const access = this.getStorageAccess( uniform.node );
  41208. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  41209. } else {
  41210. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  41211. textureType = `texture_2d<${ componentPrefix }32>`;
  41212. }
  41213. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  41214. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' ) {
  41215. const bufferNode = uniform.node;
  41216. const bufferType = this.getType( bufferNode.bufferType );
  41217. const bufferCount = bufferNode.bufferCount;
  41218. const bufferCountSnippet = bufferCount > 0 ? ', ' + bufferCount : '';
  41219. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferType }${ bufferCountSnippet } >\n`;
  41220. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode ) }` : 'uniform';
  41221. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  41222. } else {
  41223. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  41224. const groupName = uniform.groupNode.name;
  41225. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  41226. index: uniformIndexes.binding ++,
  41227. id: uniformIndexes.group,
  41228. snippets: []
  41229. } );
  41230. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  41231. }
  41232. }
  41233. for ( const name in uniformGroups ) {
  41234. const group = uniformGroups[ name ];
  41235. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  41236. }
  41237. let code = bindingSnippets.join( '\n' );
  41238. code += bufferSnippets.join( '\n' );
  41239. code += structSnippets.join( '\n' );
  41240. return code;
  41241. }
  41242. buildCode() {
  41243. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  41244. for ( const shaderStage in shadersData ) {
  41245. const stageData = shadersData[ shaderStage ];
  41246. stageData.uniforms = this.getUniforms( shaderStage );
  41247. stageData.attributes = this.getAttributes( shaderStage );
  41248. stageData.varyings = this.getVaryings( shaderStage );
  41249. stageData.structs = this.getStructs( shaderStage );
  41250. stageData.vars = this.getVars( shaderStage );
  41251. stageData.codes = this.getCodes( shaderStage );
  41252. //
  41253. let flow = '// code\n\n';
  41254. flow += this.flowCode[ shaderStage ];
  41255. const flowNodes = this.flowNodes[ shaderStage ];
  41256. const mainNode = flowNodes[ flowNodes.length - 1 ];
  41257. const outputNode = mainNode.outputNode;
  41258. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  41259. for ( const node of flowNodes ) {
  41260. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  41261. const slotName = node.name;
  41262. if ( slotName ) {
  41263. if ( flow.length > 0 ) flow += '\n';
  41264. flow += `\t// flow -> ${ slotName }\n\t`;
  41265. }
  41266. flow += `${ flowSlotData.code }\n\t`;
  41267. if ( node === mainNode && shaderStage !== 'compute' ) {
  41268. flow += '// result\n\n\t';
  41269. if ( shaderStage === 'vertex' ) {
  41270. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  41271. } else if ( shaderStage === 'fragment' ) {
  41272. if ( isOutputStruct ) {
  41273. stageData.returnType = outputNode.nodeType;
  41274. flow += `return ${ flowSlotData.result };`;
  41275. } else {
  41276. let structSnippet = '\t@location(0) color: vec4<f32>';
  41277. const builtins = this.getBuiltins( 'output' );
  41278. if ( builtins ) structSnippet += ',\n\t' + builtins;
  41279. stageData.returnType = 'OutputStruct';
  41280. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  41281. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  41282. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  41283. }
  41284. }
  41285. }
  41286. }
  41287. stageData.flow = flow;
  41288. }
  41289. if ( this.material !== null ) {
  41290. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  41291. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  41292. } else {
  41293. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  41294. }
  41295. }
  41296. getMethod( method, output = null ) {
  41297. let wgslMethod;
  41298. if ( output !== null ) {
  41299. wgslMethod = this._getWGSLMethod( method + '_' + output );
  41300. }
  41301. if ( wgslMethod === undefined ) {
  41302. wgslMethod = this._getWGSLMethod( method );
  41303. }
  41304. return wgslMethod || method;
  41305. }
  41306. getType( type ) {
  41307. return wgslTypeLib[ type ] || type;
  41308. }
  41309. isAvailable( name ) {
  41310. let result = supports[ name ];
  41311. if ( result === undefined ) {
  41312. if ( name === 'float32Filterable' ) {
  41313. result = this.renderer.hasFeature( 'float32-filterable' );
  41314. }
  41315. supports[ name ] = result;
  41316. }
  41317. return result;
  41318. }
  41319. _getWGSLMethod( method ) {
  41320. if ( wgslPolyfill[ method ] !== undefined ) {
  41321. this._include( method );
  41322. }
  41323. return wgslMethods[ method ];
  41324. }
  41325. _include( name ) {
  41326. const codeNode = wgslPolyfill[ name ];
  41327. codeNode.build( this );
  41328. if ( this.currentFunctionNode !== null ) {
  41329. this.currentFunctionNode.includes.push( codeNode );
  41330. }
  41331. return codeNode;
  41332. }
  41333. _getWGSLVertexCode( shaderData ) {
  41334. return `${ this.getSignature() }
  41335. // uniforms
  41336. ${shaderData.uniforms}
  41337. // varyings
  41338. ${shaderData.varyings}
  41339. var<private> varyings : VaryingsStruct;
  41340. // codes
  41341. ${shaderData.codes}
  41342. @vertex
  41343. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  41344. // vars
  41345. ${shaderData.vars}
  41346. // flow
  41347. ${shaderData.flow}
  41348. return varyings;
  41349. }
  41350. `;
  41351. }
  41352. _getWGSLFragmentCode( shaderData ) {
  41353. return `${ this.getSignature() }
  41354. // uniforms
  41355. ${shaderData.uniforms}
  41356. // structs
  41357. ${shaderData.structs}
  41358. // codes
  41359. ${shaderData.codes}
  41360. @fragment
  41361. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  41362. // vars
  41363. ${shaderData.vars}
  41364. // flow
  41365. ${shaderData.flow}
  41366. }
  41367. `;
  41368. }
  41369. _getWGSLComputeCode( shaderData, workgroupSize ) {
  41370. return `${ this.getSignature() }
  41371. // system
  41372. var<private> instanceIndex : u32;
  41373. // uniforms
  41374. ${shaderData.uniforms}
  41375. // codes
  41376. ${shaderData.codes}
  41377. @compute @workgroup_size( ${workgroupSize} )
  41378. fn main( ${shaderData.attributes} ) {
  41379. // system
  41380. instanceIndex = id.x;
  41381. // vars
  41382. ${shaderData.vars}
  41383. // flow
  41384. ${shaderData.flow}
  41385. }
  41386. `;
  41387. }
  41388. _getWGSLStruct( name, vars ) {
  41389. return `
  41390. struct ${name} {
  41391. ${vars}
  41392. };`;
  41393. }
  41394. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  41395. const structName = name + 'Struct';
  41396. const structSnippet = this._getWGSLStruct( structName, vars );
  41397. return `${structSnippet}
  41398. @binding( ${binding} ) @group( ${group} )
  41399. var<${access}> ${name} : ${structName};`;
  41400. }
  41401. }
  41402. class WebGPUUtils {
  41403. constructor( backend ) {
  41404. this.backend = backend;
  41405. }
  41406. getCurrentDepthStencilFormat( renderContext ) {
  41407. let format;
  41408. if ( renderContext.depthTexture !== null ) {
  41409. format = this.getTextureFormatGPU( renderContext.depthTexture );
  41410. } else if ( renderContext.depth && renderContext.stencil ) {
  41411. format = GPUTextureFormat.Depth24PlusStencil8;
  41412. } else if ( renderContext.depth ) {
  41413. format = GPUTextureFormat.Depth24Plus;
  41414. }
  41415. return format;
  41416. }
  41417. getTextureFormatGPU( texture ) {
  41418. return this.backend.get( texture ).texture.format;
  41419. }
  41420. getCurrentColorFormat( renderContext ) {
  41421. let format;
  41422. if ( renderContext.textures !== null ) {
  41423. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  41424. } else {
  41425. format = GPUTextureFormat.BGRA8Unorm; // default context format
  41426. }
  41427. return format;
  41428. }
  41429. getCurrentColorSpace( renderContext ) {
  41430. if ( renderContext.textures !== null ) {
  41431. return renderContext.textures[ 0 ].colorSpace;
  41432. }
  41433. return this.backend.renderer.outputColorSpace;
  41434. }
  41435. getPrimitiveTopology( object, material ) {
  41436. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  41437. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  41438. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  41439. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  41440. }
  41441. getSampleCount( renderContext ) {
  41442. if ( renderContext.textures !== null ) {
  41443. return renderContext.sampleCount;
  41444. }
  41445. return this.backend.parameters.sampleCount;
  41446. }
  41447. }
  41448. const typedArraysToVertexFormatPrefix = new Map( [
  41449. [ Int8Array, [ 'sint8', 'snorm8' ]],
  41450. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  41451. [ Int16Array, [ 'sint16', 'snorm16' ]],
  41452. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  41453. [ Int32Array, [ 'sint32', 'snorm32' ]],
  41454. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  41455. [ Float32Array, [ 'float32', ]],
  41456. ] );
  41457. const typedAttributeToVertexFormatPrefix = new Map( [
  41458. [ Float16BufferAttribute, [ 'float16', ]],
  41459. ] );
  41460. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  41461. [ Int32Array, 'sint32' ],
  41462. [ Int16Array, 'sint32' ], // patch for INT16
  41463. [ Uint32Array, 'uint32' ],
  41464. [ Uint16Array, 'uint32' ], // patch for UINT16
  41465. [ Float32Array, 'float32' ]
  41466. ] );
  41467. class WebGPUAttributeUtils {
  41468. constructor( backend ) {
  41469. this.backend = backend;
  41470. }
  41471. createAttribute( attribute, usage ) {
  41472. const bufferAttribute = this._getBufferAttribute( attribute );
  41473. const backend = this.backend;
  41474. const bufferData = backend.get( bufferAttribute );
  41475. let buffer = bufferData.buffer;
  41476. if ( buffer === undefined ) {
  41477. const device = backend.device;
  41478. let array = bufferAttribute.array;
  41479. // patch for INT16 and UINT16
  41480. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  41481. const tempArray = new Uint32Array( array.length );
  41482. for ( let i = 0; i < array.length; i ++ ) {
  41483. tempArray[ i ] = array[ i ];
  41484. }
  41485. array = tempArray;
  41486. }
  41487. bufferAttribute.array = array;
  41488. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  41489. array = new array.constructor( bufferAttribute.count * 4 );
  41490. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  41491. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  41492. }
  41493. // Update BufferAttribute
  41494. bufferAttribute.itemSize = 4;
  41495. bufferAttribute.array = array;
  41496. }
  41497. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  41498. buffer = device.createBuffer( {
  41499. label: bufferAttribute.name,
  41500. size: size,
  41501. usage: usage,
  41502. mappedAtCreation: true
  41503. } );
  41504. new array.constructor( buffer.getMappedRange() ).set( array );
  41505. buffer.unmap();
  41506. bufferData.buffer = buffer;
  41507. }
  41508. }
  41509. updateAttribute( attribute ) {
  41510. const bufferAttribute = this._getBufferAttribute( attribute );
  41511. const backend = this.backend;
  41512. const device = backend.device;
  41513. const buffer = backend.get( bufferAttribute ).buffer;
  41514. const array = bufferAttribute.array;
  41515. const updateRanges = bufferAttribute.updateRanges;
  41516. if ( updateRanges.length === 0 ) {
  41517. // Not using update ranges
  41518. device.queue.writeBuffer(
  41519. buffer,
  41520. 0,
  41521. array,
  41522. 0
  41523. );
  41524. } else {
  41525. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  41526. const range = updateRanges[ i ];
  41527. device.queue.writeBuffer(
  41528. buffer,
  41529. 0,
  41530. array,
  41531. range.start * array.BYTES_PER_ELEMENT,
  41532. range.count * array.BYTES_PER_ELEMENT
  41533. );
  41534. }
  41535. bufferAttribute.clearUpdateRanges();
  41536. }
  41537. }
  41538. createShaderVertexBuffers( renderObject ) {
  41539. const attributes = renderObject.getAttributes();
  41540. const vertexBuffers = new Map();
  41541. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  41542. const geometryAttribute = attributes[ slot ];
  41543. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  41544. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  41545. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  41546. if ( vertexBufferLayout === undefined ) {
  41547. let arrayStride, stepMode;
  41548. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  41549. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  41550. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  41551. } else {
  41552. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  41553. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  41554. }
  41555. // patch for INT16 and UINT16
  41556. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  41557. arrayStride = 4;
  41558. }
  41559. vertexBufferLayout = {
  41560. arrayStride,
  41561. attributes: [],
  41562. stepMode
  41563. };
  41564. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  41565. }
  41566. const format = this._getVertexFormat( geometryAttribute );
  41567. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  41568. vertexBufferLayout.attributes.push( {
  41569. shaderLocation: slot,
  41570. offset,
  41571. format
  41572. } );
  41573. }
  41574. return Array.from( vertexBuffers.values() );
  41575. }
  41576. destroyAttribute( attribute ) {
  41577. const backend = this.backend;
  41578. const data = backend.get( this._getBufferAttribute( attribute ) );
  41579. data.buffer.destroy();
  41580. backend.delete( attribute );
  41581. }
  41582. async getArrayBufferAsync( attribute ) {
  41583. const backend = this.backend;
  41584. const device = backend.device;
  41585. const data = backend.get( this._getBufferAttribute( attribute ) );
  41586. const bufferGPU = data.buffer;
  41587. const size = bufferGPU.size;
  41588. let readBufferGPU = data.readBuffer;
  41589. let needsUnmap = true;
  41590. if ( readBufferGPU === undefined ) {
  41591. readBufferGPU = device.createBuffer( {
  41592. label: attribute.name,
  41593. size,
  41594. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  41595. } );
  41596. needsUnmap = false;
  41597. data.readBuffer = readBufferGPU;
  41598. }
  41599. const cmdEncoder = device.createCommandEncoder( {} );
  41600. cmdEncoder.copyBufferToBuffer(
  41601. bufferGPU,
  41602. 0,
  41603. readBufferGPU,
  41604. 0,
  41605. size
  41606. );
  41607. if ( needsUnmap ) readBufferGPU.unmap();
  41608. const gpuCommands = cmdEncoder.finish();
  41609. device.queue.submit( [ gpuCommands ] );
  41610. await readBufferGPU.mapAsync( GPUMapMode.READ );
  41611. const arrayBuffer = readBufferGPU.getMappedRange();
  41612. return arrayBuffer;
  41613. }
  41614. _getVertexFormat( geometryAttribute ) {
  41615. const { itemSize, normalized } = geometryAttribute;
  41616. const ArrayType = geometryAttribute.array.constructor;
  41617. const AttributeType = geometryAttribute.constructor;
  41618. let format;
  41619. if ( itemSize == 1 ) {
  41620. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  41621. } else {
  41622. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  41623. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  41624. if ( prefix ) {
  41625. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  41626. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  41627. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  41628. if ( paddedItemSize % 1 ) {
  41629. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  41630. }
  41631. format = `${prefix}x${paddedItemSize}`;
  41632. }
  41633. }
  41634. if ( ! format ) {
  41635. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  41636. }
  41637. return format;
  41638. }
  41639. _getBufferAttribute( attribute ) {
  41640. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  41641. return attribute;
  41642. }
  41643. }
  41644. class WebGPUBindingUtils {
  41645. constructor( backend ) {
  41646. this.backend = backend;
  41647. }
  41648. createBindingsLayout( bindGroup ) {
  41649. const backend = this.backend;
  41650. const device = backend.device;
  41651. const entries = [];
  41652. let index = 0;
  41653. for ( const binding of bindGroup.bindings ) {
  41654. const bindingGPU = {
  41655. binding: index ++,
  41656. visibility: binding.visibility
  41657. };
  41658. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  41659. const buffer = {}; // GPUBufferBindingLayout
  41660. if ( binding.isStorageBuffer ) {
  41661. buffer.type = binding.access;
  41662. }
  41663. bindingGPU.buffer = buffer;
  41664. } else if ( binding.isSampler ) {
  41665. const sampler = {}; // GPUSamplerBindingLayout
  41666. if ( binding.texture.isDepthTexture ) {
  41667. if ( binding.texture.compareFunction !== null ) {
  41668. sampler.type = 'comparison';
  41669. }
  41670. }
  41671. bindingGPU.sampler = sampler;
  41672. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  41673. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  41674. } else if ( binding.isSampledTexture && binding.store ) {
  41675. const format = this.backend.get( binding.texture ).texture.format;
  41676. const access = binding.access;
  41677. bindingGPU.storageTexture = { format, access }; // GPUStorageTextureBindingLayout
  41678. } else if ( binding.isSampledTexture ) {
  41679. const texture = {}; // GPUTextureBindingLayout
  41680. if ( binding.texture.isDepthTexture ) {
  41681. texture.sampleType = GPUTextureSampleType.Depth;
  41682. } else if ( binding.texture.isDataTexture ) {
  41683. const type = binding.texture.type;
  41684. if ( type === IntType ) {
  41685. texture.sampleType = GPUTextureSampleType.SInt;
  41686. } else if ( type === UnsignedIntType ) {
  41687. texture.sampleType = GPUTextureSampleType.UInt;
  41688. } else if ( type === FloatType ) {
  41689. // @TODO: Add support for this soon: backend.hasFeature( 'float32-filterable' )
  41690. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  41691. }
  41692. }
  41693. if ( binding.isSampledCubeTexture ) {
  41694. texture.viewDimension = GPUTextureViewDimension.Cube;
  41695. } else if ( binding.texture.isDataArrayTexture ) {
  41696. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  41697. } else if ( binding.isSampledTexture3D ) {
  41698. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  41699. }
  41700. bindingGPU.texture = texture;
  41701. } else {
  41702. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  41703. }
  41704. entries.push( bindingGPU );
  41705. }
  41706. return device.createBindGroupLayout( { entries } );
  41707. }
  41708. createBindings( bindGroup ) {
  41709. const backend = this.backend;
  41710. const bindingsData = backend.get( bindGroup );
  41711. // setup (static) binding layout and (dynamic) binding group
  41712. const bindLayoutGPU = this.createBindingsLayout( bindGroup );
  41713. const bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  41714. bindingsData.layout = bindLayoutGPU;
  41715. bindingsData.group = bindGroupGPU;
  41716. }
  41717. updateBinding( binding ) {
  41718. const backend = this.backend;
  41719. const device = backend.device;
  41720. const buffer = binding.buffer;
  41721. const bufferGPU = backend.get( binding ).buffer;
  41722. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  41723. }
  41724. createBindGroup( bindGroup, layoutGPU ) {
  41725. const backend = this.backend;
  41726. const device = backend.device;
  41727. let bindingPoint = 0;
  41728. const entriesGPU = [];
  41729. for ( const binding of bindGroup.bindings ) {
  41730. if ( binding.isUniformBuffer ) {
  41731. const bindingData = backend.get( binding );
  41732. if ( bindingData.buffer === undefined ) {
  41733. const byteLength = binding.byteLength;
  41734. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  41735. const bufferGPU = device.createBuffer( {
  41736. label: 'bindingBuffer_' + binding.name,
  41737. size: byteLength,
  41738. usage: usage
  41739. } );
  41740. bindingData.buffer = bufferGPU;
  41741. }
  41742. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  41743. } else if ( binding.isStorageBuffer ) {
  41744. const bindingData = backend.get( binding );
  41745. if ( bindingData.buffer === undefined ) {
  41746. const attribute = binding.attribute;
  41747. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  41748. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  41749. bindingData.buffer = backend.get( attribute ).buffer;
  41750. }
  41751. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  41752. } else if ( binding.isSampler ) {
  41753. const textureGPU = backend.get( binding.texture );
  41754. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  41755. } else if ( binding.isSampledTexture ) {
  41756. const textureData = backend.get( binding.texture );
  41757. let dimensionViewGPU;
  41758. if ( binding.isSampledCubeTexture ) {
  41759. dimensionViewGPU = GPUTextureViewDimension.Cube;
  41760. } else if ( binding.isSampledTexture3D ) {
  41761. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  41762. } else if ( binding.texture.isDataArrayTexture ) {
  41763. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  41764. } else {
  41765. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  41766. }
  41767. let resourceGPU;
  41768. if ( textureData.externalTexture !== undefined ) {
  41769. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  41770. } else {
  41771. const aspectGPU = GPUTextureAspect.All;
  41772. resourceGPU = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount: binding.store ? 1 : textureData.mipLevelCount } );
  41773. }
  41774. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  41775. }
  41776. bindingPoint ++;
  41777. }
  41778. return device.createBindGroup( {
  41779. label: 'bindGroup_' + bindGroup.name,
  41780. layout: layoutGPU,
  41781. entries: entriesGPU
  41782. } );
  41783. }
  41784. }
  41785. class WebGPUPipelineUtils {
  41786. constructor( backend ) {
  41787. this.backend = backend;
  41788. }
  41789. _getSampleCount( renderObjectContext ) {
  41790. let sampleCount = this.backend.utils.getSampleCount( renderObjectContext );
  41791. if ( sampleCount > 1 ) {
  41792. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  41793. sampleCount = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  41794. if ( sampleCount === 2 ) {
  41795. sampleCount = 4;
  41796. }
  41797. }
  41798. return sampleCount;
  41799. }
  41800. createRenderPipeline( renderObject, promises ) {
  41801. const { object, material, geometry, pipeline } = renderObject;
  41802. const { vertexProgram, fragmentProgram } = pipeline;
  41803. const backend = this.backend;
  41804. const device = backend.device;
  41805. const utils = backend.utils;
  41806. const pipelineData = backend.get( pipeline );
  41807. // bind group layouts
  41808. const bindGroupLayouts = [];
  41809. for ( const bindGroup of renderObject.getBindings() ) {
  41810. const bindingsData = backend.get( bindGroup );
  41811. bindGroupLayouts.push( bindingsData.layout );
  41812. }
  41813. // vertex buffers
  41814. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  41815. // blending
  41816. let blending;
  41817. if ( material.transparent === true && material.blending !== NoBlending ) {
  41818. blending = this._getBlending( material );
  41819. }
  41820. // stencil
  41821. let stencilFront = {};
  41822. if ( material.stencilWrite === true ) {
  41823. stencilFront = {
  41824. compare: this._getStencilCompare( material ),
  41825. failOp: this._getStencilOperation( material.stencilFail ),
  41826. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  41827. passOp: this._getStencilOperation( material.stencilZPass )
  41828. };
  41829. }
  41830. const colorWriteMask = this._getColorWriteMask( material );
  41831. const targets = [];
  41832. if ( renderObject.context.textures !== null ) {
  41833. const textures = renderObject.context.textures;
  41834. for ( let i = 0; i < textures.length; i ++ ) {
  41835. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  41836. targets.push( {
  41837. format: colorFormat,
  41838. blend: blending,
  41839. writeMask: colorWriteMask
  41840. } );
  41841. }
  41842. } else {
  41843. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  41844. targets.push( {
  41845. format: colorFormat,
  41846. blend: blending,
  41847. writeMask: colorWriteMask
  41848. } );
  41849. }
  41850. const vertexModule = backend.get( vertexProgram ).module;
  41851. const fragmentModule = backend.get( fragmentProgram ).module;
  41852. const primitiveState = this._getPrimitiveState( object, geometry, material );
  41853. const depthCompare = this._getDepthCompare( material );
  41854. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  41855. const sampleCount = this._getSampleCount( renderObject.context );
  41856. const pipelineDescriptor = {
  41857. label: 'renderPipeline',
  41858. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  41859. fragment: Object.assign( {}, fragmentModule, { targets } ),
  41860. primitive: primitiveState,
  41861. depthStencil: {
  41862. format: depthStencilFormat,
  41863. depthWriteEnabled: material.depthWrite,
  41864. depthCompare: depthCompare,
  41865. stencilFront: stencilFront,
  41866. stencilBack: {}, // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  41867. stencilReadMask: material.stencilFuncMask,
  41868. stencilWriteMask: material.stencilWriteMask
  41869. },
  41870. multisample: {
  41871. count: sampleCount,
  41872. alphaToCoverageEnabled: material.alphaToCoverage
  41873. },
  41874. layout: device.createPipelineLayout( {
  41875. bindGroupLayouts
  41876. } )
  41877. };
  41878. if ( promises === null ) {
  41879. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  41880. } else {
  41881. const p = new Promise( ( resolve /*, reject*/ ) => {
  41882. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  41883. pipelineData.pipeline = pipeline;
  41884. resolve();
  41885. } );
  41886. } );
  41887. promises.push( p );
  41888. }
  41889. }
  41890. createBundleEncoder( renderContext, renderObject ) {
  41891. const backend = this.backend;
  41892. const { utils, device } = backend;
  41893. const renderContextData = backend.get( renderContext );
  41894. const renderObjectData = backend.get( renderObject );
  41895. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  41896. const colorFormat = utils.getCurrentColorFormat( renderContext );
  41897. const sampleCount = this._getSampleCount( renderObject.context );
  41898. const descriptor = {
  41899. label: 'renderBundleEncoder',
  41900. colorFormats: [ colorFormat ],
  41901. depthStencilFormat,
  41902. sampleCount
  41903. };
  41904. const bundleEncoder = device.createRenderBundleEncoder( descriptor );
  41905. renderObjectData.bundleEncoder = bundleEncoder;
  41906. renderContextData.currentSets = { attributes: {} };
  41907. renderContextData._renderBundleViewport = renderContext.width + '_' + renderContext.height;
  41908. return bundleEncoder;
  41909. }
  41910. createComputePipeline( pipeline, bindings ) {
  41911. const backend = this.backend;
  41912. const device = backend.device;
  41913. const computeProgram = backend.get( pipeline.computeProgram ).module;
  41914. const pipelineGPU = backend.get( pipeline );
  41915. // bind group layouts
  41916. const bindGroupLayouts = [];
  41917. for ( const bindingsGroup of bindings ) {
  41918. const bindingsData = backend.get( bindingsGroup );
  41919. bindGroupLayouts.push( bindingsData.layout );
  41920. }
  41921. pipelineGPU.pipeline = device.createComputePipeline( {
  41922. compute: computeProgram,
  41923. layout: device.createPipelineLayout( {
  41924. bindGroupLayouts
  41925. } )
  41926. } );
  41927. }
  41928. _getBlending( material ) {
  41929. let color, alpha;
  41930. const blending = material.blending;
  41931. const blendSrc = material.blendSrc;
  41932. const blendDst = material.blendDst;
  41933. const blendEquation = material.blendEquation;
  41934. if ( blending === CustomBlending ) {
  41935. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  41936. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  41937. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  41938. color = {
  41939. srcFactor: this._getBlendFactor( blendSrc ),
  41940. dstFactor: this._getBlendFactor( blendDst ),
  41941. operation: this._getBlendOperation( blendEquation )
  41942. };
  41943. alpha = {
  41944. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  41945. dstFactor: this._getBlendFactor( blendDstAlpha ),
  41946. operation: this._getBlendOperation( blendEquationAlpha )
  41947. };
  41948. } else {
  41949. const premultipliedAlpha = material.premultipliedAlpha;
  41950. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  41951. color = {
  41952. srcFactor: srcRGB,
  41953. dstFactor: dstRGB,
  41954. operation: GPUBlendOperation.Add
  41955. };
  41956. alpha = {
  41957. srcFactor: srcAlpha,
  41958. dstFactor: dstAlpha,
  41959. operation: GPUBlendOperation.Add
  41960. };
  41961. };
  41962. if ( premultipliedAlpha ) {
  41963. switch ( blending ) {
  41964. case NormalBlending:
  41965. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  41966. break;
  41967. case AdditiveBlending:
  41968. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  41969. break;
  41970. case SubtractiveBlending:
  41971. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  41972. break;
  41973. case MultiplyBlending:
  41974. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  41975. break;
  41976. }
  41977. } else {
  41978. switch ( blending ) {
  41979. case NormalBlending:
  41980. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  41981. break;
  41982. case AdditiveBlending:
  41983. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  41984. break;
  41985. case SubtractiveBlending:
  41986. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  41987. break;
  41988. case MultiplyBlending:
  41989. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  41990. break;
  41991. }
  41992. }
  41993. }
  41994. if ( color !== undefined && alpha !== undefined ) {
  41995. return { color, alpha };
  41996. } else {
  41997. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  41998. }
  41999. }
  42000. _getBlendFactor( blend ) {
  42001. let blendFactor;
  42002. switch ( blend ) {
  42003. case ZeroFactor:
  42004. blendFactor = GPUBlendFactor.Zero;
  42005. break;
  42006. case OneFactor:
  42007. blendFactor = GPUBlendFactor.One;
  42008. break;
  42009. case SrcColorFactor:
  42010. blendFactor = GPUBlendFactor.Src;
  42011. break;
  42012. case OneMinusSrcColorFactor:
  42013. blendFactor = GPUBlendFactor.OneMinusSrc;
  42014. break;
  42015. case SrcAlphaFactor:
  42016. blendFactor = GPUBlendFactor.SrcAlpha;
  42017. break;
  42018. case OneMinusSrcAlphaFactor:
  42019. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  42020. break;
  42021. case DstColorFactor:
  42022. blendFactor = GPUBlendFactor.Dst;
  42023. break;
  42024. case OneMinusDstColorFactor:
  42025. blendFactor = GPUBlendFactor.OneMinusDstColor;
  42026. break;
  42027. case DstAlphaFactor:
  42028. blendFactor = GPUBlendFactor.DstAlpha;
  42029. break;
  42030. case OneMinusDstAlphaFactor:
  42031. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  42032. break;
  42033. case SrcAlphaSaturateFactor:
  42034. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  42035. break;
  42036. case BlendColorFactor:
  42037. blendFactor = GPUBlendFactor.Constant;
  42038. break;
  42039. case OneMinusBlendColorFactor:
  42040. blendFactor = GPUBlendFactor.OneMinusConstant;
  42041. break;
  42042. default:
  42043. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  42044. }
  42045. return blendFactor;
  42046. }
  42047. _getStencilCompare( material ) {
  42048. let stencilCompare;
  42049. const stencilFunc = material.stencilFunc;
  42050. switch ( stencilFunc ) {
  42051. case NeverStencilFunc:
  42052. stencilCompare = GPUCompareFunction.Never;
  42053. break;
  42054. case AlwaysStencilFunc:
  42055. stencilCompare = GPUCompareFunction.Always;
  42056. break;
  42057. case LessStencilFunc:
  42058. stencilCompare = GPUCompareFunction.Less;
  42059. break;
  42060. case LessEqualStencilFunc:
  42061. stencilCompare = GPUCompareFunction.LessEqual;
  42062. break;
  42063. case EqualStencilFunc:
  42064. stencilCompare = GPUCompareFunction.Equal;
  42065. break;
  42066. case GreaterEqualStencilFunc:
  42067. stencilCompare = GPUCompareFunction.GreaterEqual;
  42068. break;
  42069. case GreaterStencilFunc:
  42070. stencilCompare = GPUCompareFunction.Greater;
  42071. break;
  42072. case NotEqualStencilFunc:
  42073. stencilCompare = GPUCompareFunction.NotEqual;
  42074. break;
  42075. default:
  42076. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  42077. }
  42078. return stencilCompare;
  42079. }
  42080. _getStencilOperation( op ) {
  42081. let stencilOperation;
  42082. switch ( op ) {
  42083. case KeepStencilOp:
  42084. stencilOperation = GPUStencilOperation.Keep;
  42085. break;
  42086. case ZeroStencilOp:
  42087. stencilOperation = GPUStencilOperation.Zero;
  42088. break;
  42089. case ReplaceStencilOp:
  42090. stencilOperation = GPUStencilOperation.Replace;
  42091. break;
  42092. case InvertStencilOp:
  42093. stencilOperation = GPUStencilOperation.Invert;
  42094. break;
  42095. case IncrementStencilOp:
  42096. stencilOperation = GPUStencilOperation.IncrementClamp;
  42097. break;
  42098. case DecrementStencilOp:
  42099. stencilOperation = GPUStencilOperation.DecrementClamp;
  42100. break;
  42101. case IncrementWrapStencilOp:
  42102. stencilOperation = GPUStencilOperation.IncrementWrap;
  42103. break;
  42104. case DecrementWrapStencilOp:
  42105. stencilOperation = GPUStencilOperation.DecrementWrap;
  42106. break;
  42107. default:
  42108. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  42109. }
  42110. return stencilOperation;
  42111. }
  42112. _getBlendOperation( blendEquation ) {
  42113. let blendOperation;
  42114. switch ( blendEquation ) {
  42115. case AddEquation:
  42116. blendOperation = GPUBlendOperation.Add;
  42117. break;
  42118. case SubtractEquation:
  42119. blendOperation = GPUBlendOperation.Subtract;
  42120. break;
  42121. case ReverseSubtractEquation:
  42122. blendOperation = GPUBlendOperation.ReverseSubtract;
  42123. break;
  42124. case MinEquation:
  42125. blendOperation = GPUBlendOperation.Min;
  42126. break;
  42127. case MaxEquation:
  42128. blendOperation = GPUBlendOperation.Max;
  42129. break;
  42130. default:
  42131. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  42132. }
  42133. return blendOperation;
  42134. }
  42135. _getPrimitiveState( object, geometry, material ) {
  42136. const descriptor = {};
  42137. const utils = this.backend.utils;
  42138. descriptor.topology = utils.getPrimitiveTopology( object, material );
  42139. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  42140. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  42141. }
  42142. switch ( material.side ) {
  42143. case FrontSide:
  42144. descriptor.frontFace = GPUFrontFace.CCW;
  42145. descriptor.cullMode = GPUCullMode.Back;
  42146. break;
  42147. case BackSide:
  42148. descriptor.frontFace = GPUFrontFace.CCW;
  42149. descriptor.cullMode = GPUCullMode.Front;
  42150. break;
  42151. case DoubleSide:
  42152. descriptor.frontFace = GPUFrontFace.CCW;
  42153. descriptor.cullMode = GPUCullMode.None;
  42154. break;
  42155. default:
  42156. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  42157. break;
  42158. }
  42159. return descriptor;
  42160. }
  42161. _getColorWriteMask( material ) {
  42162. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  42163. }
  42164. _getDepthCompare( material ) {
  42165. let depthCompare;
  42166. if ( material.depthTest === false ) {
  42167. depthCompare = GPUCompareFunction.Always;
  42168. } else {
  42169. const depthFunc = material.depthFunc;
  42170. switch ( depthFunc ) {
  42171. case NeverDepth:
  42172. depthCompare = GPUCompareFunction.Never;
  42173. break;
  42174. case AlwaysDepth:
  42175. depthCompare = GPUCompareFunction.Always;
  42176. break;
  42177. case LessDepth:
  42178. depthCompare = GPUCompareFunction.Less;
  42179. break;
  42180. case LessEqualDepth:
  42181. depthCompare = GPUCompareFunction.LessEqual;
  42182. break;
  42183. case EqualDepth:
  42184. depthCompare = GPUCompareFunction.Equal;
  42185. break;
  42186. case GreaterEqualDepth:
  42187. depthCompare = GPUCompareFunction.GreaterEqual;
  42188. break;
  42189. case GreaterDepth:
  42190. depthCompare = GPUCompareFunction.Greater;
  42191. break;
  42192. case NotEqualDepth:
  42193. depthCompare = GPUCompareFunction.NotEqual;
  42194. break;
  42195. default:
  42196. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  42197. }
  42198. }
  42199. return depthCompare;
  42200. }
  42201. }
  42202. /*// debugger tools
  42203. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  42204. //*/
  42205. //
  42206. class WebGPUBackend extends Backend {
  42207. constructor( parameters = {} ) {
  42208. super( parameters );
  42209. this.isWebGPUBackend = true;
  42210. // some parameters require default values other than "undefined"
  42211. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  42212. this.parameters.antialias = ( parameters.antialias === true );
  42213. if ( this.parameters.antialias === true ) {
  42214. this.parameters.sampleCount = ( parameters.sampleCount === undefined ) ? 4 : parameters.sampleCount;
  42215. } else {
  42216. this.parameters.sampleCount = 1;
  42217. }
  42218. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  42219. this.trackTimestamp = ( parameters.trackTimestamp === true );
  42220. this.device = null;
  42221. this.context = null;
  42222. this.colorBuffer = null;
  42223. this.defaultRenderPassdescriptor = null;
  42224. this.utils = new WebGPUUtils( this );
  42225. this.attributeUtils = new WebGPUAttributeUtils( this );
  42226. this.bindingUtils = new WebGPUBindingUtils( this );
  42227. this.pipelineUtils = new WebGPUPipelineUtils( this );
  42228. this.textureUtils = new WebGPUTextureUtils( this );
  42229. this.occludedResolveCache = new Map();
  42230. }
  42231. async init( renderer ) {
  42232. await super.init( renderer );
  42233. //
  42234. const parameters = this.parameters;
  42235. // create the device if it is not passed with parameters
  42236. let device;
  42237. if ( parameters.device === undefined ) {
  42238. const adapterOptions = {
  42239. powerPreference: parameters.powerPreference
  42240. };
  42241. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  42242. if ( adapter === null ) {
  42243. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  42244. }
  42245. // feature support
  42246. const features = Object.values( GPUFeatureName );
  42247. const supportedFeatures = [];
  42248. for ( const name of features ) {
  42249. if ( adapter.features.has( name ) ) {
  42250. supportedFeatures.push( name );
  42251. }
  42252. }
  42253. const deviceDescriptor = {
  42254. requiredFeatures: supportedFeatures,
  42255. requiredLimits: parameters.requiredLimits
  42256. };
  42257. device = await adapter.requestDevice( deviceDescriptor );
  42258. } else {
  42259. device = parameters.device;
  42260. }
  42261. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  42262. this.device = device;
  42263. this.context = context;
  42264. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  42265. this.context.configure( {
  42266. device: this.device,
  42267. format: GPUTextureFormat.BGRA8Unorm,
  42268. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  42269. alphaMode: alphaMode
  42270. } );
  42271. this.updateSize();
  42272. }
  42273. get coordinateSystem() {
  42274. return WebGPUCoordinateSystem;
  42275. }
  42276. async getArrayBufferAsync( attribute ) {
  42277. return await this.attributeUtils.getArrayBufferAsync( attribute );
  42278. }
  42279. getContext() {
  42280. return this.context;
  42281. }
  42282. _getDefaultRenderPassDescriptor() {
  42283. let descriptor = this.defaultRenderPassdescriptor;
  42284. const antialias = this.parameters.antialias;
  42285. if ( descriptor === null ) {
  42286. const renderer = this.renderer;
  42287. descriptor = {
  42288. colorAttachments: [ {
  42289. view: null
  42290. } ],
  42291. depthStencilAttachment: {
  42292. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  42293. }
  42294. };
  42295. const colorAttachment = descriptor.colorAttachments[ 0 ];
  42296. if ( antialias === true ) {
  42297. colorAttachment.view = this.colorBuffer.createView();
  42298. } else {
  42299. colorAttachment.resolveTarget = undefined;
  42300. }
  42301. this.defaultRenderPassdescriptor = descriptor;
  42302. }
  42303. const colorAttachment = descriptor.colorAttachments[ 0 ];
  42304. if ( antialias === true ) {
  42305. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  42306. } else {
  42307. colorAttachment.view = this.context.getCurrentTexture().createView();
  42308. }
  42309. return descriptor;
  42310. }
  42311. _getRenderPassDescriptor( renderContext ) {
  42312. const renderTarget = renderContext.renderTarget;
  42313. const renderTargetData = this.get( renderTarget );
  42314. let descriptors = renderTargetData.descriptors;
  42315. if ( descriptors === undefined ) {
  42316. descriptors = [];
  42317. renderTargetData.descriptors = descriptors;
  42318. }
  42319. if ( renderTargetData.width !== renderTarget.width ||
  42320. renderTargetData.height !== renderTarget.height ||
  42321. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  42322. renderTargetData.samples !== renderTarget.samples
  42323. ) {
  42324. descriptors.length = 0;
  42325. }
  42326. let descriptor = descriptors[ renderContext.activeCubeFace ];
  42327. if ( descriptor === undefined ) {
  42328. const textures = renderContext.textures;
  42329. const colorAttachments = [];
  42330. for ( let i = 0; i < textures.length; i ++ ) {
  42331. const textureData = this.get( textures[ i ] );
  42332. const textureView = textureData.texture.createView( {
  42333. baseMipLevel: renderContext.activeMipmapLevel,
  42334. mipLevelCount: 1,
  42335. baseArrayLayer: renderContext.activeCubeFace,
  42336. dimension: GPUTextureViewDimension.TwoD
  42337. } );
  42338. let view, resolveTarget;
  42339. if ( textureData.msaaTexture !== undefined ) {
  42340. view = textureData.msaaTexture.createView();
  42341. resolveTarget = textureView;
  42342. } else {
  42343. view = textureView;
  42344. resolveTarget = undefined;
  42345. }
  42346. colorAttachments.push( {
  42347. view,
  42348. resolveTarget,
  42349. loadOp: GPULoadOp.Load,
  42350. storeOp: GPUStoreOp.Store
  42351. } );
  42352. }
  42353. const depthTextureData = this.get( renderContext.depthTexture );
  42354. const depthStencilAttachment = {
  42355. view: depthTextureData.texture.createView(),
  42356. };
  42357. descriptor = {
  42358. colorAttachments,
  42359. depthStencilAttachment
  42360. };
  42361. descriptors[ renderContext.activeCubeFace ] = descriptor;
  42362. renderTargetData.width = renderTarget.width;
  42363. renderTargetData.height = renderTarget.height;
  42364. renderTargetData.samples = renderTarget.samples;
  42365. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  42366. }
  42367. return descriptor;
  42368. }
  42369. beginRender( renderContext ) {
  42370. const renderContextData = this.get( renderContext );
  42371. const device = this.device;
  42372. const occlusionQueryCount = renderContext.occlusionQueryCount;
  42373. let occlusionQuerySet;
  42374. if ( occlusionQueryCount > 0 ) {
  42375. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  42376. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  42377. // Get a reference to the array of objects with queries. The renderContextData property
  42378. // can be changed by another render pass before the buffer.mapAsyc() completes.
  42379. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  42380. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  42381. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  42382. //
  42383. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } );
  42384. renderContextData.occlusionQuerySet = occlusionQuerySet;
  42385. renderContextData.occlusionQueryIndex = 0;
  42386. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  42387. renderContextData.lastOcclusionObject = null;
  42388. }
  42389. let descriptor;
  42390. if ( renderContext.textures === null ) {
  42391. descriptor = this._getDefaultRenderPassDescriptor();
  42392. } else {
  42393. descriptor = this._getRenderPassDescriptor( renderContext );
  42394. }
  42395. this.initTimestampQuery( renderContext, descriptor );
  42396. descriptor.occlusionQuerySet = occlusionQuerySet;
  42397. const depthStencilAttachment = descriptor.depthStencilAttachment;
  42398. if ( renderContext.textures !== null ) {
  42399. const colorAttachments = descriptor.colorAttachments;
  42400. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  42401. const colorAttachment = colorAttachments[ i ];
  42402. if ( renderContext.clearColor ) {
  42403. colorAttachment.clearValue = renderContext.clearColorValue;
  42404. colorAttachment.loadOp = GPULoadOp.Clear;
  42405. colorAttachment.storeOp = GPUStoreOp.Store;
  42406. } else {
  42407. colorAttachment.loadOp = GPULoadOp.Load;
  42408. colorAttachment.storeOp = GPUStoreOp.Store;
  42409. }
  42410. }
  42411. } else {
  42412. const colorAttachment = descriptor.colorAttachments[ 0 ];
  42413. if ( renderContext.clearColor ) {
  42414. colorAttachment.clearValue = renderContext.clearColorValue;
  42415. colorAttachment.loadOp = GPULoadOp.Clear;
  42416. colorAttachment.storeOp = GPUStoreOp.Store;
  42417. } else {
  42418. colorAttachment.loadOp = GPULoadOp.Load;
  42419. colorAttachment.storeOp = GPUStoreOp.Store;
  42420. }
  42421. }
  42422. //
  42423. if ( renderContext.depth ) {
  42424. if ( renderContext.clearDepth ) {
  42425. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  42426. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  42427. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  42428. } else {
  42429. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  42430. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  42431. }
  42432. }
  42433. if ( renderContext.stencil ) {
  42434. if ( renderContext.clearStencil ) {
  42435. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  42436. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  42437. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  42438. } else {
  42439. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  42440. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  42441. }
  42442. }
  42443. //
  42444. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  42445. const currentPass = encoder.beginRenderPass( descriptor );
  42446. //
  42447. renderContextData.descriptor = descriptor;
  42448. renderContextData.encoder = encoder;
  42449. renderContextData.currentPass = currentPass;
  42450. renderContextData.currentSets = { attributes: {} };
  42451. //
  42452. if ( renderContext.viewport ) {
  42453. this.updateViewport( renderContext );
  42454. }
  42455. if ( renderContext.scissor ) {
  42456. const { x, y, width, height } = renderContext.scissorValue;
  42457. currentPass.setScissorRect( x, renderContext.height - height - y, width, height );
  42458. }
  42459. }
  42460. finishRender( renderContext ) {
  42461. const renderContextData = this.get( renderContext );
  42462. const occlusionQueryCount = renderContext.occlusionQueryCount;
  42463. if ( renderContextData.renderBundles !== undefined && renderContextData.renderBundles.length > 0 ) {
  42464. renderContextData.registerBundlesPhase = false;
  42465. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  42466. }
  42467. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  42468. renderContextData.currentPass.endOcclusionQuery();
  42469. }
  42470. renderContextData.currentPass.end();
  42471. if ( occlusionQueryCount > 0 ) {
  42472. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  42473. //
  42474. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  42475. if ( queryResolveBuffer === undefined ) {
  42476. queryResolveBuffer = this.device.createBuffer(
  42477. {
  42478. size: bufferSize,
  42479. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  42480. }
  42481. );
  42482. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  42483. }
  42484. //
  42485. const readBuffer = this.device.createBuffer(
  42486. {
  42487. size: bufferSize,
  42488. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  42489. }
  42490. );
  42491. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  42492. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  42493. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  42494. renderContextData.occlusionQueryBuffer = readBuffer;
  42495. //
  42496. this.resolveOccludedAsync( renderContext );
  42497. }
  42498. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  42499. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  42500. //
  42501. if ( renderContext.textures !== null ) {
  42502. const textures = renderContext.textures;
  42503. for ( let i = 0; i < textures.length; i ++ ) {
  42504. const texture = textures[ i ];
  42505. if ( texture.generateMipmaps === true ) {
  42506. this.textureUtils.generateMipmaps( texture );
  42507. }
  42508. }
  42509. }
  42510. }
  42511. isOccluded( renderContext, object ) {
  42512. const renderContextData = this.get( renderContext );
  42513. return renderContextData.occluded && renderContextData.occluded.has( object );
  42514. }
  42515. async resolveOccludedAsync( renderContext ) {
  42516. const renderContextData = this.get( renderContext );
  42517. // handle occlusion query results
  42518. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  42519. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  42520. const occluded = new WeakSet();
  42521. renderContextData.currentOcclusionQueryObjects = null;
  42522. renderContextData.currentOcclusionQueryBuffer = null;
  42523. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  42524. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  42525. const results = new BigUint64Array( buffer );
  42526. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  42527. if ( results[ i ] !== BigInt( 0 ) ) {
  42528. occluded.add( currentOcclusionQueryObjects[ i ] );
  42529. }
  42530. }
  42531. currentOcclusionQueryBuffer.destroy();
  42532. renderContextData.occluded = occluded;
  42533. }
  42534. }
  42535. updateViewport( renderContext ) {
  42536. const { currentPass } = this.get( renderContext );
  42537. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  42538. currentPass.setViewport( x, renderContext.height - height - y, width, height, minDepth, maxDepth );
  42539. }
  42540. clear( color, depth, stencil, renderTargetData = null ) {
  42541. const device = this.device;
  42542. const renderer = this.renderer;
  42543. let colorAttachments = [];
  42544. let depthStencilAttachment;
  42545. let clearValue;
  42546. let supportsDepth;
  42547. let supportsStencil;
  42548. if ( color ) {
  42549. const clearColor = this.getClearColor();
  42550. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  42551. }
  42552. if ( renderTargetData === null ) {
  42553. supportsDepth = renderer.depth;
  42554. supportsStencil = renderer.stencil;
  42555. const descriptor = this._getDefaultRenderPassDescriptor();
  42556. if ( color ) {
  42557. colorAttachments = descriptor.colorAttachments;
  42558. const colorAttachment = colorAttachments[ 0 ];
  42559. colorAttachment.clearValue = clearValue;
  42560. colorAttachment.loadOp = GPULoadOp.Clear;
  42561. colorAttachment.storeOp = GPUStoreOp.Store;
  42562. }
  42563. if ( supportsDepth || supportsStencil ) {
  42564. depthStencilAttachment = descriptor.depthStencilAttachment;
  42565. }
  42566. } else {
  42567. supportsDepth = renderTargetData.depth;
  42568. supportsStencil = renderTargetData.stencil;
  42569. if ( color ) {
  42570. for ( const texture of renderTargetData.textures ) {
  42571. const textureData = this.get( texture );
  42572. const textureView = textureData.texture.createView();
  42573. let view, resolveTarget;
  42574. if ( textureData.msaaTexture !== undefined ) {
  42575. view = textureData.msaaTexture.createView();
  42576. resolveTarget = textureView;
  42577. } else {
  42578. view = textureView;
  42579. resolveTarget = undefined;
  42580. }
  42581. colorAttachments.push( {
  42582. view,
  42583. resolveTarget,
  42584. clearValue,
  42585. loadOp: GPULoadOp.Clear,
  42586. storeOp: GPUStoreOp.Store
  42587. } );
  42588. }
  42589. }
  42590. if ( supportsDepth || supportsStencil ) {
  42591. const depthTextureData = this.get( renderTargetData.depthTexture );
  42592. depthStencilAttachment = {
  42593. view: depthTextureData.texture.createView()
  42594. };
  42595. }
  42596. }
  42597. //
  42598. if ( supportsDepth ) {
  42599. if ( depth ) {
  42600. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  42601. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  42602. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  42603. } else {
  42604. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  42605. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  42606. }
  42607. }
  42608. //
  42609. if ( supportsStencil ) {
  42610. if ( stencil ) {
  42611. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  42612. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  42613. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  42614. } else {
  42615. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  42616. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  42617. }
  42618. }
  42619. //
  42620. const encoder = device.createCommandEncoder( {} );
  42621. const currentPass = encoder.beginRenderPass( {
  42622. colorAttachments,
  42623. depthStencilAttachment
  42624. } );
  42625. currentPass.end();
  42626. device.queue.submit( [ encoder.finish() ] );
  42627. }
  42628. // compute
  42629. beginCompute( computeGroup ) {
  42630. const groupGPU = this.get( computeGroup );
  42631. const descriptor = {};
  42632. this.initTimestampQuery( computeGroup, descriptor );
  42633. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  42634. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  42635. }
  42636. compute( computeGroup, computeNode, bindings, pipeline ) {
  42637. const { passEncoderGPU } = this.get( computeGroup );
  42638. // pipeline
  42639. const pipelineGPU = this.get( pipeline ).pipeline;
  42640. passEncoderGPU.setPipeline( pipelineGPU );
  42641. // bind groups
  42642. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  42643. const bindGroup = bindings[ i ];
  42644. const bindingsData = this.get( bindGroup );
  42645. passEncoderGPU.setBindGroup( i, bindingsData.group );
  42646. }
  42647. passEncoderGPU.dispatchWorkgroups( computeNode.dispatchCount );
  42648. }
  42649. finishCompute( computeGroup ) {
  42650. const groupData = this.get( computeGroup );
  42651. groupData.passEncoderGPU.end();
  42652. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  42653. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  42654. }
  42655. // render object
  42656. draw( renderObject, info ) {
  42657. const { object, geometry, context, pipeline } = renderObject;
  42658. const bindings = renderObject.getBindings();
  42659. const contextData = this.get( context );
  42660. const pipelineGPU = this.get( pipeline ).pipeline;
  42661. const currentSets = contextData.currentSets;
  42662. const renderObjectData = this.get( renderObject );
  42663. const { bundleEncoder, renderBundle, lastPipelineGPU } = renderObjectData;
  42664. const renderContextData = this.get( context );
  42665. if ( renderContextData.registerBundlesPhase === true && bundleEncoder !== undefined && lastPipelineGPU === pipelineGPU ) {
  42666. renderContextData.renderBundles.push( renderBundle );
  42667. return;
  42668. }
  42669. const passEncoderGPU = this.renderer._currentRenderBundle ? this.createBundleEncoder( context, renderObject ) : contextData.currentPass;
  42670. // pipeline
  42671. if ( currentSets.pipeline !== pipelineGPU ) {
  42672. passEncoderGPU.setPipeline( pipelineGPU );
  42673. currentSets.pipeline = pipelineGPU;
  42674. }
  42675. // bind groups
  42676. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  42677. const bindGroup = bindings[ i ];
  42678. const bindingsData = this.get( bindGroup );
  42679. passEncoderGPU.setBindGroup( i, bindingsData.group );
  42680. }
  42681. // attributes
  42682. const index = renderObject.getIndex();
  42683. const hasIndex = ( index !== null );
  42684. // index
  42685. if ( hasIndex === true ) {
  42686. if ( currentSets.index !== index ) {
  42687. const buffer = this.get( index ).buffer;
  42688. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  42689. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  42690. currentSets.index = index;
  42691. }
  42692. }
  42693. // vertex buffers
  42694. const vertexBuffers = renderObject.getVertexBuffers();
  42695. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  42696. const vertexBuffer = vertexBuffers[ i ];
  42697. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  42698. const buffer = this.get( vertexBuffer ).buffer;
  42699. passEncoderGPU.setVertexBuffer( i, buffer );
  42700. currentSets.attributes[ i ] = vertexBuffer;
  42701. }
  42702. }
  42703. // occlusion queries - handle multiple consecutive draw calls for an object
  42704. if ( contextData.occlusionQuerySet !== undefined ) {
  42705. const lastObject = contextData.lastOcclusionObject;
  42706. if ( lastObject !== object ) {
  42707. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  42708. passEncoderGPU.endOcclusionQuery();
  42709. contextData.occlusionQueryIndex ++;
  42710. }
  42711. if ( object.occlusionTest === true ) {
  42712. passEncoderGPU.beginOcclusionQuery( contextData.occlusionQueryIndex );
  42713. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  42714. }
  42715. contextData.lastOcclusionObject = object;
  42716. }
  42717. }
  42718. // draw
  42719. const drawRange = renderObject.drawRange;
  42720. const firstVertex = drawRange.start;
  42721. const instanceCount = this.getInstanceCount( renderObject );
  42722. if ( instanceCount === 0 ) return;
  42723. if ( object.isBatchedMesh === true ) {
  42724. const starts = object._multiDrawStarts;
  42725. const counts = object._multiDrawCounts;
  42726. const drawCount = object._multiDrawCount;
  42727. const drawInstances = object._multiDrawInstances;
  42728. const bytesPerElement = index.bytesPerElement || 1;
  42729. for ( let i = 0; i < drawCount; i ++ ) {
  42730. const count = drawInstances ? drawInstances[ i ] : 1;
  42731. const firstInstance = count > 1 ? 0 : i;
  42732. passEncoderGPU.drawIndexed( counts[ i ] / bytesPerElement, count, starts[ i ] / 4, 0, firstInstance );
  42733. }
  42734. } else if ( hasIndex === true ) {
  42735. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  42736. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstVertex, 0, 0 );
  42737. info.update( object, indexCount, instanceCount );
  42738. } else {
  42739. const positionAttribute = geometry.attributes.position;
  42740. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : positionAttribute.count;
  42741. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  42742. info.update( object, vertexCount, instanceCount );
  42743. }
  42744. if ( this.renderer._currentRenderBundle ) {
  42745. const renderBundle = passEncoderGPU.finish();
  42746. renderObjectData.lastPipelineGPU = pipelineGPU;
  42747. renderObjectData.renderBundle = renderBundle;
  42748. renderObjectData.bundleEncoder = passEncoderGPU;
  42749. }
  42750. }
  42751. // cache key
  42752. needsRenderUpdate( renderObject ) {
  42753. const data = this.get( renderObject );
  42754. const { object, material } = renderObject;
  42755. const utils = this.utils;
  42756. const sampleCount = utils.getSampleCount( renderObject.context );
  42757. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  42758. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  42759. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  42760. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  42761. let needsUpdate = false;
  42762. if ( data.material !== material || data.materialVersion !== material.version ||
  42763. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  42764. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  42765. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  42766. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  42767. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  42768. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  42769. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  42770. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  42771. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  42772. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  42773. data.primitiveTopology !== primitiveTopology ||
  42774. data.clippingContextVersion !== renderObject.clippingContextVersion
  42775. ) {
  42776. data.material = material; data.materialVersion = material.version;
  42777. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  42778. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  42779. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  42780. data.colorWrite = material.colorWrite;
  42781. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  42782. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  42783. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  42784. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  42785. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  42786. data.sampleCount = sampleCount;
  42787. data.colorSpace = colorSpace;
  42788. data.colorFormat = colorFormat;
  42789. data.depthStencilFormat = depthStencilFormat;
  42790. data.primitiveTopology = primitiveTopology;
  42791. data.clippingContextVersion = renderObject.clippingContextVersion;
  42792. needsUpdate = true;
  42793. }
  42794. return needsUpdate;
  42795. }
  42796. getRenderCacheKey( renderObject ) {
  42797. const { object, material } = renderObject;
  42798. const utils = this.utils;
  42799. const renderContext = renderObject.context;
  42800. return [
  42801. material.transparent, material.blending, material.premultipliedAlpha,
  42802. material.blendSrc, material.blendDst, material.blendEquation,
  42803. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  42804. material.colorWrite,
  42805. material.depthWrite, material.depthTest, material.depthFunc,
  42806. material.stencilWrite, material.stencilFunc,
  42807. material.stencilFail, material.stencilZFail, material.stencilZPass,
  42808. material.stencilFuncMask, material.stencilWriteMask,
  42809. material.side,
  42810. utils.getSampleCount( renderContext ),
  42811. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  42812. utils.getPrimitiveTopology( object, material ),
  42813. renderObject.clippingContextVersion
  42814. ].join();
  42815. }
  42816. // textures
  42817. createSampler( texture ) {
  42818. this.textureUtils.createSampler( texture );
  42819. }
  42820. destroySampler( texture ) {
  42821. this.textureUtils.destroySampler( texture );
  42822. }
  42823. createDefaultTexture( texture ) {
  42824. this.textureUtils.createDefaultTexture( texture );
  42825. }
  42826. createTexture( texture, options ) {
  42827. this.textureUtils.createTexture( texture, options );
  42828. }
  42829. updateTexture( texture, options ) {
  42830. this.textureUtils.updateTexture( texture, options );
  42831. }
  42832. generateMipmaps( texture ) {
  42833. this.textureUtils.generateMipmaps( texture );
  42834. }
  42835. destroyTexture( texture ) {
  42836. this.textureUtils.destroyTexture( texture );
  42837. }
  42838. copyTextureToBuffer( texture, x, y, width, height ) {
  42839. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  42840. }
  42841. initTimestampQuery( renderContext, descriptor ) {
  42842. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  42843. const renderContextData = this.get( renderContext );
  42844. if ( ! renderContextData.timeStampQuerySet ) {
  42845. // Create a GPUQuerySet which holds 2 timestamp query results: one for the
  42846. // beginning and one for the end of compute pass execution.
  42847. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } );
  42848. const timestampWrites = {
  42849. querySet: timeStampQuerySet,
  42850. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  42851. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  42852. };
  42853. Object.assign( descriptor, {
  42854. timestampWrites,
  42855. } );
  42856. renderContextData.timeStampQuerySet = timeStampQuerySet;
  42857. }
  42858. }
  42859. // timestamp utils
  42860. prepareTimestampBuffer( renderContext, encoder ) {
  42861. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  42862. const renderContextData = this.get( renderContext );
  42863. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  42864. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  42865. renderContextData.currentTimestampQueryBuffers = {
  42866. resolveBuffer: this.device.createBuffer( {
  42867. label: 'timestamp resolve buffer',
  42868. size: size,
  42869. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  42870. } ),
  42871. resultBuffer: this.device.createBuffer( {
  42872. label: 'timestamp result buffer',
  42873. size: size,
  42874. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  42875. } ),
  42876. isMappingPending: false,
  42877. };
  42878. }
  42879. const { resolveBuffer, resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  42880. if ( isMappingPending === true ) return;
  42881. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  42882. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  42883. }
  42884. async resolveTimestampAsync( renderContext, type = 'render' ) {
  42885. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  42886. const renderContextData = this.get( renderContext );
  42887. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  42888. const { resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  42889. if ( isMappingPending === true ) return;
  42890. renderContextData.currentTimestampQueryBuffers.isMappingPending = true;
  42891. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  42892. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  42893. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  42894. this.renderer.info.updateTimestamp( type, duration );
  42895. resultBuffer.unmap();
  42896. renderContextData.currentTimestampQueryBuffers.isMappingPending = false;
  42897. } );
  42898. }
  42899. // node builder
  42900. createNodeBuilder( object, renderer ) {
  42901. return new WGSLNodeBuilder( object, renderer );
  42902. }
  42903. // program
  42904. createProgram( program ) {
  42905. const programGPU = this.get( program );
  42906. programGPU.module = {
  42907. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  42908. entryPoint: 'main'
  42909. };
  42910. }
  42911. destroyProgram( program ) {
  42912. this.delete( program );
  42913. }
  42914. // pipelines
  42915. createRenderPipeline( renderObject, promises ) {
  42916. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  42917. }
  42918. createComputePipeline( computePipeline, bindings ) {
  42919. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  42920. }
  42921. createBundleEncoder( renderContext, renderObject ) {
  42922. return this.pipelineUtils.createBundleEncoder( renderContext, renderObject );
  42923. }
  42924. // bindings
  42925. createBindings( bindGroup ) {
  42926. this.bindingUtils.createBindings( bindGroup );
  42927. }
  42928. updateBindings( bindGroup ) {
  42929. this.bindingUtils.createBindings( bindGroup );
  42930. }
  42931. updateBinding( binding ) {
  42932. this.bindingUtils.updateBinding( binding );
  42933. }
  42934. // attributes
  42935. createIndexAttribute( attribute ) {
  42936. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  42937. }
  42938. createAttribute( attribute ) {
  42939. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  42940. }
  42941. createStorageAttribute( attribute ) {
  42942. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  42943. }
  42944. updateAttribute( attribute ) {
  42945. this.attributeUtils.updateAttribute( attribute );
  42946. }
  42947. destroyAttribute( attribute ) {
  42948. this.attributeUtils.destroyAttribute( attribute );
  42949. }
  42950. // canvas
  42951. updateSize() {
  42952. this.colorBuffer = this.textureUtils.getColorBuffer();
  42953. this.defaultRenderPassdescriptor = null;
  42954. }
  42955. // utils public
  42956. getMaxAnisotropy() {
  42957. return 16;
  42958. }
  42959. hasFeature( name ) {
  42960. return this.device.features.has( name );
  42961. }
  42962. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  42963. let dstX = 0;
  42964. let dstY = 0;
  42965. let srcX = 0;
  42966. let srcY = 0;
  42967. let srcWidth = srcTexture.image.width;
  42968. let srcHeight = srcTexture.image.height;
  42969. if ( srcRegion !== null ) {
  42970. srcX = srcRegion.x;
  42971. srcY = srcRegion.y;
  42972. srcWidth = srcRegion.width;
  42973. srcHeight = srcRegion.height;
  42974. }
  42975. if ( dstPosition !== null ) {
  42976. dstX = dstPosition.x;
  42977. dstY = dstPosition.y;
  42978. }
  42979. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  42980. const sourceGPU = this.get( srcTexture ).texture;
  42981. const destinationGPU = this.get( dstTexture ).texture;
  42982. encoder.copyTextureToTexture(
  42983. {
  42984. texture: sourceGPU,
  42985. mipLevel: level,
  42986. origin: { x: srcX, y: srcY, z: 0 }
  42987. },
  42988. {
  42989. texture: destinationGPU,
  42990. mipLevel: level,
  42991. origin: { x: dstX, y: dstY, z: 0 }
  42992. },
  42993. [
  42994. srcWidth,
  42995. srcHeight
  42996. ]
  42997. );
  42998. this.device.queue.submit( [ encoder.finish() ] );
  42999. }
  43000. copyFramebufferToTexture( texture, renderContext ) {
  43001. const renderContextData = this.get( renderContext );
  43002. const { encoder, descriptor } = renderContextData;
  43003. let sourceGPU = null;
  43004. if ( renderContext.renderTarget ) {
  43005. if ( texture.isDepthTexture ) {
  43006. sourceGPU = this.get( renderContext.depthTexture ).texture;
  43007. } else {
  43008. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  43009. }
  43010. } else {
  43011. if ( texture.isDepthTexture ) {
  43012. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  43013. } else {
  43014. sourceGPU = this.context.getCurrentTexture();
  43015. }
  43016. }
  43017. const destinationGPU = this.get( texture ).texture;
  43018. if ( sourceGPU.format !== destinationGPU.format ) {
  43019. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  43020. return;
  43021. }
  43022. renderContextData.currentPass.end();
  43023. encoder.copyTextureToTexture(
  43024. {
  43025. texture: sourceGPU,
  43026. origin: { x: 0, y: 0, z: 0 }
  43027. },
  43028. {
  43029. texture: destinationGPU
  43030. },
  43031. [
  43032. texture.image.width,
  43033. texture.image.height
  43034. ]
  43035. );
  43036. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  43037. descriptor.colorAttachments[ 0 ].loadOp = GPULoadOp.Load;
  43038. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  43039. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  43040. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  43041. renderContextData.currentSets = { attributes: {} };
  43042. }
  43043. }
  43044. /*
  43045. const debugHandler = {
  43046. get: function ( target, name ) {
  43047. // Add |update
  43048. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  43049. return target[ name ];
  43050. }
  43051. };
  43052. */
  43053. class WebGPURenderer extends Renderer {
  43054. constructor( parameters = {} ) {
  43055. let BackendClass;
  43056. if ( parameters.forceWebGL ) {
  43057. BackendClass = WebGLBackend;
  43058. } else if ( WebGPU.isAvailable() ) {
  43059. BackendClass = WebGPUBackend;
  43060. } else {
  43061. BackendClass = WebGLBackend;
  43062. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  43063. }
  43064. const backend = new BackendClass( parameters );
  43065. //super( new Proxy( backend, debugHandler ) );
  43066. super( backend, parameters );
  43067. this.isWebGPURenderer = true;
  43068. }
  43069. }
  43070. const quadMesh = new QuadMesh( new NodeMaterial() );
  43071. class PostProcessing {
  43072. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  43073. this.renderer = renderer;
  43074. this.outputNode = outputNode;
  43075. }
  43076. render() {
  43077. quadMesh.material.fragmentNode = this.outputNode;
  43078. quadMesh.render( this.renderer );
  43079. }
  43080. renderAsync() {
  43081. quadMesh.material.fragmentNode = this.outputNode;
  43082. return quadMesh.renderAsync( this.renderer );
  43083. }
  43084. set needsUpdate( value ) {
  43085. quadMesh.material.needsUpdate = value;
  43086. }
  43087. }
  43088. class StorageTexture extends Texture {
  43089. constructor( width = 1, height = 1 ) {
  43090. super();
  43091. this.image = { width, height };
  43092. this.magFilter = LinearFilter;
  43093. this.minFilter = LinearFilter;
  43094. this.isStorageTexture = true;
  43095. }
  43096. }
  43097. class StorageBufferAttribute extends BufferAttribute {
  43098. constructor( array, itemSize, typeClass = Float32Array ) {
  43099. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  43100. super( array, itemSize );
  43101. this.isStorageBufferAttribute = true;
  43102. }
  43103. }
  43104. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  43105. constructor( array, itemSize, typeClass = Float32Array ) {
  43106. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  43107. super( array, itemSize );
  43108. this.isStorageInstancedBufferAttribute = true;
  43109. }
  43110. }
  43111. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  43112. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  43113. revision: REVISION,
  43114. } } ) );
  43115. }
  43116. if ( typeof window !== 'undefined' ) {
  43117. if ( window.__THREE__ ) {
  43118. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  43119. } else {
  43120. window.__THREE__ = REVISION;
  43121. }
  43122. }
  43123. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AfterImageNode, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, AnamorphicNode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrayElementNode, ArrowHelper, AssignNode, AttachedBindMode, AttributeNode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BRDF_GGX, BRDF_Lambert, BackSide, BasicDepthPacking, BasicShadowMap, BatchNode, BatchedMesh, BlendModeNode, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, Break, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferGeometryLoader, BufferNode, BumpMapNode, BypassNode, ByteType, Cache, CacheNode, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CheckerNode, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, CodeNode, Color, ColorAdjustmentNode, ColorKeyframeTrack, ColorManagement, ColorSpaceNode, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ComputeNode, CondNode, ConeGeometry, ConstNode, ConstantAlphaFactor, ConstantColorFactor, ContextNode, Continue, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeTextureNode, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, DFGApprox, D_GGX, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthOfFieldNode, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DirectionalLightNode, DiscardNode, DiscreteInterpolant, DisplayP3ColorSpace, DodecahedronGeometry, DotScreenNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EPSILON, EdgesGeometry, EllipseCurve, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, ExtrudeGeometry, F_Schlick, FileLoader, FilmNode, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fog, FogExp2, FogExp2Node, FogNode, FogRangeNode, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLBufferAttribute, GLSL1, GLSL3, GLSLNodeParser, GaussianBlurNode, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HashNode, HemisphereLight, HemisphereLightHelper, HemisphereLightNode, IESSpotLight, IESSpotLightNode, INFINITY, IcosahedronGeometry, If, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, InstanceNode, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, InstancedPointsNodeMaterial, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightNode, LightProbe, LightingContextNode, LightingModel, LightingNode, LightsNode, Line, Line2NodeMaterial, Line3, LineBasicMaterial, LineBasicNodeMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineDashedNodeMaterial, LineLoop, LineSegments, LinearDisplayP3ColorSpace, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, LoopNode, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, Lut3DNode, MOUSE, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathNode, MathUtils, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, ModelViewProjectionNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeKeywords, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalAnimationBlendMode, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OperatorNode, OrthographicCamera, OscNode, OutputStructNode, P3Primaries, PCFShadowMap, PCFSoftShadowMap, PI, PI2, PMREMGenerator, PMREMNode, PackingNode, ParameterNode, PassNode, Path, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, PointLightNode, PointUVNode, Points, PointsMaterial, PointsNodeMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PostProcessing, PosterizeNode, PropertyBinding, PropertyMixer, PropertyNode, QuadMesh, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGBShiftNode, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RawShaderMaterial, Ray, Raycaster, Rec709Primaries, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderTarget, RendererReferenceNode, RepeatWrapping, ReplaceStencilOp, Return, ReverseSubtractEquation, RingGeometry, RotateNode, RotateUVNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, Schlick_to_F0, ScriptableNode, ScriptableValueNode, SetNode, ShaderMaterial, ShaderNode, ShadowMaterial, ShadowNodeMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SkinningNode, SobelOperatorNode, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SplitNode, SpotLight, SpotLightHelper, SpotLightNode, Sprite, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TBNViewMatrix, TOUCH, TangentSpaceNormalMap, TempNode, TetrahedronGeometry, Texture, Texture3DNode, TextureBicubicNode, TextureLoader, TextureNode, TextureSizeNode, TimerNode, ToneMappingNode, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TriplanarTexturesNode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform$1 as Uniform, UniformGroupNode, UniformNode, UniformsGroup$1 as UniformsGroup, UniformsNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, V_GGX_SmithCorrelated, VarNode, VaryingNode, Vector2, Vector3, Vector4, VectorKeyframeTrack, VertexColorNode, VideoTexture, ViewportDepthNode, ViewportDepthTextureNode, ViewportNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, abs, acos, add, addLightNode, addNodeClass, addNodeElement, addNodeMaterial, afterImage, all, alphaT, anamorphic, and, anisotropy, anisotropyB, anisotropyT, any, append, arrayBuffer, asin, assign, atan, atan2, attribute, backgroundBlurriness, backgroundIntensity, batch, bitAnd, bitNot, bitOr, bitXor, bitangentGeometry, bitangentLocal, bitangentView, bitangentWorld, bitcast, blur, bmat2, bmat3, bmat4, bool, buffer, bufferAttribute, bumpMap, burn, bvec2, bvec3, bvec4, bypass, cache, call, cameraFar, cameraLogDepth, cameraNear, cameraNormalMatrix, cameraPosition, cameraProjectionMatrix, cameraProjectionMatrixInverse, cameraViewMatrix, cameraWorldMatrix, cbrt, ceil, checker, clamp, clearcoat, clearcoatRoughness, code, color, colorSpaceToLinear, colorToDirection, compute, cond, context, convert, cos, createCanvasElement, createNodeFromType, createNodeMaterialFromType, cross, cubeTexture, dFdx, dFdy, dashSize, defaultBuildStages, defaultShaderStages, defined, degrees, densityFog, depth, depthPass, difference, diffuseColor, directionToColor, discard, distance, div, dodge, dof, dot, dotScreen, drawIndex, dynamicBufferAttribute, element, equal, equals, equirectUV, exp, exp2, expression, faceDirection, faceForward, film, float, floor, fog, fract, frameGroup, frameId, frontFacing, fwidth, gain, gapSize, gaussianBlur, getConstNodeType, getCurrentStack, getDirection, getDistanceAttenuation, getGeometryRoughness, getRoughness, global, glsl, glslFn, greaterThan, greaterThanEqual, hash, hue, imat2, imat3, imat4, instance, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, int, inverseSqrt, iridescence, iridescenceIOR, iridescenceThickness, ivec2, ivec3, ivec4, js, label, length, lengthSq, lessThan, lessThanEqual, lightTargetDirection, lightingContext, lights, lightsNode, linearDepth, linearToColorSpace, linearTosRGB, log, log2, loop, lumaCoeffs, luminance, lut3D, mat2, mat3, mat4, matcapUV, materialAlphaTest, materialAnisotropy, materialAnisotropyVector, materialClearcoat, materialClearcoatNormal, materialClearcoatRoughness, materialColor, materialDispersion, materialEmissive, materialIridescence, materialIridescenceIOR, materialIridescenceThickness, materialLineDashOffset, materialLineDashSize, materialLineGapSize, materialLineScale, materialLineWidth, materialMetalness, materialNormal, materialOpacity, materialPointWidth, materialReference, materialReflectivity, materialRotation, materialRoughness, materialSheen, materialSheenRoughness, materialShininess, materialSpecular, materialSpecularStrength, max$1 as max, maxMipLevel, metalness, min$1 as min, mix, mod, modelDirection, modelNormalMatrix, modelPosition, modelScale, modelViewMatrix, modelViewPosition, modelViewProjection, modelWorldMatrix, modelWorldMatrixInverse, morphReference, mul, mx_aastep, mx_cell_noise_float, mx_contrast, mx_fractal_noise_float, mx_fractal_noise_vec2, mx_fractal_noise_vec3, mx_fractal_noise_vec4, mx_hsvtorgb, mx_noise_float, mx_noise_vec3, mx_noise_vec4, mx_ramplr, mx_ramptb, mx_rgbtohsv, mx_safepower, mx_splitlr, mx_splittb, mx_srgb_texture_to_lin_rec709, mx_transform_uv, mx_worley_noise_float, mx_worley_noise_vec2, mx_worley_noise_vec3, negate, nodeArray, nodeImmutable, nodeObject, nodeObjects, nodeProxy, normalGeometry, normalLocal, normalMap, normalView, normalWorld, normalize, not, objectDirection, objectGroup, objectNormalMatrix, objectPosition, objectScale, objectViewMatrix, objectViewPosition, objectWorldMatrix, oneMinus, or, orthographicDepthToViewZ, oscSawtooth, oscSine, oscSquare, oscTriangle, output, outputStruct, overlay, overloadingFn, parabola, parallaxDirection, parallaxUV, parameter, pass, pcurve, perspectiveDepthToViewZ, pmremTexture, pointUV, pointWidth, positionGeometry, positionLocal, positionView, positionViewDirection, positionWorld, positionWorldDirection, posterize, pow, pow2, pow3, pow4, property, radians, rand, range, rangeFog, reciprocal, reference, referenceBuffer, reflect, reflectVector, reflectView, reflector, refract, remainder, remap, remapClamp, renderGroup, rendererReference, rgbShift, rotate, rotateUV, roughness, round, rtt, sRGBToLinear, sampler, saturate, saturation, screen, scriptable, scriptableValue, setCurrentStack, shaderStages, sheen, sheenRoughness, shiftLeft, shiftRight, shininess, sign, sin, sinc, skinning, skinningReference, smoothstep, sobel, specularColor, split, spritesheetUV, sqrt, stack, step, storage, storageObject, storageTexture, string, sub, tan, tangentGeometry, tangentLocal, tangentView, tangentWorld, temp, texture, texture3D, textureBicubic, textureCubeUV, textureLoad, texturePass, textureSize, textureStore, threshold, timerDelta, timerGlobal, timerLocal, toneMapping, transformDirection, transformedBentNormalView, transformedBitangentView, transformedBitangentWorld, transformedClearcoatNormalView, transformedNormalView, transformedNormalWorld, transformedTangentView, transformedTangentWorld, transpose, triNoise3D, triplanarTexture, triplanarTextures, trunc, tslFn, uint, umat2, umat3, umat4, uniform, uniformGroup, uniforms, userData, uv, uvec2, uvec3, uvec4, varying, varyingProperty, vec2, vec3, vec4, vectorComponents, vertexColor, vertexIndex, vibrance, viewZToOrthographicDepth, viewZToPerspectiveDepth, viewport, viewportBottomLeft, viewportBottomRight, viewportCoordinate, viewportDepthTexture, viewportLinearDepth, viewportMipTexture, viewportResolution, viewportSharedTexture, viewportTexture, viewportTopLeft, viewportTopRight, wgsl, wgslFn, xor };