three.webgpu.js 1.5 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '166';
  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. return object;
  17097. }
  17098. parseShapes( json ) {
  17099. const shapes = {};
  17100. if ( json !== undefined ) {
  17101. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17102. const shape = new Shape().fromJSON( json[ i ] );
  17103. shapes[ shape.uuid ] = shape;
  17104. }
  17105. }
  17106. return shapes;
  17107. }
  17108. parseSkeletons( json, object ) {
  17109. const skeletons = {};
  17110. const bones = {};
  17111. // generate bone lookup table
  17112. object.traverse( function ( child ) {
  17113. if ( child.isBone ) bones[ child.uuid ] = child;
  17114. } );
  17115. // create skeletons
  17116. if ( json !== undefined ) {
  17117. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17118. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  17119. skeletons[ skeleton.uuid ] = skeleton;
  17120. }
  17121. }
  17122. return skeletons;
  17123. }
  17124. parseGeometries( json, shapes ) {
  17125. const geometries = {};
  17126. if ( json !== undefined ) {
  17127. const bufferGeometryLoader = new BufferGeometryLoader();
  17128. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17129. let geometry;
  17130. const data = json[ i ];
  17131. switch ( data.type ) {
  17132. case 'BufferGeometry':
  17133. case 'InstancedBufferGeometry':
  17134. geometry = bufferGeometryLoader.parse( data );
  17135. break;
  17136. default:
  17137. if ( data.type in Geometries$1 ) {
  17138. geometry = Geometries$1[ data.type ].fromJSON( data, shapes );
  17139. } else {
  17140. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  17141. }
  17142. }
  17143. geometry.uuid = data.uuid;
  17144. if ( data.name !== undefined ) geometry.name = data.name;
  17145. if ( data.userData !== undefined ) geometry.userData = data.userData;
  17146. geometries[ data.uuid ] = geometry;
  17147. }
  17148. }
  17149. return geometries;
  17150. }
  17151. parseMaterials( json, textures ) {
  17152. const cache = {}; // MultiMaterial
  17153. const materials = {};
  17154. if ( json !== undefined ) {
  17155. const loader = new MaterialLoader();
  17156. loader.setTextures( textures );
  17157. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17158. const data = json[ i ];
  17159. if ( cache[ data.uuid ] === undefined ) {
  17160. cache[ data.uuid ] = loader.parse( data );
  17161. }
  17162. materials[ data.uuid ] = cache[ data.uuid ];
  17163. }
  17164. }
  17165. return materials;
  17166. }
  17167. parseAnimations( json ) {
  17168. const animations = {};
  17169. if ( json !== undefined ) {
  17170. for ( let i = 0; i < json.length; i ++ ) {
  17171. const data = json[ i ];
  17172. const clip = AnimationClip.parse( data );
  17173. animations[ clip.uuid ] = clip;
  17174. }
  17175. }
  17176. return animations;
  17177. }
  17178. parseImages( json, onLoad ) {
  17179. const scope = this;
  17180. const images = {};
  17181. let loader;
  17182. function loadImage( url ) {
  17183. scope.manager.itemStart( url );
  17184. return loader.load( url, function () {
  17185. scope.manager.itemEnd( url );
  17186. }, undefined, function () {
  17187. scope.manager.itemError( url );
  17188. scope.manager.itemEnd( url );
  17189. } );
  17190. }
  17191. function deserializeImage( image ) {
  17192. if ( typeof image === 'string' ) {
  17193. const url = image;
  17194. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17195. return loadImage( path );
  17196. } else {
  17197. if ( image.data ) {
  17198. return {
  17199. data: getTypedArray( image.type, image.data ),
  17200. width: image.width,
  17201. height: image.height
  17202. };
  17203. } else {
  17204. return null;
  17205. }
  17206. }
  17207. }
  17208. if ( json !== undefined && json.length > 0 ) {
  17209. const manager = new LoadingManager( onLoad );
  17210. loader = new ImageLoader( manager );
  17211. loader.setCrossOrigin( this.crossOrigin );
  17212. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17213. const image = json[ i ];
  17214. const url = image.url;
  17215. if ( Array.isArray( url ) ) {
  17216. // load array of images e.g CubeTexture
  17217. const imageArray = [];
  17218. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17219. const currentUrl = url[ j ];
  17220. const deserializedImage = deserializeImage( currentUrl );
  17221. if ( deserializedImage !== null ) {
  17222. if ( deserializedImage instanceof HTMLImageElement ) {
  17223. imageArray.push( deserializedImage );
  17224. } else {
  17225. // special case: handle array of data textures for cube textures
  17226. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17227. }
  17228. }
  17229. }
  17230. images[ image.uuid ] = new Source( imageArray );
  17231. } else {
  17232. // load single image
  17233. const deserializedImage = deserializeImage( image.url );
  17234. images[ image.uuid ] = new Source( deserializedImage );
  17235. }
  17236. }
  17237. }
  17238. return images;
  17239. }
  17240. async parseImagesAsync( json ) {
  17241. const scope = this;
  17242. const images = {};
  17243. let loader;
  17244. async function deserializeImage( image ) {
  17245. if ( typeof image === 'string' ) {
  17246. const url = image;
  17247. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17248. return await loader.loadAsync( path );
  17249. } else {
  17250. if ( image.data ) {
  17251. return {
  17252. data: getTypedArray( image.type, image.data ),
  17253. width: image.width,
  17254. height: image.height
  17255. };
  17256. } else {
  17257. return null;
  17258. }
  17259. }
  17260. }
  17261. if ( json !== undefined && json.length > 0 ) {
  17262. loader = new ImageLoader( this.manager );
  17263. loader.setCrossOrigin( this.crossOrigin );
  17264. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17265. const image = json[ i ];
  17266. const url = image.url;
  17267. if ( Array.isArray( url ) ) {
  17268. // load array of images e.g CubeTexture
  17269. const imageArray = [];
  17270. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17271. const currentUrl = url[ j ];
  17272. const deserializedImage = await deserializeImage( currentUrl );
  17273. if ( deserializedImage !== null ) {
  17274. if ( deserializedImage instanceof HTMLImageElement ) {
  17275. imageArray.push( deserializedImage );
  17276. } else {
  17277. // special case: handle array of data textures for cube textures
  17278. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17279. }
  17280. }
  17281. }
  17282. images[ image.uuid ] = new Source( imageArray );
  17283. } else {
  17284. // load single image
  17285. const deserializedImage = await deserializeImage( image.url );
  17286. images[ image.uuid ] = new Source( deserializedImage );
  17287. }
  17288. }
  17289. }
  17290. return images;
  17291. }
  17292. parseTextures( json, images ) {
  17293. function parseConstant( value, type ) {
  17294. if ( typeof value === 'number' ) return value;
  17295. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  17296. return type[ value ];
  17297. }
  17298. const textures = {};
  17299. if ( json !== undefined ) {
  17300. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17301. const data = json[ i ];
  17302. if ( data.image === undefined ) {
  17303. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  17304. }
  17305. if ( images[ data.image ] === undefined ) {
  17306. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  17307. }
  17308. const source = images[ data.image ];
  17309. const image = source.data;
  17310. let texture;
  17311. if ( Array.isArray( image ) ) {
  17312. texture = new CubeTexture();
  17313. if ( image.length === 6 ) texture.needsUpdate = true;
  17314. } else {
  17315. if ( image && image.data ) {
  17316. texture = new DataTexture();
  17317. } else {
  17318. texture = new Texture();
  17319. }
  17320. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  17321. }
  17322. texture.source = source;
  17323. texture.uuid = data.uuid;
  17324. if ( data.name !== undefined ) texture.name = data.name;
  17325. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  17326. if ( data.channel !== undefined ) texture.channel = data.channel;
  17327. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  17328. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  17329. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  17330. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  17331. if ( data.wrap !== undefined ) {
  17332. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  17333. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  17334. }
  17335. if ( data.format !== undefined ) texture.format = data.format;
  17336. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  17337. if ( data.type !== undefined ) texture.type = data.type;
  17338. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  17339. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  17340. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  17341. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  17342. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  17343. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  17344. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  17345. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  17346. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  17347. if ( data.userData !== undefined ) texture.userData = data.userData;
  17348. textures[ data.uuid ] = texture;
  17349. }
  17350. }
  17351. return textures;
  17352. }
  17353. parseObject( data, geometries, materials, textures, animations ) {
  17354. let object;
  17355. function getGeometry( name ) {
  17356. if ( geometries[ name ] === undefined ) {
  17357. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  17358. }
  17359. return geometries[ name ];
  17360. }
  17361. function getMaterial( name ) {
  17362. if ( name === undefined ) return undefined;
  17363. if ( Array.isArray( name ) ) {
  17364. const array = [];
  17365. for ( let i = 0, l = name.length; i < l; i ++ ) {
  17366. const uuid = name[ i ];
  17367. if ( materials[ uuid ] === undefined ) {
  17368. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  17369. }
  17370. array.push( materials[ uuid ] );
  17371. }
  17372. return array;
  17373. }
  17374. if ( materials[ name ] === undefined ) {
  17375. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  17376. }
  17377. return materials[ name ];
  17378. }
  17379. function getTexture( uuid ) {
  17380. if ( textures[ uuid ] === undefined ) {
  17381. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  17382. }
  17383. return textures[ uuid ];
  17384. }
  17385. let geometry, material;
  17386. switch ( data.type ) {
  17387. case 'Scene':
  17388. object = new Scene();
  17389. if ( data.background !== undefined ) {
  17390. if ( Number.isInteger( data.background ) ) {
  17391. object.background = new Color( data.background );
  17392. } else {
  17393. object.background = getTexture( data.background );
  17394. }
  17395. }
  17396. if ( data.environment !== undefined ) {
  17397. object.environment = getTexture( data.environment );
  17398. }
  17399. if ( data.fog !== undefined ) {
  17400. if ( data.fog.type === 'Fog' ) {
  17401. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  17402. } else if ( data.fog.type === 'FogExp2' ) {
  17403. object.fog = new FogExp2( data.fog.color, data.fog.density );
  17404. }
  17405. if ( data.fog.name !== '' ) {
  17406. object.fog.name = data.fog.name;
  17407. }
  17408. }
  17409. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  17410. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  17411. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  17412. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  17413. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  17414. break;
  17415. case 'PerspectiveCamera':
  17416. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  17417. if ( data.focus !== undefined ) object.focus = data.focus;
  17418. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17419. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  17420. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  17421. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17422. break;
  17423. case 'OrthographicCamera':
  17424. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  17425. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17426. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17427. break;
  17428. case 'AmbientLight':
  17429. object = new AmbientLight( data.color, data.intensity );
  17430. break;
  17431. case 'DirectionalLight':
  17432. object = new DirectionalLight( data.color, data.intensity );
  17433. object.target = data.target || '';
  17434. break;
  17435. case 'PointLight':
  17436. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  17437. break;
  17438. case 'RectAreaLight':
  17439. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  17440. break;
  17441. case 'SpotLight':
  17442. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  17443. object.target = data.target || '';
  17444. break;
  17445. case 'HemisphereLight':
  17446. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  17447. break;
  17448. case 'LightProbe':
  17449. object = new LightProbe().fromJSON( data );
  17450. break;
  17451. case 'SkinnedMesh':
  17452. geometry = getGeometry( data.geometry );
  17453. material = getMaterial( data.material );
  17454. object = new SkinnedMesh( geometry, material );
  17455. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  17456. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  17457. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  17458. break;
  17459. case 'Mesh':
  17460. geometry = getGeometry( data.geometry );
  17461. material = getMaterial( data.material );
  17462. object = new Mesh( geometry, material );
  17463. break;
  17464. case 'InstancedMesh':
  17465. geometry = getGeometry( data.geometry );
  17466. material = getMaterial( data.material );
  17467. const count = data.count;
  17468. const instanceMatrix = data.instanceMatrix;
  17469. const instanceColor = data.instanceColor;
  17470. object = new InstancedMesh( geometry, material, count );
  17471. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  17472. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  17473. break;
  17474. case 'BatchedMesh':
  17475. geometry = getGeometry( data.geometry );
  17476. material = getMaterial( data.material );
  17477. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  17478. object.geometry = geometry;
  17479. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  17480. object.sortObjects = data.sortObjects;
  17481. object._drawRanges = data.drawRanges;
  17482. object._reservedRanges = data.reservedRanges;
  17483. object._visibility = data.visibility;
  17484. object._active = data.active;
  17485. object._bounds = data.bounds.map( bound => {
  17486. const box = new Box3();
  17487. box.min.fromArray( bound.boxMin );
  17488. box.max.fromArray( bound.boxMax );
  17489. const sphere = new Sphere();
  17490. sphere.radius = bound.sphereRadius;
  17491. sphere.center.fromArray( bound.sphereCenter );
  17492. return {
  17493. boxInitialized: bound.boxInitialized,
  17494. box: box,
  17495. sphereInitialized: bound.sphereInitialized,
  17496. sphere: sphere
  17497. };
  17498. } );
  17499. object._maxInstanceCount = data.maxInstanceCount;
  17500. object._maxVertexCount = data.maxVertexCount;
  17501. object._maxIndexCount = data.maxIndexCount;
  17502. object._geometryInitialized = data.geometryInitialized;
  17503. object._geometryCount = data.geometryCount;
  17504. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  17505. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  17506. break;
  17507. case 'LOD':
  17508. object = new LOD();
  17509. break;
  17510. case 'Line':
  17511. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  17512. break;
  17513. case 'LineLoop':
  17514. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  17515. break;
  17516. case 'LineSegments':
  17517. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  17518. break;
  17519. case 'PointCloud':
  17520. case 'Points':
  17521. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  17522. break;
  17523. case 'Sprite':
  17524. object = new Sprite( getMaterial( data.material ) );
  17525. break;
  17526. case 'Group':
  17527. object = new Group();
  17528. break;
  17529. case 'Bone':
  17530. object = new Bone();
  17531. break;
  17532. default:
  17533. object = new Object3D();
  17534. }
  17535. object.uuid = data.uuid;
  17536. if ( data.name !== undefined ) object.name = data.name;
  17537. if ( data.matrix !== undefined ) {
  17538. object.matrix.fromArray( data.matrix );
  17539. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  17540. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  17541. } else {
  17542. if ( data.position !== undefined ) object.position.fromArray( data.position );
  17543. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  17544. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  17545. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  17546. }
  17547. if ( data.up !== undefined ) object.up.fromArray( data.up );
  17548. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  17549. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  17550. if ( data.shadow ) {
  17551. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  17552. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  17553. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  17554. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  17555. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  17556. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  17557. }
  17558. if ( data.visible !== undefined ) object.visible = data.visible;
  17559. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  17560. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  17561. if ( data.userData !== undefined ) object.userData = data.userData;
  17562. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  17563. if ( data.children !== undefined ) {
  17564. const children = data.children;
  17565. for ( let i = 0; i < children.length; i ++ ) {
  17566. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  17567. }
  17568. }
  17569. if ( data.animations !== undefined ) {
  17570. const objectAnimations = data.animations;
  17571. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  17572. const uuid = objectAnimations[ i ];
  17573. object.animations.push( animations[ uuid ] );
  17574. }
  17575. }
  17576. if ( data.type === 'LOD' ) {
  17577. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  17578. const levels = data.levels;
  17579. for ( let l = 0; l < levels.length; l ++ ) {
  17580. const level = levels[ l ];
  17581. const child = object.getObjectByProperty( 'uuid', level.object );
  17582. if ( child !== undefined ) {
  17583. object.addLevel( child, level.distance, level.hysteresis );
  17584. }
  17585. }
  17586. }
  17587. return object;
  17588. }
  17589. bindSkeletons( object, skeletons ) {
  17590. if ( Object.keys( skeletons ).length === 0 ) return;
  17591. object.traverse( function ( child ) {
  17592. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  17593. const skeleton = skeletons[ child.skeleton ];
  17594. if ( skeleton === undefined ) {
  17595. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  17596. } else {
  17597. child.bind( skeleton, child.bindMatrix );
  17598. }
  17599. }
  17600. } );
  17601. }
  17602. bindLightTargets( object ) {
  17603. object.traverse( function ( child ) {
  17604. if ( child.isDirectionalLight || child.isSpotLight ) {
  17605. const uuid = child.target;
  17606. const target = object.getObjectByProperty( 'uuid', uuid );
  17607. if ( target !== undefined ) {
  17608. child.target = target;
  17609. } else {
  17610. child.target = new Object3D();
  17611. }
  17612. }
  17613. } );
  17614. }
  17615. }
  17616. const TEXTURE_MAPPING = {
  17617. UVMapping: UVMapping,
  17618. CubeReflectionMapping: CubeReflectionMapping,
  17619. CubeRefractionMapping: CubeRefractionMapping,
  17620. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  17621. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  17622. CubeUVReflectionMapping: CubeUVReflectionMapping
  17623. };
  17624. const TEXTURE_WRAPPING = {
  17625. RepeatWrapping: RepeatWrapping,
  17626. ClampToEdgeWrapping: ClampToEdgeWrapping,
  17627. MirroredRepeatWrapping: MirroredRepeatWrapping
  17628. };
  17629. const TEXTURE_FILTER = {
  17630. NearestFilter: NearestFilter,
  17631. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  17632. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  17633. LinearFilter: LinearFilter,
  17634. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  17635. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  17636. };
  17637. class ImageBitmapLoader extends Loader {
  17638. constructor( manager ) {
  17639. super( manager );
  17640. this.isImageBitmapLoader = true;
  17641. if ( typeof createImageBitmap === 'undefined' ) {
  17642. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  17643. }
  17644. if ( typeof fetch === 'undefined' ) {
  17645. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  17646. }
  17647. this.options = { premultiplyAlpha: 'none' };
  17648. }
  17649. setOptions( options ) {
  17650. this.options = options;
  17651. return this;
  17652. }
  17653. load( url, onLoad, onProgress, onError ) {
  17654. if ( url === undefined ) url = '';
  17655. if ( this.path !== undefined ) url = this.path + url;
  17656. url = this.manager.resolveURL( url );
  17657. const scope = this;
  17658. const cached = Cache.get( url );
  17659. if ( cached !== undefined ) {
  17660. scope.manager.itemStart( url );
  17661. // If cached is a promise, wait for it to resolve
  17662. if ( cached.then ) {
  17663. cached.then( imageBitmap => {
  17664. if ( onLoad ) onLoad( imageBitmap );
  17665. scope.manager.itemEnd( url );
  17666. } ).catch( e => {
  17667. if ( onError ) onError( e );
  17668. } );
  17669. return;
  17670. }
  17671. // If cached is not a promise (i.e., it's already an imageBitmap)
  17672. setTimeout( function () {
  17673. if ( onLoad ) onLoad( cached );
  17674. scope.manager.itemEnd( url );
  17675. }, 0 );
  17676. return cached;
  17677. }
  17678. const fetchOptions = {};
  17679. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  17680. fetchOptions.headers = this.requestHeader;
  17681. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  17682. return res.blob();
  17683. } ).then( function ( blob ) {
  17684. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  17685. } ).then( function ( imageBitmap ) {
  17686. Cache.add( url, imageBitmap );
  17687. if ( onLoad ) onLoad( imageBitmap );
  17688. scope.manager.itemEnd( url );
  17689. return imageBitmap;
  17690. } ).catch( function ( e ) {
  17691. if ( onError ) onError( e );
  17692. Cache.remove( url );
  17693. scope.manager.itemError( url );
  17694. scope.manager.itemEnd( url );
  17695. } );
  17696. Cache.add( url, promise );
  17697. scope.manager.itemStart( url );
  17698. }
  17699. }
  17700. let _context;
  17701. class AudioContext {
  17702. static getContext() {
  17703. if ( _context === undefined ) {
  17704. _context = new ( window.AudioContext || window.webkitAudioContext )();
  17705. }
  17706. return _context;
  17707. }
  17708. static setContext( value ) {
  17709. _context = value;
  17710. }
  17711. }
  17712. class AudioLoader extends Loader {
  17713. constructor( manager ) {
  17714. super( manager );
  17715. }
  17716. load( url, onLoad, onProgress, onError ) {
  17717. const scope = this;
  17718. const loader = new FileLoader( this.manager );
  17719. loader.setResponseType( 'arraybuffer' );
  17720. loader.setPath( this.path );
  17721. loader.setRequestHeader( this.requestHeader );
  17722. loader.setWithCredentials( this.withCredentials );
  17723. loader.load( url, function ( buffer ) {
  17724. try {
  17725. // Create a copy of the buffer. The `decodeAudioData` method
  17726. // detaches the buffer when complete, preventing reuse.
  17727. const bufferCopy = buffer.slice( 0 );
  17728. const context = AudioContext.getContext();
  17729. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  17730. onLoad( audioBuffer );
  17731. } ).catch( handleError );
  17732. } catch ( e ) {
  17733. handleError( e );
  17734. }
  17735. }, onProgress, onError );
  17736. function handleError( e ) {
  17737. if ( onError ) {
  17738. onError( e );
  17739. } else {
  17740. console.error( e );
  17741. }
  17742. scope.manager.itemError( url );
  17743. }
  17744. }
  17745. }
  17746. const _eyeRight = /*@__PURE__*/ new Matrix4();
  17747. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  17748. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  17749. class StereoCamera {
  17750. constructor() {
  17751. this.type = 'StereoCamera';
  17752. this.aspect = 1;
  17753. this.eyeSep = 0.064;
  17754. this.cameraL = new PerspectiveCamera();
  17755. this.cameraL.layers.enable( 1 );
  17756. this.cameraL.matrixAutoUpdate = false;
  17757. this.cameraR = new PerspectiveCamera();
  17758. this.cameraR.layers.enable( 2 );
  17759. this.cameraR.matrixAutoUpdate = false;
  17760. this._cache = {
  17761. focus: null,
  17762. fov: null,
  17763. aspect: null,
  17764. near: null,
  17765. far: null,
  17766. zoom: null,
  17767. eyeSep: null
  17768. };
  17769. }
  17770. update( camera ) {
  17771. const cache = this._cache;
  17772. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  17773. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  17774. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  17775. if ( needsUpdate ) {
  17776. cache.focus = camera.focus;
  17777. cache.fov = camera.fov;
  17778. cache.aspect = camera.aspect * this.aspect;
  17779. cache.near = camera.near;
  17780. cache.far = camera.far;
  17781. cache.zoom = camera.zoom;
  17782. cache.eyeSep = this.eyeSep;
  17783. // Off-axis stereoscopic effect based on
  17784. // http://paulbourke.net/stereographics/stereorender/
  17785. _projectionMatrix.copy( camera.projectionMatrix );
  17786. const eyeSepHalf = cache.eyeSep / 2;
  17787. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  17788. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  17789. let xmin, xmax;
  17790. // translate xOffset
  17791. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  17792. _eyeRight.elements[ 12 ] = eyeSepHalf;
  17793. // for left eye
  17794. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  17795. xmax = ymax * cache.aspect + eyeSepOnProjection;
  17796. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  17797. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  17798. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  17799. // for right eye
  17800. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  17801. xmax = ymax * cache.aspect - eyeSepOnProjection;
  17802. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  17803. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  17804. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  17805. }
  17806. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  17807. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  17808. }
  17809. }
  17810. class ArrayCamera extends PerspectiveCamera {
  17811. constructor( array = [] ) {
  17812. super();
  17813. this.isArrayCamera = true;
  17814. this.cameras = array;
  17815. }
  17816. }
  17817. class Clock {
  17818. constructor( autoStart = true ) {
  17819. this.autoStart = autoStart;
  17820. this.startTime = 0;
  17821. this.oldTime = 0;
  17822. this.elapsedTime = 0;
  17823. this.running = false;
  17824. }
  17825. start() {
  17826. this.startTime = now();
  17827. this.oldTime = this.startTime;
  17828. this.elapsedTime = 0;
  17829. this.running = true;
  17830. }
  17831. stop() {
  17832. this.getElapsedTime();
  17833. this.running = false;
  17834. this.autoStart = false;
  17835. }
  17836. getElapsedTime() {
  17837. this.getDelta();
  17838. return this.elapsedTime;
  17839. }
  17840. getDelta() {
  17841. let diff = 0;
  17842. if ( this.autoStart && ! this.running ) {
  17843. this.start();
  17844. return 0;
  17845. }
  17846. if ( this.running ) {
  17847. const newTime = now();
  17848. diff = ( newTime - this.oldTime ) / 1000;
  17849. this.oldTime = newTime;
  17850. this.elapsedTime += diff;
  17851. }
  17852. return diff;
  17853. }
  17854. }
  17855. function now() {
  17856. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  17857. }
  17858. const _position$1 = /*@__PURE__*/ new Vector3();
  17859. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  17860. const _scale$1 = /*@__PURE__*/ new Vector3();
  17861. const _orientation$1 = /*@__PURE__*/ new Vector3();
  17862. class AudioListener extends Object3D {
  17863. constructor() {
  17864. super();
  17865. this.type = 'AudioListener';
  17866. this.context = AudioContext.getContext();
  17867. this.gain = this.context.createGain();
  17868. this.gain.connect( this.context.destination );
  17869. this.filter = null;
  17870. this.timeDelta = 0;
  17871. // private
  17872. this._clock = new Clock();
  17873. }
  17874. getInput() {
  17875. return this.gain;
  17876. }
  17877. removeFilter() {
  17878. if ( this.filter !== null ) {
  17879. this.gain.disconnect( this.filter );
  17880. this.filter.disconnect( this.context.destination );
  17881. this.gain.connect( this.context.destination );
  17882. this.filter = null;
  17883. }
  17884. return this;
  17885. }
  17886. getFilter() {
  17887. return this.filter;
  17888. }
  17889. setFilter( value ) {
  17890. if ( this.filter !== null ) {
  17891. this.gain.disconnect( this.filter );
  17892. this.filter.disconnect( this.context.destination );
  17893. } else {
  17894. this.gain.disconnect( this.context.destination );
  17895. }
  17896. this.filter = value;
  17897. this.gain.connect( this.filter );
  17898. this.filter.connect( this.context.destination );
  17899. return this;
  17900. }
  17901. getMasterVolume() {
  17902. return this.gain.gain.value;
  17903. }
  17904. setMasterVolume( value ) {
  17905. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  17906. return this;
  17907. }
  17908. updateMatrixWorld( force ) {
  17909. super.updateMatrixWorld( force );
  17910. const listener = this.context.listener;
  17911. const up = this.up;
  17912. this.timeDelta = this._clock.getDelta();
  17913. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  17914. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  17915. if ( listener.positionX ) {
  17916. // code path for Chrome (see #14393)
  17917. const endTime = this.context.currentTime + this.timeDelta;
  17918. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  17919. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  17920. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  17921. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  17922. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  17923. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  17924. listener.upX.linearRampToValueAtTime( up.x, endTime );
  17925. listener.upY.linearRampToValueAtTime( up.y, endTime );
  17926. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  17927. } else {
  17928. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  17929. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  17930. }
  17931. }
  17932. }
  17933. class Audio extends Object3D {
  17934. constructor( listener ) {
  17935. super();
  17936. this.type = 'Audio';
  17937. this.listener = listener;
  17938. this.context = listener.context;
  17939. this.gain = this.context.createGain();
  17940. this.gain.connect( listener.getInput() );
  17941. this.autoplay = false;
  17942. this.buffer = null;
  17943. this.detune = 0;
  17944. this.loop = false;
  17945. this.loopStart = 0;
  17946. this.loopEnd = 0;
  17947. this.offset = 0;
  17948. this.duration = undefined;
  17949. this.playbackRate = 1;
  17950. this.isPlaying = false;
  17951. this.hasPlaybackControl = true;
  17952. this.source = null;
  17953. this.sourceType = 'empty';
  17954. this._startedAt = 0;
  17955. this._progress = 0;
  17956. this._connected = false;
  17957. this.filters = [];
  17958. }
  17959. getOutput() {
  17960. return this.gain;
  17961. }
  17962. setNodeSource( audioNode ) {
  17963. this.hasPlaybackControl = false;
  17964. this.sourceType = 'audioNode';
  17965. this.source = audioNode;
  17966. this.connect();
  17967. return this;
  17968. }
  17969. setMediaElementSource( mediaElement ) {
  17970. this.hasPlaybackControl = false;
  17971. this.sourceType = 'mediaNode';
  17972. this.source = this.context.createMediaElementSource( mediaElement );
  17973. this.connect();
  17974. return this;
  17975. }
  17976. setMediaStreamSource( mediaStream ) {
  17977. this.hasPlaybackControl = false;
  17978. this.sourceType = 'mediaStreamNode';
  17979. this.source = this.context.createMediaStreamSource( mediaStream );
  17980. this.connect();
  17981. return this;
  17982. }
  17983. setBuffer( audioBuffer ) {
  17984. this.buffer = audioBuffer;
  17985. this.sourceType = 'buffer';
  17986. if ( this.autoplay ) this.play();
  17987. return this;
  17988. }
  17989. play( delay = 0 ) {
  17990. if ( this.isPlaying === true ) {
  17991. console.warn( 'THREE.Audio: Audio is already playing.' );
  17992. return;
  17993. }
  17994. if ( this.hasPlaybackControl === false ) {
  17995. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  17996. return;
  17997. }
  17998. this._startedAt = this.context.currentTime + delay;
  17999. const source = this.context.createBufferSource();
  18000. source.buffer = this.buffer;
  18001. source.loop = this.loop;
  18002. source.loopStart = this.loopStart;
  18003. source.loopEnd = this.loopEnd;
  18004. source.onended = this.onEnded.bind( this );
  18005. source.start( this._startedAt, this._progress + this.offset, this.duration );
  18006. this.isPlaying = true;
  18007. this.source = source;
  18008. this.setDetune( this.detune );
  18009. this.setPlaybackRate( this.playbackRate );
  18010. return this.connect();
  18011. }
  18012. pause() {
  18013. if ( this.hasPlaybackControl === false ) {
  18014. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18015. return;
  18016. }
  18017. if ( this.isPlaying === true ) {
  18018. // update current progress
  18019. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  18020. if ( this.loop === true ) {
  18021. // ensure _progress does not exceed duration with looped audios
  18022. this._progress = this._progress % ( this.duration || this.buffer.duration );
  18023. }
  18024. this.source.stop();
  18025. this.source.onended = null;
  18026. this.isPlaying = false;
  18027. }
  18028. return this;
  18029. }
  18030. stop() {
  18031. if ( this.hasPlaybackControl === false ) {
  18032. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18033. return;
  18034. }
  18035. this._progress = 0;
  18036. if ( this.source !== null ) {
  18037. this.source.stop();
  18038. this.source.onended = null;
  18039. }
  18040. this.isPlaying = false;
  18041. return this;
  18042. }
  18043. connect() {
  18044. if ( this.filters.length > 0 ) {
  18045. this.source.connect( this.filters[ 0 ] );
  18046. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18047. this.filters[ i - 1 ].connect( this.filters[ i ] );
  18048. }
  18049. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  18050. } else {
  18051. this.source.connect( this.getOutput() );
  18052. }
  18053. this._connected = true;
  18054. return this;
  18055. }
  18056. disconnect() {
  18057. if ( this._connected === false ) {
  18058. return;
  18059. }
  18060. if ( this.filters.length > 0 ) {
  18061. this.source.disconnect( this.filters[ 0 ] );
  18062. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18063. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  18064. }
  18065. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  18066. } else {
  18067. this.source.disconnect( this.getOutput() );
  18068. }
  18069. this._connected = false;
  18070. return this;
  18071. }
  18072. getFilters() {
  18073. return this.filters;
  18074. }
  18075. setFilters( value ) {
  18076. if ( ! value ) value = [];
  18077. if ( this._connected === true ) {
  18078. this.disconnect();
  18079. this.filters = value.slice();
  18080. this.connect();
  18081. } else {
  18082. this.filters = value.slice();
  18083. }
  18084. return this;
  18085. }
  18086. setDetune( value ) {
  18087. this.detune = value;
  18088. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  18089. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  18090. }
  18091. return this;
  18092. }
  18093. getDetune() {
  18094. return this.detune;
  18095. }
  18096. getFilter() {
  18097. return this.getFilters()[ 0 ];
  18098. }
  18099. setFilter( filter ) {
  18100. return this.setFilters( filter ? [ filter ] : [] );
  18101. }
  18102. setPlaybackRate( value ) {
  18103. if ( this.hasPlaybackControl === false ) {
  18104. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18105. return;
  18106. }
  18107. this.playbackRate = value;
  18108. if ( this.isPlaying === true ) {
  18109. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  18110. }
  18111. return this;
  18112. }
  18113. getPlaybackRate() {
  18114. return this.playbackRate;
  18115. }
  18116. onEnded() {
  18117. this.isPlaying = false;
  18118. }
  18119. getLoop() {
  18120. if ( this.hasPlaybackControl === false ) {
  18121. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18122. return false;
  18123. }
  18124. return this.loop;
  18125. }
  18126. setLoop( value ) {
  18127. if ( this.hasPlaybackControl === false ) {
  18128. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18129. return;
  18130. }
  18131. this.loop = value;
  18132. if ( this.isPlaying === true ) {
  18133. this.source.loop = this.loop;
  18134. }
  18135. return this;
  18136. }
  18137. setLoopStart( value ) {
  18138. this.loopStart = value;
  18139. return this;
  18140. }
  18141. setLoopEnd( value ) {
  18142. this.loopEnd = value;
  18143. return this;
  18144. }
  18145. getVolume() {
  18146. return this.gain.gain.value;
  18147. }
  18148. setVolume( value ) {
  18149. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  18150. return this;
  18151. }
  18152. }
  18153. const _position = /*@__PURE__*/ new Vector3();
  18154. const _quaternion = /*@__PURE__*/ new Quaternion();
  18155. const _scale = /*@__PURE__*/ new Vector3();
  18156. const _orientation = /*@__PURE__*/ new Vector3();
  18157. class PositionalAudio extends Audio {
  18158. constructor( listener ) {
  18159. super( listener );
  18160. this.panner = this.context.createPanner();
  18161. this.panner.panningModel = 'HRTF';
  18162. this.panner.connect( this.gain );
  18163. }
  18164. connect() {
  18165. super.connect();
  18166. this.panner.connect( this.gain );
  18167. }
  18168. disconnect() {
  18169. super.disconnect();
  18170. this.panner.disconnect( this.gain );
  18171. }
  18172. getOutput() {
  18173. return this.panner;
  18174. }
  18175. getRefDistance() {
  18176. return this.panner.refDistance;
  18177. }
  18178. setRefDistance( value ) {
  18179. this.panner.refDistance = value;
  18180. return this;
  18181. }
  18182. getRolloffFactor() {
  18183. return this.panner.rolloffFactor;
  18184. }
  18185. setRolloffFactor( value ) {
  18186. this.panner.rolloffFactor = value;
  18187. return this;
  18188. }
  18189. getDistanceModel() {
  18190. return this.panner.distanceModel;
  18191. }
  18192. setDistanceModel( value ) {
  18193. this.panner.distanceModel = value;
  18194. return this;
  18195. }
  18196. getMaxDistance() {
  18197. return this.panner.maxDistance;
  18198. }
  18199. setMaxDistance( value ) {
  18200. this.panner.maxDistance = value;
  18201. return this;
  18202. }
  18203. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  18204. this.panner.coneInnerAngle = coneInnerAngle;
  18205. this.panner.coneOuterAngle = coneOuterAngle;
  18206. this.panner.coneOuterGain = coneOuterGain;
  18207. return this;
  18208. }
  18209. updateMatrixWorld( force ) {
  18210. super.updateMatrixWorld( force );
  18211. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  18212. this.matrixWorld.decompose( _position, _quaternion, _scale );
  18213. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  18214. const panner = this.panner;
  18215. if ( panner.positionX ) {
  18216. // code path for Chrome and Firefox (see #14393)
  18217. const endTime = this.context.currentTime + this.listener.timeDelta;
  18218. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  18219. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  18220. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  18221. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  18222. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  18223. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  18224. } else {
  18225. panner.setPosition( _position.x, _position.y, _position.z );
  18226. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  18227. }
  18228. }
  18229. }
  18230. class AudioAnalyser {
  18231. constructor( audio, fftSize = 2048 ) {
  18232. this.analyser = audio.context.createAnalyser();
  18233. this.analyser.fftSize = fftSize;
  18234. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  18235. audio.getOutput().connect( this.analyser );
  18236. }
  18237. getFrequencyData() {
  18238. this.analyser.getByteFrequencyData( this.data );
  18239. return this.data;
  18240. }
  18241. getAverageFrequency() {
  18242. let value = 0;
  18243. const data = this.getFrequencyData();
  18244. for ( let i = 0; i < data.length; i ++ ) {
  18245. value += data[ i ];
  18246. }
  18247. return value / data.length;
  18248. }
  18249. }
  18250. class PropertyMixer {
  18251. constructor( binding, typeName, valueSize ) {
  18252. this.binding = binding;
  18253. this.valueSize = valueSize;
  18254. let mixFunction,
  18255. mixFunctionAdditive,
  18256. setIdentity;
  18257. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  18258. //
  18259. // interpolators can use .buffer as their .result
  18260. // the data then goes to 'incoming'
  18261. //
  18262. // 'accu0' and 'accu1' are used frame-interleaved for
  18263. // the cumulative result and are compared to detect
  18264. // changes
  18265. //
  18266. // 'orig' stores the original state of the property
  18267. //
  18268. // 'add' is used for additive cumulative results
  18269. //
  18270. // 'work' is optional and is only present for quaternion types. It is used
  18271. // to store intermediate quaternion multiplication results
  18272. switch ( typeName ) {
  18273. case 'quaternion':
  18274. mixFunction = this._slerp;
  18275. mixFunctionAdditive = this._slerpAdditive;
  18276. setIdentity = this._setAdditiveIdentityQuaternion;
  18277. this.buffer = new Float64Array( valueSize * 6 );
  18278. this._workIndex = 5;
  18279. break;
  18280. case 'string':
  18281. case 'bool':
  18282. mixFunction = this._select;
  18283. // Use the regular mix function and for additive on these types,
  18284. // additive is not relevant for non-numeric types
  18285. mixFunctionAdditive = this._select;
  18286. setIdentity = this._setAdditiveIdentityOther;
  18287. this.buffer = new Array( valueSize * 5 );
  18288. break;
  18289. default:
  18290. mixFunction = this._lerp;
  18291. mixFunctionAdditive = this._lerpAdditive;
  18292. setIdentity = this._setAdditiveIdentityNumeric;
  18293. this.buffer = new Float64Array( valueSize * 5 );
  18294. }
  18295. this._mixBufferRegion = mixFunction;
  18296. this._mixBufferRegionAdditive = mixFunctionAdditive;
  18297. this._setIdentity = setIdentity;
  18298. this._origIndex = 3;
  18299. this._addIndex = 4;
  18300. this.cumulativeWeight = 0;
  18301. this.cumulativeWeightAdditive = 0;
  18302. this.useCount = 0;
  18303. this.referenceCount = 0;
  18304. }
  18305. // accumulate data in the 'incoming' region into 'accu<i>'
  18306. accumulate( accuIndex, weight ) {
  18307. // note: happily accumulating nothing when weight = 0, the caller knows
  18308. // the weight and shouldn't have made the call in the first place
  18309. const buffer = this.buffer,
  18310. stride = this.valueSize,
  18311. offset = accuIndex * stride + stride;
  18312. let currentWeight = this.cumulativeWeight;
  18313. if ( currentWeight === 0 ) {
  18314. // accuN := incoming * weight
  18315. for ( let i = 0; i !== stride; ++ i ) {
  18316. buffer[ offset + i ] = buffer[ i ];
  18317. }
  18318. currentWeight = weight;
  18319. } else {
  18320. // accuN := accuN + incoming * weight
  18321. currentWeight += weight;
  18322. const mix = weight / currentWeight;
  18323. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  18324. }
  18325. this.cumulativeWeight = currentWeight;
  18326. }
  18327. // accumulate data in the 'incoming' region into 'add'
  18328. accumulateAdditive( weight ) {
  18329. const buffer = this.buffer,
  18330. stride = this.valueSize,
  18331. offset = stride * this._addIndex;
  18332. if ( this.cumulativeWeightAdditive === 0 ) {
  18333. // add = identity
  18334. this._setIdentity();
  18335. }
  18336. // add := add + incoming * weight
  18337. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  18338. this.cumulativeWeightAdditive += weight;
  18339. }
  18340. // apply the state of 'accu<i>' to the binding when accus differ
  18341. apply( accuIndex ) {
  18342. const stride = this.valueSize,
  18343. buffer = this.buffer,
  18344. offset = accuIndex * stride + stride,
  18345. weight = this.cumulativeWeight,
  18346. weightAdditive = this.cumulativeWeightAdditive,
  18347. binding = this.binding;
  18348. this.cumulativeWeight = 0;
  18349. this.cumulativeWeightAdditive = 0;
  18350. if ( weight < 1 ) {
  18351. // accuN := accuN + original * ( 1 - cumulativeWeight )
  18352. const originalValueOffset = stride * this._origIndex;
  18353. this._mixBufferRegion(
  18354. buffer, offset, originalValueOffset, 1 - weight, stride );
  18355. }
  18356. if ( weightAdditive > 0 ) {
  18357. // accuN := accuN + additive accuN
  18358. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  18359. }
  18360. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  18361. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  18362. // value has changed -> update scene graph
  18363. binding.setValue( buffer, offset );
  18364. break;
  18365. }
  18366. }
  18367. }
  18368. // remember the state of the bound property and copy it to both accus
  18369. saveOriginalState() {
  18370. const binding = this.binding;
  18371. const buffer = this.buffer,
  18372. stride = this.valueSize,
  18373. originalValueOffset = stride * this._origIndex;
  18374. binding.getValue( buffer, originalValueOffset );
  18375. // accu[0..1] := orig -- initially detect changes against the original
  18376. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  18377. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  18378. }
  18379. // Add to identity for additive
  18380. this._setIdentity();
  18381. this.cumulativeWeight = 0;
  18382. this.cumulativeWeightAdditive = 0;
  18383. }
  18384. // apply the state previously taken via 'saveOriginalState' to the binding
  18385. restoreOriginalState() {
  18386. const originalValueOffset = this.valueSize * 3;
  18387. this.binding.setValue( this.buffer, originalValueOffset );
  18388. }
  18389. _setAdditiveIdentityNumeric() {
  18390. const startIndex = this._addIndex * this.valueSize;
  18391. const endIndex = startIndex + this.valueSize;
  18392. for ( let i = startIndex; i < endIndex; i ++ ) {
  18393. this.buffer[ i ] = 0;
  18394. }
  18395. }
  18396. _setAdditiveIdentityQuaternion() {
  18397. this._setAdditiveIdentityNumeric();
  18398. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  18399. }
  18400. _setAdditiveIdentityOther() {
  18401. const startIndex = this._origIndex * this.valueSize;
  18402. const targetIndex = this._addIndex * this.valueSize;
  18403. for ( let i = 0; i < this.valueSize; i ++ ) {
  18404. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  18405. }
  18406. }
  18407. // mix functions
  18408. _select( buffer, dstOffset, srcOffset, t, stride ) {
  18409. if ( t >= 0.5 ) {
  18410. for ( let i = 0; i !== stride; ++ i ) {
  18411. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  18412. }
  18413. }
  18414. }
  18415. _slerp( buffer, dstOffset, srcOffset, t ) {
  18416. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  18417. }
  18418. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18419. const workOffset = this._workIndex * stride;
  18420. // Store result in intermediate buffer offset
  18421. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  18422. // Slerp to the intermediate result
  18423. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  18424. }
  18425. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  18426. const s = 1 - t;
  18427. for ( let i = 0; i !== stride; ++ i ) {
  18428. const j = dstOffset + i;
  18429. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  18430. }
  18431. }
  18432. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18433. for ( let i = 0; i !== stride; ++ i ) {
  18434. const j = dstOffset + i;
  18435. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  18436. }
  18437. }
  18438. }
  18439. // Characters [].:/ are reserved for track binding syntax.
  18440. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  18441. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  18442. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  18443. // only latin characters, and the unicode \p{L} is not yet supported. So
  18444. // instead, we exclude reserved characters and match everything else.
  18445. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  18446. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  18447. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  18448. // be matched to parse the rest of the track name.
  18449. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  18450. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  18451. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  18452. // Object on target node, and accessor. May not contain reserved
  18453. // characters. Accessor may contain any character except closing bracket.
  18454. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  18455. // Property and accessor. May not contain reserved characters. Accessor may
  18456. // contain any non-bracket characters.
  18457. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  18458. const _trackRe = new RegExp( ''
  18459. + '^'
  18460. + _directoryRe
  18461. + _nodeRe
  18462. + _objectRe
  18463. + _propertyRe
  18464. + '$'
  18465. );
  18466. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  18467. class Composite {
  18468. constructor( targetGroup, path, optionalParsedPath ) {
  18469. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  18470. this._targetGroup = targetGroup;
  18471. this._bindings = targetGroup.subscribe_( path, parsedPath );
  18472. }
  18473. getValue( array, offset ) {
  18474. this.bind(); // bind all binding
  18475. const firstValidIndex = this._targetGroup.nCachedObjects_,
  18476. binding = this._bindings[ firstValidIndex ];
  18477. // and only call .getValue on the first
  18478. if ( binding !== undefined ) binding.getValue( array, offset );
  18479. }
  18480. setValue( array, offset ) {
  18481. const bindings = this._bindings;
  18482. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18483. bindings[ i ].setValue( array, offset );
  18484. }
  18485. }
  18486. bind() {
  18487. const bindings = this._bindings;
  18488. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18489. bindings[ i ].bind();
  18490. }
  18491. }
  18492. unbind() {
  18493. const bindings = this._bindings;
  18494. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18495. bindings[ i ].unbind();
  18496. }
  18497. }
  18498. }
  18499. // Note: This class uses a State pattern on a per-method basis:
  18500. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  18501. // prototype version of these methods with one that represents
  18502. // the bound state. When the property is not found, the methods
  18503. // become no-ops.
  18504. class PropertyBinding {
  18505. constructor( rootNode, path, parsedPath ) {
  18506. this.path = path;
  18507. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  18508. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  18509. this.rootNode = rootNode;
  18510. // initial state of these methods that calls 'bind'
  18511. this.getValue = this._getValue_unbound;
  18512. this.setValue = this._setValue_unbound;
  18513. }
  18514. static create( root, path, parsedPath ) {
  18515. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  18516. return new PropertyBinding( root, path, parsedPath );
  18517. } else {
  18518. return new PropertyBinding.Composite( root, path, parsedPath );
  18519. }
  18520. }
  18521. /**
  18522. * Replaces spaces with underscores and removes unsupported characters from
  18523. * node names, to ensure compatibility with parseTrackName().
  18524. *
  18525. * @param {string} name Node name to be sanitized.
  18526. * @return {string}
  18527. */
  18528. static sanitizeNodeName( name ) {
  18529. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  18530. }
  18531. static parseTrackName( trackName ) {
  18532. const matches = _trackRe.exec( trackName );
  18533. if ( matches === null ) {
  18534. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  18535. }
  18536. const results = {
  18537. // directoryName: matches[ 1 ], // (tschw) currently unused
  18538. nodeName: matches[ 2 ],
  18539. objectName: matches[ 3 ],
  18540. objectIndex: matches[ 4 ],
  18541. propertyName: matches[ 5 ], // required
  18542. propertyIndex: matches[ 6 ]
  18543. };
  18544. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  18545. if ( lastDot !== undefined && lastDot !== - 1 ) {
  18546. const objectName = results.nodeName.substring( lastDot + 1 );
  18547. // Object names must be checked against an allowlist. Otherwise, there
  18548. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  18549. // 'bar' could be the objectName, or part of a nodeName (which can
  18550. // include '.' characters).
  18551. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  18552. results.nodeName = results.nodeName.substring( 0, lastDot );
  18553. results.objectName = objectName;
  18554. }
  18555. }
  18556. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  18557. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  18558. }
  18559. return results;
  18560. }
  18561. static findNode( root, nodeName ) {
  18562. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  18563. return root;
  18564. }
  18565. // search into skeleton bones.
  18566. if ( root.skeleton ) {
  18567. const bone = root.skeleton.getBoneByName( nodeName );
  18568. if ( bone !== undefined ) {
  18569. return bone;
  18570. }
  18571. }
  18572. // search into node subtree.
  18573. if ( root.children ) {
  18574. const searchNodeSubtree = function ( children ) {
  18575. for ( let i = 0; i < children.length; i ++ ) {
  18576. const childNode = children[ i ];
  18577. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  18578. return childNode;
  18579. }
  18580. const result = searchNodeSubtree( childNode.children );
  18581. if ( result ) return result;
  18582. }
  18583. return null;
  18584. };
  18585. const subTreeNode = searchNodeSubtree( root.children );
  18586. if ( subTreeNode ) {
  18587. return subTreeNode;
  18588. }
  18589. }
  18590. return null;
  18591. }
  18592. // these are used to "bind" a nonexistent property
  18593. _getValue_unavailable() {}
  18594. _setValue_unavailable() {}
  18595. // Getters
  18596. _getValue_direct( buffer, offset ) {
  18597. buffer[ offset ] = this.targetObject[ this.propertyName ];
  18598. }
  18599. _getValue_array( buffer, offset ) {
  18600. const source = this.resolvedProperty;
  18601. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  18602. buffer[ offset ++ ] = source[ i ];
  18603. }
  18604. }
  18605. _getValue_arrayElement( buffer, offset ) {
  18606. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  18607. }
  18608. _getValue_toArray( buffer, offset ) {
  18609. this.resolvedProperty.toArray( buffer, offset );
  18610. }
  18611. // Direct
  18612. _setValue_direct( buffer, offset ) {
  18613. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18614. }
  18615. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  18616. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18617. this.targetObject.needsUpdate = true;
  18618. }
  18619. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18620. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18621. this.targetObject.matrixWorldNeedsUpdate = true;
  18622. }
  18623. // EntireArray
  18624. _setValue_array( buffer, offset ) {
  18625. const dest = this.resolvedProperty;
  18626. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18627. dest[ i ] = buffer[ offset ++ ];
  18628. }
  18629. }
  18630. _setValue_array_setNeedsUpdate( buffer, offset ) {
  18631. const dest = this.resolvedProperty;
  18632. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18633. dest[ i ] = buffer[ offset ++ ];
  18634. }
  18635. this.targetObject.needsUpdate = true;
  18636. }
  18637. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18638. const dest = this.resolvedProperty;
  18639. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18640. dest[ i ] = buffer[ offset ++ ];
  18641. }
  18642. this.targetObject.matrixWorldNeedsUpdate = true;
  18643. }
  18644. // ArrayElement
  18645. _setValue_arrayElement( buffer, offset ) {
  18646. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18647. }
  18648. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  18649. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18650. this.targetObject.needsUpdate = true;
  18651. }
  18652. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18653. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18654. this.targetObject.matrixWorldNeedsUpdate = true;
  18655. }
  18656. // HasToFromArray
  18657. _setValue_fromArray( buffer, offset ) {
  18658. this.resolvedProperty.fromArray( buffer, offset );
  18659. }
  18660. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  18661. this.resolvedProperty.fromArray( buffer, offset );
  18662. this.targetObject.needsUpdate = true;
  18663. }
  18664. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18665. this.resolvedProperty.fromArray( buffer, offset );
  18666. this.targetObject.matrixWorldNeedsUpdate = true;
  18667. }
  18668. _getValue_unbound( targetArray, offset ) {
  18669. this.bind();
  18670. this.getValue( targetArray, offset );
  18671. }
  18672. _setValue_unbound( sourceArray, offset ) {
  18673. this.bind();
  18674. this.setValue( sourceArray, offset );
  18675. }
  18676. // create getter / setter pair for a property in the scene graph
  18677. bind() {
  18678. let targetObject = this.node;
  18679. const parsedPath = this.parsedPath;
  18680. const objectName = parsedPath.objectName;
  18681. const propertyName = parsedPath.propertyName;
  18682. let propertyIndex = parsedPath.propertyIndex;
  18683. if ( ! targetObject ) {
  18684. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  18685. this.node = targetObject;
  18686. }
  18687. // set fail state so we can just 'return' on error
  18688. this.getValue = this._getValue_unavailable;
  18689. this.setValue = this._setValue_unavailable;
  18690. // ensure there is a value node
  18691. if ( ! targetObject ) {
  18692. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  18693. return;
  18694. }
  18695. if ( objectName ) {
  18696. let objectIndex = parsedPath.objectIndex;
  18697. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  18698. switch ( objectName ) {
  18699. case 'materials':
  18700. if ( ! targetObject.material ) {
  18701. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  18702. return;
  18703. }
  18704. if ( ! targetObject.material.materials ) {
  18705. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  18706. return;
  18707. }
  18708. targetObject = targetObject.material.materials;
  18709. break;
  18710. case 'bones':
  18711. if ( ! targetObject.skeleton ) {
  18712. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  18713. return;
  18714. }
  18715. // potential future optimization: skip this if propertyIndex is already an integer
  18716. // and convert the integer string to a true integer.
  18717. targetObject = targetObject.skeleton.bones;
  18718. // support resolving morphTarget names into indices.
  18719. for ( let i = 0; i < targetObject.length; i ++ ) {
  18720. if ( targetObject[ i ].name === objectIndex ) {
  18721. objectIndex = i;
  18722. break;
  18723. }
  18724. }
  18725. break;
  18726. case 'map':
  18727. if ( 'map' in targetObject ) {
  18728. targetObject = targetObject.map;
  18729. break;
  18730. }
  18731. if ( ! targetObject.material ) {
  18732. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  18733. return;
  18734. }
  18735. if ( ! targetObject.material.map ) {
  18736. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  18737. return;
  18738. }
  18739. targetObject = targetObject.material.map;
  18740. break;
  18741. default:
  18742. if ( targetObject[ objectName ] === undefined ) {
  18743. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  18744. return;
  18745. }
  18746. targetObject = targetObject[ objectName ];
  18747. }
  18748. if ( objectIndex !== undefined ) {
  18749. if ( targetObject[ objectIndex ] === undefined ) {
  18750. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  18751. return;
  18752. }
  18753. targetObject = targetObject[ objectIndex ];
  18754. }
  18755. }
  18756. // resolve property
  18757. const nodeProperty = targetObject[ propertyName ];
  18758. if ( nodeProperty === undefined ) {
  18759. const nodeName = parsedPath.nodeName;
  18760. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  18761. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  18762. return;
  18763. }
  18764. // determine versioning scheme
  18765. let versioning = this.Versioning.None;
  18766. this.targetObject = targetObject;
  18767. if ( targetObject.needsUpdate !== undefined ) { // material
  18768. versioning = this.Versioning.NeedsUpdate;
  18769. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  18770. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  18771. }
  18772. // determine how the property gets bound
  18773. let bindingType = this.BindingType.Direct;
  18774. if ( propertyIndex !== undefined ) {
  18775. // access a sub element of the property array (only primitives are supported right now)
  18776. if ( propertyName === 'morphTargetInfluences' ) {
  18777. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  18778. // support resolving morphTarget names into indices.
  18779. if ( ! targetObject.geometry ) {
  18780. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  18781. return;
  18782. }
  18783. if ( ! targetObject.geometry.morphAttributes ) {
  18784. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  18785. return;
  18786. }
  18787. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  18788. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  18789. }
  18790. }
  18791. bindingType = this.BindingType.ArrayElement;
  18792. this.resolvedProperty = nodeProperty;
  18793. this.propertyIndex = propertyIndex;
  18794. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  18795. // must use copy for Object3D.Euler/Quaternion
  18796. bindingType = this.BindingType.HasFromToArray;
  18797. this.resolvedProperty = nodeProperty;
  18798. } else if ( Array.isArray( nodeProperty ) ) {
  18799. bindingType = this.BindingType.EntireArray;
  18800. this.resolvedProperty = nodeProperty;
  18801. } else {
  18802. this.propertyName = propertyName;
  18803. }
  18804. // select getter / setter
  18805. this.getValue = this.GetterByBindingType[ bindingType ];
  18806. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  18807. }
  18808. unbind() {
  18809. this.node = null;
  18810. // back to the prototype version of getValue / setValue
  18811. // note: avoiding to mutate the shape of 'this' via 'delete'
  18812. this.getValue = this._getValue_unbound;
  18813. this.setValue = this._setValue_unbound;
  18814. }
  18815. }
  18816. PropertyBinding.Composite = Composite;
  18817. PropertyBinding.prototype.BindingType = {
  18818. Direct: 0,
  18819. EntireArray: 1,
  18820. ArrayElement: 2,
  18821. HasFromToArray: 3
  18822. };
  18823. PropertyBinding.prototype.Versioning = {
  18824. None: 0,
  18825. NeedsUpdate: 1,
  18826. MatrixWorldNeedsUpdate: 2
  18827. };
  18828. PropertyBinding.prototype.GetterByBindingType = [
  18829. PropertyBinding.prototype._getValue_direct,
  18830. PropertyBinding.prototype._getValue_array,
  18831. PropertyBinding.prototype._getValue_arrayElement,
  18832. PropertyBinding.prototype._getValue_toArray,
  18833. ];
  18834. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  18835. [
  18836. // Direct
  18837. PropertyBinding.prototype._setValue_direct,
  18838. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  18839. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  18840. ], [
  18841. // EntireArray
  18842. PropertyBinding.prototype._setValue_array,
  18843. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  18844. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  18845. ], [
  18846. // ArrayElement
  18847. PropertyBinding.prototype._setValue_arrayElement,
  18848. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  18849. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  18850. ], [
  18851. // HasToFromArray
  18852. PropertyBinding.prototype._setValue_fromArray,
  18853. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  18854. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  18855. ]
  18856. ];
  18857. /**
  18858. *
  18859. * A group of objects that receives a shared animation state.
  18860. *
  18861. * Usage:
  18862. *
  18863. * - Add objects you would otherwise pass as 'root' to the
  18864. * constructor or the .clipAction method of AnimationMixer.
  18865. *
  18866. * - Instead pass this object as 'root'.
  18867. *
  18868. * - You can also add and remove objects later when the mixer
  18869. * is running.
  18870. *
  18871. * Note:
  18872. *
  18873. * Objects of this class appear as one object to the mixer,
  18874. * so cache control of the individual objects must be done
  18875. * on the group.
  18876. *
  18877. * Limitation:
  18878. *
  18879. * - The animated properties must be compatible among the
  18880. * all objects in the group.
  18881. *
  18882. * - A single property can either be controlled through a
  18883. * target group or directly, but not both.
  18884. */
  18885. class AnimationObjectGroup {
  18886. constructor() {
  18887. this.isAnimationObjectGroup = true;
  18888. this.uuid = generateUUID();
  18889. // cached objects followed by the active ones
  18890. this._objects = Array.prototype.slice.call( arguments );
  18891. this.nCachedObjects_ = 0; // threshold
  18892. // note: read by PropertyBinding.Composite
  18893. const indices = {};
  18894. this._indicesByUUID = indices; // for bookkeeping
  18895. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18896. indices[ arguments[ i ].uuid ] = i;
  18897. }
  18898. this._paths = []; // inside: string
  18899. this._parsedPaths = []; // inside: { we don't care, here }
  18900. this._bindings = []; // inside: Array< PropertyBinding >
  18901. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  18902. const scope = this;
  18903. this.stats = {
  18904. objects: {
  18905. get total() {
  18906. return scope._objects.length;
  18907. },
  18908. get inUse() {
  18909. return this.total - scope.nCachedObjects_;
  18910. }
  18911. },
  18912. get bindingsPerObject() {
  18913. return scope._bindings.length;
  18914. }
  18915. };
  18916. }
  18917. add() {
  18918. const objects = this._objects,
  18919. indicesByUUID = this._indicesByUUID,
  18920. paths = this._paths,
  18921. parsedPaths = this._parsedPaths,
  18922. bindings = this._bindings,
  18923. nBindings = bindings.length;
  18924. let knownObject = undefined,
  18925. nObjects = objects.length,
  18926. nCachedObjects = this.nCachedObjects_;
  18927. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18928. const object = arguments[ i ],
  18929. uuid = object.uuid;
  18930. let index = indicesByUUID[ uuid ];
  18931. if ( index === undefined ) {
  18932. // unknown object -> add it to the ACTIVE region
  18933. index = nObjects ++;
  18934. indicesByUUID[ uuid ] = index;
  18935. objects.push( object );
  18936. // accounting is done, now do the same for all bindings
  18937. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  18938. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  18939. }
  18940. } else if ( index < nCachedObjects ) {
  18941. knownObject = objects[ index ];
  18942. // move existing object to the ACTIVE region
  18943. const firstActiveIndex = -- nCachedObjects,
  18944. lastCachedObject = objects[ firstActiveIndex ];
  18945. indicesByUUID[ lastCachedObject.uuid ] = index;
  18946. objects[ index ] = lastCachedObject;
  18947. indicesByUUID[ uuid ] = firstActiveIndex;
  18948. objects[ firstActiveIndex ] = object;
  18949. // accounting is done, now do the same for all bindings
  18950. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  18951. const bindingsForPath = bindings[ j ],
  18952. lastCached = bindingsForPath[ firstActiveIndex ];
  18953. let binding = bindingsForPath[ index ];
  18954. bindingsForPath[ index ] = lastCached;
  18955. if ( binding === undefined ) {
  18956. // since we do not bother to create new bindings
  18957. // for objects that are cached, the binding may
  18958. // or may not exist
  18959. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  18960. }
  18961. bindingsForPath[ firstActiveIndex ] = binding;
  18962. }
  18963. } else if ( objects[ index ] !== knownObject ) {
  18964. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  18965. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  18966. } // else the object is already where we want it to be
  18967. } // for arguments
  18968. this.nCachedObjects_ = nCachedObjects;
  18969. }
  18970. remove() {
  18971. const objects = this._objects,
  18972. indicesByUUID = this._indicesByUUID,
  18973. bindings = this._bindings,
  18974. nBindings = bindings.length;
  18975. let nCachedObjects = this.nCachedObjects_;
  18976. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18977. const object = arguments[ i ],
  18978. uuid = object.uuid,
  18979. index = indicesByUUID[ uuid ];
  18980. if ( index !== undefined && index >= nCachedObjects ) {
  18981. // move existing object into the CACHED region
  18982. const lastCachedIndex = nCachedObjects ++,
  18983. firstActiveObject = objects[ lastCachedIndex ];
  18984. indicesByUUID[ firstActiveObject.uuid ] = index;
  18985. objects[ index ] = firstActiveObject;
  18986. indicesByUUID[ uuid ] = lastCachedIndex;
  18987. objects[ lastCachedIndex ] = object;
  18988. // accounting is done, now do the same for all bindings
  18989. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  18990. const bindingsForPath = bindings[ j ],
  18991. firstActive = bindingsForPath[ lastCachedIndex ],
  18992. binding = bindingsForPath[ index ];
  18993. bindingsForPath[ index ] = firstActive;
  18994. bindingsForPath[ lastCachedIndex ] = binding;
  18995. }
  18996. }
  18997. } // for arguments
  18998. this.nCachedObjects_ = nCachedObjects;
  18999. }
  19000. // remove & forget
  19001. uncache() {
  19002. const objects = this._objects,
  19003. indicesByUUID = this._indicesByUUID,
  19004. bindings = this._bindings,
  19005. nBindings = bindings.length;
  19006. let nCachedObjects = this.nCachedObjects_,
  19007. nObjects = objects.length;
  19008. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19009. const object = arguments[ i ],
  19010. uuid = object.uuid,
  19011. index = indicesByUUID[ uuid ];
  19012. if ( index !== undefined ) {
  19013. delete indicesByUUID[ uuid ];
  19014. if ( index < nCachedObjects ) {
  19015. // object is cached, shrink the CACHED region
  19016. const firstActiveIndex = -- nCachedObjects,
  19017. lastCachedObject = objects[ firstActiveIndex ],
  19018. lastIndex = -- nObjects,
  19019. lastObject = objects[ lastIndex ];
  19020. // last cached object takes this object's place
  19021. indicesByUUID[ lastCachedObject.uuid ] = index;
  19022. objects[ index ] = lastCachedObject;
  19023. // last object goes to the activated slot and pop
  19024. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  19025. objects[ firstActiveIndex ] = lastObject;
  19026. objects.pop();
  19027. // accounting is done, now do the same for all bindings
  19028. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19029. const bindingsForPath = bindings[ j ],
  19030. lastCached = bindingsForPath[ firstActiveIndex ],
  19031. last = bindingsForPath[ lastIndex ];
  19032. bindingsForPath[ index ] = lastCached;
  19033. bindingsForPath[ firstActiveIndex ] = last;
  19034. bindingsForPath.pop();
  19035. }
  19036. } else {
  19037. // object is active, just swap with the last and pop
  19038. const lastIndex = -- nObjects,
  19039. lastObject = objects[ lastIndex ];
  19040. if ( lastIndex > 0 ) {
  19041. indicesByUUID[ lastObject.uuid ] = index;
  19042. }
  19043. objects[ index ] = lastObject;
  19044. objects.pop();
  19045. // accounting is done, now do the same for all bindings
  19046. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19047. const bindingsForPath = bindings[ j ];
  19048. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  19049. bindingsForPath.pop();
  19050. }
  19051. } // cached or active
  19052. } // if object is known
  19053. } // for arguments
  19054. this.nCachedObjects_ = nCachedObjects;
  19055. }
  19056. // Internal interface used by befriended PropertyBinding.Composite:
  19057. subscribe_( path, parsedPath ) {
  19058. // returns an array of bindings for the given path that is changed
  19059. // according to the contained objects in the group
  19060. const indicesByPath = this._bindingsIndicesByPath;
  19061. let index = indicesByPath[ path ];
  19062. const bindings = this._bindings;
  19063. if ( index !== undefined ) return bindings[ index ];
  19064. const paths = this._paths,
  19065. parsedPaths = this._parsedPaths,
  19066. objects = this._objects,
  19067. nObjects = objects.length,
  19068. nCachedObjects = this.nCachedObjects_,
  19069. bindingsForPath = new Array( nObjects );
  19070. index = bindings.length;
  19071. indicesByPath[ path ] = index;
  19072. paths.push( path );
  19073. parsedPaths.push( parsedPath );
  19074. bindings.push( bindingsForPath );
  19075. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  19076. const object = objects[ i ];
  19077. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  19078. }
  19079. return bindingsForPath;
  19080. }
  19081. unsubscribe_( path ) {
  19082. // tells the group to forget about a property path and no longer
  19083. // update the array previously obtained with 'subscribe_'
  19084. const indicesByPath = this._bindingsIndicesByPath,
  19085. index = indicesByPath[ path ];
  19086. if ( index !== undefined ) {
  19087. const paths = this._paths,
  19088. parsedPaths = this._parsedPaths,
  19089. bindings = this._bindings,
  19090. lastBindingsIndex = bindings.length - 1,
  19091. lastBindings = bindings[ lastBindingsIndex ],
  19092. lastBindingsPath = path[ lastBindingsIndex ];
  19093. indicesByPath[ lastBindingsPath ] = index;
  19094. bindings[ index ] = lastBindings;
  19095. bindings.pop();
  19096. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  19097. parsedPaths.pop();
  19098. paths[ index ] = paths[ lastBindingsIndex ];
  19099. paths.pop();
  19100. }
  19101. }
  19102. }
  19103. class AnimationAction {
  19104. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  19105. this._mixer = mixer;
  19106. this._clip = clip;
  19107. this._localRoot = localRoot;
  19108. this.blendMode = blendMode;
  19109. const tracks = clip.tracks,
  19110. nTracks = tracks.length,
  19111. interpolants = new Array( nTracks );
  19112. const interpolantSettings = {
  19113. endingStart: ZeroCurvatureEnding,
  19114. endingEnd: ZeroCurvatureEnding
  19115. };
  19116. for ( let i = 0; i !== nTracks; ++ i ) {
  19117. const interpolant = tracks[ i ].createInterpolant( null );
  19118. interpolants[ i ] = interpolant;
  19119. interpolant.settings = interpolantSettings;
  19120. }
  19121. this._interpolantSettings = interpolantSettings;
  19122. this._interpolants = interpolants; // bound by the mixer
  19123. // inside: PropertyMixer (managed by the mixer)
  19124. this._propertyBindings = new Array( nTracks );
  19125. this._cacheIndex = null; // for the memory manager
  19126. this._byClipCacheIndex = null; // for the memory manager
  19127. this._timeScaleInterpolant = null;
  19128. this._weightInterpolant = null;
  19129. this.loop = LoopRepeat;
  19130. this._loopCount = - 1;
  19131. // global mixer time when the action is to be started
  19132. // it's set back to 'null' upon start of the action
  19133. this._startTime = null;
  19134. // scaled local time of the action
  19135. // gets clamped or wrapped to 0..clip.duration according to loop
  19136. this.time = 0;
  19137. this.timeScale = 1;
  19138. this._effectiveTimeScale = 1;
  19139. this.weight = 1;
  19140. this._effectiveWeight = 1;
  19141. this.repetitions = Infinity; // no. of repetitions when looping
  19142. this.paused = false; // true -> zero effective time scale
  19143. this.enabled = true; // false -> zero effective weight
  19144. this.clampWhenFinished = false;// keep feeding the last frame?
  19145. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  19146. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  19147. }
  19148. // State & Scheduling
  19149. play() {
  19150. this._mixer._activateAction( this );
  19151. return this;
  19152. }
  19153. stop() {
  19154. this._mixer._deactivateAction( this );
  19155. return this.reset();
  19156. }
  19157. reset() {
  19158. this.paused = false;
  19159. this.enabled = true;
  19160. this.time = 0; // restart clip
  19161. this._loopCount = - 1;// forget previous loops
  19162. this._startTime = null;// forget scheduling
  19163. return this.stopFading().stopWarping();
  19164. }
  19165. isRunning() {
  19166. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  19167. this._startTime === null && this._mixer._isActiveAction( this );
  19168. }
  19169. // return true when play has been called
  19170. isScheduled() {
  19171. return this._mixer._isActiveAction( this );
  19172. }
  19173. startAt( time ) {
  19174. this._startTime = time;
  19175. return this;
  19176. }
  19177. setLoop( mode, repetitions ) {
  19178. this.loop = mode;
  19179. this.repetitions = repetitions;
  19180. return this;
  19181. }
  19182. // Weight
  19183. // set the weight stopping any scheduled fading
  19184. // although .enabled = false yields an effective weight of zero, this
  19185. // method does *not* change .enabled, because it would be confusing
  19186. setEffectiveWeight( weight ) {
  19187. this.weight = weight;
  19188. // note: same logic as when updated at runtime
  19189. this._effectiveWeight = this.enabled ? weight : 0;
  19190. return this.stopFading();
  19191. }
  19192. // return the weight considering fading and .enabled
  19193. getEffectiveWeight() {
  19194. return this._effectiveWeight;
  19195. }
  19196. fadeIn( duration ) {
  19197. return this._scheduleFading( duration, 0, 1 );
  19198. }
  19199. fadeOut( duration ) {
  19200. return this._scheduleFading( duration, 1, 0 );
  19201. }
  19202. crossFadeFrom( fadeOutAction, duration, warp ) {
  19203. fadeOutAction.fadeOut( duration );
  19204. this.fadeIn( duration );
  19205. if ( warp ) {
  19206. const fadeInDuration = this._clip.duration,
  19207. fadeOutDuration = fadeOutAction._clip.duration,
  19208. startEndRatio = fadeOutDuration / fadeInDuration,
  19209. endStartRatio = fadeInDuration / fadeOutDuration;
  19210. fadeOutAction.warp( 1.0, startEndRatio, duration );
  19211. this.warp( endStartRatio, 1.0, duration );
  19212. }
  19213. return this;
  19214. }
  19215. crossFadeTo( fadeInAction, duration, warp ) {
  19216. return fadeInAction.crossFadeFrom( this, duration, warp );
  19217. }
  19218. stopFading() {
  19219. const weightInterpolant = this._weightInterpolant;
  19220. if ( weightInterpolant !== null ) {
  19221. this._weightInterpolant = null;
  19222. this._mixer._takeBackControlInterpolant( weightInterpolant );
  19223. }
  19224. return this;
  19225. }
  19226. // Time Scale Control
  19227. // set the time scale stopping any scheduled warping
  19228. // although .paused = true yields an effective time scale of zero, this
  19229. // method does *not* change .paused, because it would be confusing
  19230. setEffectiveTimeScale( timeScale ) {
  19231. this.timeScale = timeScale;
  19232. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  19233. return this.stopWarping();
  19234. }
  19235. // return the time scale considering warping and .paused
  19236. getEffectiveTimeScale() {
  19237. return this._effectiveTimeScale;
  19238. }
  19239. setDuration( duration ) {
  19240. this.timeScale = this._clip.duration / duration;
  19241. return this.stopWarping();
  19242. }
  19243. syncWith( action ) {
  19244. this.time = action.time;
  19245. this.timeScale = action.timeScale;
  19246. return this.stopWarping();
  19247. }
  19248. halt( duration ) {
  19249. return this.warp( this._effectiveTimeScale, 0, duration );
  19250. }
  19251. warp( startTimeScale, endTimeScale, duration ) {
  19252. const mixer = this._mixer,
  19253. now = mixer.time,
  19254. timeScale = this.timeScale;
  19255. let interpolant = this._timeScaleInterpolant;
  19256. if ( interpolant === null ) {
  19257. interpolant = mixer._lendControlInterpolant();
  19258. this._timeScaleInterpolant = interpolant;
  19259. }
  19260. const times = interpolant.parameterPositions,
  19261. values = interpolant.sampleValues;
  19262. times[ 0 ] = now;
  19263. times[ 1 ] = now + duration;
  19264. values[ 0 ] = startTimeScale / timeScale;
  19265. values[ 1 ] = endTimeScale / timeScale;
  19266. return this;
  19267. }
  19268. stopWarping() {
  19269. const timeScaleInterpolant = this._timeScaleInterpolant;
  19270. if ( timeScaleInterpolant !== null ) {
  19271. this._timeScaleInterpolant = null;
  19272. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  19273. }
  19274. return this;
  19275. }
  19276. // Object Accessors
  19277. getMixer() {
  19278. return this._mixer;
  19279. }
  19280. getClip() {
  19281. return this._clip;
  19282. }
  19283. getRoot() {
  19284. return this._localRoot || this._mixer._root;
  19285. }
  19286. // Interna
  19287. _update( time, deltaTime, timeDirection, accuIndex ) {
  19288. // called by the mixer
  19289. if ( ! this.enabled ) {
  19290. // call ._updateWeight() to update ._effectiveWeight
  19291. this._updateWeight( time );
  19292. return;
  19293. }
  19294. const startTime = this._startTime;
  19295. if ( startTime !== null ) {
  19296. // check for scheduled start of action
  19297. const timeRunning = ( time - startTime ) * timeDirection;
  19298. if ( timeRunning < 0 || timeDirection === 0 ) {
  19299. deltaTime = 0;
  19300. } else {
  19301. this._startTime = null; // unschedule
  19302. deltaTime = timeDirection * timeRunning;
  19303. }
  19304. }
  19305. // apply time scale and advance time
  19306. deltaTime *= this._updateTimeScale( time );
  19307. const clipTime = this._updateTime( deltaTime );
  19308. // note: _updateTime may disable the action resulting in
  19309. // an effective weight of 0
  19310. const weight = this._updateWeight( time );
  19311. if ( weight > 0 ) {
  19312. const interpolants = this._interpolants;
  19313. const propertyMixers = this._propertyBindings;
  19314. switch ( this.blendMode ) {
  19315. case AdditiveAnimationBlendMode:
  19316. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19317. interpolants[ j ].evaluate( clipTime );
  19318. propertyMixers[ j ].accumulateAdditive( weight );
  19319. }
  19320. break;
  19321. case NormalAnimationBlendMode:
  19322. default:
  19323. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19324. interpolants[ j ].evaluate( clipTime );
  19325. propertyMixers[ j ].accumulate( accuIndex, weight );
  19326. }
  19327. }
  19328. }
  19329. }
  19330. _updateWeight( time ) {
  19331. let weight = 0;
  19332. if ( this.enabled ) {
  19333. weight = this.weight;
  19334. const interpolant = this._weightInterpolant;
  19335. if ( interpolant !== null ) {
  19336. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19337. weight *= interpolantValue;
  19338. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19339. this.stopFading();
  19340. if ( interpolantValue === 0 ) {
  19341. // faded out, disable
  19342. this.enabled = false;
  19343. }
  19344. }
  19345. }
  19346. }
  19347. this._effectiveWeight = weight;
  19348. return weight;
  19349. }
  19350. _updateTimeScale( time ) {
  19351. let timeScale = 0;
  19352. if ( ! this.paused ) {
  19353. timeScale = this.timeScale;
  19354. const interpolant = this._timeScaleInterpolant;
  19355. if ( interpolant !== null ) {
  19356. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19357. timeScale *= interpolantValue;
  19358. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19359. this.stopWarping();
  19360. if ( timeScale === 0 ) {
  19361. // motion has halted, pause
  19362. this.paused = true;
  19363. } else {
  19364. // warp done - apply final time scale
  19365. this.timeScale = timeScale;
  19366. }
  19367. }
  19368. }
  19369. }
  19370. this._effectiveTimeScale = timeScale;
  19371. return timeScale;
  19372. }
  19373. _updateTime( deltaTime ) {
  19374. const duration = this._clip.duration;
  19375. const loop = this.loop;
  19376. let time = this.time + deltaTime;
  19377. let loopCount = this._loopCount;
  19378. const pingPong = ( loop === LoopPingPong );
  19379. if ( deltaTime === 0 ) {
  19380. if ( loopCount === - 1 ) return time;
  19381. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  19382. }
  19383. if ( loop === LoopOnce ) {
  19384. if ( loopCount === - 1 ) {
  19385. // just started
  19386. this._loopCount = 0;
  19387. this._setEndings( true, true, false );
  19388. }
  19389. handle_stop: {
  19390. if ( time >= duration ) {
  19391. time = duration;
  19392. } else if ( time < 0 ) {
  19393. time = 0;
  19394. } else {
  19395. this.time = time;
  19396. break handle_stop;
  19397. }
  19398. if ( this.clampWhenFinished ) this.paused = true;
  19399. else this.enabled = false;
  19400. this.time = time;
  19401. this._mixer.dispatchEvent( {
  19402. type: 'finished', action: this,
  19403. direction: deltaTime < 0 ? - 1 : 1
  19404. } );
  19405. }
  19406. } else { // repetitive Repeat or PingPong
  19407. if ( loopCount === - 1 ) {
  19408. // just started
  19409. if ( deltaTime >= 0 ) {
  19410. loopCount = 0;
  19411. this._setEndings( true, this.repetitions === 0, pingPong );
  19412. } else {
  19413. // when looping in reverse direction, the initial
  19414. // transition through zero counts as a repetition,
  19415. // so leave loopCount at -1
  19416. this._setEndings( this.repetitions === 0, true, pingPong );
  19417. }
  19418. }
  19419. if ( time >= duration || time < 0 ) {
  19420. // wrap around
  19421. const loopDelta = Math.floor( time / duration ); // signed
  19422. time -= duration * loopDelta;
  19423. loopCount += Math.abs( loopDelta );
  19424. const pending = this.repetitions - loopCount;
  19425. if ( pending <= 0 ) {
  19426. // have to stop (switch state, clamp time, fire event)
  19427. if ( this.clampWhenFinished ) this.paused = true;
  19428. else this.enabled = false;
  19429. time = deltaTime > 0 ? duration : 0;
  19430. this.time = time;
  19431. this._mixer.dispatchEvent( {
  19432. type: 'finished', action: this,
  19433. direction: deltaTime > 0 ? 1 : - 1
  19434. } );
  19435. } else {
  19436. // keep running
  19437. if ( pending === 1 ) {
  19438. // entering the last round
  19439. const atStart = deltaTime < 0;
  19440. this._setEndings( atStart, ! atStart, pingPong );
  19441. } else {
  19442. this._setEndings( false, false, pingPong );
  19443. }
  19444. this._loopCount = loopCount;
  19445. this.time = time;
  19446. this._mixer.dispatchEvent( {
  19447. type: 'loop', action: this, loopDelta: loopDelta
  19448. } );
  19449. }
  19450. } else {
  19451. this.time = time;
  19452. }
  19453. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  19454. // invert time for the "pong round"
  19455. return duration - time;
  19456. }
  19457. }
  19458. return time;
  19459. }
  19460. _setEndings( atStart, atEnd, pingPong ) {
  19461. const settings = this._interpolantSettings;
  19462. if ( pingPong ) {
  19463. settings.endingStart = ZeroSlopeEnding;
  19464. settings.endingEnd = ZeroSlopeEnding;
  19465. } else {
  19466. // assuming for LoopOnce atStart == atEnd == true
  19467. if ( atStart ) {
  19468. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19469. } else {
  19470. settings.endingStart = WrapAroundEnding;
  19471. }
  19472. if ( atEnd ) {
  19473. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19474. } else {
  19475. settings.endingEnd = WrapAroundEnding;
  19476. }
  19477. }
  19478. }
  19479. _scheduleFading( duration, weightNow, weightThen ) {
  19480. const mixer = this._mixer, now = mixer.time;
  19481. let interpolant = this._weightInterpolant;
  19482. if ( interpolant === null ) {
  19483. interpolant = mixer._lendControlInterpolant();
  19484. this._weightInterpolant = interpolant;
  19485. }
  19486. const times = interpolant.parameterPositions,
  19487. values = interpolant.sampleValues;
  19488. times[ 0 ] = now;
  19489. values[ 0 ] = weightNow;
  19490. times[ 1 ] = now + duration;
  19491. values[ 1 ] = weightThen;
  19492. return this;
  19493. }
  19494. }
  19495. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  19496. class AnimationMixer extends EventDispatcher {
  19497. constructor( root ) {
  19498. super();
  19499. this._root = root;
  19500. this._initMemoryManager();
  19501. this._accuIndex = 0;
  19502. this.time = 0;
  19503. this.timeScale = 1.0;
  19504. }
  19505. _bindAction( action, prototypeAction ) {
  19506. const root = action._localRoot || this._root,
  19507. tracks = action._clip.tracks,
  19508. nTracks = tracks.length,
  19509. bindings = action._propertyBindings,
  19510. interpolants = action._interpolants,
  19511. rootUuid = root.uuid,
  19512. bindingsByRoot = this._bindingsByRootAndName;
  19513. let bindingsByName = bindingsByRoot[ rootUuid ];
  19514. if ( bindingsByName === undefined ) {
  19515. bindingsByName = {};
  19516. bindingsByRoot[ rootUuid ] = bindingsByName;
  19517. }
  19518. for ( let i = 0; i !== nTracks; ++ i ) {
  19519. const track = tracks[ i ],
  19520. trackName = track.name;
  19521. let binding = bindingsByName[ trackName ];
  19522. if ( binding !== undefined ) {
  19523. ++ binding.referenceCount;
  19524. bindings[ i ] = binding;
  19525. } else {
  19526. binding = bindings[ i ];
  19527. if ( binding !== undefined ) {
  19528. // existing binding, make sure the cache knows
  19529. if ( binding._cacheIndex === null ) {
  19530. ++ binding.referenceCount;
  19531. this._addInactiveBinding( binding, rootUuid, trackName );
  19532. }
  19533. continue;
  19534. }
  19535. const path = prototypeAction && prototypeAction.
  19536. _propertyBindings[ i ].binding.parsedPath;
  19537. binding = new PropertyMixer(
  19538. PropertyBinding.create( root, trackName, path ),
  19539. track.ValueTypeName, track.getValueSize() );
  19540. ++ binding.referenceCount;
  19541. this._addInactiveBinding( binding, rootUuid, trackName );
  19542. bindings[ i ] = binding;
  19543. }
  19544. interpolants[ i ].resultBuffer = binding.buffer;
  19545. }
  19546. }
  19547. _activateAction( action ) {
  19548. if ( ! this._isActiveAction( action ) ) {
  19549. if ( action._cacheIndex === null ) {
  19550. // this action has been forgotten by the cache, but the user
  19551. // appears to be still using it -> rebind
  19552. const rootUuid = ( action._localRoot || this._root ).uuid,
  19553. clipUuid = action._clip.uuid,
  19554. actionsForClip = this._actionsByClip[ clipUuid ];
  19555. this._bindAction( action,
  19556. actionsForClip && actionsForClip.knownActions[ 0 ] );
  19557. this._addInactiveAction( action, clipUuid, rootUuid );
  19558. }
  19559. const bindings = action._propertyBindings;
  19560. // increment reference counts / sort out state
  19561. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19562. const binding = bindings[ i ];
  19563. if ( binding.useCount ++ === 0 ) {
  19564. this._lendBinding( binding );
  19565. binding.saveOriginalState();
  19566. }
  19567. }
  19568. this._lendAction( action );
  19569. }
  19570. }
  19571. _deactivateAction( action ) {
  19572. if ( this._isActiveAction( action ) ) {
  19573. const bindings = action._propertyBindings;
  19574. // decrement reference counts / sort out state
  19575. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19576. const binding = bindings[ i ];
  19577. if ( -- binding.useCount === 0 ) {
  19578. binding.restoreOriginalState();
  19579. this._takeBackBinding( binding );
  19580. }
  19581. }
  19582. this._takeBackAction( action );
  19583. }
  19584. }
  19585. // Memory manager
  19586. _initMemoryManager() {
  19587. this._actions = []; // 'nActiveActions' followed by inactive ones
  19588. this._nActiveActions = 0;
  19589. this._actionsByClip = {};
  19590. // inside:
  19591. // {
  19592. // knownActions: Array< AnimationAction > - used as prototypes
  19593. // actionByRoot: AnimationAction - lookup
  19594. // }
  19595. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  19596. this._nActiveBindings = 0;
  19597. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  19598. this._controlInterpolants = []; // same game as above
  19599. this._nActiveControlInterpolants = 0;
  19600. const scope = this;
  19601. this.stats = {
  19602. actions: {
  19603. get total() {
  19604. return scope._actions.length;
  19605. },
  19606. get inUse() {
  19607. return scope._nActiveActions;
  19608. }
  19609. },
  19610. bindings: {
  19611. get total() {
  19612. return scope._bindings.length;
  19613. },
  19614. get inUse() {
  19615. return scope._nActiveBindings;
  19616. }
  19617. },
  19618. controlInterpolants: {
  19619. get total() {
  19620. return scope._controlInterpolants.length;
  19621. },
  19622. get inUse() {
  19623. return scope._nActiveControlInterpolants;
  19624. }
  19625. }
  19626. };
  19627. }
  19628. // Memory management for AnimationAction objects
  19629. _isActiveAction( action ) {
  19630. const index = action._cacheIndex;
  19631. return index !== null && index < this._nActiveActions;
  19632. }
  19633. _addInactiveAction( action, clipUuid, rootUuid ) {
  19634. const actions = this._actions,
  19635. actionsByClip = this._actionsByClip;
  19636. let actionsForClip = actionsByClip[ clipUuid ];
  19637. if ( actionsForClip === undefined ) {
  19638. actionsForClip = {
  19639. knownActions: [ action ],
  19640. actionByRoot: {}
  19641. };
  19642. action._byClipCacheIndex = 0;
  19643. actionsByClip[ clipUuid ] = actionsForClip;
  19644. } else {
  19645. const knownActions = actionsForClip.knownActions;
  19646. action._byClipCacheIndex = knownActions.length;
  19647. knownActions.push( action );
  19648. }
  19649. action._cacheIndex = actions.length;
  19650. actions.push( action );
  19651. actionsForClip.actionByRoot[ rootUuid ] = action;
  19652. }
  19653. _removeInactiveAction( action ) {
  19654. const actions = this._actions,
  19655. lastInactiveAction = actions[ actions.length - 1 ],
  19656. cacheIndex = action._cacheIndex;
  19657. lastInactiveAction._cacheIndex = cacheIndex;
  19658. actions[ cacheIndex ] = lastInactiveAction;
  19659. actions.pop();
  19660. action._cacheIndex = null;
  19661. const clipUuid = action._clip.uuid,
  19662. actionsByClip = this._actionsByClip,
  19663. actionsForClip = actionsByClip[ clipUuid ],
  19664. knownActionsForClip = actionsForClip.knownActions,
  19665. lastKnownAction =
  19666. knownActionsForClip[ knownActionsForClip.length - 1 ],
  19667. byClipCacheIndex = action._byClipCacheIndex;
  19668. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  19669. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  19670. knownActionsForClip.pop();
  19671. action._byClipCacheIndex = null;
  19672. const actionByRoot = actionsForClip.actionByRoot,
  19673. rootUuid = ( action._localRoot || this._root ).uuid;
  19674. delete actionByRoot[ rootUuid ];
  19675. if ( knownActionsForClip.length === 0 ) {
  19676. delete actionsByClip[ clipUuid ];
  19677. }
  19678. this._removeInactiveBindingsForAction( action );
  19679. }
  19680. _removeInactiveBindingsForAction( action ) {
  19681. const bindings = action._propertyBindings;
  19682. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19683. const binding = bindings[ i ];
  19684. if ( -- binding.referenceCount === 0 ) {
  19685. this._removeInactiveBinding( binding );
  19686. }
  19687. }
  19688. }
  19689. _lendAction( action ) {
  19690. // [ active actions | inactive actions ]
  19691. // [ active actions >| inactive actions ]
  19692. // s a
  19693. // <-swap->
  19694. // a s
  19695. const actions = this._actions,
  19696. prevIndex = action._cacheIndex,
  19697. lastActiveIndex = this._nActiveActions ++,
  19698. firstInactiveAction = actions[ lastActiveIndex ];
  19699. action._cacheIndex = lastActiveIndex;
  19700. actions[ lastActiveIndex ] = action;
  19701. firstInactiveAction._cacheIndex = prevIndex;
  19702. actions[ prevIndex ] = firstInactiveAction;
  19703. }
  19704. _takeBackAction( action ) {
  19705. // [ active actions | inactive actions ]
  19706. // [ active actions |< inactive actions ]
  19707. // a s
  19708. // <-swap->
  19709. // s a
  19710. const actions = this._actions,
  19711. prevIndex = action._cacheIndex,
  19712. firstInactiveIndex = -- this._nActiveActions,
  19713. lastActiveAction = actions[ firstInactiveIndex ];
  19714. action._cacheIndex = firstInactiveIndex;
  19715. actions[ firstInactiveIndex ] = action;
  19716. lastActiveAction._cacheIndex = prevIndex;
  19717. actions[ prevIndex ] = lastActiveAction;
  19718. }
  19719. // Memory management for PropertyMixer objects
  19720. _addInactiveBinding( binding, rootUuid, trackName ) {
  19721. const bindingsByRoot = this._bindingsByRootAndName,
  19722. bindings = this._bindings;
  19723. let bindingByName = bindingsByRoot[ rootUuid ];
  19724. if ( bindingByName === undefined ) {
  19725. bindingByName = {};
  19726. bindingsByRoot[ rootUuid ] = bindingByName;
  19727. }
  19728. bindingByName[ trackName ] = binding;
  19729. binding._cacheIndex = bindings.length;
  19730. bindings.push( binding );
  19731. }
  19732. _removeInactiveBinding( binding ) {
  19733. const bindings = this._bindings,
  19734. propBinding = binding.binding,
  19735. rootUuid = propBinding.rootNode.uuid,
  19736. trackName = propBinding.path,
  19737. bindingsByRoot = this._bindingsByRootAndName,
  19738. bindingByName = bindingsByRoot[ rootUuid ],
  19739. lastInactiveBinding = bindings[ bindings.length - 1 ],
  19740. cacheIndex = binding._cacheIndex;
  19741. lastInactiveBinding._cacheIndex = cacheIndex;
  19742. bindings[ cacheIndex ] = lastInactiveBinding;
  19743. bindings.pop();
  19744. delete bindingByName[ trackName ];
  19745. if ( Object.keys( bindingByName ).length === 0 ) {
  19746. delete bindingsByRoot[ rootUuid ];
  19747. }
  19748. }
  19749. _lendBinding( binding ) {
  19750. const bindings = this._bindings,
  19751. prevIndex = binding._cacheIndex,
  19752. lastActiveIndex = this._nActiveBindings ++,
  19753. firstInactiveBinding = bindings[ lastActiveIndex ];
  19754. binding._cacheIndex = lastActiveIndex;
  19755. bindings[ lastActiveIndex ] = binding;
  19756. firstInactiveBinding._cacheIndex = prevIndex;
  19757. bindings[ prevIndex ] = firstInactiveBinding;
  19758. }
  19759. _takeBackBinding( binding ) {
  19760. const bindings = this._bindings,
  19761. prevIndex = binding._cacheIndex,
  19762. firstInactiveIndex = -- this._nActiveBindings,
  19763. lastActiveBinding = bindings[ firstInactiveIndex ];
  19764. binding._cacheIndex = firstInactiveIndex;
  19765. bindings[ firstInactiveIndex ] = binding;
  19766. lastActiveBinding._cacheIndex = prevIndex;
  19767. bindings[ prevIndex ] = lastActiveBinding;
  19768. }
  19769. // Memory management of Interpolants for weight and time scale
  19770. _lendControlInterpolant() {
  19771. const interpolants = this._controlInterpolants,
  19772. lastActiveIndex = this._nActiveControlInterpolants ++;
  19773. let interpolant = interpolants[ lastActiveIndex ];
  19774. if ( interpolant === undefined ) {
  19775. interpolant = new LinearInterpolant(
  19776. new Float32Array( 2 ), new Float32Array( 2 ),
  19777. 1, _controlInterpolantsResultBuffer );
  19778. interpolant.__cacheIndex = lastActiveIndex;
  19779. interpolants[ lastActiveIndex ] = interpolant;
  19780. }
  19781. return interpolant;
  19782. }
  19783. _takeBackControlInterpolant( interpolant ) {
  19784. const interpolants = this._controlInterpolants,
  19785. prevIndex = interpolant.__cacheIndex,
  19786. firstInactiveIndex = -- this._nActiveControlInterpolants,
  19787. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  19788. interpolant.__cacheIndex = firstInactiveIndex;
  19789. interpolants[ firstInactiveIndex ] = interpolant;
  19790. lastActiveInterpolant.__cacheIndex = prevIndex;
  19791. interpolants[ prevIndex ] = lastActiveInterpolant;
  19792. }
  19793. // return an action for a clip optionally using a custom root target
  19794. // object (this method allocates a lot of dynamic memory in case a
  19795. // previously unknown clip/root combination is specified)
  19796. clipAction( clip, optionalRoot, blendMode ) {
  19797. const root = optionalRoot || this._root,
  19798. rootUuid = root.uuid;
  19799. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  19800. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  19801. const actionsForClip = this._actionsByClip[ clipUuid ];
  19802. let prototypeAction = null;
  19803. if ( blendMode === undefined ) {
  19804. if ( clipObject !== null ) {
  19805. blendMode = clipObject.blendMode;
  19806. } else {
  19807. blendMode = NormalAnimationBlendMode;
  19808. }
  19809. }
  19810. if ( actionsForClip !== undefined ) {
  19811. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  19812. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  19813. return existingAction;
  19814. }
  19815. // we know the clip, so we don't have to parse all
  19816. // the bindings again but can just copy
  19817. prototypeAction = actionsForClip.knownActions[ 0 ];
  19818. // also, take the clip from the prototype action
  19819. if ( clipObject === null )
  19820. clipObject = prototypeAction._clip;
  19821. }
  19822. // clip must be known when specified via string
  19823. if ( clipObject === null ) return null;
  19824. // allocate all resources required to run it
  19825. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  19826. this._bindAction( newAction, prototypeAction );
  19827. // and make the action known to the memory manager
  19828. this._addInactiveAction( newAction, clipUuid, rootUuid );
  19829. return newAction;
  19830. }
  19831. // get an existing action
  19832. existingAction( clip, optionalRoot ) {
  19833. const root = optionalRoot || this._root,
  19834. rootUuid = root.uuid,
  19835. clipObject = typeof clip === 'string' ?
  19836. AnimationClip.findByName( root, clip ) : clip,
  19837. clipUuid = clipObject ? clipObject.uuid : clip,
  19838. actionsForClip = this._actionsByClip[ clipUuid ];
  19839. if ( actionsForClip !== undefined ) {
  19840. return actionsForClip.actionByRoot[ rootUuid ] || null;
  19841. }
  19842. return null;
  19843. }
  19844. // deactivates all previously scheduled actions
  19845. stopAllAction() {
  19846. const actions = this._actions,
  19847. nActions = this._nActiveActions;
  19848. for ( let i = nActions - 1; i >= 0; -- i ) {
  19849. actions[ i ].stop();
  19850. }
  19851. return this;
  19852. }
  19853. // advance the time and update apply the animation
  19854. update( deltaTime ) {
  19855. deltaTime *= this.timeScale;
  19856. const actions = this._actions,
  19857. nActions = this._nActiveActions,
  19858. time = this.time += deltaTime,
  19859. timeDirection = Math.sign( deltaTime ),
  19860. accuIndex = this._accuIndex ^= 1;
  19861. // run active actions
  19862. for ( let i = 0; i !== nActions; ++ i ) {
  19863. const action = actions[ i ];
  19864. action._update( time, deltaTime, timeDirection, accuIndex );
  19865. }
  19866. // update scene graph
  19867. const bindings = this._bindings,
  19868. nBindings = this._nActiveBindings;
  19869. for ( let i = 0; i !== nBindings; ++ i ) {
  19870. bindings[ i ].apply( accuIndex );
  19871. }
  19872. return this;
  19873. }
  19874. // Allows you to seek to a specific time in an animation.
  19875. setTime( timeInSeconds ) {
  19876. this.time = 0; // Zero out time attribute for AnimationMixer object;
  19877. for ( let i = 0; i < this._actions.length; i ++ ) {
  19878. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  19879. }
  19880. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  19881. }
  19882. // return this mixer's root target object
  19883. getRoot() {
  19884. return this._root;
  19885. }
  19886. // free all resources specific to a particular clip
  19887. uncacheClip( clip ) {
  19888. const actions = this._actions,
  19889. clipUuid = clip.uuid,
  19890. actionsByClip = this._actionsByClip,
  19891. actionsForClip = actionsByClip[ clipUuid ];
  19892. if ( actionsForClip !== undefined ) {
  19893. // note: just calling _removeInactiveAction would mess up the
  19894. // iteration state and also require updating the state we can
  19895. // just throw away
  19896. const actionsToRemove = actionsForClip.knownActions;
  19897. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  19898. const action = actionsToRemove[ i ];
  19899. this._deactivateAction( action );
  19900. const cacheIndex = action._cacheIndex,
  19901. lastInactiveAction = actions[ actions.length - 1 ];
  19902. action._cacheIndex = null;
  19903. action._byClipCacheIndex = null;
  19904. lastInactiveAction._cacheIndex = cacheIndex;
  19905. actions[ cacheIndex ] = lastInactiveAction;
  19906. actions.pop();
  19907. this._removeInactiveBindingsForAction( action );
  19908. }
  19909. delete actionsByClip[ clipUuid ];
  19910. }
  19911. }
  19912. // free all resources specific to a particular root target object
  19913. uncacheRoot( root ) {
  19914. const rootUuid = root.uuid,
  19915. actionsByClip = this._actionsByClip;
  19916. for ( const clipUuid in actionsByClip ) {
  19917. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  19918. action = actionByRoot[ rootUuid ];
  19919. if ( action !== undefined ) {
  19920. this._deactivateAction( action );
  19921. this._removeInactiveAction( action );
  19922. }
  19923. }
  19924. const bindingsByRoot = this._bindingsByRootAndName,
  19925. bindingByName = bindingsByRoot[ rootUuid ];
  19926. if ( bindingByName !== undefined ) {
  19927. for ( const trackName in bindingByName ) {
  19928. const binding = bindingByName[ trackName ];
  19929. binding.restoreOriginalState();
  19930. this._removeInactiveBinding( binding );
  19931. }
  19932. }
  19933. }
  19934. // remove a targeted clip from the cache
  19935. uncacheAction( clip, optionalRoot ) {
  19936. const action = this.existingAction( clip, optionalRoot );
  19937. if ( action !== null ) {
  19938. this._deactivateAction( action );
  19939. this._removeInactiveAction( action );
  19940. }
  19941. }
  19942. }
  19943. let Uniform$1 = class Uniform {
  19944. constructor( value ) {
  19945. this.value = value;
  19946. }
  19947. clone() {
  19948. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  19949. }
  19950. };
  19951. let _id$5 = 0;
  19952. let UniformsGroup$1 = class UniformsGroup extends EventDispatcher {
  19953. constructor() {
  19954. super();
  19955. this.isUniformsGroup = true;
  19956. Object.defineProperty( this, 'id', { value: _id$5 ++ } );
  19957. this.name = '';
  19958. this.usage = StaticDrawUsage;
  19959. this.uniforms = [];
  19960. }
  19961. add( uniform ) {
  19962. this.uniforms.push( uniform );
  19963. return this;
  19964. }
  19965. remove( uniform ) {
  19966. const index = this.uniforms.indexOf( uniform );
  19967. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  19968. return this;
  19969. }
  19970. setName( name ) {
  19971. this.name = name;
  19972. return this;
  19973. }
  19974. setUsage( value ) {
  19975. this.usage = value;
  19976. return this;
  19977. }
  19978. dispose() {
  19979. this.dispatchEvent( { type: 'dispose' } );
  19980. return this;
  19981. }
  19982. copy( source ) {
  19983. this.name = source.name;
  19984. this.usage = source.usage;
  19985. const uniformsSource = source.uniforms;
  19986. this.uniforms.length = 0;
  19987. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  19988. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  19989. for ( let j = 0; j < uniforms.length; j ++ ) {
  19990. this.uniforms.push( uniforms[ j ].clone() );
  19991. }
  19992. }
  19993. return this;
  19994. }
  19995. clone() {
  19996. return new this.constructor().copy( this );
  19997. }
  19998. };
  19999. class InstancedInterleavedBuffer extends InterleavedBuffer {
  20000. constructor( array, stride, meshPerAttribute = 1 ) {
  20001. super( array, stride );
  20002. this.isInstancedInterleavedBuffer = true;
  20003. this.meshPerAttribute = meshPerAttribute;
  20004. }
  20005. copy( source ) {
  20006. super.copy( source );
  20007. this.meshPerAttribute = source.meshPerAttribute;
  20008. return this;
  20009. }
  20010. clone( data ) {
  20011. const ib = super.clone( data );
  20012. ib.meshPerAttribute = this.meshPerAttribute;
  20013. return ib;
  20014. }
  20015. toJSON( data ) {
  20016. const json = super.toJSON( data );
  20017. json.isInstancedInterleavedBuffer = true;
  20018. json.meshPerAttribute = this.meshPerAttribute;
  20019. return json;
  20020. }
  20021. }
  20022. class GLBufferAttribute {
  20023. constructor( buffer, type, itemSize, elementSize, count ) {
  20024. this.isGLBufferAttribute = true;
  20025. this.name = '';
  20026. this.buffer = buffer;
  20027. this.type = type;
  20028. this.itemSize = itemSize;
  20029. this.elementSize = elementSize;
  20030. this.count = count;
  20031. this.version = 0;
  20032. }
  20033. set needsUpdate( value ) {
  20034. if ( value === true ) this.version ++;
  20035. }
  20036. setBuffer( buffer ) {
  20037. this.buffer = buffer;
  20038. return this;
  20039. }
  20040. setType( type, elementSize ) {
  20041. this.type = type;
  20042. this.elementSize = elementSize;
  20043. return this;
  20044. }
  20045. setItemSize( itemSize ) {
  20046. this.itemSize = itemSize;
  20047. return this;
  20048. }
  20049. setCount( count ) {
  20050. this.count = count;
  20051. return this;
  20052. }
  20053. }
  20054. const _matrix = /*@__PURE__*/ new Matrix4();
  20055. class Raycaster {
  20056. constructor( origin, direction, near = 0, far = Infinity ) {
  20057. this.ray = new Ray( origin, direction );
  20058. // direction is assumed to be normalized (for accurate distance calculations)
  20059. this.near = near;
  20060. this.far = far;
  20061. this.camera = null;
  20062. this.layers = new Layers();
  20063. this.params = {
  20064. Mesh: {},
  20065. Line: { threshold: 1 },
  20066. LOD: {},
  20067. Points: { threshold: 1 },
  20068. Sprite: {}
  20069. };
  20070. }
  20071. set( origin, direction ) {
  20072. // direction is assumed to be normalized (for accurate distance calculations)
  20073. this.ray.set( origin, direction );
  20074. }
  20075. setFromCamera( coords, camera ) {
  20076. if ( camera.isPerspectiveCamera ) {
  20077. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  20078. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  20079. this.camera = camera;
  20080. } else if ( camera.isOrthographicCamera ) {
  20081. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  20082. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  20083. this.camera = camera;
  20084. } else {
  20085. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  20086. }
  20087. }
  20088. setFromXRController( controller ) {
  20089. _matrix.identity().extractRotation( controller.matrixWorld );
  20090. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  20091. this.ray.direction.set( 0, 0, - 1 ).applyMatrix4( _matrix );
  20092. return this;
  20093. }
  20094. intersectObject( object, recursive = true, intersects = [] ) {
  20095. intersect( object, this, intersects, recursive );
  20096. intersects.sort( ascSort );
  20097. return intersects;
  20098. }
  20099. intersectObjects( objects, recursive = true, intersects = [] ) {
  20100. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  20101. intersect( objects[ i ], this, intersects, recursive );
  20102. }
  20103. intersects.sort( ascSort );
  20104. return intersects;
  20105. }
  20106. }
  20107. function ascSort( a, b ) {
  20108. return a.distance - b.distance;
  20109. }
  20110. function intersect( object, raycaster, intersects, recursive ) {
  20111. let propagate = true;
  20112. if ( object.layers.test( raycaster.layers ) ) {
  20113. const result = object.raycast( raycaster, intersects );
  20114. if ( result === false ) propagate = false;
  20115. }
  20116. if ( propagate === true && recursive === true ) {
  20117. const children = object.children;
  20118. for ( let i = 0, l = children.length; i < l; i ++ ) {
  20119. intersect( children[ i ], raycaster, intersects, true );
  20120. }
  20121. }
  20122. }
  20123. /**
  20124. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  20125. *
  20126. * phi (the polar angle) is measured from the positive y-axis. The positive y-axis is up.
  20127. * theta (the azimuthal angle) is measured from the positive z-axis.
  20128. */
  20129. class Spherical {
  20130. constructor( radius = 1, phi = 0, theta = 0 ) {
  20131. this.radius = radius;
  20132. this.phi = phi; // polar angle
  20133. this.theta = theta; // azimuthal angle
  20134. return this;
  20135. }
  20136. set( radius, phi, theta ) {
  20137. this.radius = radius;
  20138. this.phi = phi;
  20139. this.theta = theta;
  20140. return this;
  20141. }
  20142. copy( other ) {
  20143. this.radius = other.radius;
  20144. this.phi = other.phi;
  20145. this.theta = other.theta;
  20146. return this;
  20147. }
  20148. // restrict phi to be between EPS and PI-EPS
  20149. makeSafe() {
  20150. const EPS = 0.000001;
  20151. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  20152. return this;
  20153. }
  20154. setFromVector3( v ) {
  20155. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20156. }
  20157. setFromCartesianCoords( x, y, z ) {
  20158. this.radius = Math.sqrt( x * x + y * y + z * z );
  20159. if ( this.radius === 0 ) {
  20160. this.theta = 0;
  20161. this.phi = 0;
  20162. } else {
  20163. this.theta = Math.atan2( x, z );
  20164. this.phi = Math.acos( clamp$1( y / this.radius, - 1, 1 ) );
  20165. }
  20166. return this;
  20167. }
  20168. clone() {
  20169. return new this.constructor().copy( this );
  20170. }
  20171. }
  20172. /**
  20173. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  20174. */
  20175. class Cylindrical {
  20176. constructor( radius = 1, theta = 0, y = 0 ) {
  20177. this.radius = radius; // distance from the origin to a point in the x-z plane
  20178. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  20179. this.y = y; // height above the x-z plane
  20180. return this;
  20181. }
  20182. set( radius, theta, y ) {
  20183. this.radius = radius;
  20184. this.theta = theta;
  20185. this.y = y;
  20186. return this;
  20187. }
  20188. copy( other ) {
  20189. this.radius = other.radius;
  20190. this.theta = other.theta;
  20191. this.y = other.y;
  20192. return this;
  20193. }
  20194. setFromVector3( v ) {
  20195. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20196. }
  20197. setFromCartesianCoords( x, y, z ) {
  20198. this.radius = Math.sqrt( x * x + z * z );
  20199. this.theta = Math.atan2( x, z );
  20200. this.y = y;
  20201. return this;
  20202. }
  20203. clone() {
  20204. return new this.constructor().copy( this );
  20205. }
  20206. }
  20207. const _vector$4 = /*@__PURE__*/ new Vector2();
  20208. class Box2 {
  20209. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  20210. this.isBox2 = true;
  20211. this.min = min;
  20212. this.max = max;
  20213. }
  20214. set( min, max ) {
  20215. this.min.copy( min );
  20216. this.max.copy( max );
  20217. return this;
  20218. }
  20219. setFromPoints( points ) {
  20220. this.makeEmpty();
  20221. for ( let i = 0, il = points.length; i < il; i ++ ) {
  20222. this.expandByPoint( points[ i ] );
  20223. }
  20224. return this;
  20225. }
  20226. setFromCenterAndSize( center, size ) {
  20227. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  20228. this.min.copy( center ).sub( halfSize );
  20229. this.max.copy( center ).add( halfSize );
  20230. return this;
  20231. }
  20232. clone() {
  20233. return new this.constructor().copy( this );
  20234. }
  20235. copy( box ) {
  20236. this.min.copy( box.min );
  20237. this.max.copy( box.max );
  20238. return this;
  20239. }
  20240. makeEmpty() {
  20241. this.min.x = this.min.y = + Infinity;
  20242. this.max.x = this.max.y = - Infinity;
  20243. return this;
  20244. }
  20245. isEmpty() {
  20246. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  20247. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  20248. }
  20249. getCenter( target ) {
  20250. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  20251. }
  20252. getSize( target ) {
  20253. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  20254. }
  20255. expandByPoint( point ) {
  20256. this.min.min( point );
  20257. this.max.max( point );
  20258. return this;
  20259. }
  20260. expandByVector( vector ) {
  20261. this.min.sub( vector );
  20262. this.max.add( vector );
  20263. return this;
  20264. }
  20265. expandByScalar( scalar ) {
  20266. this.min.addScalar( - scalar );
  20267. this.max.addScalar( scalar );
  20268. return this;
  20269. }
  20270. containsPoint( point ) {
  20271. return point.x < this.min.x || point.x > this.max.x ||
  20272. point.y < this.min.y || point.y > this.max.y ? false : true;
  20273. }
  20274. containsBox( box ) {
  20275. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  20276. this.min.y <= box.min.y && box.max.y <= this.max.y;
  20277. }
  20278. getParameter( point, target ) {
  20279. // This can potentially have a divide by zero if the box
  20280. // has a size dimension of 0.
  20281. return target.set(
  20282. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  20283. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  20284. );
  20285. }
  20286. intersectsBox( box ) {
  20287. // using 4 splitting planes to rule out intersections
  20288. return box.max.x < this.min.x || box.min.x > this.max.x ||
  20289. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  20290. }
  20291. clampPoint( point, target ) {
  20292. return target.copy( point ).clamp( this.min, this.max );
  20293. }
  20294. distanceToPoint( point ) {
  20295. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  20296. }
  20297. intersect( box ) {
  20298. this.min.max( box.min );
  20299. this.max.min( box.max );
  20300. if ( this.isEmpty() ) this.makeEmpty();
  20301. return this;
  20302. }
  20303. union( box ) {
  20304. this.min.min( box.min );
  20305. this.max.max( box.max );
  20306. return this;
  20307. }
  20308. translate( offset ) {
  20309. this.min.add( offset );
  20310. this.max.add( offset );
  20311. return this;
  20312. }
  20313. equals( box ) {
  20314. return box.min.equals( this.min ) && box.max.equals( this.max );
  20315. }
  20316. }
  20317. const _startP = /*@__PURE__*/ new Vector3();
  20318. const _startEnd = /*@__PURE__*/ new Vector3();
  20319. class Line3 {
  20320. constructor( start = new Vector3(), end = new Vector3() ) {
  20321. this.start = start;
  20322. this.end = end;
  20323. }
  20324. set( start, end ) {
  20325. this.start.copy( start );
  20326. this.end.copy( end );
  20327. return this;
  20328. }
  20329. copy( line ) {
  20330. this.start.copy( line.start );
  20331. this.end.copy( line.end );
  20332. return this;
  20333. }
  20334. getCenter( target ) {
  20335. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  20336. }
  20337. delta( target ) {
  20338. return target.subVectors( this.end, this.start );
  20339. }
  20340. distanceSq() {
  20341. return this.start.distanceToSquared( this.end );
  20342. }
  20343. distance() {
  20344. return this.start.distanceTo( this.end );
  20345. }
  20346. at( t, target ) {
  20347. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20348. }
  20349. closestPointToPointParameter( point, clampToLine ) {
  20350. _startP.subVectors( point, this.start );
  20351. _startEnd.subVectors( this.end, this.start );
  20352. const startEnd2 = _startEnd.dot( _startEnd );
  20353. const startEnd_startP = _startEnd.dot( _startP );
  20354. let t = startEnd_startP / startEnd2;
  20355. if ( clampToLine ) {
  20356. t = clamp$1( t, 0, 1 );
  20357. }
  20358. return t;
  20359. }
  20360. closestPointToPoint( point, clampToLine, target ) {
  20361. const t = this.closestPointToPointParameter( point, clampToLine );
  20362. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20363. }
  20364. applyMatrix4( matrix ) {
  20365. this.start.applyMatrix4( matrix );
  20366. this.end.applyMatrix4( matrix );
  20367. return this;
  20368. }
  20369. equals( line ) {
  20370. return line.start.equals( this.start ) && line.end.equals( this.end );
  20371. }
  20372. clone() {
  20373. return new this.constructor().copy( this );
  20374. }
  20375. }
  20376. const _vector$3 = /*@__PURE__*/ new Vector3();
  20377. class SpotLightHelper extends Object3D {
  20378. constructor( light, color ) {
  20379. super();
  20380. this.light = light;
  20381. this.matrixAutoUpdate = false;
  20382. this.color = color;
  20383. this.type = 'SpotLightHelper';
  20384. const geometry = new BufferGeometry();
  20385. const positions = [
  20386. 0, 0, 0, 0, 0, 1,
  20387. 0, 0, 0, 1, 0, 1,
  20388. 0, 0, 0, - 1, 0, 1,
  20389. 0, 0, 0, 0, 1, 1,
  20390. 0, 0, 0, 0, - 1, 1
  20391. ];
  20392. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  20393. const p1 = ( i / l ) * Math.PI * 2;
  20394. const p2 = ( j / l ) * Math.PI * 2;
  20395. positions.push(
  20396. Math.cos( p1 ), Math.sin( p1 ), 1,
  20397. Math.cos( p2 ), Math.sin( p2 ), 1
  20398. );
  20399. }
  20400. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  20401. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20402. this.cone = new LineSegments( geometry, material );
  20403. this.add( this.cone );
  20404. this.update();
  20405. }
  20406. dispose() {
  20407. this.cone.geometry.dispose();
  20408. this.cone.material.dispose();
  20409. }
  20410. update() {
  20411. this.light.updateWorldMatrix( true, false );
  20412. this.light.target.updateWorldMatrix( true, false );
  20413. // update the local matrix based on the parent and light target transforms
  20414. if ( this.parent ) {
  20415. this.parent.updateWorldMatrix( true );
  20416. this.matrix
  20417. .copy( this.parent.matrixWorld )
  20418. .invert()
  20419. .multiply( this.light.matrixWorld );
  20420. } else {
  20421. this.matrix.copy( this.light.matrixWorld );
  20422. }
  20423. this.matrixWorld.copy( this.light.matrixWorld );
  20424. const coneLength = this.light.distance ? this.light.distance : 1000;
  20425. const coneWidth = coneLength * Math.tan( this.light.angle );
  20426. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20427. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  20428. this.cone.lookAt( _vector$3 );
  20429. if ( this.color !== undefined ) {
  20430. this.cone.material.color.set( this.color );
  20431. } else {
  20432. this.cone.material.color.copy( this.light.color );
  20433. }
  20434. }
  20435. }
  20436. const _vector$2 = /*@__PURE__*/ new Vector3();
  20437. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  20438. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  20439. class SkeletonHelper extends LineSegments {
  20440. constructor( object ) {
  20441. const bones = getBoneList( object );
  20442. const geometry = new BufferGeometry();
  20443. const vertices = [];
  20444. const colors = [];
  20445. const color1 = new Color( 0, 0, 1 );
  20446. const color2 = new Color( 0, 1, 0 );
  20447. for ( let i = 0; i < bones.length; i ++ ) {
  20448. const bone = bones[ i ];
  20449. if ( bone.parent && bone.parent.isBone ) {
  20450. vertices.push( 0, 0, 0 );
  20451. vertices.push( 0, 0, 0 );
  20452. colors.push( color1.r, color1.g, color1.b );
  20453. colors.push( color2.r, color2.g, color2.b );
  20454. }
  20455. }
  20456. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20457. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20458. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  20459. super( geometry, material );
  20460. this.isSkeletonHelper = true;
  20461. this.type = 'SkeletonHelper';
  20462. this.root = object;
  20463. this.bones = bones;
  20464. this.matrix = object.matrixWorld;
  20465. this.matrixAutoUpdate = false;
  20466. }
  20467. updateMatrixWorld( force ) {
  20468. const bones = this.bones;
  20469. const geometry = this.geometry;
  20470. const position = geometry.getAttribute( 'position' );
  20471. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  20472. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  20473. const bone = bones[ i ];
  20474. if ( bone.parent && bone.parent.isBone ) {
  20475. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  20476. _vector$2.setFromMatrixPosition( _boneMatrix );
  20477. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  20478. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  20479. _vector$2.setFromMatrixPosition( _boneMatrix );
  20480. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  20481. j += 2;
  20482. }
  20483. }
  20484. geometry.getAttribute( 'position' ).needsUpdate = true;
  20485. super.updateMatrixWorld( force );
  20486. }
  20487. dispose() {
  20488. this.geometry.dispose();
  20489. this.material.dispose();
  20490. }
  20491. }
  20492. function getBoneList( object ) {
  20493. const boneList = [];
  20494. if ( object.isBone === true ) {
  20495. boneList.push( object );
  20496. }
  20497. for ( let i = 0; i < object.children.length; i ++ ) {
  20498. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  20499. }
  20500. return boneList;
  20501. }
  20502. class PointLightHelper extends Mesh {
  20503. constructor( light, sphereSize, color ) {
  20504. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  20505. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20506. super( geometry, material );
  20507. this.light = light;
  20508. this.color = color;
  20509. this.type = 'PointLightHelper';
  20510. this.matrix = this.light.matrixWorld;
  20511. this.matrixAutoUpdate = false;
  20512. this.update();
  20513. /*
  20514. // TODO: delete this comment?
  20515. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20516. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20517. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20518. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20519. const d = light.distance;
  20520. if ( d === 0.0 ) {
  20521. this.lightDistance.visible = false;
  20522. } else {
  20523. this.lightDistance.scale.set( d, d, d );
  20524. }
  20525. this.add( this.lightDistance );
  20526. */
  20527. }
  20528. dispose() {
  20529. this.geometry.dispose();
  20530. this.material.dispose();
  20531. }
  20532. update() {
  20533. this.light.updateWorldMatrix( true, false );
  20534. if ( this.color !== undefined ) {
  20535. this.material.color.set( this.color );
  20536. } else {
  20537. this.material.color.copy( this.light.color );
  20538. }
  20539. /*
  20540. const d = this.light.distance;
  20541. if ( d === 0.0 ) {
  20542. this.lightDistance.visible = false;
  20543. } else {
  20544. this.lightDistance.visible = true;
  20545. this.lightDistance.scale.set( d, d, d );
  20546. }
  20547. */
  20548. }
  20549. }
  20550. const _vector$1 = /*@__PURE__*/ new Vector3();
  20551. const _color1 = /*@__PURE__*/ new Color();
  20552. const _color2 = /*@__PURE__*/ new Color();
  20553. class HemisphereLightHelper extends Object3D {
  20554. constructor( light, size, color ) {
  20555. super();
  20556. this.light = light;
  20557. this.matrix = light.matrixWorld;
  20558. this.matrixAutoUpdate = false;
  20559. this.color = color;
  20560. this.type = 'HemisphereLightHelper';
  20561. const geometry = new OctahedronGeometry( size );
  20562. geometry.rotateY( Math.PI * 0.5 );
  20563. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20564. if ( this.color === undefined ) this.material.vertexColors = true;
  20565. const position = geometry.getAttribute( 'position' );
  20566. const colors = new Float32Array( position.count * 3 );
  20567. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  20568. this.add( new Mesh( geometry, this.material ) );
  20569. this.update();
  20570. }
  20571. dispose() {
  20572. this.children[ 0 ].geometry.dispose();
  20573. this.children[ 0 ].material.dispose();
  20574. }
  20575. update() {
  20576. const mesh = this.children[ 0 ];
  20577. if ( this.color !== undefined ) {
  20578. this.material.color.set( this.color );
  20579. } else {
  20580. const colors = mesh.geometry.getAttribute( 'color' );
  20581. _color1.copy( this.light.color );
  20582. _color2.copy( this.light.groundColor );
  20583. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  20584. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  20585. colors.setXYZ( i, color.r, color.g, color.b );
  20586. }
  20587. colors.needsUpdate = true;
  20588. }
  20589. this.light.updateWorldMatrix( true, false );
  20590. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20591. }
  20592. }
  20593. class GridHelper extends LineSegments {
  20594. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  20595. color1 = new Color( color1 );
  20596. color2 = new Color( color2 );
  20597. const center = divisions / 2;
  20598. const step = size / divisions;
  20599. const halfSize = size / 2;
  20600. const vertices = [], colors = [];
  20601. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  20602. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  20603. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  20604. const color = i === center ? color1 : color2;
  20605. color.toArray( colors, j ); j += 3;
  20606. color.toArray( colors, j ); j += 3;
  20607. color.toArray( colors, j ); j += 3;
  20608. color.toArray( colors, j ); j += 3;
  20609. }
  20610. const geometry = new BufferGeometry();
  20611. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20612. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20613. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20614. super( geometry, material );
  20615. this.type = 'GridHelper';
  20616. }
  20617. dispose() {
  20618. this.geometry.dispose();
  20619. this.material.dispose();
  20620. }
  20621. }
  20622. class PolarGridHelper extends LineSegments {
  20623. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  20624. color1 = new Color( color1 );
  20625. color2 = new Color( color2 );
  20626. const vertices = [];
  20627. const colors = [];
  20628. // create the sectors
  20629. if ( sectors > 1 ) {
  20630. for ( let i = 0; i < sectors; i ++ ) {
  20631. const v = ( i / sectors ) * ( Math.PI * 2 );
  20632. const x = Math.sin( v ) * radius;
  20633. const z = Math.cos( v ) * radius;
  20634. vertices.push( 0, 0, 0 );
  20635. vertices.push( x, 0, z );
  20636. const color = ( i & 1 ) ? color1 : color2;
  20637. colors.push( color.r, color.g, color.b );
  20638. colors.push( color.r, color.g, color.b );
  20639. }
  20640. }
  20641. // create the rings
  20642. for ( let i = 0; i < rings; i ++ ) {
  20643. const color = ( i & 1 ) ? color1 : color2;
  20644. const r = radius - ( radius / rings * i );
  20645. for ( let j = 0; j < divisions; j ++ ) {
  20646. // first vertex
  20647. let v = ( j / divisions ) * ( Math.PI * 2 );
  20648. let x = Math.sin( v ) * r;
  20649. let z = Math.cos( v ) * r;
  20650. vertices.push( x, 0, z );
  20651. colors.push( color.r, color.g, color.b );
  20652. // second vertex
  20653. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  20654. x = Math.sin( v ) * r;
  20655. z = Math.cos( v ) * r;
  20656. vertices.push( x, 0, z );
  20657. colors.push( color.r, color.g, color.b );
  20658. }
  20659. }
  20660. const geometry = new BufferGeometry();
  20661. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20662. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20663. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20664. super( geometry, material );
  20665. this.type = 'PolarGridHelper';
  20666. }
  20667. dispose() {
  20668. this.geometry.dispose();
  20669. this.material.dispose();
  20670. }
  20671. }
  20672. const _v1 = /*@__PURE__*/ new Vector3();
  20673. const _v2 = /*@__PURE__*/ new Vector3();
  20674. const _v3 = /*@__PURE__*/ new Vector3();
  20675. class DirectionalLightHelper extends Object3D {
  20676. constructor( light, size, color ) {
  20677. super();
  20678. this.light = light;
  20679. this.matrix = light.matrixWorld;
  20680. this.matrixAutoUpdate = false;
  20681. this.color = color;
  20682. this.type = 'DirectionalLightHelper';
  20683. if ( size === undefined ) size = 1;
  20684. let geometry = new BufferGeometry();
  20685. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  20686. - size, size, 0,
  20687. size, size, 0,
  20688. size, - size, 0,
  20689. - size, - size, 0,
  20690. - size, size, 0
  20691. ], 3 ) );
  20692. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20693. this.lightPlane = new Line( geometry, material );
  20694. this.add( this.lightPlane );
  20695. geometry = new BufferGeometry();
  20696. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  20697. this.targetLine = new Line( geometry, material );
  20698. this.add( this.targetLine );
  20699. this.update();
  20700. }
  20701. dispose() {
  20702. this.lightPlane.geometry.dispose();
  20703. this.lightPlane.material.dispose();
  20704. this.targetLine.geometry.dispose();
  20705. this.targetLine.material.dispose();
  20706. }
  20707. update() {
  20708. this.light.updateWorldMatrix( true, false );
  20709. this.light.target.updateWorldMatrix( true, false );
  20710. _v1.setFromMatrixPosition( this.light.matrixWorld );
  20711. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20712. _v3.subVectors( _v2, _v1 );
  20713. this.lightPlane.lookAt( _v2 );
  20714. if ( this.color !== undefined ) {
  20715. this.lightPlane.material.color.set( this.color );
  20716. this.targetLine.material.color.set( this.color );
  20717. } else {
  20718. this.lightPlane.material.color.copy( this.light.color );
  20719. this.targetLine.material.color.copy( this.light.color );
  20720. }
  20721. this.targetLine.lookAt( _v2 );
  20722. this.targetLine.scale.z = _v3.length();
  20723. }
  20724. }
  20725. const _vector = /*@__PURE__*/ new Vector3();
  20726. const _camera$1 = /*@__PURE__*/ new Camera();
  20727. /**
  20728. * - shows frustum, line of sight and up of the camera
  20729. * - suitable for fast updates
  20730. * - based on frustum visualization in lightgl.js shadowmap example
  20731. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  20732. */
  20733. class CameraHelper extends LineSegments {
  20734. constructor( camera ) {
  20735. const geometry = new BufferGeometry();
  20736. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  20737. const vertices = [];
  20738. const colors = [];
  20739. const pointMap = {};
  20740. // near
  20741. addLine( 'n1', 'n2' );
  20742. addLine( 'n2', 'n4' );
  20743. addLine( 'n4', 'n3' );
  20744. addLine( 'n3', 'n1' );
  20745. // far
  20746. addLine( 'f1', 'f2' );
  20747. addLine( 'f2', 'f4' );
  20748. addLine( 'f4', 'f3' );
  20749. addLine( 'f3', 'f1' );
  20750. // sides
  20751. addLine( 'n1', 'f1' );
  20752. addLine( 'n2', 'f2' );
  20753. addLine( 'n3', 'f3' );
  20754. addLine( 'n4', 'f4' );
  20755. // cone
  20756. addLine( 'p', 'n1' );
  20757. addLine( 'p', 'n2' );
  20758. addLine( 'p', 'n3' );
  20759. addLine( 'p', 'n4' );
  20760. // up
  20761. addLine( 'u1', 'u2' );
  20762. addLine( 'u2', 'u3' );
  20763. addLine( 'u3', 'u1' );
  20764. // target
  20765. addLine( 'c', 't' );
  20766. addLine( 'p', 'c' );
  20767. // cross
  20768. addLine( 'cn1', 'cn2' );
  20769. addLine( 'cn3', 'cn4' );
  20770. addLine( 'cf1', 'cf2' );
  20771. addLine( 'cf3', 'cf4' );
  20772. function addLine( a, b ) {
  20773. addPoint( a );
  20774. addPoint( b );
  20775. }
  20776. function addPoint( id ) {
  20777. vertices.push( 0, 0, 0 );
  20778. colors.push( 0, 0, 0 );
  20779. if ( pointMap[ id ] === undefined ) {
  20780. pointMap[ id ] = [];
  20781. }
  20782. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  20783. }
  20784. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20785. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20786. super( geometry, material );
  20787. this.type = 'CameraHelper';
  20788. this.camera = camera;
  20789. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  20790. this.matrix = camera.matrixWorld;
  20791. this.matrixAutoUpdate = false;
  20792. this.pointMap = pointMap;
  20793. this.update();
  20794. // colors
  20795. const colorFrustum = new Color( 0xffaa00 );
  20796. const colorCone = new Color( 0xff0000 );
  20797. const colorUp = new Color( 0x00aaff );
  20798. const colorTarget = new Color( 0xffffff );
  20799. const colorCross = new Color( 0x333333 );
  20800. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  20801. }
  20802. setColors( frustum, cone, up, target, cross ) {
  20803. const geometry = this.geometry;
  20804. const colorAttribute = geometry.getAttribute( 'color' );
  20805. // near
  20806. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  20807. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  20808. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  20809. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  20810. // far
  20811. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  20812. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  20813. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  20814. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  20815. // sides
  20816. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  20817. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  20818. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  20819. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  20820. // cone
  20821. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  20822. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  20823. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  20824. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  20825. // up
  20826. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  20827. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  20828. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  20829. // target
  20830. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  20831. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  20832. // cross
  20833. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  20834. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  20835. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  20836. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  20837. colorAttribute.needsUpdate = true;
  20838. }
  20839. update() {
  20840. const geometry = this.geometry;
  20841. const pointMap = this.pointMap;
  20842. const w = 1, h = 1;
  20843. // we need just camera projection matrix inverse
  20844. // world matrix must be identity
  20845. _camera$1.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  20846. // center / target
  20847. setPoint( 'c', pointMap, geometry, _camera$1, 0, 0, - 1 );
  20848. setPoint( 't', pointMap, geometry, _camera$1, 0, 0, 1 );
  20849. // near
  20850. setPoint( 'n1', pointMap, geometry, _camera$1, - w, - h, - 1 );
  20851. setPoint( 'n2', pointMap, geometry, _camera$1, w, - h, - 1 );
  20852. setPoint( 'n3', pointMap, geometry, _camera$1, - w, h, - 1 );
  20853. setPoint( 'n4', pointMap, geometry, _camera$1, w, h, - 1 );
  20854. // far
  20855. setPoint( 'f1', pointMap, geometry, _camera$1, - w, - h, 1 );
  20856. setPoint( 'f2', pointMap, geometry, _camera$1, w, - h, 1 );
  20857. setPoint( 'f3', pointMap, geometry, _camera$1, - w, h, 1 );
  20858. setPoint( 'f4', pointMap, geometry, _camera$1, w, h, 1 );
  20859. // up
  20860. setPoint( 'u1', pointMap, geometry, _camera$1, w * 0.7, h * 1.1, - 1 );
  20861. setPoint( 'u2', pointMap, geometry, _camera$1, - w * 0.7, h * 1.1, - 1 );
  20862. setPoint( 'u3', pointMap, geometry, _camera$1, 0, h * 2, - 1 );
  20863. // cross
  20864. setPoint( 'cf1', pointMap, geometry, _camera$1, - w, 0, 1 );
  20865. setPoint( 'cf2', pointMap, geometry, _camera$1, w, 0, 1 );
  20866. setPoint( 'cf3', pointMap, geometry, _camera$1, 0, - h, 1 );
  20867. setPoint( 'cf4', pointMap, geometry, _camera$1, 0, h, 1 );
  20868. setPoint( 'cn1', pointMap, geometry, _camera$1, - w, 0, - 1 );
  20869. setPoint( 'cn2', pointMap, geometry, _camera$1, w, 0, - 1 );
  20870. setPoint( 'cn3', pointMap, geometry, _camera$1, 0, - h, - 1 );
  20871. setPoint( 'cn4', pointMap, geometry, _camera$1, 0, h, - 1 );
  20872. geometry.getAttribute( 'position' ).needsUpdate = true;
  20873. }
  20874. dispose() {
  20875. this.geometry.dispose();
  20876. this.material.dispose();
  20877. }
  20878. }
  20879. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  20880. _vector.set( x, y, z ).unproject( camera );
  20881. const points = pointMap[ point ];
  20882. if ( points !== undefined ) {
  20883. const position = geometry.getAttribute( 'position' );
  20884. for ( let i = 0, l = points.length; i < l; i ++ ) {
  20885. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  20886. }
  20887. }
  20888. }
  20889. const _box = /*@__PURE__*/ new Box3();
  20890. class BoxHelper extends LineSegments {
  20891. constructor( object, color = 0xffff00 ) {
  20892. 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 ] );
  20893. const positions = new Float32Array( 8 * 3 );
  20894. const geometry = new BufferGeometry();
  20895. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  20896. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  20897. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  20898. this.object = object;
  20899. this.type = 'BoxHelper';
  20900. this.matrixAutoUpdate = false;
  20901. this.update();
  20902. }
  20903. update( object ) {
  20904. if ( object !== undefined ) {
  20905. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  20906. }
  20907. if ( this.object !== undefined ) {
  20908. _box.setFromObject( this.object );
  20909. }
  20910. if ( _box.isEmpty() ) return;
  20911. const min = _box.min;
  20912. const max = _box.max;
  20913. /*
  20914. 5____4
  20915. 1/___0/|
  20916. | 6__|_7
  20917. 2/___3/
  20918. 0: max.x, max.y, max.z
  20919. 1: min.x, max.y, max.z
  20920. 2: min.x, min.y, max.z
  20921. 3: max.x, min.y, max.z
  20922. 4: max.x, max.y, min.z
  20923. 5: min.x, max.y, min.z
  20924. 6: min.x, min.y, min.z
  20925. 7: max.x, min.y, min.z
  20926. */
  20927. const position = this.geometry.attributes.position;
  20928. const array = position.array;
  20929. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  20930. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  20931. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  20932. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  20933. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  20934. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  20935. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  20936. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  20937. position.needsUpdate = true;
  20938. this.geometry.computeBoundingSphere();
  20939. }
  20940. setFromObject( object ) {
  20941. this.object = object;
  20942. this.update();
  20943. return this;
  20944. }
  20945. copy( source, recursive ) {
  20946. super.copy( source, recursive );
  20947. this.object = source.object;
  20948. return this;
  20949. }
  20950. dispose() {
  20951. this.geometry.dispose();
  20952. this.material.dispose();
  20953. }
  20954. }
  20955. class Box3Helper extends LineSegments {
  20956. constructor( box, color = 0xffff00 ) {
  20957. 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 ] );
  20958. 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 ];
  20959. const geometry = new BufferGeometry();
  20960. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  20961. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  20962. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  20963. this.box = box;
  20964. this.type = 'Box3Helper';
  20965. this.geometry.computeBoundingSphere();
  20966. }
  20967. updateMatrixWorld( force ) {
  20968. const box = this.box;
  20969. if ( box.isEmpty() ) return;
  20970. box.getCenter( this.position );
  20971. box.getSize( this.scale );
  20972. this.scale.multiplyScalar( 0.5 );
  20973. super.updateMatrixWorld( force );
  20974. }
  20975. dispose() {
  20976. this.geometry.dispose();
  20977. this.material.dispose();
  20978. }
  20979. }
  20980. class PlaneHelper extends Line {
  20981. constructor( plane, size = 1, hex = 0xffff00 ) {
  20982. const color = hex;
  20983. 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 ];
  20984. const geometry = new BufferGeometry();
  20985. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  20986. geometry.computeBoundingSphere();
  20987. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  20988. this.type = 'PlaneHelper';
  20989. this.plane = plane;
  20990. this.size = size;
  20991. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  20992. const geometry2 = new BufferGeometry();
  20993. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  20994. geometry2.computeBoundingSphere();
  20995. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  20996. }
  20997. updateMatrixWorld( force ) {
  20998. this.position.set( 0, 0, 0 );
  20999. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  21000. this.lookAt( this.plane.normal );
  21001. this.translateZ( - this.plane.constant );
  21002. super.updateMatrixWorld( force );
  21003. }
  21004. dispose() {
  21005. this.geometry.dispose();
  21006. this.material.dispose();
  21007. this.children[ 0 ].geometry.dispose();
  21008. this.children[ 0 ].material.dispose();
  21009. }
  21010. }
  21011. const _axis = /*@__PURE__*/ new Vector3();
  21012. let _lineGeometry, _coneGeometry;
  21013. class ArrowHelper extends Object3D {
  21014. // dir is assumed to be normalized
  21015. 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 ) {
  21016. super();
  21017. this.type = 'ArrowHelper';
  21018. if ( _lineGeometry === undefined ) {
  21019. _lineGeometry = new BufferGeometry();
  21020. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  21021. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  21022. _coneGeometry.translate( 0, - 0.5, 0 );
  21023. }
  21024. this.position.copy( origin );
  21025. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21026. this.line.matrixAutoUpdate = false;
  21027. this.add( this.line );
  21028. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  21029. this.cone.matrixAutoUpdate = false;
  21030. this.add( this.cone );
  21031. this.setDirection( dir );
  21032. this.setLength( length, headLength, headWidth );
  21033. }
  21034. setDirection( dir ) {
  21035. // dir is assumed to be normalized
  21036. if ( dir.y > 0.99999 ) {
  21037. this.quaternion.set( 0, 0, 0, 1 );
  21038. } else if ( dir.y < - 0.99999 ) {
  21039. this.quaternion.set( 1, 0, 0, 0 );
  21040. } else {
  21041. _axis.set( dir.z, 0, - dir.x ).normalize();
  21042. const radians = Math.acos( dir.y );
  21043. this.quaternion.setFromAxisAngle( _axis, radians );
  21044. }
  21045. }
  21046. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  21047. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  21048. this.line.updateMatrix();
  21049. this.cone.scale.set( headWidth, headLength, headWidth );
  21050. this.cone.position.y = length;
  21051. this.cone.updateMatrix();
  21052. }
  21053. setColor( color ) {
  21054. this.line.material.color.set( color );
  21055. this.cone.material.color.set( color );
  21056. }
  21057. copy( source ) {
  21058. super.copy( source, false );
  21059. this.line.copy( source.line );
  21060. this.cone.copy( source.cone );
  21061. return this;
  21062. }
  21063. dispose() {
  21064. this.line.geometry.dispose();
  21065. this.line.material.dispose();
  21066. this.cone.geometry.dispose();
  21067. this.cone.material.dispose();
  21068. }
  21069. }
  21070. class AxesHelper extends LineSegments {
  21071. constructor( size = 1 ) {
  21072. const vertices = [
  21073. 0, 0, 0, size, 0, 0,
  21074. 0, 0, 0, 0, size, 0,
  21075. 0, 0, 0, 0, 0, size
  21076. ];
  21077. const colors = [
  21078. 1, 0, 0, 1, 0.6, 0,
  21079. 0, 1, 0, 0.6, 1, 0,
  21080. 0, 0, 1, 0, 0.6, 1
  21081. ];
  21082. const geometry = new BufferGeometry();
  21083. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21084. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  21085. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  21086. super( geometry, material );
  21087. this.type = 'AxesHelper';
  21088. }
  21089. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  21090. const color = new Color();
  21091. const array = this.geometry.attributes.color.array;
  21092. color.set( xAxisColor );
  21093. color.toArray( array, 0 );
  21094. color.toArray( array, 3 );
  21095. color.set( yAxisColor );
  21096. color.toArray( array, 6 );
  21097. color.toArray( array, 9 );
  21098. color.set( zAxisColor );
  21099. color.toArray( array, 12 );
  21100. color.toArray( array, 15 );
  21101. this.geometry.attributes.color.needsUpdate = true;
  21102. return this;
  21103. }
  21104. dispose() {
  21105. this.geometry.dispose();
  21106. this.material.dispose();
  21107. }
  21108. }
  21109. class ShapePath {
  21110. constructor() {
  21111. this.type = 'ShapePath';
  21112. this.color = new Color();
  21113. this.subPaths = [];
  21114. this.currentPath = null;
  21115. }
  21116. moveTo( x, y ) {
  21117. this.currentPath = new Path();
  21118. this.subPaths.push( this.currentPath );
  21119. this.currentPath.moveTo( x, y );
  21120. return this;
  21121. }
  21122. lineTo( x, y ) {
  21123. this.currentPath.lineTo( x, y );
  21124. return this;
  21125. }
  21126. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  21127. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  21128. return this;
  21129. }
  21130. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21131. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  21132. return this;
  21133. }
  21134. splineThru( pts ) {
  21135. this.currentPath.splineThru( pts );
  21136. return this;
  21137. }
  21138. toShapes( isCCW ) {
  21139. function toShapesNoHoles( inSubpaths ) {
  21140. const shapes = [];
  21141. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21142. const tmpPath = inSubpaths[ i ];
  21143. const tmpShape = new Shape();
  21144. tmpShape.curves = tmpPath.curves;
  21145. shapes.push( tmpShape );
  21146. }
  21147. return shapes;
  21148. }
  21149. function isPointInsidePolygon( inPt, inPolygon ) {
  21150. const polyLen = inPolygon.length;
  21151. // inPt on polygon contour => immediate success or
  21152. // toggling of inside/outside at every single! intersection point of an edge
  21153. // with the horizontal line through inPt, left of inPt
  21154. // not counting lowerY endpoints of edges and whole edges on that line
  21155. let inside = false;
  21156. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21157. let edgeLowPt = inPolygon[ p ];
  21158. let edgeHighPt = inPolygon[ q ];
  21159. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  21160. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  21161. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21162. // not parallel
  21163. if ( edgeDy < 0 ) {
  21164. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21165. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21166. }
  21167. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21168. if ( inPt.y === edgeLowPt.y ) {
  21169. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21170. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21171. } else {
  21172. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21173. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21174. if ( perpEdge < 0 ) continue;
  21175. inside = ! inside; // true intersection left of inPt
  21176. }
  21177. } else {
  21178. // parallel or collinear
  21179. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21180. // edge lies on the same horizontal line as inPt
  21181. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21182. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21183. // continue;
  21184. }
  21185. }
  21186. return inside;
  21187. }
  21188. const isClockWise = ShapeUtils.isClockWise;
  21189. const subPaths = this.subPaths;
  21190. if ( subPaths.length === 0 ) return [];
  21191. let solid, tmpPath, tmpShape;
  21192. const shapes = [];
  21193. if ( subPaths.length === 1 ) {
  21194. tmpPath = subPaths[ 0 ];
  21195. tmpShape = new Shape();
  21196. tmpShape.curves = tmpPath.curves;
  21197. shapes.push( tmpShape );
  21198. return shapes;
  21199. }
  21200. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21201. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21202. // console.log("Holes first", holesFirst);
  21203. const betterShapeHoles = [];
  21204. const newShapes = [];
  21205. let newShapeHoles = [];
  21206. let mainIdx = 0;
  21207. let tmpPoints;
  21208. newShapes[ mainIdx ] = undefined;
  21209. newShapeHoles[ mainIdx ] = [];
  21210. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  21211. tmpPath = subPaths[ i ];
  21212. tmpPoints = tmpPath.getPoints();
  21213. solid = isClockWise( tmpPoints );
  21214. solid = isCCW ? ! solid : solid;
  21215. if ( solid ) {
  21216. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21217. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21218. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21219. if ( holesFirst ) mainIdx ++;
  21220. newShapeHoles[ mainIdx ] = [];
  21221. //console.log('cw', i);
  21222. } else {
  21223. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21224. //console.log('ccw', i);
  21225. }
  21226. }
  21227. // only Holes? -> probably all Shapes with wrong orientation
  21228. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21229. if ( newShapes.length > 1 ) {
  21230. let ambiguous = false;
  21231. let toChange = 0;
  21232. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21233. betterShapeHoles[ sIdx ] = [];
  21234. }
  21235. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21236. const sho = newShapeHoles[ sIdx ];
  21237. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21238. const ho = sho[ hIdx ];
  21239. let hole_unassigned = true;
  21240. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21241. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21242. if ( sIdx !== s2Idx ) toChange ++;
  21243. if ( hole_unassigned ) {
  21244. hole_unassigned = false;
  21245. betterShapeHoles[ s2Idx ].push( ho );
  21246. } else {
  21247. ambiguous = true;
  21248. }
  21249. }
  21250. }
  21251. if ( hole_unassigned ) {
  21252. betterShapeHoles[ sIdx ].push( ho );
  21253. }
  21254. }
  21255. }
  21256. if ( toChange > 0 && ambiguous === false ) {
  21257. newShapeHoles = betterShapeHoles;
  21258. }
  21259. }
  21260. let tmpHoles;
  21261. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  21262. tmpShape = newShapes[ i ].s;
  21263. shapes.push( tmpShape );
  21264. tmpHoles = newShapeHoles[ i ];
  21265. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21266. tmpShape.holes.push( tmpHoles[ j ].h );
  21267. }
  21268. }
  21269. //console.log("shape", shapes);
  21270. return shapes;
  21271. }
  21272. }
  21273. class WebGLMultipleRenderTargets extends WebGLRenderTarget { // @deprecated, r162
  21274. constructor( width = 1, height = 1, count = 1, options = {} ) {
  21275. console.warn( 'THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.' );
  21276. super( width, height, { ...options, count } );
  21277. this.isWebGLMultipleRenderTargets = true;
  21278. }
  21279. get texture() {
  21280. return this.textures;
  21281. }
  21282. }
  21283. if ( self.GPUShaderStage === undefined ) {
  21284. self.GPUShaderStage = { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  21285. }
  21286. // statics
  21287. let isAvailable = navigator.gpu !== undefined;
  21288. if ( typeof window !== 'undefined' && isAvailable ) {
  21289. isAvailable = await navigator.gpu.requestAdapter();
  21290. }
  21291. class WebGPU {
  21292. static isAvailable() {
  21293. return Boolean( isAvailable );
  21294. }
  21295. static getStaticAdapter() {
  21296. return isAvailable;
  21297. }
  21298. static getErrorMessage() {
  21299. const message = 'Your browser does not support <a href="https://gpuweb.github.io/gpuweb/" style="color:blue">WebGPU</a> yet';
  21300. const element = document.createElement( 'div' );
  21301. element.id = 'webgpumessage';
  21302. element.style.fontFamily = 'monospace';
  21303. element.style.fontSize = '13px';
  21304. element.style.fontWeight = 'normal';
  21305. element.style.textAlign = 'center';
  21306. element.style.background = '#fff';
  21307. element.style.color = '#000';
  21308. element.style.padding = '1.5em';
  21309. element.style.maxWidth = '400px';
  21310. element.style.margin = '5em auto 0';
  21311. element.innerHTML = message;
  21312. return element;
  21313. }
  21314. }
  21315. class Animation {
  21316. constructor( nodes, info ) {
  21317. this.nodes = nodes;
  21318. this.info = info;
  21319. this.animationLoop = null;
  21320. this.requestId = null;
  21321. this._init();
  21322. }
  21323. _init() {
  21324. const update = ( time, frame ) => {
  21325. this.requestId = self.requestAnimationFrame( update );
  21326. if ( this.info.autoReset === true ) this.info.reset();
  21327. this.nodes.nodeFrame.update();
  21328. this.info.frame = this.nodes.nodeFrame.frameId;
  21329. if ( this.animationLoop !== null ) this.animationLoop( time, frame );
  21330. };
  21331. update();
  21332. }
  21333. dispose() {
  21334. self.cancelAnimationFrame( this.requestId );
  21335. this.requestId = null;
  21336. }
  21337. setAnimationLoop( callback ) {
  21338. this.animationLoop = callback;
  21339. }
  21340. }
  21341. class ChainMap {
  21342. constructor() {
  21343. this.weakMap = new WeakMap();
  21344. }
  21345. get( keys ) {
  21346. let map = this.weakMap;
  21347. for ( let i = 0; i < keys.length; i ++ ) {
  21348. map = map.get( keys[ i ] );
  21349. if ( map === undefined ) return undefined;
  21350. }
  21351. return map.get( keys[ keys.length - 1 ] );
  21352. }
  21353. set( keys, value ) {
  21354. let map = this.weakMap;
  21355. for ( let i = 0; i < keys.length; i ++ ) {
  21356. const key = keys[ i ];
  21357. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  21358. map = map.get( key );
  21359. }
  21360. return map.set( keys[ keys.length - 1 ], value );
  21361. }
  21362. delete( keys ) {
  21363. let map = this.weakMap;
  21364. for ( let i = 0; i < keys.length; i ++ ) {
  21365. map = map.get( keys[ i ] );
  21366. if ( map === undefined ) return false;
  21367. }
  21368. return map.delete( keys[ keys.length - 1 ] );
  21369. }
  21370. }
  21371. const _plane = new Plane();
  21372. let _clippingContextVersion = 0;
  21373. class ClippingContext {
  21374. constructor() {
  21375. this.version = ++ _clippingContextVersion;
  21376. this.globalClippingCount = 0;
  21377. this.localClippingCount = 0;
  21378. this.localClippingEnabled = false;
  21379. this.localClipIntersection = false;
  21380. this.planes = [];
  21381. this.parentVersion = 0;
  21382. this.viewNormalMatrix = new Matrix3();
  21383. }
  21384. projectPlanes( source, offset ) {
  21385. const l = source.length;
  21386. const planes = this.planes;
  21387. for ( let i = 0; i < l; i ++ ) {
  21388. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  21389. const v = planes[ offset + i ];
  21390. const normal = _plane.normal;
  21391. v.x = - normal.x;
  21392. v.y = - normal.y;
  21393. v.z = - normal.z;
  21394. v.w = _plane.constant;
  21395. }
  21396. }
  21397. updateGlobal( renderer, camera ) {
  21398. const rendererClippingPlanes = renderer.clippingPlanes;
  21399. this.viewMatrix = camera.matrixWorldInverse;
  21400. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  21401. let update = false;
  21402. if ( Array.isArray( rendererClippingPlanes ) && rendererClippingPlanes.length !== 0 ) {
  21403. const l = rendererClippingPlanes.length;
  21404. if ( l !== this.globalClippingCount ) {
  21405. const planes = [];
  21406. for ( let i = 0; i < l; i ++ ) {
  21407. planes.push( new Vector4() );
  21408. }
  21409. this.globalClippingCount = l;
  21410. this.planes = planes;
  21411. update = true;
  21412. }
  21413. this.projectPlanes( rendererClippingPlanes, 0 );
  21414. } else if ( this.globalClippingCount !== 0 ) {
  21415. this.globalClippingCount = 0;
  21416. this.planes = [];
  21417. update = true;
  21418. }
  21419. if ( renderer.localClippingEnabled !== this.localClippingEnabled ) {
  21420. this.localClippingEnabled = renderer.localClippingEnabled;
  21421. update = true;
  21422. }
  21423. if ( update ) this.version = _clippingContextVersion ++;
  21424. }
  21425. update( parent, material ) {
  21426. let update = false;
  21427. if ( this !== parent && parent.version !== this.parentVersion ) {
  21428. this.globalClippingCount = material.isShadowNodeMaterial ? 0 : parent.globalClippingCount;
  21429. this.localClippingEnabled = parent.localClippingEnabled;
  21430. this.planes = Array.from( parent.planes );
  21431. this.parentVersion = parent.version;
  21432. this.viewMatrix = parent.viewMatrix;
  21433. this.viewNormalMatrix = parent.viewNormalMatrix;
  21434. update = true;
  21435. }
  21436. if ( this.localClippingEnabled ) {
  21437. const localClippingPlanes = material.clippingPlanes;
  21438. if ( ( Array.isArray( localClippingPlanes ) && localClippingPlanes.length !== 0 ) ) {
  21439. const l = localClippingPlanes.length;
  21440. const planes = this.planes;
  21441. const offset = this.globalClippingCount;
  21442. if ( update || l !== this.localClippingCount ) {
  21443. planes.length = offset + l;
  21444. for ( let i = 0; i < l; i ++ ) {
  21445. planes[ offset + i ] = new Vector4();
  21446. }
  21447. this.localClippingCount = l;
  21448. update = true;
  21449. }
  21450. this.projectPlanes( localClippingPlanes, offset );
  21451. } else if ( this.localClippingCount !== 0 ) {
  21452. this.localClippingCount = 0;
  21453. update = true;
  21454. }
  21455. if ( this.localClipIntersection !== material.clipIntersection ) {
  21456. this.localClipIntersection = material.clipIntersection;
  21457. update = true;
  21458. }
  21459. }
  21460. if ( update ) this.version = _clippingContextVersion ++;
  21461. }
  21462. }
  21463. let id$4 = 0;
  21464. function getKeys( obj ) {
  21465. const keys = Object.keys( obj );
  21466. let proto = Object.getPrototypeOf( obj );
  21467. while ( proto ) {
  21468. const descriptors = Object.getOwnPropertyDescriptors( proto );
  21469. for ( const key in descriptors ) {
  21470. if ( descriptors[ key ] !== undefined ) {
  21471. const descriptor = descriptors[ key ];
  21472. if ( descriptor && typeof descriptor.get === 'function' ) {
  21473. keys.push( key );
  21474. }
  21475. }
  21476. }
  21477. proto = Object.getPrototypeOf( proto );
  21478. }
  21479. return keys;
  21480. }
  21481. class RenderObject {
  21482. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext ) {
  21483. this._nodes = nodes;
  21484. this._geometries = geometries;
  21485. this.id = id$4 ++;
  21486. this.renderer = renderer;
  21487. this.object = object;
  21488. this.material = material;
  21489. this.scene = scene;
  21490. this.camera = camera;
  21491. this.lightsNode = lightsNode;
  21492. this.context = renderContext;
  21493. this.geometry = object.geometry;
  21494. this.version = material.version;
  21495. this.drawRange = null;
  21496. this.attributes = null;
  21497. this.pipeline = null;
  21498. this.vertexBuffers = null;
  21499. this.updateClipping( renderContext.clippingContext );
  21500. this.clippingContextVersion = this.clippingContext.version;
  21501. this.initialNodesCacheKey = this.getNodesCacheKey();
  21502. this.initialCacheKey = this.getCacheKey();
  21503. this._nodeBuilderState = null;
  21504. this._bindings = null;
  21505. this.onDispose = null;
  21506. this.isRenderObject = true;
  21507. this.onMaterialDispose = () => {
  21508. this.dispose();
  21509. };
  21510. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  21511. }
  21512. updateClipping( parent ) {
  21513. const material = this.material;
  21514. let clippingContext = this.clippingContext;
  21515. if ( Array.isArray( material.clippingPlanes ) ) {
  21516. if ( clippingContext === parent || ! clippingContext ) {
  21517. clippingContext = new ClippingContext();
  21518. this.clippingContext = clippingContext;
  21519. }
  21520. clippingContext.update( parent, material );
  21521. } else if ( this.clippingContext !== parent ) {
  21522. this.clippingContext = parent;
  21523. }
  21524. }
  21525. get clippingNeedsUpdate() {
  21526. if ( this.clippingContext.version === this.clippingContextVersion ) return false;
  21527. this.clippingContextVersion = this.clippingContext.version;
  21528. return true;
  21529. }
  21530. getNodeBuilderState() {
  21531. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  21532. }
  21533. getBindings() {
  21534. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  21535. }
  21536. getIndex() {
  21537. return this._geometries.getIndex( this );
  21538. }
  21539. getChainArray() {
  21540. return [ this.object, this.material, this.context, this.lightsNode ];
  21541. }
  21542. getAttributes() {
  21543. if ( this.attributes !== null ) return this.attributes;
  21544. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  21545. const geometry = this.geometry;
  21546. const attributes = [];
  21547. const vertexBuffers = new Set();
  21548. for ( const nodeAttribute of nodeAttributes ) {
  21549. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  21550. if ( attribute === undefined ) continue;
  21551. attributes.push( attribute );
  21552. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  21553. vertexBuffers.add( bufferAttribute );
  21554. }
  21555. this.attributes = attributes;
  21556. this.vertexBuffers = Array.from( vertexBuffers.values() );
  21557. return attributes;
  21558. }
  21559. getVertexBuffers() {
  21560. if ( this.vertexBuffers === null ) this.getAttributes();
  21561. return this.vertexBuffers;
  21562. }
  21563. getMaterialCacheKey() {
  21564. const { object, material } = this;
  21565. let cacheKey = material.customProgramCacheKey();
  21566. for ( const property of getKeys( material ) ) {
  21567. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  21568. let value = material[ property ];
  21569. if ( value !== null ) {
  21570. const type = typeof value;
  21571. if ( type === 'number' ) value = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  21572. else if ( type === 'object' ) value = '{}';
  21573. }
  21574. cacheKey += /*property + ':' +*/ value + ',';
  21575. }
  21576. cacheKey += this.clippingContextVersion + ',';
  21577. if ( object.skeleton ) {
  21578. cacheKey += object.skeleton.bones.length + ',';
  21579. }
  21580. if ( object.morphTargetInfluences ) {
  21581. cacheKey += object.morphTargetInfluences.length + ',';
  21582. }
  21583. if ( object.isBatchedMesh ) {
  21584. cacheKey += object._matricesTexture.uuid + ',';
  21585. if ( object._colorsTexture !== null ) {
  21586. cacheKey += object._colorsTexture.uuid + ',';
  21587. }
  21588. }
  21589. if ( object.count > 1 ) {
  21590. cacheKey += object.count + ',';
  21591. }
  21592. return cacheKey;
  21593. }
  21594. get needsUpdate() {
  21595. return this.initialNodesCacheKey !== this.getNodesCacheKey() || this.clippingNeedsUpdate;
  21596. }
  21597. getNodesCacheKey() {
  21598. // Environment Nodes Cache Key
  21599. return this._nodes.getCacheKey( this.scene, this.lightsNode );
  21600. }
  21601. getCacheKey() {
  21602. return this.getMaterialCacheKey() + ',' + this.getNodesCacheKey();
  21603. }
  21604. dispose() {
  21605. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  21606. this.onDispose();
  21607. }
  21608. }
  21609. class RenderObjects {
  21610. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  21611. this.renderer = renderer;
  21612. this.nodes = nodes;
  21613. this.geometries = geometries;
  21614. this.pipelines = pipelines;
  21615. this.bindings = bindings;
  21616. this.info = info;
  21617. this.chainMaps = {};
  21618. }
  21619. get( object, material, scene, camera, lightsNode, renderContext, passId ) {
  21620. const chainMap = this.getChainMap( passId );
  21621. const chainArray = [ object, material, renderContext, lightsNode ];
  21622. let renderObject = chainMap.get( chainArray );
  21623. if ( renderObject === undefined ) {
  21624. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, passId );
  21625. chainMap.set( chainArray, renderObject );
  21626. } else {
  21627. renderObject.updateClipping( renderContext.clippingContext );
  21628. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  21629. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  21630. renderObject.dispose();
  21631. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, passId );
  21632. } else {
  21633. renderObject.version = material.version;
  21634. }
  21635. }
  21636. }
  21637. return renderObject;
  21638. }
  21639. getChainMap( passId = 'default' ) {
  21640. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  21641. }
  21642. dispose() {
  21643. this.chainMaps = {};
  21644. }
  21645. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, passId ) {
  21646. const chainMap = this.getChainMap( passId );
  21647. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext );
  21648. renderObject.onDispose = () => {
  21649. this.pipelines.delete( renderObject );
  21650. this.bindings.delete( renderObject );
  21651. this.nodes.delete( renderObject );
  21652. chainMap.delete( renderObject.getChainArray() );
  21653. };
  21654. return renderObject;
  21655. }
  21656. }
  21657. class DataMap {
  21658. constructor() {
  21659. this.data = new WeakMap();
  21660. }
  21661. get( object ) {
  21662. let map = this.data.get( object );
  21663. if ( map === undefined ) {
  21664. map = {};
  21665. this.data.set( object, map );
  21666. }
  21667. return map;
  21668. }
  21669. delete( object ) {
  21670. let map;
  21671. if ( this.data.has( object ) ) {
  21672. map = this.data.get( object );
  21673. this.data.delete( object );
  21674. }
  21675. return map;
  21676. }
  21677. has( object ) {
  21678. return this.data.has( object );
  21679. }
  21680. dispose() {
  21681. this.data = new WeakMap();
  21682. }
  21683. }
  21684. const AttributeType = {
  21685. VERTEX: 1,
  21686. INDEX: 2,
  21687. STORAGE: 4
  21688. };
  21689. // size of a chunk in bytes (STD140 layout)
  21690. const GPU_CHUNK_BYTES = 16;
  21691. // @TODO: Move to src/constants.js
  21692. const BlendColorFactor = 211;
  21693. const OneMinusBlendColorFactor = 212;
  21694. class Attributes extends DataMap {
  21695. constructor( backend ) {
  21696. super();
  21697. this.backend = backend;
  21698. }
  21699. delete( attribute ) {
  21700. const attributeData = super.delete( attribute );
  21701. if ( attributeData !== undefined ) {
  21702. this.backend.destroyAttribute( attribute );
  21703. }
  21704. return attributeData;
  21705. }
  21706. update( attribute, type ) {
  21707. const data = this.get( attribute );
  21708. if ( data.version === undefined ) {
  21709. if ( type === AttributeType.VERTEX ) {
  21710. this.backend.createAttribute( attribute );
  21711. } else if ( type === AttributeType.INDEX ) {
  21712. this.backend.createIndexAttribute( attribute );
  21713. } else if ( type === AttributeType.STORAGE ) {
  21714. this.backend.createStorageAttribute( attribute );
  21715. }
  21716. data.version = this._getBufferAttribute( attribute ).version;
  21717. } else {
  21718. const bufferAttribute = this._getBufferAttribute( attribute );
  21719. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  21720. this.backend.updateAttribute( attribute );
  21721. data.version = bufferAttribute.version;
  21722. }
  21723. }
  21724. }
  21725. _getBufferAttribute( attribute ) {
  21726. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  21727. return attribute;
  21728. }
  21729. }
  21730. function arrayNeedsUint32( array ) {
  21731. // assumes larger values usually on last
  21732. for ( let i = array.length - 1; i >= 0; -- i ) {
  21733. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  21734. }
  21735. return false;
  21736. }
  21737. function getWireframeVersion( geometry ) {
  21738. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  21739. }
  21740. function getWireframeIndex( geometry ) {
  21741. const indices = [];
  21742. const geometryIndex = geometry.index;
  21743. const geometryPosition = geometry.attributes.position;
  21744. if ( geometryIndex !== null ) {
  21745. const array = geometryIndex.array;
  21746. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  21747. const a = array[ i + 0 ];
  21748. const b = array[ i + 1 ];
  21749. const c = array[ i + 2 ];
  21750. indices.push( a, b, b, c, c, a );
  21751. }
  21752. } else {
  21753. const array = geometryPosition.array;
  21754. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  21755. const a = i + 0;
  21756. const b = i + 1;
  21757. const c = i + 2;
  21758. indices.push( a, b, b, c, c, a );
  21759. }
  21760. }
  21761. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  21762. attribute.version = getWireframeVersion( geometry );
  21763. return attribute;
  21764. }
  21765. class Geometries extends DataMap {
  21766. constructor( attributes, info ) {
  21767. super();
  21768. this.attributes = attributes;
  21769. this.info = info;
  21770. this.wireframes = new WeakMap();
  21771. this.attributeCall = new WeakMap();
  21772. }
  21773. has( renderObject ) {
  21774. const geometry = renderObject.geometry;
  21775. return super.has( geometry ) && this.get( geometry ).initialized === true;
  21776. }
  21777. updateForRender( renderObject ) {
  21778. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  21779. this.updateAttributes( renderObject );
  21780. }
  21781. initGeometry( renderObject ) {
  21782. const geometry = renderObject.geometry;
  21783. const geometryData = this.get( geometry );
  21784. geometryData.initialized = true;
  21785. this.info.memory.geometries ++;
  21786. const onDispose = () => {
  21787. this.info.memory.geometries --;
  21788. const index = geometry.index;
  21789. const geometryAttributes = renderObject.getAttributes();
  21790. if ( index !== null ) {
  21791. this.attributes.delete( index );
  21792. }
  21793. for ( const geometryAttribute of geometryAttributes ) {
  21794. this.attributes.delete( geometryAttribute );
  21795. }
  21796. const wireframeAttribute = this.wireframes.get( geometry );
  21797. if ( wireframeAttribute !== undefined ) {
  21798. this.attributes.delete( wireframeAttribute );
  21799. }
  21800. geometry.removeEventListener( 'dispose', onDispose );
  21801. };
  21802. geometry.addEventListener( 'dispose', onDispose );
  21803. }
  21804. updateAttributes( renderObject ) {
  21805. const attributes = renderObject.getAttributes();
  21806. for ( const attribute of attributes ) {
  21807. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  21808. this.updateAttribute( attribute, AttributeType.STORAGE );
  21809. } else {
  21810. this.updateAttribute( attribute, AttributeType.VERTEX );
  21811. }
  21812. }
  21813. const index = this.getIndex( renderObject );
  21814. if ( index !== null ) {
  21815. this.updateAttribute( index, AttributeType.INDEX );
  21816. }
  21817. }
  21818. updateAttribute( attribute, type ) {
  21819. const callId = this.info.render.calls;
  21820. if ( ! attribute.isInterleavedBufferAttribute ) {
  21821. if ( this.attributeCall.get( attribute ) !== callId ) {
  21822. this.attributes.update( attribute, type );
  21823. this.attributeCall.set( attribute, callId );
  21824. }
  21825. } else {
  21826. if ( this.attributeCall.get( attribute ) === undefined ) {
  21827. this.attributes.update( attribute, type );
  21828. this.attributeCall.set( attribute, callId );
  21829. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  21830. this.attributes.update( attribute, type );
  21831. this.attributeCall.set( attribute.data, callId );
  21832. this.attributeCall.set( attribute, callId );
  21833. }
  21834. }
  21835. }
  21836. getIndex( renderObject ) {
  21837. const { geometry, material } = renderObject;
  21838. let index = geometry.index;
  21839. if ( material.wireframe === true ) {
  21840. const wireframes = this.wireframes;
  21841. let wireframeAttribute = wireframes.get( geometry );
  21842. if ( wireframeAttribute === undefined ) {
  21843. wireframeAttribute = getWireframeIndex( geometry );
  21844. wireframes.set( geometry, wireframeAttribute );
  21845. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  21846. this.attributes.delete( wireframeAttribute );
  21847. wireframeAttribute = getWireframeIndex( geometry );
  21848. wireframes.set( geometry, wireframeAttribute );
  21849. }
  21850. index = wireframeAttribute;
  21851. }
  21852. return index;
  21853. }
  21854. }
  21855. class Info {
  21856. constructor() {
  21857. this.autoReset = true;
  21858. this.frame = 0;
  21859. this.calls = 0;
  21860. this.render = {
  21861. calls: 0,
  21862. frameCalls: 0,
  21863. drawCalls: 0,
  21864. triangles: 0,
  21865. points: 0,
  21866. lines: 0,
  21867. timestamp: 0,
  21868. previousFrameCalls: 0,
  21869. timestampCalls: 0
  21870. };
  21871. this.compute = {
  21872. calls: 0,
  21873. frameCalls: 0,
  21874. timestamp: 0,
  21875. previousFrameCalls: 0,
  21876. timestampCalls: 0
  21877. };
  21878. this.memory = {
  21879. geometries: 0,
  21880. textures: 0
  21881. };
  21882. }
  21883. update( object, count, instanceCount ) {
  21884. this.render.drawCalls ++;
  21885. if ( object.isMesh || object.isSprite ) {
  21886. this.render.triangles += instanceCount * ( count / 3 );
  21887. } else if ( object.isPoints ) {
  21888. this.render.points += instanceCount * count;
  21889. } else if ( object.isLineSegments ) {
  21890. this.render.lines += instanceCount * ( count / 2 );
  21891. } else if ( object.isLine ) {
  21892. this.render.lines += instanceCount * ( count - 1 );
  21893. } else {
  21894. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  21895. }
  21896. }
  21897. updateTimestamp( type, time ) {
  21898. if ( this[ type ].timestampCalls === 0 ) {
  21899. this[ type ].timestamp = 0;
  21900. }
  21901. this[ type ].timestamp += time;
  21902. this[ type ].timestampCalls ++;
  21903. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  21904. this[ type ].timestampCalls = 0;
  21905. }
  21906. }
  21907. reset() {
  21908. const previousRenderFrameCalls = this.render.frameCalls;
  21909. this.render.previousFrameCalls = previousRenderFrameCalls;
  21910. const previousComputeFrameCalls = this.compute.frameCalls;
  21911. this.compute.previousFrameCalls = previousComputeFrameCalls;
  21912. this.render.drawCalls = 0;
  21913. this.render.frameCalls = 0;
  21914. this.compute.frameCalls = 0;
  21915. this.render.triangles = 0;
  21916. this.render.points = 0;
  21917. this.render.lines = 0;
  21918. }
  21919. dispose() {
  21920. this.reset();
  21921. this.calls = 0;
  21922. this.render.calls = 0;
  21923. this.compute.calls = 0;
  21924. this.render.timestamp = 0;
  21925. this.compute.timestamp = 0;
  21926. this.memory.geometries = 0;
  21927. this.memory.textures = 0;
  21928. }
  21929. }
  21930. class Pipeline {
  21931. constructor( cacheKey ) {
  21932. this.cacheKey = cacheKey;
  21933. this.usedTimes = 0;
  21934. }
  21935. }
  21936. class RenderPipeline extends Pipeline {
  21937. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  21938. super( cacheKey );
  21939. this.vertexProgram = vertexProgram;
  21940. this.fragmentProgram = fragmentProgram;
  21941. }
  21942. }
  21943. class ComputePipeline extends Pipeline {
  21944. constructor( cacheKey, computeProgram ) {
  21945. super( cacheKey );
  21946. this.computeProgram = computeProgram;
  21947. this.isComputePipeline = true;
  21948. }
  21949. }
  21950. let _id$4 = 0;
  21951. class ProgrammableStage {
  21952. constructor( code, type, transforms = null, attributes = null ) {
  21953. this.id = _id$4 ++;
  21954. this.code = code;
  21955. this.stage = type;
  21956. this.transforms = transforms;
  21957. this.attributes = attributes;
  21958. this.usedTimes = 0;
  21959. }
  21960. }
  21961. class Pipelines extends DataMap {
  21962. constructor( backend, nodes ) {
  21963. super();
  21964. this.backend = backend;
  21965. this.nodes = nodes;
  21966. this.bindings = null; // set by the bindings
  21967. this.caches = new Map();
  21968. this.programs = {
  21969. vertex: new Map(),
  21970. fragment: new Map(),
  21971. compute: new Map()
  21972. };
  21973. }
  21974. getForCompute( computeNode, bindings ) {
  21975. const { backend } = this;
  21976. const data = this.get( computeNode );
  21977. if ( this._needsComputeUpdate( computeNode ) ) {
  21978. const previousPipeline = data.pipeline;
  21979. if ( previousPipeline ) {
  21980. previousPipeline.usedTimes --;
  21981. previousPipeline.computeProgram.usedTimes --;
  21982. }
  21983. // get shader
  21984. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  21985. // programmable stage
  21986. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  21987. if ( stageCompute === undefined ) {
  21988. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  21989. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  21990. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  21991. backend.createProgram( stageCompute );
  21992. }
  21993. // determine compute pipeline
  21994. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  21995. let pipeline = this.caches.get( cacheKey );
  21996. if ( pipeline === undefined ) {
  21997. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21998. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  21999. }
  22000. // keep track of all used times
  22001. pipeline.usedTimes ++;
  22002. stageCompute.usedTimes ++;
  22003. //
  22004. data.version = computeNode.version;
  22005. data.pipeline = pipeline;
  22006. }
  22007. return data.pipeline;
  22008. }
  22009. getForRender( renderObject, promises = null ) {
  22010. const { backend } = this;
  22011. const data = this.get( renderObject );
  22012. if ( this._needsRenderUpdate( renderObject ) ) {
  22013. const previousPipeline = data.pipeline;
  22014. if ( previousPipeline ) {
  22015. previousPipeline.usedTimes --;
  22016. previousPipeline.vertexProgram.usedTimes --;
  22017. previousPipeline.fragmentProgram.usedTimes --;
  22018. }
  22019. // get shader
  22020. const nodeBuilderState = renderObject.getNodeBuilderState();
  22021. // programmable stages
  22022. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  22023. if ( stageVertex === undefined ) {
  22024. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  22025. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  22026. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  22027. backend.createProgram( stageVertex );
  22028. }
  22029. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  22030. if ( stageFragment === undefined ) {
  22031. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  22032. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  22033. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  22034. backend.createProgram( stageFragment );
  22035. }
  22036. // determine render pipeline
  22037. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22038. let pipeline = this.caches.get( cacheKey );
  22039. if ( pipeline === undefined ) {
  22040. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  22041. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  22042. } else {
  22043. renderObject.pipeline = pipeline;
  22044. }
  22045. // keep track of all used times
  22046. pipeline.usedTimes ++;
  22047. stageVertex.usedTimes ++;
  22048. stageFragment.usedTimes ++;
  22049. //
  22050. data.pipeline = pipeline;
  22051. }
  22052. return data.pipeline;
  22053. }
  22054. delete( object ) {
  22055. const pipeline = this.get( object ).pipeline;
  22056. if ( pipeline ) {
  22057. // pipeline
  22058. pipeline.usedTimes --;
  22059. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  22060. // programs
  22061. if ( pipeline.isComputePipeline ) {
  22062. pipeline.computeProgram.usedTimes --;
  22063. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  22064. } else {
  22065. pipeline.fragmentProgram.usedTimes --;
  22066. pipeline.vertexProgram.usedTimes --;
  22067. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  22068. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  22069. }
  22070. }
  22071. return super.delete( object );
  22072. }
  22073. dispose() {
  22074. super.dispose();
  22075. this.caches = new Map();
  22076. this.programs = {
  22077. vertex: new Map(),
  22078. fragment: new Map(),
  22079. compute: new Map()
  22080. };
  22081. }
  22082. updateForRender( renderObject ) {
  22083. this.getForRender( renderObject );
  22084. }
  22085. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  22086. // check for existing pipeline
  22087. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  22088. let pipeline = this.caches.get( cacheKey );
  22089. if ( pipeline === undefined ) {
  22090. pipeline = new ComputePipeline( cacheKey, stageCompute );
  22091. this.caches.set( cacheKey, pipeline );
  22092. this.backend.createComputePipeline( pipeline, bindings );
  22093. }
  22094. return pipeline;
  22095. }
  22096. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  22097. // check for existing pipeline
  22098. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22099. let pipeline = this.caches.get( cacheKey );
  22100. if ( pipeline === undefined ) {
  22101. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  22102. this.caches.set( cacheKey, pipeline );
  22103. renderObject.pipeline = pipeline;
  22104. this.backend.createRenderPipeline( renderObject, promises );
  22105. }
  22106. return pipeline;
  22107. }
  22108. _getComputeCacheKey( computeNode, stageCompute ) {
  22109. return computeNode.id + ',' + stageCompute.id;
  22110. }
  22111. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  22112. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  22113. }
  22114. _releasePipeline( pipeline ) {
  22115. this.caches.delete( pipeline.cacheKey );
  22116. }
  22117. _releaseProgram( program ) {
  22118. const code = program.code;
  22119. const stage = program.stage;
  22120. this.programs[ stage ].delete( code );
  22121. }
  22122. _needsComputeUpdate( computeNode ) {
  22123. const data = this.get( computeNode );
  22124. return data.pipeline === undefined || data.version !== computeNode.version;
  22125. }
  22126. _needsRenderUpdate( renderObject ) {
  22127. const data = this.get( renderObject );
  22128. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  22129. }
  22130. }
  22131. class Bindings extends DataMap {
  22132. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  22133. super();
  22134. this.backend = backend;
  22135. this.textures = textures;
  22136. this.pipelines = pipelines;
  22137. this.attributes = attributes;
  22138. this.nodes = nodes;
  22139. this.info = info;
  22140. this.pipelines.bindings = this; // assign bindings to pipelines
  22141. }
  22142. getForRender( renderObject ) {
  22143. const bindings = renderObject.getBindings();
  22144. for ( const bindGroup of bindings ) {
  22145. const groupData = this.get( bindGroup );
  22146. if ( groupData.bindGroup === undefined ) {
  22147. // each object defines an array of bindings (ubos, textures, samplers etc.)
  22148. this._init( bindGroup );
  22149. this.backend.createBindings( bindGroup, bindings );
  22150. groupData.bindGroup = bindGroup;
  22151. }
  22152. }
  22153. return bindings;
  22154. }
  22155. getForCompute( computeNode ) {
  22156. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  22157. for ( const bindGroup of bindings ) {
  22158. const groupData = this.get( bindGroup );
  22159. if ( groupData.bindGroup === undefined ) {
  22160. this._init( bindGroup );
  22161. this.backend.createBindings( bindGroup, bindings );
  22162. groupData.bindGroup = bindGroup;
  22163. }
  22164. }
  22165. return bindings;
  22166. }
  22167. updateForCompute( computeNode ) {
  22168. this._updateBindings( computeNode, this.getForCompute( computeNode ) );
  22169. }
  22170. updateForRender( renderObject ) {
  22171. this._updateBindings( renderObject, this.getForRender( renderObject ) );
  22172. }
  22173. _updateBindings( object, bindings ) {
  22174. for ( const bindGroup of bindings ) {
  22175. this._update( object, bindGroup, bindings );
  22176. }
  22177. }
  22178. _init( bindGroup ) {
  22179. for ( const binding of bindGroup.bindings ) {
  22180. if ( binding.isSampledTexture ) {
  22181. this.textures.updateTexture( binding.texture );
  22182. } else if ( binding.isStorageBuffer ) {
  22183. const attribute = binding.attribute;
  22184. this.attributes.update( attribute, AttributeType.STORAGE );
  22185. }
  22186. }
  22187. }
  22188. _update( object, bindGroup, bindings ) {
  22189. const { backend } = this;
  22190. let needsBindingsUpdate = false;
  22191. // iterate over all bindings and check if buffer updates or a new binding group is required
  22192. for ( const binding of bindGroup.bindings ) {
  22193. if ( binding.isNodeUniformsGroup ) {
  22194. const updated = this.nodes.updateGroup( binding );
  22195. if ( ! updated ) continue;
  22196. }
  22197. if ( binding.isUniformBuffer ) {
  22198. const updated = binding.update();
  22199. if ( updated ) {
  22200. backend.updateBinding( binding );
  22201. }
  22202. } else if ( binding.isSampler ) {
  22203. binding.update();
  22204. } else if ( binding.isSampledTexture ) {
  22205. const texture = binding.texture;
  22206. if ( binding.needsBindingsUpdate ) needsBindingsUpdate = true;
  22207. const updated = binding.update();
  22208. if ( updated ) {
  22209. this.textures.updateTexture( binding.texture );
  22210. }
  22211. const textureData = backend.get( binding.texture );
  22212. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  22213. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  22214. console.error( 'Bindings._update: binding should be available:', binding, updated, binding.texture, binding.textureNode.value );
  22215. this.textures.updateTexture( binding.texture );
  22216. needsBindingsUpdate = true;
  22217. }
  22218. if ( texture.isStorageTexture === true ) {
  22219. const textureData = this.get( texture );
  22220. if ( binding.store === true ) {
  22221. textureData.needsMipmap = true;
  22222. } else if ( texture.generateMipmaps === true && this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  22223. this.backend.generateMipmaps( texture );
  22224. textureData.needsMipmap = false;
  22225. }
  22226. }
  22227. }
  22228. }
  22229. if ( needsBindingsUpdate === true ) {
  22230. const pipeline = this.pipelines.getForRender( object );
  22231. this.backend.updateBindings( bindGroup, bindings, pipeline );
  22232. }
  22233. }
  22234. }
  22235. const NodeShaderStage = {
  22236. VERTEX: 'vertex',
  22237. FRAGMENT: 'fragment'
  22238. };
  22239. const NodeUpdateType = {
  22240. NONE: 'none',
  22241. FRAME: 'frame',
  22242. RENDER: 'render',
  22243. OBJECT: 'object'
  22244. };
  22245. const NodeType = {
  22246. BOOLEAN: 'bool',
  22247. INTEGER: 'int',
  22248. FLOAT: 'float',
  22249. VECTOR2: 'vec2',
  22250. VECTOR3: 'vec3',
  22251. VECTOR4: 'vec4',
  22252. MATRIX2: 'mat2',
  22253. MATRIX3: 'mat3',
  22254. MATRIX4: 'mat4'
  22255. };
  22256. const defaultShaderStages = [ 'fragment', 'vertex' ];
  22257. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  22258. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  22259. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  22260. function getCacheKey( object, force = false ) {
  22261. let cacheKey = '{';
  22262. if ( object.isNode === true ) {
  22263. cacheKey += object.id;
  22264. }
  22265. for ( const { property, childNode } of getNodeChildren( object ) ) {
  22266. cacheKey += ',' + property.slice( 0, - 4 ) + ':' + childNode.getCacheKey( force );
  22267. }
  22268. cacheKey += '}';
  22269. return cacheKey;
  22270. }
  22271. function* getNodeChildren( node, toJSON = false ) {
  22272. for ( const property in node ) {
  22273. // Ignore private properties.
  22274. if ( property.startsWith( '_' ) === true ) continue;
  22275. const object = node[ property ];
  22276. if ( Array.isArray( object ) === true ) {
  22277. for ( let i = 0; i < object.length; i ++ ) {
  22278. const child = object[ i ];
  22279. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  22280. yield { property, index: i, childNode: child };
  22281. }
  22282. }
  22283. } else if ( object && object.isNode === true ) {
  22284. yield { property, childNode: object };
  22285. } else if ( typeof object === 'object' ) {
  22286. for ( const subProperty in object ) {
  22287. const child = object[ subProperty ];
  22288. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  22289. yield { property, index: subProperty, childNode: child };
  22290. }
  22291. }
  22292. }
  22293. }
  22294. }
  22295. function getValueType( value ) {
  22296. if ( value === undefined || value === null ) return null;
  22297. const typeOf = typeof value;
  22298. if ( value.isNode === true ) {
  22299. return 'node';
  22300. } else if ( typeOf === 'number' ) {
  22301. return 'float';
  22302. } else if ( typeOf === 'boolean' ) {
  22303. return 'bool';
  22304. } else if ( typeOf === 'string' ) {
  22305. return 'string';
  22306. } else if ( typeOf === 'function' ) {
  22307. return 'shader';
  22308. } else if ( value.isVector2 === true ) {
  22309. return 'vec2';
  22310. } else if ( value.isVector3 === true ) {
  22311. return 'vec3';
  22312. } else if ( value.isVector4 === true ) {
  22313. return 'vec4';
  22314. } else if ( value.isMatrix3 === true ) {
  22315. return 'mat3';
  22316. } else if ( value.isMatrix4 === true ) {
  22317. return 'mat4';
  22318. } else if ( value.isColor === true ) {
  22319. return 'color';
  22320. } else if ( value instanceof ArrayBuffer ) {
  22321. return 'ArrayBuffer';
  22322. }
  22323. return null;
  22324. }
  22325. function getValueFromType( type, ...params ) {
  22326. const last4 = type ? type.slice( - 4 ) : undefined;
  22327. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  22328. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  22329. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  22330. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  22331. }
  22332. if ( type === 'color' ) {
  22333. return new Color( ...params );
  22334. } else if ( last4 === 'vec2' ) {
  22335. return new Vector2( ...params );
  22336. } else if ( last4 === 'vec3' ) {
  22337. return new Vector3( ...params );
  22338. } else if ( last4 === 'vec4' ) {
  22339. return new Vector4( ...params );
  22340. } else if ( last4 === 'mat3' ) {
  22341. return new Matrix3( ...params );
  22342. } else if ( last4 === 'mat4' ) {
  22343. return new Matrix4( ...params );
  22344. } else if ( type === 'bool' ) {
  22345. return params[ 0 ] || false;
  22346. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  22347. return params[ 0 ] || 0;
  22348. } else if ( type === 'string' ) {
  22349. return params[ 0 ] || '';
  22350. } else if ( type === 'ArrayBuffer' ) {
  22351. return base64ToArrayBuffer( params[ 0 ] );
  22352. }
  22353. return null;
  22354. }
  22355. function arrayBufferToBase64( arrayBuffer ) {
  22356. let chars = '';
  22357. const array = new Uint8Array( arrayBuffer );
  22358. for ( let i = 0; i < array.length; i ++ ) {
  22359. chars += String.fromCharCode( array[ i ] );
  22360. }
  22361. return btoa( chars );
  22362. }
  22363. function base64ToArrayBuffer( base64 ) {
  22364. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  22365. }
  22366. var NodeUtils = /*#__PURE__*/Object.freeze({
  22367. __proto__: null,
  22368. arrayBufferToBase64: arrayBufferToBase64,
  22369. base64ToArrayBuffer: base64ToArrayBuffer,
  22370. getCacheKey: getCacheKey,
  22371. getNodeChildren: getNodeChildren,
  22372. getValueFromType: getValueFromType,
  22373. getValueType: getValueType
  22374. });
  22375. const NodeClasses = new Map();
  22376. let _nodeId = 0;
  22377. class Node extends EventDispatcher {
  22378. constructor( nodeType = null ) {
  22379. super();
  22380. this.nodeType = nodeType;
  22381. this.updateType = NodeUpdateType.NONE;
  22382. this.updateBeforeType = NodeUpdateType.NONE;
  22383. this.updateAfterType = NodeUpdateType.NONE;
  22384. this.uuid = MathUtils.generateUUID();
  22385. this.version = 0;
  22386. this._cacheKey = null;
  22387. this._cacheKeyVersion = 0;
  22388. this.global = false;
  22389. this.isNode = true;
  22390. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  22391. }
  22392. set needsUpdate( value ) {
  22393. if ( value === true ) {
  22394. this.version ++;
  22395. }
  22396. }
  22397. get type() {
  22398. return this.constructor.type;
  22399. }
  22400. onUpdate( callback, updateType ) {
  22401. this.updateType = updateType;
  22402. this.update = callback.bind( this.getSelf() );
  22403. return this;
  22404. }
  22405. onFrameUpdate( callback ) {
  22406. return this.onUpdate( callback, NodeUpdateType.FRAME );
  22407. }
  22408. onRenderUpdate( callback ) {
  22409. return this.onUpdate( callback, NodeUpdateType.RENDER );
  22410. }
  22411. onObjectUpdate( callback ) {
  22412. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  22413. }
  22414. onReference( callback ) {
  22415. this.updateReference = callback.bind( this.getSelf() );
  22416. return this;
  22417. }
  22418. getSelf() {
  22419. // Returns non-node object.
  22420. return this.self || this;
  22421. }
  22422. updateReference( /*state*/ ) {
  22423. return this;
  22424. }
  22425. isGlobal( /*builder*/ ) {
  22426. return this.global;
  22427. }
  22428. * getChildren() {
  22429. for ( const { childNode } of getNodeChildren( this ) ) {
  22430. yield childNode;
  22431. }
  22432. }
  22433. dispose() {
  22434. this.dispatchEvent( { type: 'dispose' } );
  22435. }
  22436. traverse( callback ) {
  22437. callback( this );
  22438. for ( const childNode of this.getChildren() ) {
  22439. childNode.traverse( callback );
  22440. }
  22441. }
  22442. getCacheKey( force = false ) {
  22443. force = force || this.version !== this._cacheKeyVersion;
  22444. if ( force === true || this._cacheKey === null ) {
  22445. this._cacheKey = getCacheKey( this, force );
  22446. this._cacheKeyVersion = this.version;
  22447. }
  22448. return this._cacheKey;
  22449. }
  22450. getHash( /*builder*/ ) {
  22451. return this.uuid;
  22452. }
  22453. getUpdateType() {
  22454. return this.updateType;
  22455. }
  22456. getUpdateBeforeType() {
  22457. return this.updateBeforeType;
  22458. }
  22459. getUpdateAfterType() {
  22460. return this.updateAfterType;
  22461. }
  22462. getElementType( builder ) {
  22463. const type = this.getNodeType( builder );
  22464. const elementType = builder.getElementType( type );
  22465. return elementType;
  22466. }
  22467. getNodeType( builder ) {
  22468. const nodeProperties = builder.getNodeProperties( this );
  22469. if ( nodeProperties.outputNode ) {
  22470. return nodeProperties.outputNode.getNodeType( builder );
  22471. }
  22472. return this.nodeType;
  22473. }
  22474. getShared( builder ) {
  22475. const hash = this.getHash( builder );
  22476. const nodeFromHash = builder.getNodeFromHash( hash );
  22477. return nodeFromHash || this;
  22478. }
  22479. setup( builder ) {
  22480. const nodeProperties = builder.getNodeProperties( this );
  22481. let index = 0;
  22482. for ( const childNode of this.getChildren() ) {
  22483. nodeProperties[ 'node' + index ++ ] = childNode;
  22484. }
  22485. // return a outputNode if exists
  22486. return null;
  22487. }
  22488. construct( builder ) { // @deprecated, r157
  22489. console.warn( 'THREE.Node: construct() is deprecated. Use setup() instead.' );
  22490. return this.setup( builder );
  22491. }
  22492. increaseUsage( builder ) {
  22493. const nodeData = builder.getDataFromNode( this );
  22494. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  22495. return nodeData.usageCount;
  22496. }
  22497. analyze( builder ) {
  22498. const usageCount = this.increaseUsage( builder );
  22499. if ( usageCount === 1 ) {
  22500. // node flow children
  22501. const nodeProperties = builder.getNodeProperties( this );
  22502. for ( const childNode of Object.values( nodeProperties ) ) {
  22503. if ( childNode && childNode.isNode === true ) {
  22504. childNode.build( builder );
  22505. }
  22506. }
  22507. }
  22508. }
  22509. generate( builder, output ) {
  22510. const { outputNode } = builder.getNodeProperties( this );
  22511. if ( outputNode && outputNode.isNode === true ) {
  22512. return outputNode.build( builder, output );
  22513. }
  22514. }
  22515. updateBefore( /*frame*/ ) {
  22516. console.warn( 'Abstract function.' );
  22517. }
  22518. updateAfter( /*frame*/ ) {
  22519. console.warn( 'Abstract function.' );
  22520. }
  22521. update( /*frame*/ ) {
  22522. console.warn( 'Abstract function.' );
  22523. }
  22524. build( builder, output = null ) {
  22525. const refNode = this.getShared( builder );
  22526. if ( this !== refNode ) {
  22527. return refNode.build( builder, output );
  22528. }
  22529. builder.addNode( this );
  22530. builder.addChain( this );
  22531. /* Build stages expected results:
  22532. - "setup" -> Node
  22533. - "analyze" -> null
  22534. - "generate" -> String
  22535. */
  22536. let result = null;
  22537. const buildStage = builder.getBuildStage();
  22538. if ( buildStage === 'setup' ) {
  22539. this.updateReference( builder );
  22540. const properties = builder.getNodeProperties( this );
  22541. if ( properties.initialized !== true ) {
  22542. const stackNodesBeforeSetup = builder.stack.nodes.length;
  22543. properties.initialized = true;
  22544. properties.outputNode = this.setup( builder );
  22545. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  22546. properties.outputNode = builder.stack;
  22547. }
  22548. for ( const childNode of Object.values( properties ) ) {
  22549. if ( childNode && childNode.isNode === true ) {
  22550. childNode.build( builder );
  22551. }
  22552. }
  22553. }
  22554. } else if ( buildStage === 'analyze' ) {
  22555. this.analyze( builder );
  22556. } else if ( buildStage === 'generate' ) {
  22557. const isGenerateOnce = this.generate.length === 1;
  22558. if ( isGenerateOnce ) {
  22559. const type = this.getNodeType( builder );
  22560. const nodeData = builder.getDataFromNode( this );
  22561. result = nodeData.snippet;
  22562. if ( result === undefined ) {
  22563. result = this.generate( builder ) || '';
  22564. nodeData.snippet = result;
  22565. }
  22566. result = builder.format( result, type, output );
  22567. } else {
  22568. result = this.generate( builder, output ) || '';
  22569. }
  22570. }
  22571. builder.removeChain( this );
  22572. return result;
  22573. }
  22574. getSerializeChildren() {
  22575. return getNodeChildren( this );
  22576. }
  22577. serialize( json ) {
  22578. const nodeChildren = this.getSerializeChildren();
  22579. const inputNodes = {};
  22580. for ( const { property, index, childNode } of nodeChildren ) {
  22581. if ( index !== undefined ) {
  22582. if ( inputNodes[ property ] === undefined ) {
  22583. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  22584. }
  22585. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  22586. } else {
  22587. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  22588. }
  22589. }
  22590. if ( Object.keys( inputNodes ).length > 0 ) {
  22591. json.inputNodes = inputNodes;
  22592. }
  22593. }
  22594. deserialize( json ) {
  22595. if ( json.inputNodes !== undefined ) {
  22596. const nodes = json.meta.nodes;
  22597. for ( const property in json.inputNodes ) {
  22598. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  22599. const inputArray = [];
  22600. for ( const uuid of json.inputNodes[ property ] ) {
  22601. inputArray.push( nodes[ uuid ] );
  22602. }
  22603. this[ property ] = inputArray;
  22604. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  22605. const inputObject = {};
  22606. for ( const subProperty in json.inputNodes[ property ] ) {
  22607. const uuid = json.inputNodes[ property ][ subProperty ];
  22608. inputObject[ subProperty ] = nodes[ uuid ];
  22609. }
  22610. this[ property ] = inputObject;
  22611. } else {
  22612. const uuid = json.inputNodes[ property ];
  22613. this[ property ] = nodes[ uuid ];
  22614. }
  22615. }
  22616. }
  22617. }
  22618. toJSON( meta ) {
  22619. const { uuid, type } = this;
  22620. const isRoot = ( meta === undefined || typeof meta === 'string' );
  22621. if ( isRoot ) {
  22622. meta = {
  22623. textures: {},
  22624. images: {},
  22625. nodes: {}
  22626. };
  22627. }
  22628. // serialize
  22629. let data = meta.nodes[ uuid ];
  22630. if ( data === undefined ) {
  22631. data = {
  22632. uuid,
  22633. type,
  22634. meta,
  22635. metadata: {
  22636. version: 4.6,
  22637. type: 'Node',
  22638. generator: 'Node.toJSON'
  22639. }
  22640. };
  22641. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  22642. this.serialize( data );
  22643. delete data.meta;
  22644. }
  22645. // TODO: Copied from Object3D.toJSON
  22646. function extractFromCache( cache ) {
  22647. const values = [];
  22648. for ( const key in cache ) {
  22649. const data = cache[ key ];
  22650. delete data.metadata;
  22651. values.push( data );
  22652. }
  22653. return values;
  22654. }
  22655. if ( isRoot ) {
  22656. const textures = extractFromCache( meta.textures );
  22657. const images = extractFromCache( meta.images );
  22658. const nodes = extractFromCache( meta.nodes );
  22659. if ( textures.length > 0 ) data.textures = textures;
  22660. if ( images.length > 0 ) data.images = images;
  22661. if ( nodes.length > 0 ) data.nodes = nodes;
  22662. }
  22663. return data;
  22664. }
  22665. }
  22666. function addNodeClass( type, nodeClass ) {
  22667. if ( typeof nodeClass !== 'function' || ! type ) throw new Error( `Node class ${ type } is not a class` );
  22668. if ( NodeClasses.has( type ) ) {
  22669. console.warn( `Redefinition of node class ${ type }` );
  22670. return;
  22671. }
  22672. NodeClasses.set( type, nodeClass );
  22673. nodeClass.type = type;
  22674. }
  22675. function createNodeFromType( type ) {
  22676. const Class = NodeClasses.get( type );
  22677. if ( Class !== undefined ) {
  22678. return new Class();
  22679. }
  22680. }
  22681. class TempNode extends Node {
  22682. constructor( type ) {
  22683. super( type );
  22684. this.isTempNode = true;
  22685. }
  22686. hasDependencies( builder ) {
  22687. return builder.getDataFromNode( this ).usageCount > 1;
  22688. }
  22689. build( builder, output ) {
  22690. const buildStage = builder.getBuildStage();
  22691. if ( buildStage === 'generate' ) {
  22692. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  22693. const nodeData = builder.getDataFromNode( this );
  22694. if ( nodeData.propertyName !== undefined ) {
  22695. return builder.format( nodeData.propertyName, type, output );
  22696. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  22697. const snippet = super.build( builder, type );
  22698. const nodeVar = builder.getVarFromNode( this, null, type );
  22699. const propertyName = builder.getPropertyName( nodeVar );
  22700. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  22701. nodeData.snippet = snippet;
  22702. nodeData.propertyName = propertyName;
  22703. return builder.format( nodeData.propertyName, type, output );
  22704. }
  22705. }
  22706. return super.build( builder, output );
  22707. }
  22708. }
  22709. addNodeClass( 'TempNode', TempNode );
  22710. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  22711. constructor( node, indexNode ) {
  22712. super();
  22713. this.node = node;
  22714. this.indexNode = indexNode;
  22715. this.isArrayElementNode = true;
  22716. }
  22717. getNodeType( builder ) {
  22718. return this.node.getElementType( builder );
  22719. }
  22720. generate( builder ) {
  22721. const nodeSnippet = this.node.build( builder );
  22722. const indexSnippet = this.indexNode.build( builder, 'uint' );
  22723. return `${nodeSnippet}[ ${indexSnippet} ]`;
  22724. }
  22725. }
  22726. addNodeClass( 'ArrayElementNode', ArrayElementNode );
  22727. class ConvertNode extends Node {
  22728. constructor( node, convertTo ) {
  22729. super();
  22730. this.node = node;
  22731. this.convertTo = convertTo;
  22732. }
  22733. getNodeType( builder ) {
  22734. const requestType = this.node.getNodeType( builder );
  22735. let convertTo = null;
  22736. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  22737. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  22738. convertTo = overloadingType;
  22739. }
  22740. }
  22741. return convertTo;
  22742. }
  22743. serialize( data ) {
  22744. super.serialize( data );
  22745. data.convertTo = this.convertTo;
  22746. }
  22747. deserialize( data ) {
  22748. super.deserialize( data );
  22749. this.convertTo = data.convertTo;
  22750. }
  22751. generate( builder, output ) {
  22752. const node = this.node;
  22753. const type = this.getNodeType( builder );
  22754. const snippet = node.build( builder, type );
  22755. return builder.format( snippet, type, output );
  22756. }
  22757. }
  22758. addNodeClass( 'ConvertNode', ConvertNode );
  22759. class JoinNode extends TempNode {
  22760. constructor( nodes = [], nodeType = null ) {
  22761. super( nodeType );
  22762. this.nodes = nodes;
  22763. }
  22764. getNodeType( builder ) {
  22765. if ( this.nodeType !== null ) {
  22766. return builder.getVectorType( this.nodeType );
  22767. }
  22768. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  22769. }
  22770. generate( builder, output ) {
  22771. const type = this.getNodeType( builder );
  22772. const nodes = this.nodes;
  22773. const primitiveType = builder.getComponentType( type );
  22774. const snippetValues = [];
  22775. for ( const input of nodes ) {
  22776. let inputSnippet = input.build( builder );
  22777. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  22778. if ( inputPrimitiveType !== primitiveType ) {
  22779. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  22780. }
  22781. snippetValues.push( inputSnippet );
  22782. }
  22783. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  22784. return builder.format( snippet, type, output );
  22785. }
  22786. }
  22787. addNodeClass( 'JoinNode', JoinNode );
  22788. const stringVectorComponents = vectorComponents.join( '' );
  22789. class SplitNode extends Node {
  22790. constructor( node, components = 'x' ) {
  22791. super();
  22792. this.node = node;
  22793. this.components = components;
  22794. this.isSplitNode = true;
  22795. }
  22796. getVectorLength() {
  22797. let vectorLength = this.components.length;
  22798. for ( const c of this.components ) {
  22799. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  22800. }
  22801. return vectorLength;
  22802. }
  22803. getComponentType( builder ) {
  22804. return builder.getComponentType( this.node.getNodeType( builder ) );
  22805. }
  22806. getNodeType( builder ) {
  22807. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  22808. }
  22809. generate( builder, output ) {
  22810. const node = this.node;
  22811. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  22812. let snippet = null;
  22813. if ( nodeTypeLength > 1 ) {
  22814. let type = null;
  22815. const componentsLength = this.getVectorLength();
  22816. if ( componentsLength >= nodeTypeLength ) {
  22817. // needed expand the input node
  22818. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  22819. }
  22820. const nodeSnippet = node.build( builder, type );
  22821. if ( this.components.length === nodeTypeLength && this.components === stringVectorComponents.slice( 0, this.components.length ) ) {
  22822. // unnecessary swizzle
  22823. snippet = builder.format( nodeSnippet, type, output );
  22824. } else {
  22825. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  22826. }
  22827. } else {
  22828. // ignore .components if .node returns float/integer
  22829. snippet = node.build( builder, output );
  22830. }
  22831. return snippet;
  22832. }
  22833. serialize( data ) {
  22834. super.serialize( data );
  22835. data.components = this.components;
  22836. }
  22837. deserialize( data ) {
  22838. super.deserialize( data );
  22839. this.components = data.components;
  22840. }
  22841. }
  22842. addNodeClass( 'SplitNode', SplitNode );
  22843. class SetNode extends TempNode {
  22844. constructor( sourceNode, components, targetNode ) {
  22845. super();
  22846. this.sourceNode = sourceNode;
  22847. this.components = components;
  22848. this.targetNode = targetNode;
  22849. }
  22850. getNodeType( builder ) {
  22851. return this.sourceNode.getNodeType( builder );
  22852. }
  22853. generate( builder ) {
  22854. const { sourceNode, components, targetNode } = this;
  22855. const sourceType = this.getNodeType( builder );
  22856. const targetType = builder.getTypeFromLength( components.length );
  22857. const targetSnippet = targetNode.build( builder, targetType );
  22858. const sourceSnippet = sourceNode.build( builder, sourceType );
  22859. const length = builder.getTypeLength( sourceType );
  22860. const snippetValues = [];
  22861. for ( let i = 0; i < length; i ++ ) {
  22862. const component = vectorComponents[ i ];
  22863. if ( component === components[ 0 ] ) {
  22864. snippetValues.push( targetSnippet );
  22865. i += components.length - 1;
  22866. } else {
  22867. snippetValues.push( sourceSnippet + '.' + component );
  22868. }
  22869. }
  22870. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  22871. }
  22872. }
  22873. addNodeClass( 'SetNode', SetNode );
  22874. class InputNode extends Node {
  22875. constructor( value, nodeType = null ) {
  22876. super( nodeType );
  22877. this.isInputNode = true;
  22878. this.value = value;
  22879. this.precision = null;
  22880. }
  22881. getNodeType( /*builder*/ ) {
  22882. if ( this.nodeType === null ) {
  22883. return getValueType( this.value );
  22884. }
  22885. return this.nodeType;
  22886. }
  22887. getInputType( builder ) {
  22888. return this.getNodeType( builder );
  22889. }
  22890. setPrecision( precision ) {
  22891. this.precision = precision;
  22892. return this;
  22893. }
  22894. serialize( data ) {
  22895. super.serialize( data );
  22896. data.value = this.value;
  22897. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  22898. data.valueType = getValueType( this.value );
  22899. data.nodeType = this.nodeType;
  22900. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  22901. data.precision = this.precision;
  22902. }
  22903. deserialize( data ) {
  22904. super.deserialize( data );
  22905. this.nodeType = data.nodeType;
  22906. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  22907. this.precision = data.precision || null;
  22908. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  22909. }
  22910. generate( /*builder, output*/ ) {
  22911. console.warn( 'Abstract function.' );
  22912. }
  22913. }
  22914. addNodeClass( 'InputNode', InputNode );
  22915. class ConstNode extends InputNode {
  22916. constructor( value, nodeType = null ) {
  22917. super( value, nodeType );
  22918. this.isConstNode = true;
  22919. }
  22920. generateConst( builder ) {
  22921. return builder.generateConst( this.getNodeType( builder ), this.value );
  22922. }
  22923. generate( builder, output ) {
  22924. const type = this.getNodeType( builder );
  22925. return builder.format( this.generateConst( builder ), type, output );
  22926. }
  22927. }
  22928. addNodeClass( 'ConstNode', ConstNode );
  22929. //
  22930. let currentStack = null;
  22931. const NodeElements = new Map(); // @TODO: Currently only a few nodes are added, probably also add others
  22932. function addNodeElement( name, nodeElement ) {
  22933. if ( NodeElements.has( name ) ) {
  22934. console.warn( `Redefinition of node element ${ name }` );
  22935. return;
  22936. }
  22937. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  22938. NodeElements.set( name, nodeElement );
  22939. }
  22940. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  22941. const shaderNodeHandler = {
  22942. setup( NodeClosure, params ) {
  22943. const inputs = params.shift();
  22944. return NodeClosure( nodeObjects( inputs ), ...params );
  22945. },
  22946. get( node, prop, nodeObj ) {
  22947. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22948. if ( node.isStackNode !== true && prop === 'assign' ) {
  22949. return ( ...params ) => {
  22950. currentStack.assign( nodeObj, ...params );
  22951. return nodeObj;
  22952. };
  22953. } else if ( NodeElements.has( prop ) ) {
  22954. const nodeElement = NodeElements.get( prop );
  22955. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  22956. } else if ( prop === 'self' ) {
  22957. return node;
  22958. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  22959. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  22960. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  22961. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  22962. // accessing properties ( swizzle )
  22963. prop = parseSwizzle( prop );
  22964. return nodeObject( new SplitNode( nodeObj, prop ) );
  22965. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  22966. // set properties ( swizzle )
  22967. prop = parseSwizzle( prop.slice( 3 ).toLowerCase() );
  22968. // sort to xyzw sequence
  22969. prop = prop.split( '' ).sort().join( '' );
  22970. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  22971. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  22972. // accessing property
  22973. if ( prop === 'width' ) prop = 'x';
  22974. else if ( prop === 'height' ) prop = 'y';
  22975. else if ( prop === 'depth' ) prop = 'z';
  22976. return nodeObject( new SplitNode( node, prop ) );
  22977. } else if ( /^\d+$/.test( prop ) === true ) {
  22978. // accessing array
  22979. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  22980. }
  22981. }
  22982. return Reflect.get( node, prop, nodeObj );
  22983. },
  22984. set( node, prop, value, nodeObj ) {
  22985. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22986. // setting properties
  22987. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  22988. nodeObj[ prop ].assign( value );
  22989. return true;
  22990. }
  22991. }
  22992. return Reflect.set( node, prop, value, nodeObj );
  22993. }
  22994. };
  22995. const nodeObjectsCacheMap = new WeakMap();
  22996. const nodeBuilderFunctionsCacheMap = new WeakMap();
  22997. const ShaderNodeObject = function ( obj, altType = null ) {
  22998. const type = getValueType( obj );
  22999. if ( type === 'node' ) {
  23000. let nodeObject = nodeObjectsCacheMap.get( obj );
  23001. if ( nodeObject === undefined ) {
  23002. nodeObject = new Proxy( obj, shaderNodeHandler );
  23003. nodeObjectsCacheMap.set( obj, nodeObject );
  23004. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  23005. }
  23006. return nodeObject;
  23007. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  23008. return nodeObject( getConstNode( obj, altType ) );
  23009. } else if ( type === 'shader' ) {
  23010. return tslFn( obj );
  23011. }
  23012. return obj;
  23013. };
  23014. const ShaderNodeObjects = function ( objects, altType = null ) {
  23015. for ( const name in objects ) {
  23016. objects[ name ] = nodeObject( objects[ name ], altType );
  23017. }
  23018. return objects;
  23019. };
  23020. const ShaderNodeArray = function ( array, altType = null ) {
  23021. const len = array.length;
  23022. for ( let i = 0; i < len; i ++ ) {
  23023. array[ i ] = nodeObject( array[ i ], altType );
  23024. }
  23025. return array;
  23026. };
  23027. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  23028. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  23029. if ( scope === null ) {
  23030. return ( ...params ) => {
  23031. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  23032. };
  23033. } else if ( factor !== null ) {
  23034. factor = nodeObject( factor );
  23035. return ( ...params ) => {
  23036. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  23037. };
  23038. } else {
  23039. return ( ...params ) => {
  23040. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  23041. };
  23042. }
  23043. };
  23044. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  23045. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  23046. };
  23047. class ShaderCallNodeInternal extends Node {
  23048. constructor( shaderNode, inputNodes ) {
  23049. super();
  23050. this.shaderNode = shaderNode;
  23051. this.inputNodes = inputNodes;
  23052. }
  23053. getNodeType( builder ) {
  23054. const properties = builder.getNodeProperties( this );
  23055. if ( properties.outputNode === null ) {
  23056. properties.outputNode = this.setupOutput( builder );
  23057. }
  23058. return properties.outputNode.getNodeType( builder );
  23059. }
  23060. call( builder ) {
  23061. const { shaderNode, inputNodes } = this;
  23062. if ( shaderNode.layout ) {
  23063. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  23064. if ( functionNodesCacheMap === undefined ) {
  23065. functionNodesCacheMap = new WeakMap();
  23066. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  23067. }
  23068. let functionNode = functionNodesCacheMap.get( shaderNode );
  23069. if ( functionNode === undefined ) {
  23070. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  23071. functionNodesCacheMap.set( shaderNode, functionNode );
  23072. }
  23073. if ( builder.currentFunctionNode !== null ) {
  23074. builder.currentFunctionNode.includes.push( functionNode );
  23075. }
  23076. return nodeObject( functionNode.call( inputNodes ) );
  23077. }
  23078. const jsFunc = shaderNode.jsFunc;
  23079. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder.stack, builder ) : jsFunc( builder.stack, builder );
  23080. return nodeObject( outputNode );
  23081. }
  23082. setup( builder ) {
  23083. const { outputNode } = builder.getNodeProperties( this );
  23084. return outputNode || this.setupOutput( builder );
  23085. }
  23086. setupOutput( builder ) {
  23087. builder.addStack();
  23088. builder.stack.outputNode = this.call( builder );
  23089. return builder.removeStack();
  23090. }
  23091. generate( builder, output ) {
  23092. const { outputNode } = builder.getNodeProperties( this );
  23093. if ( outputNode === null ) {
  23094. // TSL: It's recommended to use `tslFn` in setup() pass.
  23095. return this.call( builder ).build( builder, output );
  23096. }
  23097. return super.generate( builder, output );
  23098. }
  23099. }
  23100. class ShaderNodeInternal extends Node {
  23101. constructor( jsFunc ) {
  23102. super();
  23103. this.jsFunc = jsFunc;
  23104. this.layout = null;
  23105. this.global = true;
  23106. }
  23107. get isArrayInput() {
  23108. return /^\((\s+)?\[/.test( this.jsFunc.toString() );
  23109. }
  23110. setLayout( layout ) {
  23111. this.layout = layout;
  23112. return this;
  23113. }
  23114. call( inputs = null ) {
  23115. nodeObjects( inputs );
  23116. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  23117. }
  23118. setup() {
  23119. return this.call();
  23120. }
  23121. }
  23122. const bools = [ false, true ];
  23123. const uints = [ 0, 1, 2, 3 ];
  23124. const ints = [ - 1, - 2 ];
  23125. 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 ];
  23126. const boolsCacheMap = new Map();
  23127. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  23128. const uintsCacheMap = new Map();
  23129. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  23130. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  23131. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  23132. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  23133. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  23134. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  23135. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  23136. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  23137. const getConstNode = ( value, type ) => {
  23138. if ( constNodesCacheMap.has( value ) ) {
  23139. return constNodesCacheMap.get( value );
  23140. } else if ( value.isNode === true ) {
  23141. return value;
  23142. } else {
  23143. return new ConstNode( value, type );
  23144. }
  23145. };
  23146. const safeGetNodeType = ( node ) => {
  23147. try {
  23148. return node.getNodeType();
  23149. } catch ( _ ) {
  23150. return undefined;
  23151. }
  23152. };
  23153. const ConvertType = function ( type, cacheMap = null ) {
  23154. return ( ...params ) => {
  23155. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  23156. params = [ getValueFromType( type, ...params ) ];
  23157. }
  23158. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  23159. return nodeObject( cacheMap.get( params[ 0 ] ) );
  23160. }
  23161. if ( params.length === 1 ) {
  23162. const node = getConstNode( params[ 0 ], type );
  23163. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  23164. return nodeObject( new ConvertNode( node, type ) );
  23165. }
  23166. const nodes = params.map( param => getConstNode( param ) );
  23167. return nodeObject( new JoinNode( nodes, type ) );
  23168. };
  23169. };
  23170. // exports
  23171. const defined = ( value ) => value && value.value;
  23172. // utils
  23173. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  23174. // shader node base
  23175. function ShaderNode( jsFunc ) {
  23176. return new Proxy( new ShaderNodeInternal( jsFunc ), shaderNodeHandler );
  23177. }
  23178. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  23179. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  23180. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  23181. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  23182. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  23183. const tslFn = ( jsFunc ) => {
  23184. const shaderNode = new ShaderNode( jsFunc );
  23185. const fn = ( ...params ) => {
  23186. let inputs;
  23187. nodeObjects( params );
  23188. if ( params[ 0 ] && params[ 0 ].isNode ) {
  23189. inputs = [ ...params ];
  23190. } else {
  23191. inputs = params[ 0 ];
  23192. }
  23193. return shaderNode.call( inputs );
  23194. };
  23195. fn.shaderNode = shaderNode;
  23196. fn.setLayout = ( layout ) => {
  23197. shaderNode.setLayout( layout );
  23198. return fn;
  23199. };
  23200. return fn;
  23201. };
  23202. addNodeClass( 'ShaderNode', ShaderNode );
  23203. //
  23204. addNodeElement( 'toGlobal', ( node ) => {
  23205. node.global = true;
  23206. return node;
  23207. } );
  23208. //
  23209. const setCurrentStack = ( stack ) => {
  23210. currentStack = stack;
  23211. };
  23212. const getCurrentStack = () => currentStack;
  23213. const If = ( ...params ) => currentStack.if( ...params );
  23214. function append( node ) {
  23215. if ( currentStack ) currentStack.add( node );
  23216. return node;
  23217. }
  23218. addNodeElement( 'append', append );
  23219. // types
  23220. // @TODO: Maybe export from ConstNode.js?
  23221. const color = new ConvertType( 'color' );
  23222. const float = new ConvertType( 'float', cacheMaps.float );
  23223. const int = new ConvertType( 'int', cacheMaps.ints );
  23224. const uint = new ConvertType( 'uint', cacheMaps.uint );
  23225. const bool = new ConvertType( 'bool', cacheMaps.bool );
  23226. const vec2 = new ConvertType( 'vec2' );
  23227. const ivec2 = new ConvertType( 'ivec2' );
  23228. const uvec2 = new ConvertType( 'uvec2' );
  23229. const bvec2 = new ConvertType( 'bvec2' );
  23230. const vec3 = new ConvertType( 'vec3' );
  23231. const ivec3 = new ConvertType( 'ivec3' );
  23232. const uvec3 = new ConvertType( 'uvec3' );
  23233. const bvec3 = new ConvertType( 'bvec3' );
  23234. const vec4 = new ConvertType( 'vec4' );
  23235. const ivec4 = new ConvertType( 'ivec4' );
  23236. const uvec4 = new ConvertType( 'uvec4' );
  23237. const bvec4 = new ConvertType( 'bvec4' );
  23238. const mat2 = new ConvertType( 'mat2' );
  23239. const imat2 = new ConvertType( 'imat2' );
  23240. const umat2 = new ConvertType( 'umat2' );
  23241. const bmat2 = new ConvertType( 'bmat2' );
  23242. const mat3 = new ConvertType( 'mat3' );
  23243. const imat3 = new ConvertType( 'imat3' );
  23244. const umat3 = new ConvertType( 'umat3' );
  23245. const bmat3 = new ConvertType( 'bmat3' );
  23246. const mat4 = new ConvertType( 'mat4' );
  23247. const imat4 = new ConvertType( 'imat4' );
  23248. const umat4 = new ConvertType( 'umat4' );
  23249. const bmat4 = new ConvertType( 'bmat4' );
  23250. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  23251. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  23252. addNodeElement( 'toColor', color );
  23253. addNodeElement( 'toFloat', float );
  23254. addNodeElement( 'toInt', int );
  23255. addNodeElement( 'toUint', uint );
  23256. addNodeElement( 'toBool', bool );
  23257. addNodeElement( 'toVec2', vec2 );
  23258. addNodeElement( 'toIvec2', ivec2 );
  23259. addNodeElement( 'toUvec2', uvec2 );
  23260. addNodeElement( 'toBvec2', bvec2 );
  23261. addNodeElement( 'toVec3', vec3 );
  23262. addNodeElement( 'toIvec3', ivec3 );
  23263. addNodeElement( 'toUvec3', uvec3 );
  23264. addNodeElement( 'toBvec3', bvec3 );
  23265. addNodeElement( 'toVec4', vec4 );
  23266. addNodeElement( 'toIvec4', ivec4 );
  23267. addNodeElement( 'toUvec4', uvec4 );
  23268. addNodeElement( 'toBvec4', bvec4 );
  23269. addNodeElement( 'toMat2', mat2 );
  23270. addNodeElement( 'toImat2', imat2 );
  23271. addNodeElement( 'toUmat2', umat2 );
  23272. addNodeElement( 'toBmat2', bmat2 );
  23273. addNodeElement( 'toMat3', mat3 );
  23274. addNodeElement( 'toImat3', imat3 );
  23275. addNodeElement( 'toUmat3', umat3 );
  23276. addNodeElement( 'toBmat3', bmat3 );
  23277. addNodeElement( 'toMat4', mat4 );
  23278. addNodeElement( 'toImat4', imat4 );
  23279. addNodeElement( 'toUmat4', umat4 );
  23280. addNodeElement( 'toBmat4', bmat4 );
  23281. // basic nodes
  23282. // HACK - we cannot export them from the corresponding files because of the cyclic dependency
  23283. const element = nodeProxy( ArrayElementNode );
  23284. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  23285. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  23286. addNodeElement( 'element', element );
  23287. addNodeElement( 'convert', convert );
  23288. class AssignNode extends TempNode {
  23289. constructor( targetNode, sourceNode ) {
  23290. super();
  23291. this.targetNode = targetNode;
  23292. this.sourceNode = sourceNode;
  23293. }
  23294. hasDependencies() {
  23295. return false;
  23296. }
  23297. getNodeType( builder, output ) {
  23298. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  23299. }
  23300. needsSplitAssign( builder ) {
  23301. const { targetNode } = this;
  23302. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  23303. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  23304. const assignDiferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  23305. return assignDiferentVector;
  23306. }
  23307. return false;
  23308. }
  23309. generate( builder, output ) {
  23310. const { targetNode, sourceNode } = this;
  23311. const needsSplitAssign = this.needsSplitAssign( builder );
  23312. const targetType = targetNode.getNodeType( builder );
  23313. const target = targetNode.context( { assign: true } ).build( builder );
  23314. const source = sourceNode.build( builder, targetType );
  23315. const sourceType = sourceNode.getNodeType( builder );
  23316. const nodeData = builder.getDataFromNode( this );
  23317. //
  23318. let snippet;
  23319. if ( nodeData.initialized === true ) {
  23320. if ( output !== 'void' ) {
  23321. snippet = target;
  23322. }
  23323. } else if ( needsSplitAssign ) {
  23324. const sourceVar = builder.getVarFromNode( this, null, targetType );
  23325. const sourceProperty = builder.getPropertyName( sourceVar );
  23326. builder.addLineFlowCode( `${ sourceProperty } = ${ source }` );
  23327. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  23328. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  23329. const component = targetNode.components[ i ];
  23330. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]` );
  23331. }
  23332. if ( output !== 'void' ) {
  23333. snippet = target;
  23334. }
  23335. } else {
  23336. snippet = `${ target } = ${ source }`;
  23337. if ( output === 'void' || sourceType === 'void' ) {
  23338. builder.addLineFlowCode( snippet );
  23339. if ( output !== 'void' ) {
  23340. snippet = target;
  23341. }
  23342. }
  23343. }
  23344. nodeData.initialized = true;
  23345. return builder.format( snippet, targetType, output );
  23346. }
  23347. }
  23348. const assign = nodeProxy( AssignNode );
  23349. addNodeClass( 'AssignNode', AssignNode );
  23350. addNodeElement( 'assign', assign );
  23351. class VaryingNode extends Node {
  23352. constructor( node, name = null ) {
  23353. super();
  23354. this.node = node;
  23355. this.name = name;
  23356. this.isVaryingNode = true;
  23357. }
  23358. isGlobal() {
  23359. return true;
  23360. }
  23361. getHash( builder ) {
  23362. return this.name || super.getHash( builder );
  23363. }
  23364. getNodeType( builder ) {
  23365. // VaryingNode is auto type
  23366. return this.node.getNodeType( builder );
  23367. }
  23368. setupVarying( builder ) {
  23369. const properties = builder.getNodeProperties( this );
  23370. let varying = properties.varying;
  23371. if ( varying === undefined ) {
  23372. const name = this.name;
  23373. const type = this.getNodeType( builder );
  23374. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  23375. properties.node = this.node;
  23376. }
  23377. // this property can be used to check if the varying can be optimized for a variable
  23378. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  23379. return varying;
  23380. }
  23381. setup( builder ) {
  23382. this.setupVarying( builder );
  23383. }
  23384. analyze( builder ) {
  23385. this.setupVarying( builder );
  23386. return this.node.analyze( builder );
  23387. }
  23388. generate( builder ) {
  23389. const properties = builder.getNodeProperties( this );
  23390. const varying = this.setupVarying( builder );
  23391. if ( properties.propertyName === undefined ) {
  23392. const type = this.getNodeType( builder );
  23393. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  23394. // force node run in vertex stage
  23395. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  23396. properties.propertyName = propertyName;
  23397. }
  23398. return builder.getPropertyName( varying );
  23399. }
  23400. }
  23401. const varying = nodeProxy( VaryingNode );
  23402. addNodeElement( 'varying', varying );
  23403. addNodeClass( 'VaryingNode', VaryingNode );
  23404. class AttributeNode extends Node {
  23405. constructor( attributeName, nodeType = null, defaultNode = null ) {
  23406. super( nodeType );
  23407. this.defaultNode = defaultNode;
  23408. this.global = true;
  23409. this._attributeName = attributeName;
  23410. }
  23411. getHash( builder ) {
  23412. return this.getAttributeName( builder );
  23413. }
  23414. getNodeType( builder ) {
  23415. let nodeType = super.getNodeType( builder );
  23416. if ( nodeType === null ) {
  23417. const attributeName = this.getAttributeName( builder );
  23418. if ( builder.hasGeometryAttribute( attributeName ) ) {
  23419. const attribute = builder.geometry.getAttribute( attributeName );
  23420. nodeType = builder.getTypeFromAttribute( attribute );
  23421. } else {
  23422. nodeType = 'float';
  23423. }
  23424. }
  23425. return nodeType;
  23426. }
  23427. setAttributeName( attributeName ) {
  23428. this._attributeName = attributeName;
  23429. return this;
  23430. }
  23431. getAttributeName( /*builder*/ ) {
  23432. return this._attributeName;
  23433. }
  23434. generate( builder ) {
  23435. const attributeName = this.getAttributeName( builder );
  23436. const nodeType = this.getNodeType( builder );
  23437. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  23438. if ( geometryAttribute === true ) {
  23439. const attribute = builder.geometry.getAttribute( attributeName );
  23440. const attributeType = builder.getTypeFromAttribute( attribute );
  23441. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  23442. if ( builder.shaderStage === 'vertex' ) {
  23443. return builder.format( nodeAttribute.name, attributeType, nodeType );
  23444. } else {
  23445. const nodeVarying = varying( this );
  23446. return nodeVarying.build( builder, nodeType );
  23447. }
  23448. } else {
  23449. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  23450. const { defaultNode } = this;
  23451. if ( defaultNode !== null ) {
  23452. return defaultNode.build( builder, nodeType );
  23453. } else {
  23454. return builder.generateConst( nodeType );
  23455. }
  23456. }
  23457. }
  23458. }
  23459. const attribute = ( name, nodeType, defaultNode ) => nodeObject( new AttributeNode( name, nodeType, nodeObject( defaultNode ) ) );
  23460. addNodeClass( 'AttributeNode', AttributeNode );
  23461. class BypassNode extends Node {
  23462. constructor( returnNode, callNode ) {
  23463. super();
  23464. this.isBypassNode = true;
  23465. this.outputNode = returnNode;
  23466. this.callNode = callNode;
  23467. }
  23468. getNodeType( builder ) {
  23469. return this.outputNode.getNodeType( builder );
  23470. }
  23471. generate( builder ) {
  23472. const snippet = this.callNode.build( builder, 'void' );
  23473. if ( snippet !== '' ) {
  23474. builder.addLineFlowCode( snippet );
  23475. }
  23476. return this.outputNode.build( builder );
  23477. }
  23478. }
  23479. const bypass = nodeProxy( BypassNode );
  23480. addNodeElement( 'bypass', bypass );
  23481. addNodeClass( 'BypassNode', BypassNode );
  23482. class CacheNode extends Node {
  23483. constructor( node, parent = true ) {
  23484. super();
  23485. this.node = node;
  23486. this.parent = parent;
  23487. this.isCacheNode = true;
  23488. }
  23489. getNodeType( builder ) {
  23490. return this.node.getNodeType( builder );
  23491. }
  23492. build( builder, ...params ) {
  23493. const previousCache = builder.getCache();
  23494. const cache = builder.getCacheFromNode( this, parent );
  23495. builder.setCache( cache );
  23496. const data = this.node.build( builder, ...params );
  23497. builder.setCache( previousCache );
  23498. return data;
  23499. }
  23500. }
  23501. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  23502. addNodeElement( 'cache', cache );
  23503. addNodeClass( 'CacheNode', CacheNode );
  23504. class ContextNode extends Node {
  23505. constructor( node, context = {} ) {
  23506. super();
  23507. this.isContextNode = true;
  23508. this.node = node;
  23509. this.context = context;
  23510. }
  23511. getNodeType( builder ) {
  23512. return this.node.getNodeType( builder );
  23513. }
  23514. analyze( builder ) {
  23515. this.node.build( builder );
  23516. }
  23517. setup( builder ) {
  23518. const previousContext = builder.getContext();
  23519. builder.setContext( { ...builder.context, ...this.context } );
  23520. const node = this.node.build( builder );
  23521. builder.setContext( previousContext );
  23522. return node;
  23523. }
  23524. generate( builder, output ) {
  23525. const previousContext = builder.getContext();
  23526. builder.setContext( { ...builder.context, ...this.context } );
  23527. const snippet = this.node.build( builder, output );
  23528. builder.setContext( previousContext );
  23529. return snippet;
  23530. }
  23531. }
  23532. const context = nodeProxy( ContextNode );
  23533. const label = ( node, name ) => context( node, { label: name } );
  23534. addNodeElement( 'context', context );
  23535. addNodeElement( 'label', label );
  23536. addNodeClass( 'ContextNode', ContextNode );
  23537. class IndexNode extends Node {
  23538. constructor( scope ) {
  23539. super( 'uint' );
  23540. this.scope = scope;
  23541. this.isInstanceIndexNode = true;
  23542. }
  23543. generate( builder ) {
  23544. const nodeType = this.getNodeType( builder );
  23545. const scope = this.scope;
  23546. let propertyName;
  23547. if ( scope === IndexNode.VERTEX ) {
  23548. propertyName = builder.getVertexIndex();
  23549. } else if ( scope === IndexNode.INSTANCE ) {
  23550. propertyName = builder.getInstanceIndex();
  23551. } else if ( scope === IndexNode.DRAW ) {
  23552. propertyName = builder.getDrawIndex();
  23553. } else {
  23554. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  23555. }
  23556. let output;
  23557. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  23558. output = propertyName;
  23559. } else {
  23560. const nodeVarying = varying( this );
  23561. output = nodeVarying.build( builder, nodeType );
  23562. }
  23563. return output;
  23564. }
  23565. }
  23566. IndexNode.VERTEX = 'vertex';
  23567. IndexNode.INSTANCE = 'instance';
  23568. IndexNode.DRAW = 'draw';
  23569. const vertexIndex = nodeImmutable( IndexNode, IndexNode.VERTEX );
  23570. const instanceIndex = nodeImmutable( IndexNode, IndexNode.INSTANCE );
  23571. const drawIndex = nodeImmutable( IndexNode, IndexNode.DRAW );
  23572. addNodeClass( 'IndexNode', IndexNode );
  23573. class LightingModel {
  23574. start( /*input, stack, builder*/ ) { }
  23575. finish( /*input, stack, builder*/ ) { }
  23576. direct( /*input, stack, builder*/ ) { }
  23577. directRectArea( /*input, stack, builder*/ ) {}
  23578. indirectDiffuse( /*input, stack, builder*/ ) { }
  23579. indirectSpecular( /*input, stack, builder*/ ) { }
  23580. ambientOcclusion( /*input, stack, builder*/ ) { }
  23581. }
  23582. class VarNode extends Node {
  23583. constructor( node, name = null ) {
  23584. super();
  23585. this.node = node;
  23586. this.name = name;
  23587. this.global = true;
  23588. this.isVarNode = true;
  23589. }
  23590. getHash( builder ) {
  23591. return this.name || super.getHash( builder );
  23592. }
  23593. getNodeType( builder ) {
  23594. return this.node.getNodeType( builder );
  23595. }
  23596. generate( builder ) {
  23597. const { node, name } = this;
  23598. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  23599. const propertyName = builder.getPropertyName( nodeVar );
  23600. const snippet = node.build( builder, nodeVar.type );
  23601. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  23602. return propertyName;
  23603. }
  23604. }
  23605. const temp = nodeProxy( VarNode );
  23606. addNodeElement( 'temp', temp ); // @TODO: Will be removed in the future
  23607. addNodeElement( 'toVar', ( ...params ) => temp( ...params ).append() );
  23608. addNodeClass( 'VarNode', VarNode );
  23609. class NodeAttribute {
  23610. constructor( name, type, node = null ) {
  23611. this.isNodeAttribute = true;
  23612. this.name = name;
  23613. this.type = type;
  23614. this.node = node;
  23615. }
  23616. }
  23617. class NodeUniform {
  23618. constructor( name, type, node ) {
  23619. this.isNodeUniform = true;
  23620. this.name = name;
  23621. this.type = type;
  23622. this.node = node.getSelf();
  23623. }
  23624. get value() {
  23625. return this.node.value;
  23626. }
  23627. set value( val ) {
  23628. this.node.value = val;
  23629. }
  23630. get id() {
  23631. return this.node.id;
  23632. }
  23633. get groupNode() {
  23634. return this.node.groupNode;
  23635. }
  23636. }
  23637. class NodeVar {
  23638. constructor( name, type ) {
  23639. this.isNodeVar = true;
  23640. this.name = name;
  23641. this.type = type;
  23642. }
  23643. }
  23644. class NodeVarying extends NodeVar {
  23645. constructor( name, type ) {
  23646. super( name, type );
  23647. this.needsInterpolation = false;
  23648. this.isNodeVarying = true;
  23649. }
  23650. }
  23651. class NodeCode {
  23652. constructor( name, type, code = '' ) {
  23653. this.name = name;
  23654. this.type = type;
  23655. this.code = code;
  23656. Object.defineProperty( this, 'isNodeCode', { value: true } );
  23657. }
  23658. }
  23659. class NodeKeywords {
  23660. constructor() {
  23661. this.keywords = [];
  23662. this.nodes = {};
  23663. this.keywordsCallback = {};
  23664. }
  23665. getNode( name ) {
  23666. let node = this.nodes[ name ];
  23667. if ( node === undefined && this.keywordsCallback[ name ] !== undefined ) {
  23668. node = this.keywordsCallback[ name ]( name );
  23669. this.nodes[ name ] = node;
  23670. }
  23671. return node;
  23672. }
  23673. addKeyword( name, callback ) {
  23674. this.keywords.push( name );
  23675. this.keywordsCallback[ name ] = callback;
  23676. return this;
  23677. }
  23678. parse( code ) {
  23679. const keywordNames = this.keywords;
  23680. const regExp = new RegExp( `\\b${keywordNames.join( '\\b|\\b' )}\\b`, 'g' );
  23681. const codeKeywords = code.match( regExp );
  23682. const keywordNodes = [];
  23683. if ( codeKeywords !== null ) {
  23684. for ( const keyword of codeKeywords ) {
  23685. const node = this.getNode( keyword );
  23686. if ( node !== undefined && keywordNodes.indexOf( node ) === - 1 ) {
  23687. keywordNodes.push( node );
  23688. }
  23689. }
  23690. }
  23691. return keywordNodes;
  23692. }
  23693. include( builder, code ) {
  23694. const keywordNodes = this.parse( code );
  23695. for ( const keywordNode of keywordNodes ) {
  23696. keywordNode.build( builder );
  23697. }
  23698. }
  23699. }
  23700. let id$3 = 0;
  23701. class NodeCache {
  23702. constructor( parent = null ) {
  23703. this.id = id$3 ++;
  23704. this.nodesData = new WeakMap();
  23705. this.parent = parent;
  23706. }
  23707. getData( node ) {
  23708. let data = this.nodesData.get( node );
  23709. if ( data === undefined && this.parent !== null ) {
  23710. data = this.parent.getData( node );
  23711. }
  23712. return data;
  23713. }
  23714. setData( node, data ) {
  23715. this.nodesData.set( node, data );
  23716. }
  23717. }
  23718. class PropertyNode extends Node {
  23719. constructor( nodeType, name = null, varying = false ) {
  23720. super( nodeType );
  23721. this.name = name;
  23722. this.varying = varying;
  23723. this.isPropertyNode = true;
  23724. }
  23725. getHash( builder ) {
  23726. return this.name || super.getHash( builder );
  23727. }
  23728. isGlobal( /*builder*/ ) {
  23729. return true;
  23730. }
  23731. generate( builder ) {
  23732. let nodeVar;
  23733. if ( this.varying === true ) {
  23734. nodeVar = builder.getVaryingFromNode( this, this.name );
  23735. nodeVar.needsInterpolation = true;
  23736. } else {
  23737. nodeVar = builder.getVarFromNode( this, this.name );
  23738. }
  23739. return builder.getPropertyName( nodeVar );
  23740. }
  23741. }
  23742. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  23743. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  23744. const diffuseColor = nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  23745. const roughness = nodeImmutable( PropertyNode, 'float', 'Roughness' );
  23746. const metalness = nodeImmutable( PropertyNode, 'float', 'Metalness' );
  23747. const clearcoat = nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  23748. const clearcoatRoughness = nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  23749. const sheen = nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  23750. const sheenRoughness = nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  23751. const iridescence = nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  23752. const iridescenceIOR = nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  23753. const iridescenceThickness = nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  23754. const alphaT = nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  23755. const anisotropy = nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  23756. const anisotropyT = nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  23757. const anisotropyB = nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  23758. const specularColor = nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  23759. const specularF90 = nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  23760. const shininess = nodeImmutable( PropertyNode, 'float', 'Shininess' );
  23761. const output = nodeImmutable( PropertyNode, 'vec4', 'Output' );
  23762. const dashSize = nodeImmutable( PropertyNode, 'float', 'dashSize' );
  23763. const gapSize = nodeImmutable( PropertyNode, 'float', 'gapSize' );
  23764. const pointWidth = nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  23765. const ior = nodeImmutable( PropertyNode, 'float', 'IOR' );
  23766. const transmission = nodeImmutable( PropertyNode, 'float', 'Transmission' );
  23767. const thickness = nodeImmutable( PropertyNode, 'float', 'Thickness' );
  23768. const attenuationDistance = nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  23769. const attenuationColor = nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  23770. const dispersion = nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  23771. addNodeClass( 'PropertyNode', PropertyNode );
  23772. class ParameterNode extends PropertyNode {
  23773. constructor( nodeType, name = null ) {
  23774. super( nodeType, name );
  23775. this.isParameterNode = true;
  23776. }
  23777. getHash() {
  23778. return this.uuid;
  23779. }
  23780. generate() {
  23781. return this.name;
  23782. }
  23783. }
  23784. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  23785. addNodeClass( 'ParameterNode', ParameterNode );
  23786. class CodeNode extends Node {
  23787. constructor( code = '', includes = [], language = '' ) {
  23788. super( 'code' );
  23789. this.isCodeNode = true;
  23790. this.code = code;
  23791. this.language = language;
  23792. this.includes = includes;
  23793. }
  23794. isGlobal() {
  23795. return true;
  23796. }
  23797. setIncludes( includes ) {
  23798. this.includes = includes;
  23799. return this;
  23800. }
  23801. getIncludes( /*builder*/ ) {
  23802. return this.includes;
  23803. }
  23804. generate( builder ) {
  23805. const includes = this.getIncludes( builder );
  23806. for ( const include of includes ) {
  23807. include.build( builder );
  23808. }
  23809. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  23810. nodeCode.code = this.code;
  23811. return nodeCode.code;
  23812. }
  23813. serialize( data ) {
  23814. super.serialize( data );
  23815. data.code = this.code;
  23816. data.language = this.language;
  23817. }
  23818. deserialize( data ) {
  23819. super.deserialize( data );
  23820. this.code = data.code;
  23821. this.language = data.language;
  23822. }
  23823. }
  23824. const code = nodeProxy( CodeNode );
  23825. const js = ( src, includes ) => code( src, includes, 'js' );
  23826. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  23827. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  23828. addNodeClass( 'CodeNode', CodeNode );
  23829. class FunctionNode extends CodeNode {
  23830. constructor( code = '', includes = [], language = '' ) {
  23831. super( code, includes, language );
  23832. this.keywords = {};
  23833. }
  23834. getNodeType( builder ) {
  23835. return this.getNodeFunction( builder ).type;
  23836. }
  23837. getInputs( builder ) {
  23838. return this.getNodeFunction( builder ).inputs;
  23839. }
  23840. getNodeFunction( builder ) {
  23841. const nodeData = builder.getDataFromNode( this );
  23842. let nodeFunction = nodeData.nodeFunction;
  23843. if ( nodeFunction === undefined ) {
  23844. nodeFunction = builder.parser.parseFunction( this.code );
  23845. nodeData.nodeFunction = nodeFunction;
  23846. }
  23847. return nodeFunction;
  23848. }
  23849. generate( builder, output ) {
  23850. super.generate( builder );
  23851. const nodeFunction = this.getNodeFunction( builder );
  23852. const name = nodeFunction.name;
  23853. const type = nodeFunction.type;
  23854. const nodeCode = builder.getCodeFromNode( this, type );
  23855. if ( name !== '' ) {
  23856. // use a custom property name
  23857. nodeCode.name = name;
  23858. }
  23859. const propertyName = builder.getPropertyName( nodeCode );
  23860. let code = this.getNodeFunction( builder ).getCode( propertyName );
  23861. const keywords = this.keywords;
  23862. const keywordsProperties = Object.keys( keywords );
  23863. if ( keywordsProperties.length > 0 ) {
  23864. for ( const property of keywordsProperties ) {
  23865. const propertyRegExp = new RegExp( `\\b${property}\\b`, 'g' );
  23866. const nodeProperty = keywords[ property ].build( builder, 'property' );
  23867. code = code.replace( propertyRegExp, nodeProperty );
  23868. }
  23869. }
  23870. nodeCode.code = code + '\n';
  23871. if ( output === 'property' ) {
  23872. return propertyName;
  23873. } else {
  23874. return builder.format( `${ propertyName }()`, type, output );
  23875. }
  23876. }
  23877. }
  23878. const nativeFn = ( code, includes = [], language = '' ) => {
  23879. for ( let i = 0; i < includes.length; i ++ ) {
  23880. const include = includes[ i ];
  23881. // TSL Function: glslFn, wgslFn
  23882. if ( typeof include === 'function' ) {
  23883. includes[ i ] = include.functionNode;
  23884. }
  23885. }
  23886. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  23887. const fn = ( ...params ) => functionNode.call( ...params );
  23888. fn.functionNode = functionNode;
  23889. return fn;
  23890. };
  23891. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  23892. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  23893. addNodeClass( 'FunctionNode', FunctionNode );
  23894. class UniformGroupNode extends Node {
  23895. constructor( name, shared = false ) {
  23896. super( 'string' );
  23897. this.name = name;
  23898. this.version = 0;
  23899. this.shared = shared;
  23900. this.isUniformGroup = true;
  23901. }
  23902. set needsUpdate( value ) {
  23903. if ( value === true ) this.version ++;
  23904. }
  23905. }
  23906. const uniformGroup = ( name ) => new UniformGroupNode( name );
  23907. const sharedUniformGroup = ( name ) => new UniformGroupNode( name, true );
  23908. const frameGroup = sharedUniformGroup( 'frame' );
  23909. const renderGroup = sharedUniformGroup( 'render' );
  23910. const objectGroup = uniformGroup( 'object' );
  23911. addNodeClass( 'UniformGroupNode', UniformGroupNode );
  23912. class UniformNode extends InputNode {
  23913. constructor( value, nodeType = null ) {
  23914. super( value, nodeType );
  23915. this.isUniformNode = true;
  23916. this.name = '';
  23917. this.groupNode = objectGroup;
  23918. }
  23919. label( name ) {
  23920. this.name = name;
  23921. return this;
  23922. }
  23923. setGroup( group ) {
  23924. this.groupNode = group;
  23925. return this;
  23926. }
  23927. getGroup() {
  23928. return this.groupNode;
  23929. }
  23930. getUniformHash( builder ) {
  23931. return this.getHash( builder );
  23932. }
  23933. onUpdate( callback, updateType ) {
  23934. const self = this.getSelf();
  23935. callback = callback.bind( self );
  23936. return super.onUpdate( ( frame ) => {
  23937. const value = callback( frame, self );
  23938. if ( value !== undefined ) {
  23939. this.value = value;
  23940. }
  23941. }, updateType );
  23942. }
  23943. generate( builder, output ) {
  23944. const type = this.getNodeType( builder );
  23945. const hash = this.getUniformHash( builder );
  23946. let sharedNode = builder.getNodeFromHash( hash );
  23947. if ( sharedNode === undefined ) {
  23948. builder.setHashNode( this, hash );
  23949. sharedNode = this;
  23950. }
  23951. const sharedNodeType = sharedNode.getInputType( builder );
  23952. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  23953. const propertyName = builder.getPropertyName( nodeUniform );
  23954. if ( builder.context.label !== undefined ) delete builder.context.label;
  23955. return builder.format( propertyName, type, output );
  23956. }
  23957. }
  23958. const uniform = ( arg1, arg2 ) => {
  23959. const nodeType = getConstNodeType( arg2 || arg1 );
  23960. // @TODO: get ConstNode from .traverse() in the future
  23961. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  23962. return nodeObject( new UniformNode( value, nodeType ) );
  23963. };
  23964. addNodeClass( 'UniformNode', UniformNode );
  23965. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  23966. class TextureSizeNode extends Node {
  23967. constructor( textureNode, levelNode = null ) {
  23968. super( 'uvec2' );
  23969. this.isTextureSizeNode = true;
  23970. this.textureNode = textureNode;
  23971. this.levelNode = levelNode;
  23972. }
  23973. generate( builder, output ) {
  23974. const textureProperty = this.textureNode.build( builder, 'property' );
  23975. const levelNode = this.levelNode.build( builder, 'int' );
  23976. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ levelNode } )`, this.getNodeType( builder ), output );
  23977. }
  23978. }
  23979. const textureSize = nodeProxy( TextureSizeNode );
  23980. addNodeElement( 'textureSize', textureSize );
  23981. addNodeClass( 'TextureSizeNode', TextureSizeNode );
  23982. class OperatorNode extends TempNode {
  23983. constructor( op, aNode, bNode, ...params ) {
  23984. super();
  23985. if ( params.length > 0 ) {
  23986. let finalOp = new OperatorNode( op, aNode, bNode );
  23987. for ( let i = 0; i < params.length - 1; i ++ ) {
  23988. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  23989. }
  23990. aNode = finalOp;
  23991. bNode = params[ params.length - 1 ];
  23992. }
  23993. this.op = op;
  23994. this.aNode = aNode;
  23995. this.bNode = bNode;
  23996. }
  23997. getNodeType( builder, output ) {
  23998. const op = this.op;
  23999. const aNode = this.aNode;
  24000. const bNode = this.bNode;
  24001. const typeA = aNode.getNodeType( builder );
  24002. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  24003. if ( typeA === 'void' || typeB === 'void' ) {
  24004. return 'void';
  24005. } else if ( op === '%' ) {
  24006. return typeA;
  24007. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  24008. return builder.getIntegerType( typeA );
  24009. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  24010. return 'bool';
  24011. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  24012. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  24013. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  24014. } else {
  24015. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  24016. return typeB;
  24017. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  24018. // matrix x vector
  24019. return builder.getVectorFromMatrix( typeA );
  24020. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  24021. // vector x matrix
  24022. return builder.getVectorFromMatrix( typeB );
  24023. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  24024. // anytype x anytype: use the greater length vector
  24025. return typeB;
  24026. }
  24027. return typeA;
  24028. }
  24029. }
  24030. generate( builder, output ) {
  24031. const op = this.op;
  24032. const aNode = this.aNode;
  24033. const bNode = this.bNode;
  24034. const type = this.getNodeType( builder, output );
  24035. let typeA = null;
  24036. let typeB = null;
  24037. if ( type !== 'void' ) {
  24038. typeA = aNode.getNodeType( builder );
  24039. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  24040. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  24041. if ( builder.isVector( typeA ) ) {
  24042. typeB = typeA;
  24043. } else {
  24044. typeA = typeB = 'float';
  24045. }
  24046. } else if ( op === '>>' || op === '<<' ) {
  24047. typeA = type;
  24048. typeB = builder.changeComponentType( typeB, 'uint' );
  24049. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  24050. // matrix x vector
  24051. typeB = builder.getVectorFromMatrix( typeA );
  24052. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  24053. // vector x matrix
  24054. typeA = builder.getVectorFromMatrix( typeB );
  24055. } else {
  24056. // anytype x anytype
  24057. typeA = typeB = type;
  24058. }
  24059. } else {
  24060. typeA = typeB = type;
  24061. }
  24062. const a = aNode.build( builder, typeA );
  24063. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  24064. const outputLength = builder.getTypeLength( output );
  24065. const fnOpSnippet = builder.getFunctionOperator( op );
  24066. if ( output !== 'void' ) {
  24067. if ( op === '<' && outputLength > 1 ) {
  24068. return builder.format( `${ builder.getMethod( 'lessThan' ) }( ${ a }, ${ b } )`, type, output );
  24069. } else if ( op === '<=' && outputLength > 1 ) {
  24070. return builder.format( `${ builder.getMethod( 'lessThanEqual' ) }( ${ a }, ${ b } )`, type, output );
  24071. } else if ( op === '>' && outputLength > 1 ) {
  24072. return builder.format( `${ builder.getMethod( 'greaterThan' ) }( ${ a }, ${ b } )`, type, output );
  24073. } else if ( op === '>=' && outputLength > 1 ) {
  24074. return builder.format( `${ builder.getMethod( 'greaterThanEqual' ) }( ${ a }, ${ b } )`, type, output );
  24075. } else if ( op === '!' || op === '~' ) {
  24076. return builder.format( `(${op}${a})`, typeA, output );
  24077. } else if ( fnOpSnippet ) {
  24078. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  24079. } else {
  24080. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  24081. }
  24082. } else if ( typeA !== 'void' ) {
  24083. if ( fnOpSnippet ) {
  24084. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  24085. } else {
  24086. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  24087. }
  24088. }
  24089. }
  24090. serialize( data ) {
  24091. super.serialize( data );
  24092. data.op = this.op;
  24093. }
  24094. deserialize( data ) {
  24095. super.deserialize( data );
  24096. this.op = data.op;
  24097. }
  24098. }
  24099. const add = nodeProxy( OperatorNode, '+' );
  24100. const sub = nodeProxy( OperatorNode, '-' );
  24101. const mul = nodeProxy( OperatorNode, '*' );
  24102. const div = nodeProxy( OperatorNode, '/' );
  24103. const remainder = nodeProxy( OperatorNode, '%' );
  24104. const equal = nodeProxy( OperatorNode, '==' );
  24105. const notEqual = nodeProxy( OperatorNode, '!=' );
  24106. const lessThan = nodeProxy( OperatorNode, '<' );
  24107. const greaterThan = nodeProxy( OperatorNode, '>' );
  24108. const lessThanEqual = nodeProxy( OperatorNode, '<=' );
  24109. const greaterThanEqual = nodeProxy( OperatorNode, '>=' );
  24110. const and = nodeProxy( OperatorNode, '&&' );
  24111. const or = nodeProxy( OperatorNode, '||' );
  24112. const not = nodeProxy( OperatorNode, '!' );
  24113. const xor = nodeProxy( OperatorNode, '^^' );
  24114. const bitAnd = nodeProxy( OperatorNode, '&' );
  24115. const bitNot = nodeProxy( OperatorNode, '~' );
  24116. const bitOr = nodeProxy( OperatorNode, '|' );
  24117. const bitXor = nodeProxy( OperatorNode, '^' );
  24118. const shiftLeft = nodeProxy( OperatorNode, '<<' );
  24119. const shiftRight = nodeProxy( OperatorNode, '>>' );
  24120. addNodeElement( 'add', add );
  24121. addNodeElement( 'sub', sub );
  24122. addNodeElement( 'mul', mul );
  24123. addNodeElement( 'div', div );
  24124. addNodeElement( 'remainder', remainder );
  24125. addNodeElement( 'equal', equal );
  24126. addNodeElement( 'notEqual', notEqual );
  24127. addNodeElement( 'lessThan', lessThan );
  24128. addNodeElement( 'greaterThan', greaterThan );
  24129. addNodeElement( 'lessThanEqual', lessThanEqual );
  24130. addNodeElement( 'greaterThanEqual', greaterThanEqual );
  24131. addNodeElement( 'and', and );
  24132. addNodeElement( 'or', or );
  24133. addNodeElement( 'not', not );
  24134. addNodeElement( 'xor', xor );
  24135. addNodeElement( 'bitAnd', bitAnd );
  24136. addNodeElement( 'bitNot', bitNot );
  24137. addNodeElement( 'bitOr', bitOr );
  24138. addNodeElement( 'bitXor', bitXor );
  24139. addNodeElement( 'shiftLeft', shiftLeft );
  24140. addNodeElement( 'shiftRight', shiftRight );
  24141. addNodeClass( 'OperatorNode', OperatorNode );
  24142. class MathNode extends TempNode {
  24143. constructor( method, aNode, bNode = null, cNode = null ) {
  24144. super();
  24145. this.method = method;
  24146. this.aNode = aNode;
  24147. this.bNode = bNode;
  24148. this.cNode = cNode;
  24149. }
  24150. getInputType( builder ) {
  24151. const aType = this.aNode.getNodeType( builder );
  24152. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  24153. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  24154. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  24155. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  24156. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  24157. if ( aLen > bLen && aLen > cLen ) {
  24158. return aType;
  24159. } else if ( bLen > cLen ) {
  24160. return bType;
  24161. } else if ( cLen > aLen ) {
  24162. return cType;
  24163. }
  24164. return aType;
  24165. }
  24166. getNodeType( builder ) {
  24167. const method = this.method;
  24168. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  24169. return 'float';
  24170. } else if ( method === MathNode.CROSS ) {
  24171. return 'vec3';
  24172. } else if ( method === MathNode.ALL ) {
  24173. return 'bool';
  24174. } else if ( method === MathNode.EQUALS ) {
  24175. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  24176. } else if ( method === MathNode.MOD ) {
  24177. return this.aNode.getNodeType( builder );
  24178. } else {
  24179. return this.getInputType( builder );
  24180. }
  24181. }
  24182. generate( builder, output ) {
  24183. const method = this.method;
  24184. const type = this.getNodeType( builder );
  24185. const inputType = this.getInputType( builder );
  24186. const a = this.aNode;
  24187. const b = this.bNode;
  24188. const c = this.cNode;
  24189. const isWebGL = builder.renderer.isWebGLRenderer === true;
  24190. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  24191. // dir can be either a direction vector or a normal vector
  24192. // upper-left 3x3 of matrix is assumed to be orthogonal
  24193. let tA = a;
  24194. let tB = b;
  24195. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  24196. tB = vec4( vec3( tB ), 0.0 );
  24197. } else {
  24198. tA = vec4( vec3( tA ), 0.0 );
  24199. }
  24200. const mulNode = mul( tA, tB ).xyz;
  24201. return normalize( mulNode ).build( builder, output );
  24202. } else if ( method === MathNode.NEGATE ) {
  24203. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  24204. } else if ( method === MathNode.ONE_MINUS ) {
  24205. return sub( 1.0, a ).build( builder, output );
  24206. } else if ( method === MathNode.RECIPROCAL ) {
  24207. return div( 1.0, a ).build( builder, output );
  24208. } else if ( method === MathNode.DIFFERENCE ) {
  24209. return abs( sub( a, b ) ).build( builder, output );
  24210. } else {
  24211. const params = [];
  24212. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  24213. params.push(
  24214. a.build( builder, type ),
  24215. b.build( builder, type )
  24216. );
  24217. } else if ( method === MathNode.STEP ) {
  24218. params.push(
  24219. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  24220. b.build( builder, inputType )
  24221. );
  24222. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  24223. params.push(
  24224. a.build( builder, inputType ),
  24225. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  24226. );
  24227. } else if ( method === MathNode.REFRACT ) {
  24228. params.push(
  24229. a.build( builder, inputType ),
  24230. b.build( builder, inputType ),
  24231. c.build( builder, 'float' )
  24232. );
  24233. } else if ( method === MathNode.MIX ) {
  24234. params.push(
  24235. a.build( builder, inputType ),
  24236. b.build( builder, inputType ),
  24237. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  24238. );
  24239. } else {
  24240. params.push( a.build( builder, inputType ) );
  24241. if ( b !== null ) params.push( b.build( builder, inputType ) );
  24242. if ( c !== null ) params.push( c.build( builder, inputType ) );
  24243. }
  24244. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  24245. }
  24246. }
  24247. serialize( data ) {
  24248. super.serialize( data );
  24249. data.method = this.method;
  24250. }
  24251. deserialize( data ) {
  24252. super.deserialize( data );
  24253. this.method = data.method;
  24254. }
  24255. }
  24256. // 1 input
  24257. MathNode.ALL = 'all';
  24258. MathNode.ANY = 'any';
  24259. MathNode.EQUALS = 'equals';
  24260. MathNode.RADIANS = 'radians';
  24261. MathNode.DEGREES = 'degrees';
  24262. MathNode.EXP = 'exp';
  24263. MathNode.EXP2 = 'exp2';
  24264. MathNode.LOG = 'log';
  24265. MathNode.LOG2 = 'log2';
  24266. MathNode.SQRT = 'sqrt';
  24267. MathNode.INVERSE_SQRT = 'inversesqrt';
  24268. MathNode.FLOOR = 'floor';
  24269. MathNode.CEIL = 'ceil';
  24270. MathNode.NORMALIZE = 'normalize';
  24271. MathNode.FRACT = 'fract';
  24272. MathNode.SIN = 'sin';
  24273. MathNode.COS = 'cos';
  24274. MathNode.TAN = 'tan';
  24275. MathNode.ASIN = 'asin';
  24276. MathNode.ACOS = 'acos';
  24277. MathNode.ATAN = 'atan';
  24278. MathNode.ABS = 'abs';
  24279. MathNode.SIGN = 'sign';
  24280. MathNode.LENGTH = 'length';
  24281. MathNode.NEGATE = 'negate';
  24282. MathNode.ONE_MINUS = 'oneMinus';
  24283. MathNode.DFDX = 'dFdx';
  24284. MathNode.DFDY = 'dFdy';
  24285. MathNode.ROUND = 'round';
  24286. MathNode.RECIPROCAL = 'reciprocal';
  24287. MathNode.TRUNC = 'trunc';
  24288. MathNode.FWIDTH = 'fwidth';
  24289. MathNode.BITCAST = 'bitcast';
  24290. MathNode.TRANSPOSE = 'transpose';
  24291. // 2 inputs
  24292. MathNode.ATAN2 = 'atan2';
  24293. MathNode.MIN = 'min';
  24294. MathNode.MAX = 'max';
  24295. MathNode.MOD = 'mod';
  24296. MathNode.STEP = 'step';
  24297. MathNode.REFLECT = 'reflect';
  24298. MathNode.DISTANCE = 'distance';
  24299. MathNode.DIFFERENCE = 'difference';
  24300. MathNode.DOT = 'dot';
  24301. MathNode.CROSS = 'cross';
  24302. MathNode.POW = 'pow';
  24303. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  24304. // 3 inputs
  24305. MathNode.MIX = 'mix';
  24306. MathNode.CLAMP = 'clamp';
  24307. MathNode.REFRACT = 'refract';
  24308. MathNode.SMOOTHSTEP = 'smoothstep';
  24309. MathNode.FACEFORWARD = 'faceforward';
  24310. const EPSILON = float( 1e-6 );
  24311. const INFINITY = float( 1e6 );
  24312. const PI = float( Math.PI );
  24313. const PI2 = float( Math.PI * 2 );
  24314. const all = nodeProxy( MathNode, MathNode.ALL );
  24315. const any = nodeProxy( MathNode, MathNode.ANY );
  24316. const equals = nodeProxy( MathNode, MathNode.EQUALS );
  24317. const radians = nodeProxy( MathNode, MathNode.RADIANS );
  24318. const degrees = nodeProxy( MathNode, MathNode.DEGREES );
  24319. const exp = nodeProxy( MathNode, MathNode.EXP );
  24320. const exp2 = nodeProxy( MathNode, MathNode.EXP2 );
  24321. const log = nodeProxy( MathNode, MathNode.LOG );
  24322. const log2 = nodeProxy( MathNode, MathNode.LOG2 );
  24323. const sqrt = nodeProxy( MathNode, MathNode.SQRT );
  24324. const inverseSqrt = nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  24325. const floor = nodeProxy( MathNode, MathNode.FLOOR );
  24326. const ceil = nodeProxy( MathNode, MathNode.CEIL );
  24327. const normalize = nodeProxy( MathNode, MathNode.NORMALIZE );
  24328. const fract = nodeProxy( MathNode, MathNode.FRACT );
  24329. const sin = nodeProxy( MathNode, MathNode.SIN );
  24330. const cos = nodeProxy( MathNode, MathNode.COS );
  24331. const tan = nodeProxy( MathNode, MathNode.TAN );
  24332. const asin = nodeProxy( MathNode, MathNode.ASIN );
  24333. const acos = nodeProxy( MathNode, MathNode.ACOS );
  24334. const atan = nodeProxy( MathNode, MathNode.ATAN );
  24335. const abs = nodeProxy( MathNode, MathNode.ABS );
  24336. const sign = nodeProxy( MathNode, MathNode.SIGN );
  24337. const length = nodeProxy( MathNode, MathNode.LENGTH );
  24338. const negate = nodeProxy( MathNode, MathNode.NEGATE );
  24339. const oneMinus = nodeProxy( MathNode, MathNode.ONE_MINUS );
  24340. const dFdx = nodeProxy( MathNode, MathNode.DFDX );
  24341. const dFdy = nodeProxy( MathNode, MathNode.DFDY );
  24342. const round = nodeProxy( MathNode, MathNode.ROUND );
  24343. const reciprocal = nodeProxy( MathNode, MathNode.RECIPROCAL );
  24344. const trunc = nodeProxy( MathNode, MathNode.TRUNC );
  24345. const fwidth = nodeProxy( MathNode, MathNode.FWIDTH );
  24346. const bitcast = nodeProxy( MathNode, MathNode.BITCAST );
  24347. const transpose = nodeProxy( MathNode, MathNode.TRANSPOSE );
  24348. const atan2 = nodeProxy( MathNode, MathNode.ATAN2 );
  24349. const min$1 = nodeProxy( MathNode, MathNode.MIN );
  24350. const max$1 = nodeProxy( MathNode, MathNode.MAX );
  24351. const mod = nodeProxy( MathNode, MathNode.MOD );
  24352. const step = nodeProxy( MathNode, MathNode.STEP );
  24353. const reflect = nodeProxy( MathNode, MathNode.REFLECT );
  24354. const distance = nodeProxy( MathNode, MathNode.DISTANCE );
  24355. const difference = nodeProxy( MathNode, MathNode.DIFFERENCE );
  24356. const dot = nodeProxy( MathNode, MathNode.DOT );
  24357. const cross = nodeProxy( MathNode, MathNode.CROSS );
  24358. const pow = nodeProxy( MathNode, MathNode.POW );
  24359. const pow2 = nodeProxy( MathNode, MathNode.POW, 2 );
  24360. const pow3 = nodeProxy( MathNode, MathNode.POW, 3 );
  24361. const pow4 = nodeProxy( MathNode, MathNode.POW, 4 );
  24362. const transformDirection = nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  24363. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  24364. const lengthSq = ( a ) => dot( a, a );
  24365. const mix = nodeProxy( MathNode, MathNode.MIX );
  24366. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  24367. const saturate = ( value ) => clamp( value );
  24368. const refract = nodeProxy( MathNode, MathNode.REFRACT );
  24369. const smoothstep = nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  24370. const faceForward = nodeProxy( MathNode, MathNode.FACEFORWARD );
  24371. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  24372. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  24373. addNodeElement( 'all', all );
  24374. addNodeElement( 'any', any );
  24375. addNodeElement( 'equals', equals );
  24376. addNodeElement( 'radians', radians );
  24377. addNodeElement( 'degrees', degrees );
  24378. addNodeElement( 'exp', exp );
  24379. addNodeElement( 'exp2', exp2 );
  24380. addNodeElement( 'log', log );
  24381. addNodeElement( 'log2', log2 );
  24382. addNodeElement( 'sqrt', sqrt );
  24383. addNodeElement( 'inverseSqrt', inverseSqrt );
  24384. addNodeElement( 'floor', floor );
  24385. addNodeElement( 'ceil', ceil );
  24386. addNodeElement( 'normalize', normalize );
  24387. addNodeElement( 'fract', fract );
  24388. addNodeElement( 'sin', sin );
  24389. addNodeElement( 'cos', cos );
  24390. addNodeElement( 'tan', tan );
  24391. addNodeElement( 'asin', asin );
  24392. addNodeElement( 'acos', acos );
  24393. addNodeElement( 'atan', atan );
  24394. addNodeElement( 'abs', abs );
  24395. addNodeElement( 'sign', sign );
  24396. addNodeElement( 'length', length );
  24397. addNodeElement( 'lengthSq', lengthSq );
  24398. addNodeElement( 'negate', negate );
  24399. addNodeElement( 'oneMinus', oneMinus );
  24400. addNodeElement( 'dFdx', dFdx );
  24401. addNodeElement( 'dFdy', dFdy );
  24402. addNodeElement( 'round', round );
  24403. addNodeElement( 'reciprocal', reciprocal );
  24404. addNodeElement( 'trunc', trunc );
  24405. addNodeElement( 'fwidth', fwidth );
  24406. addNodeElement( 'atan2', atan2 );
  24407. addNodeElement( 'min', min$1 );
  24408. addNodeElement( 'max', max$1 );
  24409. addNodeElement( 'mod', mod );
  24410. addNodeElement( 'step', step );
  24411. addNodeElement( 'reflect', reflect );
  24412. addNodeElement( 'distance', distance );
  24413. addNodeElement( 'dot', dot );
  24414. addNodeElement( 'cross', cross );
  24415. addNodeElement( 'pow', pow );
  24416. addNodeElement( 'pow2', pow2 );
  24417. addNodeElement( 'pow3', pow3 );
  24418. addNodeElement( 'pow4', pow4 );
  24419. addNodeElement( 'transformDirection', transformDirection );
  24420. addNodeElement( 'mix', mixElement );
  24421. addNodeElement( 'clamp', clamp );
  24422. addNodeElement( 'refract', refract );
  24423. addNodeElement( 'smoothstep', smoothstepElement );
  24424. addNodeElement( 'faceForward', faceForward );
  24425. addNodeElement( 'difference', difference );
  24426. addNodeElement( 'saturate', saturate );
  24427. addNodeElement( 'cbrt', cbrt );
  24428. addNodeElement( 'transpose', transpose );
  24429. addNodeClass( 'MathNode', MathNode );
  24430. const sRGBToLinearShader = tslFn( ( inputs ) => {
  24431. const { value } = inputs;
  24432. const { rgb } = value;
  24433. const a = rgb.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  24434. const b = rgb.mul( 0.0773993808 );
  24435. const factor = rgb.lessThanEqual( 0.04045 );
  24436. const rgbResult = mix( a, b, factor );
  24437. return vec4( rgbResult, value.a );
  24438. } );
  24439. const LinearTosRGBShader = tslFn( ( inputs ) => {
  24440. const { value } = inputs;
  24441. const { rgb } = value;
  24442. const a = rgb.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  24443. const b = rgb.mul( 12.92 );
  24444. const factor = rgb.lessThanEqual( 0.0031308 );
  24445. const rgbResult = mix( a, b, factor );
  24446. return vec4( rgbResult, value.a );
  24447. } );
  24448. const getColorSpaceMethod = ( colorSpace ) => {
  24449. let method = null;
  24450. if ( colorSpace === LinearSRGBColorSpace ) {
  24451. method = 'Linear';
  24452. } else if ( colorSpace === SRGBColorSpace ) {
  24453. method = 'sRGB';
  24454. }
  24455. return method;
  24456. };
  24457. const getMethod = ( source, target ) => {
  24458. return getColorSpaceMethod( source ) + 'To' + getColorSpaceMethod( target );
  24459. };
  24460. class ColorSpaceNode extends TempNode {
  24461. constructor( method, node ) {
  24462. super( 'vec4' );
  24463. this.method = method;
  24464. this.node = node;
  24465. }
  24466. setup() {
  24467. const { method, node } = this;
  24468. if ( method === ColorSpaceNode.LINEAR_TO_LINEAR )
  24469. return node;
  24470. return Methods[ method ]( { value: node } );
  24471. }
  24472. }
  24473. ColorSpaceNode.LINEAR_TO_LINEAR = 'LinearToLinear';
  24474. ColorSpaceNode.LINEAR_TO_sRGB = 'LinearTosRGB';
  24475. ColorSpaceNode.sRGB_TO_LINEAR = 'sRGBToLinear';
  24476. const Methods = {
  24477. [ ColorSpaceNode.LINEAR_TO_sRGB ]: LinearTosRGBShader,
  24478. [ ColorSpaceNode.sRGB_TO_LINEAR ]: sRGBToLinearShader
  24479. };
  24480. const linearToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( getMethod( LinearSRGBColorSpace, colorSpace ), nodeObject( node ) ) );
  24481. const colorSpaceToLinear = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( getMethod( colorSpace, LinearSRGBColorSpace ), nodeObject( node ) ) );
  24482. const linearTosRGB = nodeProxy( ColorSpaceNode, ColorSpaceNode.LINEAR_TO_sRGB );
  24483. const sRGBToLinear = nodeProxy( ColorSpaceNode, ColorSpaceNode.sRGB_TO_LINEAR );
  24484. addNodeElement( 'linearTosRGB', linearTosRGB );
  24485. addNodeElement( 'sRGBToLinear', sRGBToLinear );
  24486. addNodeElement( 'linearToColorSpace', linearToColorSpace );
  24487. addNodeElement( 'colorSpaceToLinear', colorSpaceToLinear );
  24488. addNodeClass( 'ColorSpaceNode', ColorSpaceNode );
  24489. class ExpressionNode extends Node {
  24490. constructor( snippet = '', nodeType = 'void' ) {
  24491. super( nodeType );
  24492. this.snippet = snippet;
  24493. }
  24494. generate( builder, output ) {
  24495. const type = this.getNodeType( builder );
  24496. const snippet = this.snippet;
  24497. if ( type === 'void' ) {
  24498. builder.addLineFlowCode( snippet );
  24499. } else {
  24500. return builder.format( `( ${ snippet } )`, type, output );
  24501. }
  24502. }
  24503. }
  24504. const expression = nodeProxy( ExpressionNode );
  24505. addNodeClass( 'ExpressionNode', ExpressionNode );
  24506. class MaxMipLevelNode extends UniformNode {
  24507. constructor( textureNode ) {
  24508. super( 0 );
  24509. this.textureNode = textureNode;
  24510. this.updateType = NodeUpdateType.FRAME;
  24511. }
  24512. get texture() {
  24513. return this.textureNode.value;
  24514. }
  24515. update() {
  24516. const texture = this.texture;
  24517. const images = texture.images;
  24518. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  24519. if ( image && image.width !== undefined ) {
  24520. const { width, height } = image;
  24521. this.value = Math.log2( Math.max( width, height ) );
  24522. }
  24523. }
  24524. }
  24525. const maxMipLevel = nodeProxy( MaxMipLevelNode );
  24526. addNodeClass( 'MaxMipLevelNode', MaxMipLevelNode );
  24527. class TextureNode extends UniformNode {
  24528. constructor( value, uvNode = null, levelNode = null ) {
  24529. super( value );
  24530. this.isTextureNode = true;
  24531. this.uvNode = uvNode;
  24532. this.levelNode = levelNode;
  24533. this.compareNode = null;
  24534. this.depthNode = null;
  24535. this.gradNode = null;
  24536. this.sampler = true;
  24537. this.updateMatrix = false;
  24538. this.updateType = NodeUpdateType.NONE;
  24539. this.referenceNode = null;
  24540. this._value = value;
  24541. this.setUpdateMatrix( uvNode === null );
  24542. }
  24543. set value( value ) {
  24544. if ( this.referenceNode ) {
  24545. this.referenceNode.value = value;
  24546. } else {
  24547. this._value = value;
  24548. }
  24549. }
  24550. get value() {
  24551. return this.referenceNode ? this.referenceNode.value : this._value;
  24552. }
  24553. getUniformHash( /*builder*/ ) {
  24554. return this.value.uuid;
  24555. }
  24556. getNodeType( /*builder*/ ) {
  24557. if ( this.value.isDepthTexture === true ) return 'float';
  24558. if ( this.value.type === UnsignedIntType ) {
  24559. return 'uvec4';
  24560. } else if ( this.value.type === IntType ) {
  24561. return 'ivec4';
  24562. }
  24563. return 'vec4';
  24564. }
  24565. getInputType( /*builder*/ ) {
  24566. return 'texture';
  24567. }
  24568. getDefaultUV() {
  24569. return uv( this.value.channel );
  24570. }
  24571. updateReference( /*state*/ ) {
  24572. return this.value;
  24573. }
  24574. getTransformedUV( uvNode ) {
  24575. const texture = this.value;
  24576. return uniform( texture.matrix ).mul( vec3( uvNode, 1 ) ).xy;
  24577. }
  24578. setUpdateMatrix( value ) {
  24579. this.updateMatrix = value;
  24580. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  24581. return this;
  24582. }
  24583. setupUV( builder, uvNode ) {
  24584. const texture = this.value;
  24585. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  24586. uvNode = uvNode.setY( uvNode.y.oneMinus() );
  24587. }
  24588. return uvNode;
  24589. }
  24590. setup( builder ) {
  24591. const properties = builder.getNodeProperties( this );
  24592. //
  24593. let uvNode = this.uvNode;
  24594. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  24595. uvNode = builder.context.getUV( this );
  24596. }
  24597. if ( ! uvNode ) uvNode = this.getDefaultUV();
  24598. if ( this.updateMatrix === true ) {
  24599. uvNode = this.getTransformedUV( uvNode );
  24600. }
  24601. uvNode = this.setupUV( builder, uvNode );
  24602. //
  24603. let levelNode = this.levelNode;
  24604. if ( levelNode === null && builder.context.getTextureLevel ) {
  24605. levelNode = builder.context.getTextureLevel( this );
  24606. }
  24607. //
  24608. properties.uvNode = uvNode;
  24609. properties.levelNode = levelNode;
  24610. properties.compareNode = this.compareNode;
  24611. properties.gradNode = this.gradNode;
  24612. properties.depthNode = this.depthNode;
  24613. }
  24614. generateUV( builder, uvNode ) {
  24615. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  24616. }
  24617. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  24618. const texture = this.value;
  24619. let snippet;
  24620. if ( levelSnippet ) {
  24621. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  24622. } else if ( gradSnippet ) {
  24623. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  24624. } else if ( compareSnippet ) {
  24625. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  24626. } else if ( this.sampler === false ) {
  24627. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  24628. } else {
  24629. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  24630. }
  24631. return snippet;
  24632. }
  24633. generate( builder, output ) {
  24634. const properties = builder.getNodeProperties( this );
  24635. const texture = this.value;
  24636. if ( ! texture || texture.isTexture !== true ) {
  24637. throw new Error( 'TextureNode: Need a three.js texture.' );
  24638. }
  24639. const textureProperty = super.generate( builder, 'property' );
  24640. if ( output === 'sampler' ) {
  24641. return textureProperty + '_sampler';
  24642. } else if ( builder.isReference( output ) ) {
  24643. return textureProperty;
  24644. } else {
  24645. const nodeData = builder.getDataFromNode( this );
  24646. let propertyName = nodeData.propertyName;
  24647. if ( propertyName === undefined ) {
  24648. const { uvNode, levelNode, compareNode, depthNode, gradNode } = properties;
  24649. const uvSnippet = this.generateUV( builder, uvNode );
  24650. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  24651. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  24652. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  24653. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  24654. const nodeVar = builder.getVarFromNode( this );
  24655. propertyName = builder.getPropertyName( nodeVar );
  24656. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, depthSnippet, compareSnippet, gradSnippet );
  24657. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  24658. nodeData.snippet = snippet;
  24659. nodeData.propertyName = propertyName;
  24660. }
  24661. let snippet = propertyName;
  24662. const nodeType = this.getNodeType( builder );
  24663. if ( builder.needsColorSpaceToLinear( texture ) ) {
  24664. snippet = colorSpaceToLinear( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  24665. }
  24666. return builder.format( snippet, nodeType, output );
  24667. }
  24668. }
  24669. setSampler( value ) {
  24670. this.sampler = value;
  24671. return this;
  24672. }
  24673. getSampler() {
  24674. return this.sampler;
  24675. }
  24676. // @TODO: Move to TSL
  24677. uv( uvNode ) {
  24678. const textureNode = this.clone();
  24679. textureNode.uvNode = uvNode;
  24680. textureNode.referenceNode = this;
  24681. return nodeObject( textureNode );
  24682. }
  24683. blur( levelNode ) {
  24684. const textureNode = this.clone();
  24685. textureNode.levelNode = levelNode.mul( maxMipLevel( textureNode ) );
  24686. textureNode.referenceNode = this;
  24687. return nodeObject( textureNode );
  24688. }
  24689. level( levelNode ) {
  24690. const textureNode = this.clone();
  24691. textureNode.levelNode = levelNode;
  24692. textureNode.referenceNode = this;
  24693. return textureNode;
  24694. }
  24695. size( levelNode ) {
  24696. return textureSize( this, levelNode );
  24697. }
  24698. compare( compareNode ) {
  24699. const textureNode = this.clone();
  24700. textureNode.compareNode = nodeObject( compareNode );
  24701. textureNode.referenceNode = this;
  24702. return nodeObject( textureNode );
  24703. }
  24704. grad( gradNodeX, gradNodeY ) {
  24705. const textureNode = this.clone();
  24706. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  24707. textureNode.referenceNode = this;
  24708. return nodeObject( textureNode );
  24709. }
  24710. depth( depthNode ) {
  24711. const textureNode = this.clone();
  24712. textureNode.depthNode = nodeObject( depthNode );
  24713. textureNode.referenceNode = this;
  24714. return nodeObject( textureNode );
  24715. }
  24716. // --
  24717. serialize( data ) {
  24718. super.serialize( data );
  24719. data.value = this.value.toJSON( data.meta ).uuid;
  24720. }
  24721. deserialize( data ) {
  24722. super.deserialize( data );
  24723. this.value = data.meta.textures[ data.value ];
  24724. }
  24725. update() {
  24726. const texture = this.value;
  24727. if ( texture.matrixAutoUpdate === true ) {
  24728. texture.updateMatrix();
  24729. }
  24730. }
  24731. clone() {
  24732. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode );
  24733. newNode.sampler = this.sampler;
  24734. return newNode;
  24735. }
  24736. }
  24737. const texture = nodeProxy( TextureNode );
  24738. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  24739. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  24740. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  24741. addNodeElement( 'texture', texture );
  24742. //addNodeElement( 'textureLevel', textureLevel );
  24743. addNodeClass( 'TextureNode', TextureNode );
  24744. class BufferNode extends UniformNode {
  24745. constructor( value, bufferType, bufferCount = 0 ) {
  24746. super( value, bufferType );
  24747. this.isBufferNode = true;
  24748. this.bufferType = bufferType;
  24749. this.bufferCount = bufferCount;
  24750. }
  24751. getElementType( builder ) {
  24752. return this.getNodeType( builder );
  24753. }
  24754. getInputType( /*builder*/ ) {
  24755. return 'buffer';
  24756. }
  24757. }
  24758. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  24759. addNodeClass( 'BufferNode', BufferNode );
  24760. class UniformsElementNode extends ArrayElementNode {
  24761. constructor( arrayBuffer, indexNode ) {
  24762. super( arrayBuffer, indexNode );
  24763. this.isArrayBufferElementNode = true;
  24764. }
  24765. getNodeType( builder ) {
  24766. return this.node.getElementType( builder );
  24767. }
  24768. generate( builder ) {
  24769. const snippet = super.generate( builder );
  24770. const type = this.getNodeType();
  24771. return builder.format( snippet, 'vec4', type );
  24772. }
  24773. }
  24774. class UniformsNode extends BufferNode {
  24775. constructor( value, elementType = null ) {
  24776. super( null, 'vec4' );
  24777. this.array = value;
  24778. this.elementType = elementType;
  24779. this._elementType = null;
  24780. this._elementLength = 0;
  24781. this.updateType = NodeUpdateType.RENDER;
  24782. this.isArrayBufferNode = true;
  24783. }
  24784. getElementType() {
  24785. return this.elementType || this._elementType;
  24786. }
  24787. getElementLength() {
  24788. return this._elementLength;
  24789. }
  24790. update( /*frame*/ ) {
  24791. const { array, value } = this;
  24792. const elementLength = this.getElementLength();
  24793. const elementType = this.getElementType();
  24794. if ( elementLength === 1 ) {
  24795. for ( let i = 0; i < array.length; i ++ ) {
  24796. const index = i * 4;
  24797. value[ index ] = array[ i ];
  24798. }
  24799. } else if ( elementType === 'color' ) {
  24800. for ( let i = 0; i < array.length; i ++ ) {
  24801. const index = i * 4;
  24802. const vector = array[ i ];
  24803. value[ index ] = vector.r;
  24804. value[ index + 1 ] = vector.g;
  24805. value[ index + 2 ] = vector.b || 0;
  24806. //value[ index + 3 ] = vector.a || 0;
  24807. }
  24808. } else {
  24809. for ( let i = 0; i < array.length; i ++ ) {
  24810. const index = i * 4;
  24811. const vector = array[ i ];
  24812. value[ index ] = vector.x;
  24813. value[ index + 1 ] = vector.y;
  24814. value[ index + 2 ] = vector.z || 0;
  24815. value[ index + 3 ] = vector.w || 0;
  24816. }
  24817. }
  24818. }
  24819. setup( builder ) {
  24820. const length = this.array.length;
  24821. this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType;
  24822. this._elementLength = builder.getTypeLength( this._elementType );
  24823. let arrayType = Float32Array;
  24824. if ( this._elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  24825. else if ( this._elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  24826. this.value = new arrayType( length * 4 );
  24827. this.bufferCount = length;
  24828. this.bufferType = builder.changeComponentType( 'vec4', builder.getComponentType( this._elementType ) );
  24829. return super.setup( builder );
  24830. }
  24831. element( indexNode ) {
  24832. return nodeObject( new UniformsElementNode( this, nodeObject( indexNode ) ) );
  24833. }
  24834. }
  24835. const uniforms = ( values, nodeType ) => nodeObject( new UniformsNode( values, nodeType ) );
  24836. addNodeClass( 'UniformsNode', UniformsNode );
  24837. class ReferenceElementNode extends ArrayElementNode {
  24838. constructor( referenceNode, indexNode ) {
  24839. super( referenceNode, indexNode );
  24840. this.referenceNode = referenceNode;
  24841. this.isReferenceElementNode = true;
  24842. }
  24843. getNodeType() {
  24844. return this.referenceNode.uniformType;
  24845. }
  24846. generate( builder ) {
  24847. const snippet = super.generate( builder );
  24848. const arrayType = this.referenceNode.getNodeType();
  24849. const elementType = this.getNodeType();
  24850. return builder.format( snippet, arrayType, elementType );
  24851. }
  24852. }
  24853. class ReferenceNode extends Node {
  24854. constructor( property, uniformType, object = null, count = null ) {
  24855. super();
  24856. this.property = property;
  24857. this.uniformType = uniformType;
  24858. this.object = object;
  24859. this.count = count;
  24860. this.properties = property.split( '.' );
  24861. this.reference = null;
  24862. this.node = null;
  24863. this.updateType = NodeUpdateType.OBJECT;
  24864. }
  24865. element( indexNode ) {
  24866. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  24867. }
  24868. setNodeType( uniformType ) {
  24869. let node = null;
  24870. if ( this.count !== null ) {
  24871. node = buffer( null, uniformType, this.count );
  24872. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  24873. node = uniforms( null, uniformType );
  24874. } else if ( uniformType === 'texture' ) {
  24875. node = texture( null );
  24876. } else {
  24877. node = uniform( null, uniformType );
  24878. }
  24879. this.node = node;
  24880. }
  24881. getNodeType( builder ) {
  24882. if ( this.node === null ) {
  24883. this.updateValue();
  24884. }
  24885. return this.node.getNodeType( builder );
  24886. }
  24887. getValueFromReference( object = this.reference ) {
  24888. const { properties } = this;
  24889. let value = object[ properties[ 0 ] ];
  24890. for ( let i = 1; i < properties.length; i ++ ) {
  24891. value = value[ properties[ i ] ];
  24892. }
  24893. return value;
  24894. }
  24895. updateReference( state ) {
  24896. this.reference = this.object !== null ? this.object : state.object;
  24897. return this.reference;
  24898. }
  24899. setup() {
  24900. this.updateValue();
  24901. return this.node;
  24902. }
  24903. update( /*frame*/ ) {
  24904. this.updateValue();
  24905. }
  24906. updateValue() {
  24907. if ( this.node === null ) this.setNodeType( this.uniformType );
  24908. const value = this.getValueFromReference();
  24909. if ( Array.isArray( value ) ) {
  24910. this.node.array = value;
  24911. } else {
  24912. this.node.value = value;
  24913. }
  24914. }
  24915. }
  24916. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  24917. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  24918. addNodeClass( 'ReferenceNode', ReferenceNode );
  24919. class MaterialReferenceNode extends ReferenceNode {
  24920. constructor( property, inputType, material = null ) {
  24921. super( property, inputType, material );
  24922. this.material = material;
  24923. //this.updateType = NodeUpdateType.RENDER;
  24924. }
  24925. /*setNodeType( node ) {
  24926. super.setNodeType( node );
  24927. this.node.groupNode = renderGroup;
  24928. }*/
  24929. updateReference( state ) {
  24930. this.reference = this.material !== null ? this.material : state.material;
  24931. return this.reference;
  24932. }
  24933. }
  24934. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  24935. addNodeClass( 'MaterialReferenceNode', MaterialReferenceNode );
  24936. const cameraGroup = /*#__PURE__*/ sharedUniformGroup( 'camera' ).onRenderUpdate( () => {
  24937. cameraGroup.needsUpdate = true;
  24938. } );
  24939. const cameraNear = /*#__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  24940. const cameraFar = /*#__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  24941. const cameraLogDepth = /*#__PURE__*/ uniform( 'float' ).label( 'cameraLogDepth' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  24942. const cameraProjectionMatrix = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  24943. const cameraProjectionMatrixInverse = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  24944. const cameraViewMatrix = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  24945. const cameraWorldMatrix = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  24946. const cameraNormalMatrix = /*#__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  24947. const cameraPosition = /*#__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  24948. class Object3DNode extends Node {
  24949. constructor( scope = Object3DNode.VIEW_MATRIX, object3d = null ) {
  24950. super();
  24951. this.scope = scope;
  24952. this.object3d = object3d;
  24953. this.updateType = NodeUpdateType.OBJECT;
  24954. this._uniformNode = new UniformNode( null );
  24955. }
  24956. getNodeType() {
  24957. const scope = this.scope;
  24958. if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) {
  24959. return 'mat4';
  24960. } else if ( scope === Object3DNode.NORMAL_MATRIX ) {
  24961. return 'mat3';
  24962. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  24963. return 'vec3';
  24964. }
  24965. }
  24966. update( frame ) {
  24967. const object = this.object3d;
  24968. const uniformNode = this._uniformNode;
  24969. const scope = this.scope;
  24970. if ( scope === Object3DNode.VIEW_MATRIX ) {
  24971. uniformNode.value = object.modelViewMatrix;
  24972. } else if ( scope === Object3DNode.NORMAL_MATRIX ) {
  24973. uniformNode.value = object.normalMatrix;
  24974. } else if ( scope === Object3DNode.WORLD_MATRIX ) {
  24975. uniformNode.value = object.matrixWorld;
  24976. } else if ( scope === Object3DNode.POSITION ) {
  24977. uniformNode.value = uniformNode.value || new Vector3();
  24978. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  24979. } else if ( scope === Object3DNode.SCALE ) {
  24980. uniformNode.value = uniformNode.value || new Vector3();
  24981. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  24982. } else if ( scope === Object3DNode.DIRECTION ) {
  24983. uniformNode.value = uniformNode.value || new Vector3();
  24984. object.getWorldDirection( uniformNode.value );
  24985. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  24986. const camera = frame.camera;
  24987. uniformNode.value = uniformNode.value || new Vector3();
  24988. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  24989. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  24990. }
  24991. }
  24992. generate( builder ) {
  24993. const scope = this.scope;
  24994. if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) {
  24995. this._uniformNode.nodeType = 'mat4';
  24996. } else if ( scope === Object3DNode.NORMAL_MATRIX ) {
  24997. this._uniformNode.nodeType = 'mat3';
  24998. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  24999. this._uniformNode.nodeType = 'vec3';
  25000. }
  25001. return this._uniformNode.build( builder );
  25002. }
  25003. serialize( data ) {
  25004. super.serialize( data );
  25005. data.scope = this.scope;
  25006. }
  25007. deserialize( data ) {
  25008. super.deserialize( data );
  25009. this.scope = data.scope;
  25010. }
  25011. }
  25012. Object3DNode.VIEW_MATRIX = 'viewMatrix';
  25013. Object3DNode.NORMAL_MATRIX = 'normalMatrix';
  25014. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  25015. Object3DNode.POSITION = 'position';
  25016. Object3DNode.SCALE = 'scale';
  25017. Object3DNode.VIEW_POSITION = 'viewPosition';
  25018. Object3DNode.DIRECTION = 'direction';
  25019. const objectDirection = nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  25020. const objectViewMatrix = nodeProxy( Object3DNode, Object3DNode.VIEW_MATRIX );
  25021. const objectNormalMatrix = nodeProxy( Object3DNode, Object3DNode.NORMAL_MATRIX );
  25022. const objectWorldMatrix = nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  25023. const objectPosition = nodeProxy( Object3DNode, Object3DNode.POSITION );
  25024. const objectScale = nodeProxy( Object3DNode, Object3DNode.SCALE );
  25025. const objectViewPosition = nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  25026. addNodeClass( 'Object3DNode', Object3DNode );
  25027. class ModelNode extends Object3DNode {
  25028. constructor( scope = ModelNode.VIEW_MATRIX ) {
  25029. super( scope );
  25030. }
  25031. update( frame ) {
  25032. this.object3d = frame.object;
  25033. super.update( frame );
  25034. }
  25035. }
  25036. const modelDirection = nodeImmutable( ModelNode, ModelNode.DIRECTION );
  25037. const modelViewMatrix = nodeImmutable( ModelNode, ModelNode.VIEW_MATRIX ).label( 'modelViewMatrix' ).temp( 'ModelViewMatrix' );
  25038. const modelNormalMatrix = nodeImmutable( ModelNode, ModelNode.NORMAL_MATRIX );
  25039. const modelWorldMatrix = nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  25040. const modelPosition = nodeImmutable( ModelNode, ModelNode.POSITION );
  25041. const modelScale = nodeImmutable( ModelNode, ModelNode.SCALE );
  25042. const modelViewPosition = nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  25043. const modelWorldMatrixInverse = uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  25044. addNodeClass( 'ModelNode', ModelNode );
  25045. const normalGeometry = /*#__PURE__*/ attribute( 'normal', 'vec3', vec3( 0, 1, 0 ) );
  25046. const normalLocal = /*#__PURE__*/ normalGeometry.toVar( 'normalLocal' );
  25047. const normalView = /*#__PURE__*/ varying( modelNormalMatrix.mul( normalLocal ), 'v_normalView' ).normalize().toVar( 'normalView' );
  25048. const normalWorld = /*#__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'transformedNormalWorld' );
  25049. const transformedNormalView = /*#__PURE__*/ property( 'vec3', 'transformedNormalView' );
  25050. const transformedNormalWorld = /*#__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedNormalWorld' );
  25051. const transformedClearcoatNormalView = /*#__PURE__*/ property( 'vec3', 'transformedClearcoatNormalView' );
  25052. const _propertyCache = new Map();
  25053. class MaterialNode extends Node {
  25054. constructor( scope ) {
  25055. super();
  25056. this.scope = scope;
  25057. }
  25058. getCache( property, type ) {
  25059. let node = _propertyCache.get( property );
  25060. if ( node === undefined ) {
  25061. node = materialReference( property, type );
  25062. _propertyCache.set( property, node );
  25063. }
  25064. return node;
  25065. }
  25066. getFloat( property ) {
  25067. return this.getCache( property, 'float' );
  25068. }
  25069. getColor( property ) {
  25070. return this.getCache( property, 'color' );
  25071. }
  25072. getTexture( property ) {
  25073. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  25074. }
  25075. setup( builder ) {
  25076. const material = builder.context.material;
  25077. const scope = this.scope;
  25078. let node = null;
  25079. if ( scope === MaterialNode.COLOR ) {
  25080. const colorNode = this.getColor( scope );
  25081. if ( material.map && material.map.isTexture === true ) {
  25082. node = colorNode.mul( this.getTexture( 'map' ) );
  25083. } else {
  25084. node = colorNode;
  25085. }
  25086. } else if ( scope === MaterialNode.OPACITY ) {
  25087. const opacityNode = this.getFloat( scope );
  25088. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  25089. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  25090. } else {
  25091. node = opacityNode;
  25092. }
  25093. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  25094. if ( material.specularMap && material.specularMap.isTexture === true ) {
  25095. node = this.getTexture( 'specular' ).r;
  25096. } else {
  25097. node = float( 1 );
  25098. }
  25099. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  25100. const specularIntensity = this.getFloat( scope );
  25101. if ( material.specularMap ) {
  25102. node = specularIntensity.mul( this.getTexture( scope ).a );
  25103. } else {
  25104. node = specularIntensity;
  25105. }
  25106. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  25107. const specularColorNode = this.getColor( scope );
  25108. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  25109. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  25110. } else {
  25111. node = specularColorNode;
  25112. }
  25113. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  25114. const roughnessNode = this.getFloat( scope );
  25115. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  25116. node = roughnessNode.mul( this.getTexture( scope ).g );
  25117. } else {
  25118. node = roughnessNode;
  25119. }
  25120. } else if ( scope === MaterialNode.METALNESS ) {
  25121. const metalnessNode = this.getFloat( scope );
  25122. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  25123. node = metalnessNode.mul( this.getTexture( scope ).b );
  25124. } else {
  25125. node = metalnessNode;
  25126. }
  25127. } else if ( scope === MaterialNode.EMISSIVE ) {
  25128. const emissiveNode = this.getColor( scope );
  25129. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  25130. node = emissiveNode.mul( this.getTexture( scope ) );
  25131. } else {
  25132. node = emissiveNode;
  25133. }
  25134. } else if ( scope === MaterialNode.NORMAL ) {
  25135. if ( material.normalMap ) {
  25136. node = this.getTexture( 'normal' ).normalMap( this.getCache( 'normalScale', 'vec2' ) );
  25137. } else if ( material.bumpMap ) {
  25138. node = this.getTexture( 'bump' ).r.bumpMap( this.getFloat( 'bumpScale' ) );
  25139. } else {
  25140. node = normalView;
  25141. }
  25142. } else if ( scope === MaterialNode.CLEARCOAT ) {
  25143. const clearcoatNode = this.getFloat( scope );
  25144. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  25145. node = clearcoatNode.mul( this.getTexture( scope ).r );
  25146. } else {
  25147. node = clearcoatNode;
  25148. }
  25149. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  25150. const clearcoatRoughnessNode = this.getFloat( scope );
  25151. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  25152. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  25153. } else {
  25154. node = clearcoatRoughnessNode;
  25155. }
  25156. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  25157. if ( material.clearcoatNormalMap ) {
  25158. node = this.getTexture( scope ).normalMap( this.getCache( scope + 'Scale', 'vec2' ) );
  25159. } else {
  25160. node = normalView;
  25161. }
  25162. } else if ( scope === MaterialNode.SHEEN ) {
  25163. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  25164. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  25165. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  25166. } else {
  25167. node = sheenNode;
  25168. }
  25169. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  25170. const sheenRoughnessNode = this.getFloat( scope );
  25171. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  25172. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  25173. } else {
  25174. node = sheenRoughnessNode;
  25175. }
  25176. node = node.clamp( 0.07, 1.0 );
  25177. } else if ( scope === MaterialNode.ANISOTROPY ) {
  25178. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  25179. const anisotropyPolar = this.getTexture( scope );
  25180. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  25181. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  25182. } else {
  25183. node = materialAnisotropyVector;
  25184. }
  25185. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  25186. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  25187. if ( material.iridescenceThicknessMap ) {
  25188. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  25189. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  25190. } else {
  25191. node = iridescenceThicknessMaximum;
  25192. }
  25193. } else if ( scope === MaterialNode.TRANSMISSION ) {
  25194. const transmissionNode = this.getFloat( scope );
  25195. if ( material.transmissionMap ) {
  25196. node = transmissionNode.mul( this.getTexture( scope ).r );
  25197. } else {
  25198. node = transmissionNode;
  25199. }
  25200. } else if ( scope === MaterialNode.THICKNESS ) {
  25201. const thicknessNode = this.getFloat( scope );
  25202. if ( material.thicknessMap ) {
  25203. node = thicknessNode.mul( this.getTexture( scope ).g );
  25204. } else {
  25205. node = thicknessNode;
  25206. }
  25207. } else if ( scope === MaterialNode.IOR ) {
  25208. node = this.getFloat( scope );
  25209. } else {
  25210. const outputType = this.getNodeType( builder );
  25211. node = this.getCache( scope, outputType );
  25212. }
  25213. return node;
  25214. }
  25215. }
  25216. MaterialNode.ALPHA_TEST = 'alphaTest';
  25217. MaterialNode.COLOR = 'color';
  25218. MaterialNode.OPACITY = 'opacity';
  25219. MaterialNode.SHININESS = 'shininess';
  25220. MaterialNode.SPECULAR = 'specular';
  25221. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  25222. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  25223. MaterialNode.SPECULAR_COLOR = 'specularColor';
  25224. MaterialNode.REFLECTIVITY = 'reflectivity';
  25225. MaterialNode.ROUGHNESS = 'roughness';
  25226. MaterialNode.METALNESS = 'metalness';
  25227. MaterialNode.NORMAL = 'normal';
  25228. MaterialNode.CLEARCOAT = 'clearcoat';
  25229. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  25230. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  25231. MaterialNode.EMISSIVE = 'emissive';
  25232. MaterialNode.ROTATION = 'rotation';
  25233. MaterialNode.SHEEN = 'sheen';
  25234. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  25235. MaterialNode.ANISOTROPY = 'anisotropy';
  25236. MaterialNode.IRIDESCENCE = 'iridescence';
  25237. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  25238. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  25239. MaterialNode.IOR = 'ior';
  25240. MaterialNode.TRANSMISSION = 'transmission';
  25241. MaterialNode.THICKNESS = 'thickness';
  25242. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  25243. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  25244. MaterialNode.LINE_SCALE = 'scale';
  25245. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  25246. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  25247. MaterialNode.LINE_WIDTH = 'linewidth';
  25248. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  25249. MaterialNode.POINT_WIDTH = 'pointWidth';
  25250. MaterialNode.DISPERSION = 'dispersion';
  25251. const materialAlphaTest = nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  25252. const materialColor = nodeImmutable( MaterialNode, MaterialNode.COLOR );
  25253. const materialShininess = nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  25254. const materialEmissive = nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  25255. const materialOpacity = nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  25256. const materialSpecular = nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  25257. const materialSpecularIntensity = nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  25258. const materialSpecularColor = nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  25259. const materialSpecularStrength = nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  25260. const materialReflectivity = nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  25261. const materialRoughness = nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  25262. const materialMetalness = nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  25263. const materialNormal = nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  25264. const materialClearcoat = nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  25265. const materialClearcoatRoughness = nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  25266. const materialClearcoatNormal = nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  25267. const materialRotation = nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  25268. const materialSheen = nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  25269. const materialSheenRoughness = nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  25270. const materialAnisotropy = nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  25271. const materialIridescence = nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  25272. const materialIridescenceIOR = nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  25273. const materialIridescenceThickness = nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  25274. const materialTransmission = nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  25275. const materialThickness = nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  25276. const materialIOR = nodeImmutable( MaterialNode, MaterialNode.IOR );
  25277. const materialAttenuationDistance = nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  25278. const materialAttenuationColor = nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  25279. const materialLineScale = nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  25280. const materialLineDashSize = nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  25281. const materialLineGapSize = nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  25282. const materialLineWidth = nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  25283. const materialLineDashOffset = nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  25284. const materialPointWidth = nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  25285. const materialDispersion = nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  25286. const materialAnisotropyVector = uniform( new Vector2() ).onReference( function ( frame ) {
  25287. return frame.material;
  25288. } ).onRenderUpdate( function ( { material } ) {
  25289. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  25290. } );
  25291. addNodeClass( 'MaterialNode', MaterialNode );
  25292. const positionGeometry = /*#__PURE__*/ attribute( 'position', 'vec3' );
  25293. const positionLocal = /*#__PURE__*/ positionGeometry.toVar( 'positionLocal' );
  25294. const positionWorld = /*#__PURE__*/ varying( modelWorldMatrix.mul( positionLocal ).xyz, 'v_positionWorld' );
  25295. const positionWorldDirection = /*#__PURE__*/ varying( positionLocal.transformDirection( modelWorldMatrix ), 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  25296. const positionView = /*#__PURE__*/ varying( modelViewMatrix.mul( positionLocal ).xyz, 'v_positionView' );
  25297. const positionViewDirection = /*#__PURE__*/ varying( positionView.negate(), 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  25298. class ModelViewProjectionNode extends TempNode {
  25299. constructor( positionNode = null ) {
  25300. super( 'vec4' );
  25301. this.positionNode = positionNode;
  25302. }
  25303. setup( builder ) {
  25304. if ( builder.shaderStage === 'fragment' ) {
  25305. return varying( builder.context.mvp );
  25306. }
  25307. const position = this.positionNode || positionLocal;
  25308. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( position );
  25309. }
  25310. }
  25311. const modelViewProjection = nodeProxy( ModelViewProjectionNode );
  25312. addNodeClass( 'ModelViewProjectionNode', ModelViewProjectionNode );
  25313. class BufferAttributeNode extends InputNode {
  25314. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  25315. super( value, bufferType );
  25316. this.isBufferNode = true;
  25317. this.bufferType = bufferType;
  25318. this.bufferStride = bufferStride;
  25319. this.bufferOffset = bufferOffset;
  25320. this.usage = StaticDrawUsage;
  25321. this.instanced = false;
  25322. this.attribute = null;
  25323. this.global = true;
  25324. if ( value && value.isBufferAttribute === true ) {
  25325. this.attribute = value;
  25326. this.usage = value.usage;
  25327. this.instanced = value.isInstancedBufferAttribute;
  25328. }
  25329. }
  25330. getHash( builder ) {
  25331. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  25332. let bufferData = builder.globalCache.getData( this.value );
  25333. if ( bufferData === undefined ) {
  25334. bufferData = {
  25335. node: this
  25336. };
  25337. builder.globalCache.setData( this.value, bufferData );
  25338. }
  25339. return bufferData.node.uuid;
  25340. }
  25341. return this.uuid;
  25342. }
  25343. getNodeType( builder ) {
  25344. if ( this.bufferType === null ) {
  25345. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  25346. }
  25347. return this.bufferType;
  25348. }
  25349. setup( builder ) {
  25350. if ( this.attribute !== null ) return;
  25351. const type = this.getNodeType( builder );
  25352. const array = this.value;
  25353. const itemSize = builder.getTypeLength( type );
  25354. const stride = this.bufferStride || itemSize;
  25355. const offset = this.bufferOffset;
  25356. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  25357. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  25358. buffer.setUsage( this.usage );
  25359. this.attribute = bufferAttribute;
  25360. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  25361. }
  25362. generate( builder ) {
  25363. const nodeType = this.getNodeType( builder );
  25364. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  25365. const propertyName = builder.getPropertyName( nodeAttribute );
  25366. let output = null;
  25367. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  25368. this.name = propertyName;
  25369. output = propertyName;
  25370. } else {
  25371. const nodeVarying = varying( this );
  25372. output = nodeVarying.build( builder, nodeType );
  25373. }
  25374. return output;
  25375. }
  25376. getInputType( /*builder*/ ) {
  25377. return 'bufferAttribute';
  25378. }
  25379. setUsage( value ) {
  25380. this.usage = value;
  25381. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  25382. this.attribute.usage = value;
  25383. }
  25384. return this;
  25385. }
  25386. setInstanced( value ) {
  25387. this.instanced = value;
  25388. return this;
  25389. }
  25390. }
  25391. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  25392. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  25393. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  25394. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  25395. addNodeElement( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  25396. addNodeClass( 'BufferAttributeNode', BufferAttributeNode );
  25397. class InstanceNode extends Node {
  25398. constructor( instanceMesh ) {
  25399. super( 'void' );
  25400. this.instanceMesh = instanceMesh;
  25401. this.instanceMatrixNode = null;
  25402. this.instanceColorNode = null;
  25403. this.updateType = NodeUpdateType.FRAME;
  25404. this.buffer = null;
  25405. this.bufferColor = null;
  25406. }
  25407. setup( /*builder*/ ) {
  25408. let instanceMatrixNode = this.instanceMatrixNode;
  25409. const instanceMesh = this.instanceMesh;
  25410. if ( instanceMatrixNode === null ) {
  25411. const instanceAttribute = instanceMesh.instanceMatrix;
  25412. const buffer = new InstancedInterleavedBuffer( instanceAttribute.array, 16, 1 );
  25413. this.buffer = buffer;
  25414. const bufferFn = instanceAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25415. const instanceBuffers = [
  25416. // F.Signature -> bufferAttribute( array, type, stride, offset )
  25417. bufferFn( buffer, 'vec4', 16, 0 ),
  25418. bufferFn( buffer, 'vec4', 16, 4 ),
  25419. bufferFn( buffer, 'vec4', 16, 8 ),
  25420. bufferFn( buffer, 'vec4', 16, 12 )
  25421. ];
  25422. instanceMatrixNode = mat4( ...instanceBuffers );
  25423. this.instanceMatrixNode = instanceMatrixNode;
  25424. }
  25425. const instanceColorAttribute = instanceMesh.instanceColor;
  25426. if ( instanceColorAttribute && this.instanceColorNode === null ) {
  25427. const buffer = new InstancedBufferAttribute( instanceColorAttribute.array, 3 );
  25428. const bufferFn = instanceColorAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25429. this.bufferColor = buffer;
  25430. this.instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  25431. }
  25432. // POSITION
  25433. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  25434. // NORMAL
  25435. const m = mat3( instanceMatrixNode[ 0 ].xyz, instanceMatrixNode[ 1 ].xyz, instanceMatrixNode[ 2 ].xyz );
  25436. const transformedNormal = normalLocal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  25437. const instanceNormal = m.mul( transformedNormal ).xyz;
  25438. // ASSIGNS
  25439. positionLocal.assign( instancePosition );
  25440. normalLocal.assign( instanceNormal );
  25441. // COLOR
  25442. if ( this.instanceColorNode !== null ) {
  25443. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  25444. }
  25445. }
  25446. update( /*frame*/ ) {
  25447. if ( this.instanceMesh.instanceMatrix.usage !== DynamicDrawUsage && this.instanceMesh.instanceMatrix.version !== this.buffer.version ) {
  25448. this.buffer.version = this.instanceMesh.instanceMatrix.version;
  25449. }
  25450. if ( this.instanceMesh.instanceColor && this.instanceMesh.instanceColor.usage !== DynamicDrawUsage && this.instanceMesh.instanceColor.version !== this.bufferColor.version ) {
  25451. this.bufferColor.version = this.instanceMesh.instanceColor.version;
  25452. }
  25453. }
  25454. }
  25455. const instance = nodeProxy( InstanceNode );
  25456. addNodeClass( 'InstanceNode', InstanceNode );
  25457. const tangentGeometry = /*#__PURE__*/ tslFn( ( stack, builder ) => {
  25458. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  25459. builder.geometry.computeTangents();
  25460. }
  25461. return attribute( 'tangent', 'vec4' );
  25462. } )();
  25463. const tangentLocal = /*#__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  25464. const tangentView = /*#__PURE__*/ varying( modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz, 'v_tangentView' ).normalize().toVar( 'tangentView' );
  25465. const tangentWorld = /*#__PURE__*/ varying( tangentView.transformDirection( cameraViewMatrix ), 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  25466. const transformedTangentView = /*#__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  25467. const transformedTangentWorld = /*#__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  25468. class BatchNode extends Node {
  25469. constructor( batchMesh ) {
  25470. super( 'void' );
  25471. this.batchMesh = batchMesh;
  25472. this.instanceColorNode = null;
  25473. this.batchingIdNode = null;
  25474. }
  25475. setup( builder ) {
  25476. // POSITION
  25477. if ( this.batchingIdNode === null ) {
  25478. if ( builder.getDrawIndex() === null ) {
  25479. this.batchingIdNode = instanceIndex;
  25480. } else {
  25481. this.batchingIdNode = drawIndex;
  25482. }
  25483. }
  25484. const getIndirectIndex = tslFn( ( [ id ] ) => {
  25485. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  25486. const x = int( id ).remainder( int( size ) );
  25487. const y = int( id ).div( int( size ) );
  25488. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ), null, 'uvec4' ).x;
  25489. } ).setLayout( {
  25490. name: 'getIndirectIndex',
  25491. type: 'uint',
  25492. inputs: [
  25493. { name: 'id', type: 'int' }
  25494. ]
  25495. } );
  25496. const matriceTexture = this.batchMesh._matricesTexture;
  25497. const size = textureSize( textureLoad( matriceTexture ), 0 );
  25498. const j = float( getIndirectIndex( int( this.batchingIdNode ) ) ).mul( 4 ).toVar();
  25499. const x = int( j.mod( size ) );
  25500. const y = int( j ).div( int( size ) );
  25501. const batchingMatrix = mat4(
  25502. textureLoad( matriceTexture, ivec2( x, y ) ),
  25503. textureLoad( matriceTexture, ivec2( x.add( 1 ), y ) ),
  25504. textureLoad( matriceTexture, ivec2( x.add( 2 ), y ) ),
  25505. textureLoad( matriceTexture, ivec2( x.add( 3 ), y ) )
  25506. );
  25507. const bm = mat3(
  25508. batchingMatrix[ 0 ].xyz,
  25509. batchingMatrix[ 1 ].xyz,
  25510. batchingMatrix[ 2 ].xyz
  25511. );
  25512. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  25513. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  25514. const batchingNormal = bm.mul( transformedNormal ).xyz;
  25515. normalLocal.assign( batchingNormal );
  25516. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25517. tangentLocal.mulAssign( bm );
  25518. }
  25519. }
  25520. }
  25521. const batch = nodeProxy( BatchNode );
  25522. addNodeClass( 'batch', BatchNode );
  25523. class SkinningNode extends Node {
  25524. constructor( skinnedMesh, useReference = false ) {
  25525. super( 'void' );
  25526. this.skinnedMesh = skinnedMesh;
  25527. this.useReference = useReference;
  25528. this.updateType = NodeUpdateType.OBJECT;
  25529. //
  25530. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  25531. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  25532. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  25533. if ( useReference ) {
  25534. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  25535. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  25536. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  25537. } else {
  25538. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  25539. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  25540. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  25541. }
  25542. this.bindMatrixNode = bindMatrixNode;
  25543. this.bindMatrixInverseNode = bindMatrixInverseNode;
  25544. this.boneMatricesNode = boneMatricesNode;
  25545. }
  25546. setup( builder ) {
  25547. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode, boneMatricesNode } = this;
  25548. const boneMatX = boneMatricesNode.element( skinIndexNode.x );
  25549. const boneMatY = boneMatricesNode.element( skinIndexNode.y );
  25550. const boneMatZ = boneMatricesNode.element( skinIndexNode.z );
  25551. const boneMatW = boneMatricesNode.element( skinIndexNode.w );
  25552. // POSITION
  25553. const skinVertex = bindMatrixNode.mul( positionLocal );
  25554. const skinned = add(
  25555. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  25556. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  25557. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  25558. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  25559. );
  25560. const skinPosition = bindMatrixInverseNode.mul( skinned ).xyz;
  25561. // NORMAL
  25562. let skinMatrix = add(
  25563. skinWeightNode.x.mul( boneMatX ),
  25564. skinWeightNode.y.mul( boneMatY ),
  25565. skinWeightNode.z.mul( boneMatZ ),
  25566. skinWeightNode.w.mul( boneMatW )
  25567. );
  25568. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  25569. const skinNormal = skinMatrix.transformDirection( normalLocal ).xyz;
  25570. // ASSIGNS
  25571. positionLocal.assign( skinPosition );
  25572. normalLocal.assign( skinNormal );
  25573. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25574. tangentLocal.assign( skinNormal );
  25575. }
  25576. }
  25577. generate( builder, output ) {
  25578. if ( output !== 'void' ) {
  25579. return positionLocal.build( builder, output );
  25580. }
  25581. }
  25582. update( frame ) {
  25583. const object = this.useReference ? frame.object : this.skinnedMesh;
  25584. object.skeleton.update();
  25585. }
  25586. }
  25587. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  25588. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  25589. addNodeClass( 'SkinningNode', SkinningNode );
  25590. class LoopNode extends Node {
  25591. constructor( params = [] ) {
  25592. super();
  25593. this.params = params;
  25594. }
  25595. getVarName( index ) {
  25596. return String.fromCharCode( 'i'.charCodeAt() + index );
  25597. }
  25598. getProperties( builder ) {
  25599. const properties = builder.getNodeProperties( this );
  25600. if ( properties.stackNode !== undefined ) return properties;
  25601. //
  25602. const inputs = {};
  25603. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25604. const param = this.params[ i ];
  25605. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  25606. const type = ( param.isNode !== true && param.type ) || 'int';
  25607. inputs[ name ] = expression( name, type );
  25608. }
  25609. const stack = builder.addStack(); // TODO: cache() it
  25610. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  25611. properties.stackNode = stack;
  25612. builder.removeStack();
  25613. return properties;
  25614. }
  25615. getNodeType( builder ) {
  25616. const { returnsNode } = this.getProperties( builder );
  25617. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  25618. }
  25619. setup( builder ) {
  25620. // setup properties
  25621. this.getProperties( builder );
  25622. }
  25623. generate( builder ) {
  25624. const properties = this.getProperties( builder );
  25625. const params = this.params;
  25626. const stackNode = properties.stackNode;
  25627. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  25628. const param = params[ i ];
  25629. let start = null, end = null, name = null, type = null, condition = null, update = null;
  25630. if ( param.isNode ) {
  25631. type = 'int';
  25632. name = this.getVarName( i );
  25633. start = '0';
  25634. end = param.build( builder, type );
  25635. condition = '<';
  25636. } else {
  25637. type = param.type || 'int';
  25638. name = param.name || this.getVarName( i );
  25639. start = param.start;
  25640. end = param.end;
  25641. condition = param.condition;
  25642. update = param.update;
  25643. if ( typeof start === 'number' ) start = start.toString();
  25644. else if ( start && start.isNode ) start = start.build( builder, type );
  25645. if ( typeof end === 'number' ) end = end.toString();
  25646. else if ( end && end.isNode ) end = end.build( builder, type );
  25647. if ( start !== undefined && end === undefined ) {
  25648. start = start + ' - 1';
  25649. end = '0';
  25650. condition = '>=';
  25651. } else if ( end !== undefined && start === undefined ) {
  25652. start = '0';
  25653. condition = '<';
  25654. }
  25655. if ( condition === undefined ) {
  25656. if ( Number( start ) > Number( end ) ) {
  25657. condition = '>=';
  25658. } else {
  25659. condition = '<';
  25660. }
  25661. }
  25662. }
  25663. const internalParam = { start, end, condition };
  25664. //
  25665. const startSnippet = internalParam.start;
  25666. const endSnippet = internalParam.end;
  25667. let declarationSnippet = '';
  25668. let conditionalSnippet = '';
  25669. let updateSnippet = '';
  25670. if ( ! update ) {
  25671. if ( type === 'int' || type === 'uint' ) {
  25672. if ( condition.includes( '<' ) ) update = '++';
  25673. else update = '--';
  25674. } else {
  25675. if ( condition.includes( '<' ) ) update = '+= 1.';
  25676. else update = '-= 1.';
  25677. }
  25678. }
  25679. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  25680. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  25681. updateSnippet += name + ' ' + update;
  25682. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  25683. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  25684. }
  25685. const stackSnippet = stackNode.build( builder, 'void' );
  25686. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  25687. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  25688. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25689. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  25690. }
  25691. builder.addFlowTab();
  25692. return returnsSnippet;
  25693. }
  25694. }
  25695. const loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  25696. const Continue = () => expression( 'continue' ).append();
  25697. const Break = () => expression( 'break' ).append();
  25698. addNodeElement( 'loop', ( returns, ...params ) => bypass( returns, loop( ...params ) ) );
  25699. addNodeClass( 'LoopNode', LoopNode );
  25700. const morphTextures = new WeakMap();
  25701. const morphVec4 = new Vector4();
  25702. const getMorph = tslFn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  25703. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  25704. const y = texelIndex.div( width );
  25705. const x = texelIndex.sub( y.mul( width ) );
  25706. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  25707. return bufferAttrib.mul( influence );
  25708. } );
  25709. function getEntry( geometry ) {
  25710. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  25711. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  25712. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  25713. // instead of using attributes, the WebGL 2 code path encodes morph targets
  25714. // into an array of data textures. Each layer represents a single morph target.
  25715. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  25716. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  25717. let entry = morphTextures.get( geometry );
  25718. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  25719. if ( entry !== undefined ) entry.texture.dispose();
  25720. const morphTargets = geometry.morphAttributes.position || [];
  25721. const morphNormals = geometry.morphAttributes.normal || [];
  25722. const morphColors = geometry.morphAttributes.color || [];
  25723. let vertexDataCount = 0;
  25724. if ( hasMorphPosition === true ) vertexDataCount = 1;
  25725. if ( hasMorphNormals === true ) vertexDataCount = 2;
  25726. if ( hasMorphColors === true ) vertexDataCount = 3;
  25727. let width = geometry.attributes.position.count * vertexDataCount;
  25728. let height = 1;
  25729. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  25730. if ( width > maxTextureSize ) {
  25731. height = Math.ceil( width / maxTextureSize );
  25732. width = maxTextureSize;
  25733. }
  25734. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  25735. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  25736. bufferTexture.type = FloatType;
  25737. bufferTexture.needsUpdate = true;
  25738. // fill buffer
  25739. const vertexDataStride = vertexDataCount * 4;
  25740. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  25741. const morphTarget = morphTargets[ i ];
  25742. const morphNormal = morphNormals[ i ];
  25743. const morphColor = morphColors[ i ];
  25744. const offset = width * height * 4 * i;
  25745. for ( let j = 0; j < morphTarget.count; j ++ ) {
  25746. const stride = j * vertexDataStride;
  25747. if ( hasMorphPosition === true ) {
  25748. morphVec4.fromBufferAttribute( morphTarget, j );
  25749. buffer[ offset + stride + 0 ] = morphVec4.x;
  25750. buffer[ offset + stride + 1 ] = morphVec4.y;
  25751. buffer[ offset + stride + 2 ] = morphVec4.z;
  25752. buffer[ offset + stride + 3 ] = 0;
  25753. }
  25754. if ( hasMorphNormals === true ) {
  25755. morphVec4.fromBufferAttribute( morphNormal, j );
  25756. buffer[ offset + stride + 4 ] = morphVec4.x;
  25757. buffer[ offset + stride + 5 ] = morphVec4.y;
  25758. buffer[ offset + stride + 6 ] = morphVec4.z;
  25759. buffer[ offset + stride + 7 ] = 0;
  25760. }
  25761. if ( hasMorphColors === true ) {
  25762. morphVec4.fromBufferAttribute( morphColor, j );
  25763. buffer[ offset + stride + 8 ] = morphVec4.x;
  25764. buffer[ offset + stride + 9 ] = morphVec4.y;
  25765. buffer[ offset + stride + 10 ] = morphVec4.z;
  25766. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morphVec4.w : 1;
  25767. }
  25768. }
  25769. }
  25770. entry = {
  25771. count: morphTargetsCount,
  25772. texture: bufferTexture,
  25773. stride: vertexDataCount,
  25774. size: new Vector2( width, height )
  25775. };
  25776. morphTextures.set( geometry, entry );
  25777. function disposeTexture() {
  25778. bufferTexture.dispose();
  25779. morphTextures.delete( geometry );
  25780. geometry.removeEventListener( 'dispose', disposeTexture );
  25781. }
  25782. geometry.addEventListener( 'dispose', disposeTexture );
  25783. }
  25784. return entry;
  25785. }
  25786. class MorphNode extends Node {
  25787. constructor( mesh ) {
  25788. super( 'void' );
  25789. this.mesh = mesh;
  25790. this.morphBaseInfluence = uniform( 1 );
  25791. this.updateType = NodeUpdateType.OBJECT;
  25792. }
  25793. setup( builder ) {
  25794. const { geometry } = builder;
  25795. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  25796. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  25797. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  25798. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  25799. // nodes
  25800. const { texture: bufferMap, stride, size } = getEntry( geometry );
  25801. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  25802. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  25803. const width = int( size.width );
  25804. loop( morphTargetsCount, ( { i } ) => {
  25805. const influence = float( 0 ).toVar();
  25806. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  25807. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  25808. } else {
  25809. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  25810. }
  25811. if ( hasMorphPosition === true ) {
  25812. positionLocal.addAssign( getMorph( {
  25813. bufferMap,
  25814. influence,
  25815. stride,
  25816. width,
  25817. depth: i,
  25818. offset: int( 0 )
  25819. } ) );
  25820. }
  25821. if ( hasMorphNormals === true ) {
  25822. normalLocal.addAssign( getMorph( {
  25823. bufferMap,
  25824. influence,
  25825. stride,
  25826. width,
  25827. depth: i,
  25828. offset: int( 1 )
  25829. } ) );
  25830. }
  25831. } );
  25832. }
  25833. update() {
  25834. const morphBaseInfluence = this.morphBaseInfluence;
  25835. if ( this.mesh.geometry.morphTargetsRelative ) {
  25836. morphBaseInfluence.value = 1;
  25837. } else {
  25838. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  25839. }
  25840. }
  25841. }
  25842. const morphReference = nodeProxy( MorphNode );
  25843. addNodeClass( 'MorphNode', MorphNode );
  25844. const reflectView = /*#__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  25845. const reflectVector = /*#__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  25846. class CubeTextureNode extends TextureNode {
  25847. constructor( value, uvNode = null, levelNode = null ) {
  25848. super( value, uvNode, levelNode );
  25849. this.isCubeTextureNode = true;
  25850. }
  25851. getInputType( /*builder*/ ) {
  25852. return 'cubeTexture';
  25853. }
  25854. getDefaultUV() {
  25855. return reflectVector;
  25856. }
  25857. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  25858. setupUV( builder, uvNode ) {
  25859. const texture = this.value;
  25860. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  25861. return vec3( uvNode.x.negate(), uvNode.yz );
  25862. } else {
  25863. return uvNode;
  25864. }
  25865. }
  25866. generateUV( builder, cubeUV ) {
  25867. return cubeUV.build( builder, 'vec3' );
  25868. }
  25869. }
  25870. const cubeTexture = nodeProxy( CubeTextureNode );
  25871. addNodeElement( 'cubeTexture', cubeTexture );
  25872. addNodeClass( 'CubeTextureNode', CubeTextureNode );
  25873. class LightingNode extends Node {
  25874. constructor() {
  25875. super( 'vec3' );
  25876. }
  25877. generate( /*builder*/ ) {
  25878. console.warn( 'Abstract function.' );
  25879. }
  25880. }
  25881. addNodeClass( 'LightingNode', LightingNode );
  25882. let overrideMaterial = null;
  25883. class AnalyticLightNode extends LightingNode {
  25884. constructor( light = null ) {
  25885. super();
  25886. this.updateType = NodeUpdateType.FRAME;
  25887. this.light = light;
  25888. this.rtt = null;
  25889. this.shadowNode = null;
  25890. this.shadowMaskNode = null;
  25891. this.color = new Color();
  25892. this._defaultColorNode = uniform( this.color );
  25893. this.colorNode = this._defaultColorNode;
  25894. this.isAnalyticLightNode = true;
  25895. }
  25896. getCacheKey() {
  25897. return super.getCacheKey() + '-' + ( this.light.id + '-' + ( this.light.castShadow ? '1' : '0' ) );
  25898. }
  25899. getHash() {
  25900. return this.light.uuid;
  25901. }
  25902. setupShadow( builder ) {
  25903. const { object } = builder;
  25904. if ( object.receiveShadow === false ) return;
  25905. let shadowNode = this.shadowNode;
  25906. if ( shadowNode === null ) {
  25907. if ( overrideMaterial === null ) {
  25908. overrideMaterial = builder.createNodeMaterial();
  25909. overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 );
  25910. overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode
  25911. }
  25912. const shadow = this.light.shadow;
  25913. const rtt = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  25914. const depthTexture = new DepthTexture();
  25915. depthTexture.minFilter = NearestFilter;
  25916. depthTexture.magFilter = NearestFilter;
  25917. depthTexture.image.width = shadow.mapSize.width;
  25918. depthTexture.image.height = shadow.mapSize.height;
  25919. depthTexture.compareFunction = LessCompare;
  25920. rtt.depthTexture = depthTexture;
  25921. shadow.camera.updateProjectionMatrix();
  25922. //
  25923. const shadowIntensity = reference( 'intensity', 'float', shadow );
  25924. const bias = reference( 'bias', 'float', shadow );
  25925. const normalBias = reference( 'normalBias', 'float', shadow );
  25926. const position = object.material.shadowPositionNode || positionWorld;
  25927. let shadowCoord = uniform( shadow.matrix ).mul( position.add( normalWorld.mul( normalBias ) ) );
  25928. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  25929. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  25930. .and( shadowCoord.x.lessThanEqual( 1 ) )
  25931. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  25932. .and( shadowCoord.y.lessThanEqual( 1 ) )
  25933. .and( shadowCoord.z.lessThanEqual( 1 ) );
  25934. let coordZ = shadowCoord.z.add( bias );
  25935. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  25936. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Convertion [ 0, 1 ] to [ - 1, 1 ]
  25937. }
  25938. shadowCoord = vec3(
  25939. shadowCoord.x,
  25940. shadowCoord.y.oneMinus(), // follow webgpu standards
  25941. coordZ
  25942. );
  25943. const textureCompare = ( depthTexture, shadowCoord, compare ) => texture( depthTexture, shadowCoord ).compare( compare );
  25944. //const textureCompare = ( depthTexture, shadowCoord, compare ) => compare.step( texture( depthTexture, shadowCoord ) );
  25945. // BasicShadowMap
  25946. shadowNode = textureCompare( depthTexture, shadowCoord.xy, shadowCoord.z );
  25947. // PCFShadowMap
  25948. /*
  25949. const mapSize = reference( 'mapSize', 'vec2', shadow );
  25950. const radius = reference( 'radius', 'float', shadow );
  25951. const texelSize = vec2( 1 ).div( mapSize );
  25952. const dx0 = texelSize.x.negate().mul( radius );
  25953. const dy0 = texelSize.y.negate().mul( radius );
  25954. const dx1 = texelSize.x.mul( radius );
  25955. const dy1 = texelSize.y.mul( radius );
  25956. const dx2 = dx0.mul( 2 );
  25957. const dy2 = dy0.mul( 2 );
  25958. const dx3 = dx1.mul( 2 );
  25959. const dy3 = dy1.mul( 2 );
  25960. shadowNode = add(
  25961. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  25962. textureCompare( depthTexture, shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  25963. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  25964. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  25965. textureCompare( depthTexture, shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  25966. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  25967. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  25968. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  25969. textureCompare( depthTexture, shadowCoord.xy, shadowCoord.z ),
  25970. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  25971. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  25972. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  25973. textureCompare( depthTexture, shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  25974. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  25975. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  25976. textureCompare( depthTexture, shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  25977. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  25978. ).mul( 1 / 17 );
  25979. */
  25980. //
  25981. const shadowColor = texture( rtt.texture, shadowCoord );
  25982. const shadowMaskNode = frustumTest.mix( 1, shadowNode.mix( shadowColor.a.mix( 1, shadowColor ), 1 ) );
  25983. this.rtt = rtt;
  25984. this.colorNode = this.colorNode.mul( mix( 1, shadowMaskNode, shadowIntensity ) );
  25985. this.shadowNode = shadowNode;
  25986. this.shadowMaskNode = shadowMaskNode;
  25987. //
  25988. this.updateBeforeType = NodeUpdateType.RENDER;
  25989. }
  25990. }
  25991. setup( builder ) {
  25992. if ( this.light.castShadow ) this.setupShadow( builder );
  25993. else if ( this.shadowNode !== null ) this.disposeShadow();
  25994. }
  25995. updateShadow( frame ) {
  25996. const { rtt, light } = this;
  25997. const { renderer, scene, camera } = frame;
  25998. const currentOverrideMaterial = scene.overrideMaterial;
  25999. scene.overrideMaterial = overrideMaterial;
  26000. rtt.setSize( light.shadow.mapSize.width, light.shadow.mapSize.height );
  26001. light.shadow.updateMatrices( light );
  26002. light.shadow.camera.layers.mask = camera.layers.mask;
  26003. const currentToneMapping = renderer.toneMapping;
  26004. const currentRenderTarget = renderer.getRenderTarget();
  26005. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  26006. renderer.setRenderObjectFunction( ( object, ...params ) => {
  26007. if ( object.castShadow === true ) {
  26008. renderer.renderObject( object, ...params );
  26009. }
  26010. } );
  26011. renderer.setRenderTarget( rtt );
  26012. renderer.toneMapping = NoToneMapping;
  26013. renderer.render( scene, light.shadow.camera );
  26014. renderer.setRenderTarget( currentRenderTarget );
  26015. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  26016. renderer.toneMapping = currentToneMapping;
  26017. scene.overrideMaterial = currentOverrideMaterial;
  26018. }
  26019. disposeShadow() {
  26020. this.rtt.dispose();
  26021. this.shadowNode = null;
  26022. this.shadowMaskNode = null;
  26023. this.rtt = null;
  26024. this.colorNode = this._defaultColorNode;
  26025. }
  26026. updateBefore( frame ) {
  26027. const { light } = this;
  26028. if ( light.castShadow ) this.updateShadow( frame );
  26029. }
  26030. update( /*frame*/ ) {
  26031. const { light } = this;
  26032. this.color.copy( light.color ).multiplyScalar( light.intensity );
  26033. }
  26034. }
  26035. addNodeClass( 'AnalyticLightNode', AnalyticLightNode );
  26036. const LightNodes = new WeakMap();
  26037. const sortLights = ( lights ) => {
  26038. return lights.sort( ( a, b ) => a.id - b.id );
  26039. };
  26040. class LightsNode extends Node {
  26041. constructor( lightNodes = [] ) {
  26042. super( 'vec3' );
  26043. this.totalDiffuseNode = vec3().temp( 'totalDiffuse' );
  26044. this.totalSpecularNode = vec3().temp( 'totalSpecular' );
  26045. this.outgoingLightNode = vec3().temp( 'outgoingLight' );
  26046. this.lightNodes = lightNodes;
  26047. this._hash = null;
  26048. }
  26049. get hasLight() {
  26050. return this.lightNodes.length > 0;
  26051. }
  26052. getHash() {
  26053. if ( this._hash === null ) {
  26054. const hash = [];
  26055. for ( const lightNode of this.lightNodes ) {
  26056. hash.push( lightNode.getHash() );
  26057. }
  26058. this._hash = 'lights-' + hash.join( ',' );
  26059. }
  26060. return this._hash;
  26061. }
  26062. analyze( builder ) {
  26063. const properties = builder.getDataFromNode( this );
  26064. for ( const node of properties.nodes ) {
  26065. node.build( builder );
  26066. }
  26067. }
  26068. setup( builder ) {
  26069. const context = builder.context;
  26070. const lightingModel = context.lightingModel;
  26071. let outgoingLightNode = this.outgoingLightNode;
  26072. if ( lightingModel ) {
  26073. const { lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  26074. context.outgoingLight = outgoingLightNode;
  26075. const stack = builder.addStack();
  26076. //
  26077. const properties = builder.getDataFromNode( this );
  26078. properties.nodes = stack.nodes;
  26079. //
  26080. lightingModel.start( context, stack, builder );
  26081. // lights
  26082. for ( const lightNode of lightNodes ) {
  26083. lightNode.build( builder );
  26084. }
  26085. //
  26086. lightingModel.indirectDiffuse( context, stack, builder );
  26087. lightingModel.indirectSpecular( context, stack, builder );
  26088. lightingModel.ambientOcclusion( context, stack, builder );
  26089. //
  26090. const { backdrop, backdropAlpha } = context;
  26091. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  26092. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  26093. if ( backdrop !== null ) {
  26094. if ( backdropAlpha !== null ) {
  26095. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  26096. } else {
  26097. totalDiffuse = vec3( backdrop );
  26098. }
  26099. context.material.transparent = true;
  26100. }
  26101. totalDiffuseNode.assign( totalDiffuse );
  26102. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  26103. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  26104. //
  26105. lightingModel.finish( context, stack, builder );
  26106. //
  26107. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  26108. }
  26109. return outgoingLightNode;
  26110. }
  26111. _getLightNodeById( id ) {
  26112. for ( const lightNode of this.lightNodes ) {
  26113. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  26114. return lightNode;
  26115. }
  26116. }
  26117. return null;
  26118. }
  26119. fromLights( lights = [] ) {
  26120. const lightNodes = [];
  26121. lights = sortLights( lights );
  26122. for ( const light of lights ) {
  26123. let lightNode = this._getLightNodeById( light.id );
  26124. if ( lightNode === null ) {
  26125. const lightClass = light.constructor;
  26126. const lightNodeClass = LightNodes.has( lightClass ) ? LightNodes.get( lightClass ) : AnalyticLightNode;
  26127. lightNode = nodeObject( new lightNodeClass( light ) );
  26128. }
  26129. lightNodes.push( lightNode );
  26130. }
  26131. this.lightNodes = lightNodes;
  26132. this._hash = null;
  26133. return this;
  26134. }
  26135. }
  26136. const lights = ( lights ) => nodeObject( new LightsNode().fromLights( lights ) );
  26137. const lightsNode = nodeProxy( LightsNode );
  26138. function addLightNode( lightClass, lightNodeClass ) {
  26139. if ( LightNodes.has( lightClass ) ) {
  26140. console.warn( `Redefinition of light node ${ lightNodeClass.type }` );
  26141. return;
  26142. }
  26143. if ( typeof lightClass !== 'function' ) throw new Error( `Light ${ lightClass.name } is not a class` );
  26144. if ( typeof lightNodeClass !== 'function' || ! lightNodeClass.type ) throw new Error( `Light node ${ lightNodeClass.type } is not a class` );
  26145. LightNodes.set( lightClass, lightNodeClass );
  26146. }
  26147. class AONode extends LightingNode {
  26148. constructor( aoNode = null ) {
  26149. super();
  26150. this.aoNode = aoNode;
  26151. }
  26152. setup( builder ) {
  26153. const aoIntensity = 1;
  26154. const aoNode = this.aoNode.x.sub( 1.0 ).mul( aoIntensity ).add( 1.0 );
  26155. builder.context.ambientOcclusion.mulAssign( aoNode );
  26156. }
  26157. }
  26158. addNodeClass( 'AONode', AONode );
  26159. class LightingContextNode extends ContextNode {
  26160. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  26161. super( node );
  26162. this.lightingModel = lightingModel;
  26163. this.backdropNode = backdropNode;
  26164. this.backdropAlphaNode = backdropAlphaNode;
  26165. this._context = null;
  26166. }
  26167. getContext() {
  26168. const { backdropNode, backdropAlphaNode } = this;
  26169. const directDiffuse = vec3().temp( 'directDiffuse' ),
  26170. directSpecular = vec3().temp( 'directSpecular' ),
  26171. indirectDiffuse = vec3().temp( 'indirectDiffuse' ),
  26172. indirectSpecular = vec3().temp( 'indirectSpecular' );
  26173. const reflectedLight = {
  26174. directDiffuse,
  26175. directSpecular,
  26176. indirectDiffuse,
  26177. indirectSpecular
  26178. };
  26179. const context = {
  26180. radiance: vec3().temp( 'radiance' ),
  26181. irradiance: vec3().temp( 'irradiance' ),
  26182. iblIrradiance: vec3().temp( 'iblIrradiance' ),
  26183. ambientOcclusion: float( 1 ).temp( 'ambientOcclusion' ),
  26184. reflectedLight,
  26185. backdrop: backdropNode,
  26186. backdropAlpha: backdropAlphaNode
  26187. };
  26188. return context;
  26189. }
  26190. setup( builder ) {
  26191. this.context = this._context || ( this._context = this.getContext() );
  26192. this.context.lightingModel = this.lightingModel || builder.context.lightingModel;
  26193. return super.setup( builder );
  26194. }
  26195. }
  26196. const lightingContext = nodeProxy( LightingContextNode );
  26197. addNodeElement( 'lightingContext', lightingContext );
  26198. addNodeClass( 'LightingContextNode', LightingContextNode );
  26199. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  26200. const bitangentGeometry = /*#__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  26201. const bitangentLocal = /*#__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  26202. const bitangentView = /*#__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  26203. const bitangentWorld = /*#__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  26204. const transformedBitangentView = /*#__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  26205. const transformedBitangentWorld = /*#__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  26206. const TBNViewMatrix = mat3( tangentView, bitangentView, normalView );
  26207. const parallaxDirection = positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  26208. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  26209. const transformedBentNormalView = ( () => {
  26210. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  26211. let bentNormal = anisotropyB.cross( positionViewDirection );
  26212. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  26213. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  26214. return bentNormal;
  26215. } )();
  26216. class CondNode extends Node {
  26217. constructor( condNode, ifNode, elseNode = null ) {
  26218. super();
  26219. this.condNode = condNode;
  26220. this.ifNode = ifNode;
  26221. this.elseNode = elseNode;
  26222. }
  26223. getNodeType( builder ) {
  26224. const ifType = this.ifNode.getNodeType( builder );
  26225. if ( this.elseNode !== null ) {
  26226. const elseType = this.elseNode.getNodeType( builder );
  26227. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  26228. return elseType;
  26229. }
  26230. }
  26231. return ifType;
  26232. }
  26233. setup( builder ) {
  26234. const properties = builder.getNodeProperties( this );
  26235. properties.condNode = this.condNode.cache();
  26236. properties.ifNode = this.ifNode.cache();
  26237. properties.elseNode = this.elseNode ? this.elseNode.cache() : null;
  26238. }
  26239. generate( builder, output ) {
  26240. const type = this.getNodeType( builder );
  26241. const nodeData = builder.getDataFromNode( this );
  26242. if ( nodeData.nodeProperty !== undefined ) {
  26243. return nodeData.nodeProperty;
  26244. }
  26245. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  26246. const needsOutput = output !== 'void';
  26247. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  26248. nodeData.nodeProperty = nodeProperty;
  26249. const nodeSnippet = condNode.build( builder, 'bool' );
  26250. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  26251. let ifSnippet = ifNode.build( builder, type );
  26252. if ( ifSnippet ) {
  26253. if ( needsOutput ) {
  26254. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  26255. } else {
  26256. ifSnippet = 'return ' + ifSnippet + ';';
  26257. }
  26258. }
  26259. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  26260. if ( elseNode !== null ) {
  26261. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  26262. let elseSnippet = elseNode.build( builder, type );
  26263. if ( elseSnippet ) {
  26264. if ( needsOutput ) {
  26265. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  26266. } else {
  26267. elseSnippet = 'return ' + elseSnippet + ';';
  26268. }
  26269. }
  26270. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  26271. } else {
  26272. builder.addFlowCode( '\n\n' );
  26273. }
  26274. return builder.format( nodeProperty, type, output );
  26275. }
  26276. }
  26277. const cond = nodeProxy( CondNode );
  26278. addNodeElement( 'cond', cond );
  26279. addNodeClass( 'CondNode', CondNode );
  26280. // These defines must match with PMREMGenerator
  26281. const cubeUV_r0 = float( 1.0 );
  26282. const cubeUV_m0 = float( - 2.0 );
  26283. const cubeUV_r1 = float( 0.8 );
  26284. const cubeUV_m1 = float( - 1.0 );
  26285. const cubeUV_r4 = float( 0.4 );
  26286. const cubeUV_m4 = float( 2.0 );
  26287. const cubeUV_r5 = float( 0.305 );
  26288. const cubeUV_m5 = float( 3.0 );
  26289. const cubeUV_r6 = float( 0.21 );
  26290. const cubeUV_m6 = float( 4.0 );
  26291. const cubeUV_minMipLevel = float( 4.0 );
  26292. const cubeUV_minTileSize = float( 16.0 );
  26293. // These shader functions convert between the UV coordinates of a single face of
  26294. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  26295. // sampling a textureCube (not generally normalized ).
  26296. const getFace = tslFn( ( [ direction ] ) => {
  26297. const absDirection = vec3( abs( direction ) ).toVar();
  26298. const face = float( - 1.0 ).toVar();
  26299. If( absDirection.x.greaterThan( absDirection.z ), () => {
  26300. If( absDirection.x.greaterThan( absDirection.y ), () => {
  26301. face.assign( cond( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  26302. } ).else( () => {
  26303. face.assign( cond( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  26304. } );
  26305. } ).else( () => {
  26306. If( absDirection.z.greaterThan( absDirection.y ), () => {
  26307. face.assign( cond( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  26308. } ).else( () => {
  26309. face.assign( cond( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  26310. } );
  26311. } );
  26312. return face;
  26313. } ).setLayout( {
  26314. name: 'getFace',
  26315. type: 'float',
  26316. inputs: [
  26317. { name: 'direction', type: 'vec3' }
  26318. ]
  26319. } );
  26320. // RH coordinate system; PMREM face-indexing convention
  26321. const getUV = tslFn( ( [ direction, face ] ) => {
  26322. const uv = vec2().toVar();
  26323. If( face.equal( 0.0 ), () => {
  26324. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  26325. } ).elseif( face.equal( 1.0 ), () => {
  26326. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  26327. } ).elseif( face.equal( 2.0 ), () => {
  26328. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  26329. } ).elseif( face.equal( 3.0 ), () => {
  26330. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  26331. } ).elseif( face.equal( 4.0 ), () => {
  26332. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  26333. } ).else( () => {
  26334. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  26335. } );
  26336. return mul( 0.5, uv.add( 1.0 ) );
  26337. } ).setLayout( {
  26338. name: 'getUV',
  26339. type: 'vec2',
  26340. inputs: [
  26341. { name: 'direction', type: 'vec3' },
  26342. { name: 'face', type: 'float' }
  26343. ]
  26344. } );
  26345. const roughnessToMip = tslFn( ( [ roughness ] ) => {
  26346. const mip = float( 0.0 ).toVar();
  26347. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  26348. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  26349. } ).elseif( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  26350. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  26351. } ).elseif( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  26352. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  26353. } ).elseif( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  26354. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  26355. } ).else( () => {
  26356. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  26357. } );
  26358. return mip;
  26359. } ).setLayout( {
  26360. name: 'roughnessToMip',
  26361. type: 'float',
  26362. inputs: [
  26363. { name: 'roughness', type: 'float' }
  26364. ]
  26365. } );
  26366. // RH coordinate system; PMREM face-indexing convention
  26367. const getDirection = tslFn( ( [ uv_immutable, face ] ) => {
  26368. const uv = uv_immutable.toVar();
  26369. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  26370. const direction = vec3( uv, 1.0 ).toVar();
  26371. If( face.equal( 0.0 ), () => {
  26372. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  26373. } ).elseif( face.equal( 1.0 ), () => {
  26374. direction.assign( direction.xzy );
  26375. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  26376. } ).elseif( face.equal( 2.0 ), () => {
  26377. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  26378. } ).elseif( face.equal( 3.0 ), () => {
  26379. direction.assign( direction.zyx );
  26380. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  26381. } ).elseif( face.equal( 4.0 ), () => {
  26382. direction.assign( direction.xzy );
  26383. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  26384. } ).elseif( face.equal( 5.0 ), () => {
  26385. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  26386. } );
  26387. return direction;
  26388. } ).setLayout( {
  26389. name: 'getDirection',
  26390. type: 'vec3',
  26391. inputs: [
  26392. { name: 'uv', type: 'vec2' },
  26393. { name: 'face', type: 'float' }
  26394. ]
  26395. } );
  26396. //
  26397. const textureCubeUV = tslFn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  26398. const roughness = float( roughness_immutable );
  26399. const sampleDir = vec3( sampleDir_immutable );
  26400. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  26401. const mipF = fract( mip );
  26402. const mipInt = floor( mip );
  26403. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  26404. If( mipF.notEqual( 0.0 ), () => {
  26405. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  26406. color0.assign( mix( color0, color1, mipF ) );
  26407. } );
  26408. return color0;
  26409. } );
  26410. const bilinearCubeUV = tslFn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  26411. const mipInt = float( mipInt_immutable ).toVar();
  26412. const direction = vec3( direction_immutable );
  26413. const face = float( getFace( direction ) ).toVar();
  26414. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  26415. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  26416. const faceSize = float( exp2( mipInt ) ).toVar();
  26417. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  26418. If( face.greaterThan( 2.0 ), () => {
  26419. uv.y.addAssign( faceSize );
  26420. face.subAssign( 3.0 );
  26421. } );
  26422. uv.x.addAssign( face.mul( faceSize ) );
  26423. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  26424. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  26425. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  26426. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  26427. return envMap.uv( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  26428. } );
  26429. const getSample = tslFn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  26430. const cosTheta = cos( theta );
  26431. // Rodrigues' axis-angle rotation
  26432. const sampleDirection = outputDirection.mul( cosTheta )
  26433. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  26434. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  26435. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  26436. } );
  26437. const blur = tslFn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  26438. const axis = vec3( cond( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  26439. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  26440. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  26441. } );
  26442. axis.assign( normalize( axis ) );
  26443. const gl_FragColor = vec3().toVar();
  26444. 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 } ) ) );
  26445. loop( { start: int( 1 ), end: n }, ( { i } ) => {
  26446. If( i.greaterThanEqual( samples ), () => {
  26447. Break();
  26448. } );
  26449. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  26450. 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 } ) ) );
  26451. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  26452. } );
  26453. return vec4( gl_FragColor, 1 );
  26454. } );
  26455. let _generator = null;
  26456. const _cache = new WeakMap();
  26457. function _generateCubeUVSize( imageHeight ) {
  26458. const maxMip = Math.log2( imageHeight ) - 2;
  26459. const texelHeight = 1.0 / imageHeight;
  26460. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  26461. return { texelWidth, texelHeight, maxMip };
  26462. }
  26463. function _getPMREMFromTexture( texture ) {
  26464. let cacheTexture = _cache.get( texture );
  26465. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  26466. if ( pmremVersion !== texture.pmremVersion ) {
  26467. if ( texture.isCubeTexture ) {
  26468. if ( texture.source.data.some( ( texture ) => texture === undefined ) ) {
  26469. throw new Error( 'PMREMNode: Undefined texture in CubeTexture. Use onLoad callback or async loader' );
  26470. }
  26471. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  26472. } else {
  26473. if ( texture.image === undefined ) {
  26474. throw new Error( 'PMREMNode: Undefined image in Texture. Use onLoad callback or async loader' );
  26475. }
  26476. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  26477. }
  26478. cacheTexture.pmremVersion = texture.pmremVersion;
  26479. _cache.set( texture, cacheTexture );
  26480. }
  26481. return cacheTexture.texture;
  26482. }
  26483. class PMREMNode extends TempNode {
  26484. constructor( value, uvNode = null, levelNode = null ) {
  26485. super( 'vec3' );
  26486. this._value = value;
  26487. this._pmrem = null;
  26488. this.uvNode = uvNode;
  26489. this.levelNode = levelNode;
  26490. this._generator = null;
  26491. this._texture = texture( null );
  26492. this._width = uniform( 0 );
  26493. this._height = uniform( 0 );
  26494. this._maxMip = uniform( 0 );
  26495. this.updateBeforeType = NodeUpdateType.RENDER;
  26496. }
  26497. set value( value ) {
  26498. this._value = value;
  26499. this._pmrem = null;
  26500. }
  26501. get value() {
  26502. return this._value;
  26503. }
  26504. updateFromTexture( texture ) {
  26505. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  26506. this._texture.value = texture;
  26507. this._width.value = cubeUVSize.texelWidth;
  26508. this._height.value = cubeUVSize.texelHeight;
  26509. this._maxMip.value = cubeUVSize.maxMip;
  26510. }
  26511. updateBefore() {
  26512. let pmrem = this._pmrem;
  26513. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  26514. const texture = this._value;
  26515. if ( pmremVersion !== texture.pmremVersion ) {
  26516. if ( texture.isPMREMTexture === true ) {
  26517. pmrem = texture;
  26518. } else {
  26519. pmrem = _getPMREMFromTexture( texture );
  26520. }
  26521. this._pmrem = pmrem;
  26522. this.updateFromTexture( pmrem );
  26523. }
  26524. }
  26525. setup( builder ) {
  26526. if ( _generator === null ) {
  26527. _generator = builder.createPMREMGenerator();
  26528. }
  26529. //
  26530. this.updateBefore( builder );
  26531. //
  26532. let uvNode = this.uvNode;
  26533. if ( uvNode === null && builder.context.getUV ) {
  26534. uvNode = builder.context.getUV( this );
  26535. }
  26536. //
  26537. const texture = this.value;
  26538. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  26539. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  26540. }
  26541. //
  26542. let levelNode = this.levelNode;
  26543. if ( levelNode === null && builder.context.getTextureLevel ) {
  26544. levelNode = builder.context.getTextureLevel( this );
  26545. }
  26546. //
  26547. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  26548. }
  26549. }
  26550. const pmremTexture = nodeProxy( PMREMNode );
  26551. addNodeClass( 'PMREMNode', PMREMNode );
  26552. const envNodeCache = new WeakMap();
  26553. class EnvironmentNode extends LightingNode {
  26554. constructor( envNode = null ) {
  26555. super();
  26556. this.envNode = envNode;
  26557. }
  26558. setup( builder ) {
  26559. let envNode = this.envNode;
  26560. if ( envNode.isTextureNode ) {
  26561. let cacheEnvNode = envNodeCache.get( envNode.value );
  26562. if ( cacheEnvNode === undefined ) {
  26563. cacheEnvNode = pmremTexture( envNode.value );
  26564. envNodeCache.set( envNode.value, cacheEnvNode );
  26565. }
  26566. envNode = cacheEnvNode;
  26567. }
  26568. //
  26569. const { material } = builder;
  26570. const envMap = material.envMap;
  26571. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  26572. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  26573. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  26574. const radiance = context( envNode, createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  26575. const irradiance = context( envNode, createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  26576. const isolateRadiance = cache( radiance );
  26577. const isolateIrradiance = cache( irradiance );
  26578. //
  26579. builder.context.radiance.addAssign( isolateRadiance );
  26580. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  26581. //
  26582. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  26583. if ( clearcoatRadiance ) {
  26584. const clearcoatRadianceContext = context( envNode, createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  26585. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  26586. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  26587. }
  26588. }
  26589. }
  26590. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  26591. let reflectVec = null;
  26592. return {
  26593. getUV: () => {
  26594. if ( reflectVec === null ) {
  26595. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  26596. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  26597. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  26598. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  26599. }
  26600. return reflectVec;
  26601. },
  26602. getTextureLevel: () => {
  26603. return roughnessNode;
  26604. }
  26605. };
  26606. };
  26607. const createIrradianceContext = ( normalWorldNode ) => {
  26608. return {
  26609. getUV: () => {
  26610. return normalWorldNode;
  26611. },
  26612. getTextureLevel: () => {
  26613. return float( 1.0 );
  26614. }
  26615. };
  26616. };
  26617. addNodeClass( 'EnvironmentNode', EnvironmentNode );
  26618. class IrradianceNode extends LightingNode {
  26619. constructor( node ) {
  26620. super();
  26621. this.node = node;
  26622. }
  26623. setup( builder ) {
  26624. builder.context.irradiance.addAssign( this.node );
  26625. }
  26626. }
  26627. addNodeClass( 'IrradianceNode', IrradianceNode );
  26628. let resolution, viewportResult;
  26629. class ViewportNode extends Node {
  26630. constructor( scope ) {
  26631. super();
  26632. this.scope = scope;
  26633. this.isViewportNode = true;
  26634. }
  26635. getNodeType() {
  26636. if ( this.scope === ViewportNode.VIEWPORT ) return 'vec4';
  26637. else if ( this.scope === ViewportNode.COORDINATE ) return 'vec3';
  26638. else return 'vec2';
  26639. }
  26640. getUpdateType() {
  26641. let updateType = NodeUpdateType.NONE;
  26642. if ( this.scope === ViewportNode.RESOLUTION || this.scope === ViewportNode.VIEWPORT ) {
  26643. updateType = NodeUpdateType.RENDER;
  26644. }
  26645. this.updateType = updateType;
  26646. return updateType;
  26647. }
  26648. update( { renderer } ) {
  26649. if ( this.scope === ViewportNode.VIEWPORT ) {
  26650. renderer.getViewport( viewportResult );
  26651. } else {
  26652. renderer.getDrawingBufferSize( resolution );
  26653. }
  26654. }
  26655. setup( /*builder*/ ) {
  26656. const scope = this.scope;
  26657. let output = null;
  26658. if ( scope === ViewportNode.RESOLUTION ) {
  26659. output = uniform( resolution || ( resolution = new Vector2() ) );
  26660. } else if ( scope === ViewportNode.VIEWPORT ) {
  26661. output = uniform( viewportResult || ( viewportResult = new Vector4() ) );
  26662. } else {
  26663. output = viewportCoordinate.div( viewportResolution );
  26664. let outX = output.x;
  26665. let outY = output.y;
  26666. if ( /bottom/i.test( scope ) ) outY = outY.oneMinus();
  26667. if ( /right/i.test( scope ) ) outX = outX.oneMinus();
  26668. output = vec2( outX, outY );
  26669. }
  26670. return output;
  26671. }
  26672. generate( builder ) {
  26673. if ( this.scope === ViewportNode.COORDINATE ) {
  26674. let coord = builder.getFragCoord();
  26675. if ( builder.isFlipY() ) {
  26676. // follow webgpu standards
  26677. const resolution = builder.getNodeProperties( viewportResolution ).outputNode.build( builder );
  26678. coord = `${ builder.getType( 'vec3' ) }( ${ coord }.x, ${ resolution }.y - ${ coord }.y, ${ coord }.z )`;
  26679. }
  26680. return coord;
  26681. }
  26682. return super.generate( builder );
  26683. }
  26684. }
  26685. ViewportNode.COORDINATE = 'coordinate';
  26686. ViewportNode.RESOLUTION = 'resolution';
  26687. ViewportNode.VIEWPORT = 'viewport';
  26688. ViewportNode.TOP_LEFT = 'topLeft';
  26689. ViewportNode.BOTTOM_LEFT = 'bottomLeft';
  26690. ViewportNode.TOP_RIGHT = 'topRight';
  26691. ViewportNode.BOTTOM_RIGHT = 'bottomRight';
  26692. const viewportCoordinate = nodeImmutable( ViewportNode, ViewportNode.COORDINATE );
  26693. const viewportResolution = nodeImmutable( ViewportNode, ViewportNode.RESOLUTION );
  26694. const viewport = nodeImmutable( ViewportNode, ViewportNode.VIEWPORT );
  26695. const viewportTopLeft = nodeImmutable( ViewportNode, ViewportNode.TOP_LEFT );
  26696. const viewportBottomLeft = nodeImmutable( ViewportNode, ViewportNode.BOTTOM_LEFT );
  26697. const viewportTopRight = nodeImmutable( ViewportNode, ViewportNode.TOP_RIGHT );
  26698. const viewportBottomRight = nodeImmutable( ViewportNode, ViewportNode.BOTTOM_RIGHT );
  26699. addNodeClass( 'ViewportNode', ViewportNode );
  26700. const _size$4 = new Vector2();
  26701. class ViewportTextureNode extends TextureNode {
  26702. constructor( uvNode = viewportTopLeft, levelNode = null, framebufferTexture = null ) {
  26703. if ( framebufferTexture === null ) {
  26704. framebufferTexture = new FramebufferTexture();
  26705. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  26706. }
  26707. super( framebufferTexture, uvNode, levelNode );
  26708. this.generateMipmaps = false;
  26709. this.isOutputTextureNode = true;
  26710. this.updateBeforeType = NodeUpdateType.FRAME;
  26711. }
  26712. updateBefore( frame ) {
  26713. const renderer = frame.renderer;
  26714. renderer.getDrawingBufferSize( _size$4 );
  26715. //
  26716. const framebufferTexture = this.value;
  26717. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  26718. framebufferTexture.image.width = _size$4.width;
  26719. framebufferTexture.image.height = _size$4.height;
  26720. framebufferTexture.needsUpdate = true;
  26721. }
  26722. //
  26723. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  26724. framebufferTexture.generateMipmaps = this.generateMipmaps;
  26725. renderer.copyFramebufferToTexture( framebufferTexture );
  26726. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  26727. }
  26728. clone() {
  26729. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  26730. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  26731. return viewportTextureNode;
  26732. }
  26733. }
  26734. const viewportTexture = nodeProxy( ViewportTextureNode );
  26735. const viewportMipTexture = nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  26736. addNodeElement( 'viewportTexture', viewportTexture );
  26737. addNodeElement( 'viewportMipTexture', viewportMipTexture );
  26738. addNodeClass( 'ViewportTextureNode', ViewportTextureNode );
  26739. let sharedDepthbuffer = null;
  26740. class ViewportDepthTextureNode extends ViewportTextureNode {
  26741. constructor( uvNode = viewportTopLeft, levelNode = null ) {
  26742. if ( sharedDepthbuffer === null ) {
  26743. sharedDepthbuffer = new DepthTexture();
  26744. }
  26745. super( uvNode, levelNode, sharedDepthbuffer );
  26746. }
  26747. }
  26748. const viewportDepthTexture = nodeProxy( ViewportDepthTextureNode );
  26749. addNodeElement( 'viewportDepthTexture', viewportDepthTexture );
  26750. addNodeClass( 'ViewportDepthTextureNode', ViewportDepthTextureNode );
  26751. class ViewportDepthNode extends Node {
  26752. constructor( scope, valueNode = null ) {
  26753. super( 'float' );
  26754. this.scope = scope;
  26755. this.valueNode = valueNode;
  26756. this.isViewportDepthNode = true;
  26757. }
  26758. generate( builder ) {
  26759. const { scope } = this;
  26760. if ( scope === ViewportDepthNode.DEPTH ) {
  26761. return builder.getFragDepth();
  26762. }
  26763. return super.generate( builder );
  26764. }
  26765. setup( { camera } ) {
  26766. const { scope } = this;
  26767. const texture = this.valueNode;
  26768. let node = null;
  26769. if ( scope === ViewportDepthNode.DEPTH ) {
  26770. if ( texture !== null ) {
  26771. node = depthBase().assign( texture );
  26772. } else {
  26773. if ( camera.isPerspectiveCamera ) {
  26774. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  26775. } else {
  26776. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26777. }
  26778. }
  26779. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  26780. if ( texture !== null ) {
  26781. if ( camera.isPerspectiveCamera ) {
  26782. const viewZ = perspectiveDepthToViewZ( texture, cameraNear, cameraFar );
  26783. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  26784. } else {
  26785. node = texture;
  26786. }
  26787. } else {
  26788. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26789. }
  26790. }
  26791. return node;
  26792. }
  26793. }
  26794. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  26795. // -near maps to 0; -far maps to 1
  26796. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  26797. // maps orthographic depth in [ 0, 1 ] to viewZ
  26798. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  26799. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  26800. // -near maps to 0; -far maps to 1
  26801. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  26802. // maps perspective depth in [ 0, 1 ] to viewZ
  26803. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  26804. ViewportDepthNode.DEPTH = 'depth';
  26805. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  26806. const depthBase = nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH );
  26807. const depth = nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  26808. const linearDepth = nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  26809. const viewportLinearDepth = linearDepth( viewportDepthTexture() );
  26810. depth.assign = ( value ) => depthBase( value );
  26811. addNodeClass( 'ViewportDepthNode', ViewportDepthNode );
  26812. class ClippingNode extends Node {
  26813. constructor( scope = ClippingNode.DEFAULT ) {
  26814. super();
  26815. this.scope = scope;
  26816. }
  26817. setup( builder ) {
  26818. super.setup( builder );
  26819. const clippingContext = builder.clippingContext;
  26820. const { localClipIntersection, localClippingCount, globalClippingCount } = clippingContext;
  26821. const numClippingPlanes = globalClippingCount + localClippingCount;
  26822. const numUnionClippingPlanes = localClipIntersection ? numClippingPlanes - localClippingCount : numClippingPlanes;
  26823. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  26824. return this.setupAlphaToCoverage( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26825. } else {
  26826. return this.setupDefault( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26827. }
  26828. }
  26829. setupAlphaToCoverage( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26830. return tslFn( () => {
  26831. const clippingPlanes = uniforms( planes );
  26832. const distanceToPlane = property( 'float', 'distanceToPlane' );
  26833. const distanceGradient = property( 'float', 'distanceToGradient' );
  26834. const clipOpacity = property( 'float', 'clipOpacity' );
  26835. clipOpacity.assign( 1 );
  26836. let plane;
  26837. loop( numUnionClippingPlanes, ( { i } ) => {
  26838. plane = clippingPlanes.element( i );
  26839. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26840. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26841. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  26842. clipOpacity.equal( 0.0 ).discard();
  26843. } );
  26844. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26845. const unionClipOpacity = property( 'float', 'unionclipOpacity' );
  26846. unionClipOpacity.assign( 1 );
  26847. loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26848. plane = clippingPlanes.element( i );
  26849. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26850. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26851. unionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  26852. } );
  26853. clipOpacity.mulAssign( unionClipOpacity.oneMinus() );
  26854. }
  26855. diffuseColor.a.mulAssign( clipOpacity );
  26856. diffuseColor.a.equal( 0.0 ).discard();
  26857. } )();
  26858. }
  26859. setupDefault( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26860. return tslFn( () => {
  26861. const clippingPlanes = uniforms( planes );
  26862. let plane;
  26863. loop( numUnionClippingPlanes, ( { i } ) => {
  26864. plane = clippingPlanes.element( i );
  26865. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  26866. } );
  26867. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26868. const clipped = property( 'bool', 'clipped' );
  26869. clipped.assign( true );
  26870. loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26871. plane = clippingPlanes.element( i );
  26872. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  26873. } );
  26874. clipped.discard();
  26875. }
  26876. } )();
  26877. }
  26878. }
  26879. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  26880. ClippingNode.DEFAULT = 'default';
  26881. const clipping = () => nodeObject( new ClippingNode() );
  26882. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  26883. class FrontFacingNode extends Node {
  26884. constructor() {
  26885. super( 'bool' );
  26886. this.isFrontFacingNode = true;
  26887. }
  26888. generate( builder ) {
  26889. const { renderer, material } = builder;
  26890. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  26891. if ( material.side === BackSide ) {
  26892. return 'false';
  26893. }
  26894. }
  26895. return builder.getFrontFacing();
  26896. }
  26897. }
  26898. const frontFacing = nodeImmutable( FrontFacingNode );
  26899. const faceDirection = float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  26900. addNodeClass( 'FrontFacingNode', FrontFacingNode );
  26901. const NodeMaterials = new Map();
  26902. class NodeMaterial extends Material {
  26903. constructor() {
  26904. super();
  26905. this.isNodeMaterial = true;
  26906. this.type = this.constructor.type;
  26907. this.forceSinglePass = false;
  26908. this.fog = true;
  26909. this.lights = true;
  26910. this.normals = true;
  26911. this.lightsNode = null;
  26912. this.envNode = null;
  26913. this.aoNode = null;
  26914. this.colorNode = null;
  26915. this.normalNode = null;
  26916. this.opacityNode = null;
  26917. this.backdropNode = null;
  26918. this.backdropAlphaNode = null;
  26919. this.alphaTestNode = null;
  26920. this.positionNode = null;
  26921. this.depthNode = null;
  26922. this.shadowNode = null;
  26923. this.shadowPositionNode = null;
  26924. this.outputNode = null;
  26925. this.fragmentNode = null;
  26926. this.vertexNode = null;
  26927. }
  26928. customProgramCacheKey() {
  26929. return this.type + getCacheKey( this );
  26930. }
  26931. build( builder ) {
  26932. this.setup( builder );
  26933. }
  26934. setup( builder ) {
  26935. // < VERTEX STAGE >
  26936. builder.addStack();
  26937. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  26938. builder.addFlow( 'vertex', builder.removeStack() );
  26939. // < FRAGMENT STAGE >
  26940. builder.addStack();
  26941. let resultNode;
  26942. const clippingNode = this.setupClipping( builder );
  26943. if ( this.depthWrite === true ) this.setupDepth( builder );
  26944. if ( this.fragmentNode === null ) {
  26945. if ( this.normals === true ) this.setupNormal( builder );
  26946. this.setupDiffuseColor( builder );
  26947. this.setupVariants( builder );
  26948. const outgoingLightNode = this.setupLighting( builder );
  26949. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  26950. // force unsigned floats - useful for RenderTargets
  26951. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  26952. resultNode = this.setupOutput( builder, basicOutput );
  26953. // OUTPUT NODE
  26954. output.assign( resultNode );
  26955. //
  26956. if ( this.outputNode !== null ) resultNode = this.outputNode;
  26957. } else {
  26958. let fragmentNode = this.fragmentNode;
  26959. if ( fragmentNode.isOutputStructNode !== true ) {
  26960. fragmentNode = vec4( fragmentNode );
  26961. }
  26962. resultNode = this.setupOutput( builder, fragmentNode );
  26963. }
  26964. builder.stack.outputNode = resultNode;
  26965. builder.addFlow( 'fragment', builder.removeStack() );
  26966. }
  26967. setupClipping( builder ) {
  26968. if ( builder.clippingContext === null ) return null;
  26969. const { globalClippingCount, localClippingCount } = builder.clippingContext;
  26970. let result = null;
  26971. if ( globalClippingCount || localClippingCount ) {
  26972. if ( this.alphaToCoverage ) {
  26973. // to be added to flow when the color/alpha value has been determined
  26974. result = clippingAlpha();
  26975. } else {
  26976. builder.stack.add( clipping() );
  26977. }
  26978. }
  26979. return result;
  26980. }
  26981. setupDepth( builder ) {
  26982. const { renderer } = builder;
  26983. // Depth
  26984. let depthNode = this.depthNode;
  26985. if ( depthNode === null && renderer.logarithmicDepthBuffer === true ) {
  26986. const fragDepth = modelViewProjection().w.add( 1 );
  26987. depthNode = fragDepth.log2().mul( cameraLogDepth ).mul( 0.5 );
  26988. }
  26989. if ( depthNode !== null ) {
  26990. depth.assign( depthNode ).append();
  26991. }
  26992. }
  26993. setupPosition( builder ) {
  26994. const { object } = builder;
  26995. const geometry = object.geometry;
  26996. builder.addStack();
  26997. // Vertex
  26998. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  26999. morphReference( object ).append();
  27000. }
  27001. if ( object.isSkinnedMesh === true ) {
  27002. skinningReference( object ).append();
  27003. }
  27004. if ( this.displacementMap ) {
  27005. const displacementMap = materialReference( 'displacementMap', 'texture' );
  27006. const displacementScale = materialReference( 'displacementScale', 'float' );
  27007. const displacementBias = materialReference( 'displacementBias', 'float' );
  27008. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  27009. }
  27010. if ( object.isBatchedMesh ) {
  27011. batch( object ).append();
  27012. }
  27013. if ( ( object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  27014. instance( object ).append();
  27015. }
  27016. if ( this.positionNode !== null ) {
  27017. positionLocal.assign( this.positionNode );
  27018. }
  27019. const mvp = modelViewProjection();
  27020. builder.context.vertex = builder.removeStack();
  27021. builder.context.mvp = mvp;
  27022. return mvp;
  27023. }
  27024. setupDiffuseColor( { object, geometry } ) {
  27025. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  27026. // VERTEX COLORS
  27027. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  27028. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  27029. }
  27030. // Instanced colors
  27031. if ( object.instanceColor ) {
  27032. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  27033. colorNode = instanceColor.mul( colorNode );
  27034. }
  27035. // COLOR
  27036. diffuseColor.assign( colorNode );
  27037. // OPACITY
  27038. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  27039. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  27040. // ALPHA TEST
  27041. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  27042. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  27043. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  27044. }
  27045. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  27046. diffuseColor.a.assign( 1.0 );
  27047. }
  27048. }
  27049. setupVariants( /*builder*/ ) {
  27050. // Interface function.
  27051. }
  27052. setupNormal() {
  27053. // NORMAL VIEW
  27054. if ( this.flatShading === true ) {
  27055. const normalNode = positionView.dFdx().cross( positionView.dFdy() ).normalize();
  27056. transformedNormalView.assign( normalNode.mul( faceDirection ) );
  27057. } else {
  27058. const normalNode = this.normalNode ? vec3( this.normalNode ) : materialNormal;
  27059. transformedNormalView.assign( normalNode.mul( faceDirection ) );
  27060. }
  27061. }
  27062. getEnvNode( builder ) {
  27063. let node = null;
  27064. if ( this.envNode ) {
  27065. node = this.envNode;
  27066. } else if ( this.envMap ) {
  27067. node = this.envMap.isCubeTexture ? cubeTexture( this.envMap ) : texture( this.envMap );
  27068. } else if ( builder.environmentNode ) {
  27069. node = builder.environmentNode;
  27070. }
  27071. return node;
  27072. }
  27073. setupLights( builder ) {
  27074. const envNode = this.getEnvNode( builder );
  27075. //
  27076. const materialLightsNode = [];
  27077. if ( envNode ) {
  27078. materialLightsNode.push( new EnvironmentNode( envNode ) );
  27079. }
  27080. if ( builder.material.lightMap ) {
  27081. materialLightsNode.push( new IrradianceNode( materialReference( 'lightMap', 'texture' ) ) );
  27082. }
  27083. if ( this.aoNode !== null || builder.material.aoMap ) {
  27084. const aoNode = this.aoNode !== null ? this.aoNode : texture( builder.material.aoMap );
  27085. materialLightsNode.push( new AONode( aoNode ) );
  27086. }
  27087. let lightsN = this.lightsNode || builder.lightsNode;
  27088. if ( materialLightsNode.length > 0 ) {
  27089. lightsN = lightsNode( [ ...lightsN.lightNodes, ...materialLightsNode ] );
  27090. }
  27091. return lightsN;
  27092. }
  27093. setupLightingModel( /*builder*/ ) {
  27094. // Interface function.
  27095. }
  27096. setupLighting( builder ) {
  27097. const { material } = builder;
  27098. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  27099. // OUTGOING LIGHT
  27100. const lights = this.lights === true || this.lightsNode !== null;
  27101. const lightsNode = lights ? this.setupLights( builder ) : null;
  27102. let outgoingLightNode = diffuseColor.rgb;
  27103. if ( lightsNode && lightsNode.hasLight !== false ) {
  27104. const lightingModel = this.setupLightingModel( builder );
  27105. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  27106. } else if ( backdropNode !== null ) {
  27107. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  27108. }
  27109. // EMISSIVE
  27110. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  27111. outgoingLightNode = outgoingLightNode.add( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  27112. }
  27113. return outgoingLightNode;
  27114. }
  27115. setupOutput( builder, outputNode ) {
  27116. // FOG
  27117. if ( this.fog === true ) {
  27118. const fogNode = builder.fogNode;
  27119. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  27120. }
  27121. return outputNode;
  27122. }
  27123. setDefaultValues( material ) {
  27124. // This approach is to reuse the native refreshUniforms*
  27125. // and turn available the use of features like transmission and environment in core
  27126. for ( const property in material ) {
  27127. const value = material[ property ];
  27128. if ( this[ property ] === undefined ) {
  27129. this[ property ] = value;
  27130. if ( value && value.clone ) this[ property ] = value.clone();
  27131. }
  27132. }
  27133. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  27134. for ( const key in descriptors ) {
  27135. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  27136. descriptors[ key ].get !== undefined ) {
  27137. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  27138. }
  27139. }
  27140. }
  27141. toJSON( meta ) {
  27142. const isRoot = ( meta === undefined || typeof meta === 'string' );
  27143. if ( isRoot ) {
  27144. meta = {
  27145. textures: {},
  27146. images: {},
  27147. nodes: {}
  27148. };
  27149. }
  27150. const data = Material.prototype.toJSON.call( this, meta );
  27151. const nodeChildren = getNodeChildren( this );
  27152. data.inputNodes = {};
  27153. for ( const { property, childNode } of nodeChildren ) {
  27154. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  27155. }
  27156. // TODO: Copied from Object3D.toJSON
  27157. function extractFromCache( cache ) {
  27158. const values = [];
  27159. for ( const key in cache ) {
  27160. const data = cache[ key ];
  27161. delete data.metadata;
  27162. values.push( data );
  27163. }
  27164. return values;
  27165. }
  27166. if ( isRoot ) {
  27167. const textures = extractFromCache( meta.textures );
  27168. const images = extractFromCache( meta.images );
  27169. const nodes = extractFromCache( meta.nodes );
  27170. if ( textures.length > 0 ) data.textures = textures;
  27171. if ( images.length > 0 ) data.images = images;
  27172. if ( nodes.length > 0 ) data.nodes = nodes;
  27173. }
  27174. return data;
  27175. }
  27176. copy( source ) {
  27177. this.lightsNode = source.lightsNode;
  27178. this.envNode = source.envNode;
  27179. this.colorNode = source.colorNode;
  27180. this.normalNode = source.normalNode;
  27181. this.opacityNode = source.opacityNode;
  27182. this.backdropNode = source.backdropNode;
  27183. this.backdropAlphaNode = source.backdropAlphaNode;
  27184. this.alphaTestNode = source.alphaTestNode;
  27185. this.positionNode = source.positionNode;
  27186. this.depthNode = source.depthNode;
  27187. this.shadowNode = source.shadowNode;
  27188. this.shadowPositionNode = source.shadowPositionNode;
  27189. this.outputNode = source.outputNode;
  27190. this.fragmentNode = source.fragmentNode;
  27191. this.vertexNode = source.vertexNode;
  27192. return super.copy( source );
  27193. }
  27194. static fromMaterial( material ) {
  27195. if ( material.isNodeMaterial === true ) { // is already a node material
  27196. return material;
  27197. }
  27198. const type = material.type.replace( 'Material', 'NodeMaterial' );
  27199. const nodeMaterial = createNodeMaterialFromType( type );
  27200. if ( nodeMaterial === undefined ) {
  27201. throw new Error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  27202. }
  27203. for ( const key in material ) {
  27204. nodeMaterial[ key ] = material[ key ];
  27205. }
  27206. return nodeMaterial;
  27207. }
  27208. }
  27209. function addNodeMaterial( type, nodeMaterial ) {
  27210. if ( typeof nodeMaterial !== 'function' || ! type ) throw new Error( `Node material ${ type } is not a class` );
  27211. if ( NodeMaterials.has( type ) ) {
  27212. console.warn( `Redefinition of node material ${ type }` );
  27213. return;
  27214. }
  27215. NodeMaterials.set( type, nodeMaterial );
  27216. nodeMaterial.type = type;
  27217. }
  27218. function createNodeMaterialFromType( type ) {
  27219. const Material = NodeMaterials.get( type );
  27220. if ( Material !== undefined ) {
  27221. return new Material();
  27222. }
  27223. }
  27224. addNodeMaterial( 'NodeMaterial', NodeMaterial );
  27225. class Uniform {
  27226. constructor( name, value ) {
  27227. this.name = name;
  27228. this.value = value;
  27229. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  27230. this.itemSize = 0;
  27231. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  27232. }
  27233. setValue( value ) {
  27234. this.value = value;
  27235. }
  27236. getValue() {
  27237. return this.value;
  27238. }
  27239. }
  27240. class NumberUniform extends Uniform {
  27241. constructor( name, value = 0 ) {
  27242. super( name, value );
  27243. this.isNumberUniform = true;
  27244. this.boundary = 4;
  27245. this.itemSize = 1;
  27246. }
  27247. }
  27248. class Vector2Uniform extends Uniform {
  27249. constructor( name, value = new Vector2() ) {
  27250. super( name, value );
  27251. this.isVector2Uniform = true;
  27252. this.boundary = 8;
  27253. this.itemSize = 2;
  27254. }
  27255. }
  27256. class Vector3Uniform extends Uniform {
  27257. constructor( name, value = new Vector3() ) {
  27258. super( name, value );
  27259. this.isVector3Uniform = true;
  27260. this.boundary = 16;
  27261. this.itemSize = 3;
  27262. }
  27263. }
  27264. class Vector4Uniform extends Uniform {
  27265. constructor( name, value = new Vector4() ) {
  27266. super( name, value );
  27267. this.isVector4Uniform = true;
  27268. this.boundary = 16;
  27269. this.itemSize = 4;
  27270. }
  27271. }
  27272. class ColorUniform extends Uniform {
  27273. constructor( name, value = new Color() ) {
  27274. super( name, value );
  27275. this.isColorUniform = true;
  27276. this.boundary = 16;
  27277. this.itemSize = 3;
  27278. }
  27279. }
  27280. class Matrix3Uniform extends Uniform {
  27281. constructor( name, value = new Matrix3() ) {
  27282. super( name, value );
  27283. this.isMatrix3Uniform = true;
  27284. this.boundary = 48;
  27285. this.itemSize = 12;
  27286. }
  27287. }
  27288. class Matrix4Uniform extends Uniform {
  27289. constructor( name, value = new Matrix4() ) {
  27290. super( name, value );
  27291. this.isMatrix4Uniform = true;
  27292. this.boundary = 64;
  27293. this.itemSize = 16;
  27294. }
  27295. }
  27296. class NumberNodeUniform extends NumberUniform {
  27297. constructor( nodeUniform ) {
  27298. super( nodeUniform.name, nodeUniform.value );
  27299. this.nodeUniform = nodeUniform;
  27300. }
  27301. getValue() {
  27302. return this.nodeUniform.value;
  27303. }
  27304. }
  27305. class Vector2NodeUniform extends Vector2Uniform {
  27306. constructor( nodeUniform ) {
  27307. super( nodeUniform.name, nodeUniform.value );
  27308. this.nodeUniform = nodeUniform;
  27309. }
  27310. getValue() {
  27311. return this.nodeUniform.value;
  27312. }
  27313. }
  27314. class Vector3NodeUniform extends Vector3Uniform {
  27315. constructor( nodeUniform ) {
  27316. super( nodeUniform.name, nodeUniform.value );
  27317. this.nodeUniform = nodeUniform;
  27318. }
  27319. getValue() {
  27320. return this.nodeUniform.value;
  27321. }
  27322. }
  27323. class Vector4NodeUniform extends Vector4Uniform {
  27324. constructor( nodeUniform ) {
  27325. super( nodeUniform.name, nodeUniform.value );
  27326. this.nodeUniform = nodeUniform;
  27327. }
  27328. getValue() {
  27329. return this.nodeUniform.value;
  27330. }
  27331. }
  27332. class ColorNodeUniform extends ColorUniform {
  27333. constructor( nodeUniform ) {
  27334. super( nodeUniform.name, nodeUniform.value );
  27335. this.nodeUniform = nodeUniform;
  27336. }
  27337. getValue() {
  27338. return this.nodeUniform.value;
  27339. }
  27340. }
  27341. class Matrix3NodeUniform extends Matrix3Uniform {
  27342. constructor( nodeUniform ) {
  27343. super( nodeUniform.name, nodeUniform.value );
  27344. this.nodeUniform = nodeUniform;
  27345. }
  27346. getValue() {
  27347. return this.nodeUniform.value;
  27348. }
  27349. }
  27350. class Matrix4NodeUniform extends Matrix4Uniform {
  27351. constructor( nodeUniform ) {
  27352. super( nodeUniform.name, nodeUniform.value );
  27353. this.nodeUniform = nodeUniform;
  27354. }
  27355. getValue() {
  27356. return this.nodeUniform.value;
  27357. }
  27358. }
  27359. class StackNode extends Node {
  27360. constructor( parent = null ) {
  27361. super();
  27362. this.nodes = [];
  27363. this.outputNode = null;
  27364. this.parent = parent;
  27365. this._currentCond = null;
  27366. this.isStackNode = true;
  27367. }
  27368. getNodeType( builder ) {
  27369. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  27370. }
  27371. add( node ) {
  27372. this.nodes.push( node );
  27373. return this;
  27374. }
  27375. if( boolNode, method ) {
  27376. const methodNode = new ShaderNode( method );
  27377. this._currentCond = cond( boolNode, methodNode );
  27378. return this.add( this._currentCond );
  27379. }
  27380. elseif( boolNode, method ) {
  27381. const methodNode = new ShaderNode( method );
  27382. const ifNode = cond( boolNode, methodNode );
  27383. this._currentCond.elseNode = ifNode;
  27384. this._currentCond = ifNode;
  27385. return this;
  27386. }
  27387. else( method ) {
  27388. this._currentCond.elseNode = new ShaderNode( method );
  27389. return this;
  27390. }
  27391. build( builder, ...params ) {
  27392. const previousStack = getCurrentStack();
  27393. setCurrentStack( this );
  27394. for ( const node of this.nodes ) {
  27395. node.build( builder, 'void' );
  27396. }
  27397. setCurrentStack( previousStack );
  27398. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  27399. }
  27400. }
  27401. const stack = nodeProxy( StackNode );
  27402. addNodeClass( 'StackNode', StackNode );
  27403. class EquirectUVNode extends TempNode {
  27404. constructor( dirNode = positionWorldDirection ) {
  27405. super( 'vec2' );
  27406. this.dirNode = dirNode;
  27407. }
  27408. setup() {
  27409. const dir = this.dirNode;
  27410. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  27411. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  27412. return vec2( u, v );
  27413. }
  27414. }
  27415. const equirectUV = nodeProxy( EquirectUVNode );
  27416. addNodeClass( 'EquirectUVNode', EquirectUVNode );
  27417. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  27418. class CubeRenderTarget extends WebGLCubeRenderTarget {
  27419. constructor( size = 1, options = {} ) {
  27420. super( size, options );
  27421. this.isCubeRenderTarget = true;
  27422. }
  27423. fromEquirectangularTexture( renderer, texture$1 ) {
  27424. const currentMinFilter = texture$1.minFilter;
  27425. const currentGenerateMipmaps = texture$1.generateMipmaps;
  27426. texture$1.generateMipmaps = true;
  27427. this.texture.type = texture$1.type;
  27428. this.texture.colorSpace = texture$1.colorSpace;
  27429. this.texture.generateMipmaps = texture$1.generateMipmaps;
  27430. this.texture.minFilter = texture$1.minFilter;
  27431. this.texture.magFilter = texture$1.magFilter;
  27432. const geometry = new BoxGeometry( 5, 5, 5 );
  27433. const uvNode = equirectUV( positionWorldDirection );
  27434. const material = createNodeMaterialFromType( 'MeshBasicNodeMaterial' );
  27435. material.colorNode = texture( texture$1, uvNode, 0 );
  27436. material.side = BackSide;
  27437. material.blending = NoBlending;
  27438. const mesh = new Mesh( geometry, material );
  27439. const scene = new Scene();
  27440. scene.add( mesh );
  27441. // Avoid blurred poles
  27442. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  27443. const camera = new CubeCamera( 1, 10, this );
  27444. camera.update( renderer, scene );
  27445. texture$1.minFilter = currentMinFilter;
  27446. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  27447. mesh.geometry.dispose();
  27448. mesh.material.dispose();
  27449. return this;
  27450. }
  27451. }
  27452. const LOD_MIN = 4;
  27453. // The standard deviations (radians) associated with the extra mips. These are
  27454. // chosen to approximate a Trowbridge-Reitz distribution function times the
  27455. // geometric shadowing function. These sigma values squared must match the
  27456. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  27457. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  27458. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  27459. // samples and exit early, but not recompile the shader.
  27460. const MAX_SAMPLES = 20;
  27461. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  27462. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  27463. const _clearColor$1 = /*@__PURE__*/ new Color();
  27464. let _oldTarget = null;
  27465. let _oldActiveCubeFace = 0;
  27466. let _oldActiveMipmapLevel = 0;
  27467. // Golden Ratio
  27468. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  27469. const INV_PHI = 1 / PHI;
  27470. // Vertices of a dodecahedron (except the opposites, which represent the
  27471. // same axis), used as axis directions evenly spread on a sphere.
  27472. const _axisDirections = [
  27473. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  27474. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  27475. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  27476. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  27477. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  27478. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  27479. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  27480. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  27481. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  27482. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  27483. ];
  27484. //
  27485. // WebGPU Face indices
  27486. const _faceLib = [
  27487. 3, 1, 5,
  27488. 0, 4, 2
  27489. ];
  27490. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  27491. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  27492. /**
  27493. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  27494. * (PMREM) from a cubeMap environment texture. This allows different levels of
  27495. * blur to be quickly accessed based on material roughness. It is packed into a
  27496. * special CubeUV format that allows us to perform custom interpolation so that
  27497. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  27498. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  27499. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  27500. * higher roughness levels. In this way we maintain resolution to smoothly
  27501. * interpolate diffuse lighting while limiting sampling computation.
  27502. *
  27503. * Paper: Fast, Accurate Image-Based Lighting
  27504. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  27505. */
  27506. class PMREMGenerator {
  27507. constructor( renderer ) {
  27508. this._renderer = renderer;
  27509. this._pingPongRenderTarget = null;
  27510. this._lodMax = 0;
  27511. this._cubeSize = 0;
  27512. this._lodPlanes = [];
  27513. this._sizeLods = [];
  27514. this._sigmas = [];
  27515. this._lodMeshes = [];
  27516. this._blurMaterial = null;
  27517. this._cubemapMaterial = null;
  27518. this._equirectMaterial = null;
  27519. this._backgroundBox = null;
  27520. }
  27521. /**
  27522. * Generates a PMREM from a supplied Scene, which can be faster than using an
  27523. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  27524. * in radians to be applied to the scene before PMREM generation. Optional near
  27525. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  27526. * is placed at the origin).
  27527. */
  27528. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  27529. _oldTarget = this._renderer.getRenderTarget();
  27530. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  27531. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  27532. this._setSize( 256 );
  27533. const cubeUVRenderTarget = this._allocateTargets();
  27534. cubeUVRenderTarget.depthBuffer = true;
  27535. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  27536. if ( sigma > 0 ) {
  27537. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  27538. }
  27539. this._applyPMREM( cubeUVRenderTarget );
  27540. this._cleanup( cubeUVRenderTarget );
  27541. return cubeUVRenderTarget;
  27542. }
  27543. /**
  27544. * Generates a PMREM from an equirectangular texture, which can be either LDR
  27545. * or HDR. The ideal input image size is 1k (1024 x 512),
  27546. * as this matches best with the 256 x 256 cubemap output.
  27547. */
  27548. fromEquirectangular( equirectangular, renderTarget = null ) {
  27549. return this._fromTexture( equirectangular, renderTarget );
  27550. }
  27551. /**
  27552. * Generates a PMREM from an cubemap texture, which can be either LDR
  27553. * or HDR. The ideal input cube size is 256 x 256,
  27554. * as this matches best with the 256 x 256 cubemap output.
  27555. */
  27556. fromCubemap( cubemap, renderTarget = null ) {
  27557. return this._fromTexture( cubemap, renderTarget );
  27558. }
  27559. /**
  27560. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  27561. * your texture's network fetch for increased concurrency.
  27562. */
  27563. compileCubemapShader() {
  27564. if ( this._cubemapMaterial === null ) {
  27565. this._cubemapMaterial = _getCubemapMaterial();
  27566. this._compileMaterial( this._cubemapMaterial );
  27567. }
  27568. }
  27569. /**
  27570. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  27571. * your texture's network fetch for increased concurrency.
  27572. */
  27573. compileEquirectangularShader() {
  27574. if ( this._equirectMaterial === null ) {
  27575. this._equirectMaterial = _getEquirectMaterial();
  27576. this._compileMaterial( this._equirectMaterial );
  27577. }
  27578. }
  27579. /**
  27580. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  27581. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  27582. * one of them will cause any others to also become unusable.
  27583. */
  27584. dispose() {
  27585. this._dispose();
  27586. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  27587. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  27588. if ( this._backgroundBox !== null ) {
  27589. this._backgroundBox.geometry.dispose();
  27590. this._backgroundBox.material.dispose();
  27591. }
  27592. }
  27593. // private interface
  27594. _setSize( cubeSize ) {
  27595. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  27596. this._cubeSize = Math.pow( 2, this._lodMax );
  27597. }
  27598. _dispose() {
  27599. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  27600. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  27601. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  27602. this._lodPlanes[ i ].dispose();
  27603. }
  27604. }
  27605. _cleanup( outputTarget ) {
  27606. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  27607. outputTarget.scissorTest = false;
  27608. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  27609. }
  27610. _fromTexture( texture, renderTarget ) {
  27611. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  27612. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  27613. } else { // Equirectangular
  27614. this._setSize( texture.image.width / 4 );
  27615. }
  27616. _oldTarget = this._renderer.getRenderTarget();
  27617. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  27618. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  27619. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  27620. this._textureToCubeUV( texture, cubeUVRenderTarget );
  27621. this._applyPMREM( cubeUVRenderTarget );
  27622. this._cleanup( cubeUVRenderTarget );
  27623. return cubeUVRenderTarget;
  27624. }
  27625. _allocateTargets() {
  27626. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  27627. const height = 4 * this._cubeSize;
  27628. const params = {
  27629. magFilter: LinearFilter,
  27630. minFilter: LinearFilter,
  27631. generateMipmaps: false,
  27632. type: HalfFloatType,
  27633. format: RGBAFormat,
  27634. colorSpace: LinearSRGBColorSpace,
  27635. //depthBuffer: false
  27636. };
  27637. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  27638. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  27639. if ( this._pingPongRenderTarget !== null ) {
  27640. this._dispose();
  27641. }
  27642. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  27643. const { _lodMax } = this;
  27644. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  27645. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  27646. }
  27647. return cubeUVRenderTarget;
  27648. }
  27649. _compileMaterial( material ) {
  27650. const tmpMesh = this._lodMeshes[ 0 ];
  27651. tmpMesh.material = material;
  27652. this._renderer.compile( tmpMesh, _flatCamera );
  27653. }
  27654. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  27655. const cubeCamera = _cubeCamera;
  27656. cubeCamera.near = near;
  27657. cubeCamera.far = far;
  27658. // px, py, pz, nx, ny, nz
  27659. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  27660. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  27661. const renderer = this._renderer;
  27662. const originalAutoClear = renderer.autoClear;
  27663. renderer.getClearColor( _clearColor$1 );
  27664. renderer.autoClear = false;
  27665. let backgroundBox = this._backgroundBox;
  27666. if ( backgroundBox === null ) {
  27667. const backgroundMaterial = new MeshBasicMaterial( {
  27668. name: 'PMREM.Background',
  27669. side: BackSide,
  27670. depthWrite: false,
  27671. depthTest: false
  27672. } );
  27673. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  27674. }
  27675. let useSolidColor = false;
  27676. const background = scene.background;
  27677. if ( background ) {
  27678. if ( background.isColor ) {
  27679. backgroundBox.material.color.copy( background );
  27680. scene.background = null;
  27681. useSolidColor = true;
  27682. }
  27683. } else {
  27684. backgroundBox.material.color.copy( _clearColor$1 );
  27685. useSolidColor = true;
  27686. }
  27687. renderer.setRenderTarget( cubeUVRenderTarget );
  27688. renderer.clear();
  27689. if ( useSolidColor ) {
  27690. renderer.render( backgroundBox, cubeCamera );
  27691. }
  27692. for ( let i = 0; i < 6; i ++ ) {
  27693. const col = i % 3;
  27694. if ( col === 0 ) {
  27695. cubeCamera.up.set( 0, upSign[ i ], 0 );
  27696. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  27697. } else if ( col === 1 ) {
  27698. cubeCamera.up.set( 0, 0, upSign[ i ] );
  27699. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  27700. } else {
  27701. cubeCamera.up.set( 0, upSign[ i ], 0 );
  27702. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  27703. }
  27704. const size = this._cubeSize;
  27705. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  27706. renderer.render( scene, cubeCamera );
  27707. }
  27708. renderer.autoClear = originalAutoClear;
  27709. scene.background = background;
  27710. }
  27711. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  27712. const renderer = this._renderer;
  27713. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  27714. if ( isCubeTexture ) {
  27715. if ( this._cubemapMaterial === null ) {
  27716. this._cubemapMaterial = _getCubemapMaterial( texture );
  27717. }
  27718. } else {
  27719. if ( this._equirectMaterial === null ) {
  27720. this._equirectMaterial = _getEquirectMaterial( texture );
  27721. }
  27722. }
  27723. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  27724. material.fragmentNode.value = texture;
  27725. const mesh = this._lodMeshes[ 0 ];
  27726. mesh.material = material;
  27727. const size = this._cubeSize;
  27728. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  27729. renderer.setRenderTarget( cubeUVRenderTarget );
  27730. renderer.render( mesh, _flatCamera );
  27731. }
  27732. _applyPMREM( cubeUVRenderTarget ) {
  27733. const renderer = this._renderer;
  27734. const autoClear = renderer.autoClear;
  27735. renderer.autoClear = false;
  27736. const n = this._lodPlanes.length;
  27737. for ( let i = 1; i < n; i ++ ) {
  27738. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  27739. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  27740. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  27741. }
  27742. renderer.autoClear = autoClear;
  27743. }
  27744. /**
  27745. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  27746. * vertically and horizontally, but this breaks down on a cube. Here we apply
  27747. * the blur latitudinally (around the poles), and then longitudinally (towards
  27748. * the poles) to approximate the orthogonally-separable blur. It is least
  27749. * accurate at the poles, but still does a decent job.
  27750. */
  27751. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  27752. const pingPongRenderTarget = this._pingPongRenderTarget;
  27753. this._halfBlur(
  27754. cubeUVRenderTarget,
  27755. pingPongRenderTarget,
  27756. lodIn,
  27757. lodOut,
  27758. sigma,
  27759. 'latitudinal',
  27760. poleAxis );
  27761. this._halfBlur(
  27762. pingPongRenderTarget,
  27763. cubeUVRenderTarget,
  27764. lodOut,
  27765. lodOut,
  27766. sigma,
  27767. 'longitudinal',
  27768. poleAxis );
  27769. }
  27770. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  27771. const renderer = this._renderer;
  27772. const blurMaterial = this._blurMaterial;
  27773. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  27774. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  27775. }
  27776. // Number of standard deviations at which to cut off the discrete approximation.
  27777. const STANDARD_DEVIATIONS = 3;
  27778. const blurMesh = this._lodMeshes[ lodOut ];
  27779. blurMesh.material = blurMaterial;
  27780. const blurUniforms = blurMaterial.uniforms;
  27781. const pixels = this._sizeLods[ lodIn ] - 1;
  27782. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  27783. const sigmaPixels = sigmaRadians / radiansPerPixel;
  27784. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  27785. if ( samples > MAX_SAMPLES ) {
  27786. console.warn( `sigmaRadians, ${
  27787. sigmaRadians}, is too large and will clip, as it requested ${
  27788. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  27789. }
  27790. const weights = [];
  27791. let sum = 0;
  27792. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  27793. const x = i / sigmaPixels;
  27794. const weight = Math.exp( - x * x / 2 );
  27795. weights.push( weight );
  27796. if ( i === 0 ) {
  27797. sum += weight;
  27798. } else if ( i < samples ) {
  27799. sum += 2 * weight;
  27800. }
  27801. }
  27802. for ( let i = 0; i < weights.length; i ++ ) {
  27803. weights[ i ] = weights[ i ] / sum;
  27804. }
  27805. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  27806. blurUniforms.envMap.value = targetIn.texture;
  27807. blurUniforms.samples.value = samples;
  27808. blurUniforms.weights.array = weights;
  27809. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  27810. if ( poleAxis ) {
  27811. blurUniforms.poleAxis.value = poleAxis;
  27812. }
  27813. const { _lodMax } = this;
  27814. blurUniforms.dTheta.value = radiansPerPixel;
  27815. blurUniforms.mipInt.value = _lodMax - lodIn;
  27816. const outputSize = this._sizeLods[ lodOut ];
  27817. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  27818. const y = 4 * ( this._cubeSize - outputSize );
  27819. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  27820. renderer.setRenderTarget( targetOut );
  27821. renderer.render( blurMesh, _flatCamera );
  27822. }
  27823. }
  27824. function _createPlanes( lodMax ) {
  27825. const lodPlanes = [];
  27826. const sizeLods = [];
  27827. const sigmas = [];
  27828. const lodMeshes = [];
  27829. let lod = lodMax;
  27830. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  27831. for ( let i = 0; i < totalLods; i ++ ) {
  27832. const sizeLod = Math.pow( 2, lod );
  27833. sizeLods.push( sizeLod );
  27834. let sigma = 1.0 / sizeLod;
  27835. if ( i > lodMax - LOD_MIN ) {
  27836. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  27837. } else if ( i === 0 ) {
  27838. sigma = 0;
  27839. }
  27840. sigmas.push( sigma );
  27841. const texelSize = 1.0 / ( sizeLod - 2 );
  27842. const min = - texelSize;
  27843. const max = 1 + texelSize;
  27844. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  27845. const cubeFaces = 6;
  27846. const vertices = 6;
  27847. const positionSize = 3;
  27848. const uvSize = 2;
  27849. const faceIndexSize = 1;
  27850. const position = new Float32Array( positionSize * vertices * cubeFaces );
  27851. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  27852. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  27853. for ( let face = 0; face < cubeFaces; face ++ ) {
  27854. const x = ( face % 3 ) * 2 / 3 - 1;
  27855. const y = face > 2 ? 0 : - 1;
  27856. const coordinates = [
  27857. x, y, 0,
  27858. x + 2 / 3, y, 0,
  27859. x + 2 / 3, y + 1, 0,
  27860. x, y, 0,
  27861. x + 2 / 3, y + 1, 0,
  27862. x, y + 1, 0
  27863. ];
  27864. const faceIdx = _faceLib[ face ];
  27865. position.set( coordinates, positionSize * vertices * faceIdx );
  27866. uv.set( uv1, uvSize * vertices * faceIdx );
  27867. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  27868. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  27869. }
  27870. const planes = new BufferGeometry();
  27871. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  27872. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  27873. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  27874. lodPlanes.push( planes );
  27875. lodMeshes.push( new Mesh( planes, null ) );
  27876. if ( lod > LOD_MIN ) {
  27877. lod --;
  27878. }
  27879. }
  27880. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  27881. }
  27882. function _createRenderTarget( width, height, params ) {
  27883. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  27884. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  27885. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  27886. cubeUVRenderTarget.texture.isPMREMTexture = true;
  27887. cubeUVRenderTarget.scissorTest = true;
  27888. return cubeUVRenderTarget;
  27889. }
  27890. function _setViewport( target, x, y, width, height ) {
  27891. const viewY = target.height - height - y;
  27892. target.viewport.set( x, viewY, width, height );
  27893. target.scissor.set( x, viewY, width, height );
  27894. }
  27895. function _getMaterial() {
  27896. const material = new NodeMaterial();
  27897. material.depthTest = false;
  27898. material.depthWrite = false;
  27899. material.blending = NoBlending;
  27900. return material;
  27901. }
  27902. function _getBlurShader( lodMax, width, height ) {
  27903. const weights = uniforms( new Array( MAX_SAMPLES ).fill( 0 ) );
  27904. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  27905. const dTheta = uniform( 0 );
  27906. const n = float( MAX_SAMPLES );
  27907. const latitudinal = uniform( 0 ); // false, bool
  27908. const samples = uniform( 1 ); // int
  27909. const envMap = texture( null );
  27910. const mipInt = uniform( 0 ); // int
  27911. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  27912. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  27913. const CUBEUV_MAX_MIP = float( lodMax );
  27914. const materialUniforms = {
  27915. n,
  27916. latitudinal,
  27917. weights,
  27918. poleAxis,
  27919. outputDirection,
  27920. dTheta,
  27921. samples,
  27922. envMap,
  27923. mipInt,
  27924. CUBEUV_TEXEL_WIDTH,
  27925. CUBEUV_TEXEL_HEIGHT,
  27926. CUBEUV_MAX_MIP
  27927. };
  27928. const material = _getMaterial();
  27929. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  27930. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  27931. return material;
  27932. }
  27933. function _getCubemapMaterial( envTexture ) {
  27934. const material = _getMaterial();
  27935. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  27936. return material;
  27937. }
  27938. function _getEquirectMaterial( envTexture ) {
  27939. const material = _getMaterial();
  27940. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  27941. return material;
  27942. }
  27943. let _id$3 = 0;
  27944. class BindGroup {
  27945. constructor( name = '', bindings = [] ) {
  27946. this.name = name;
  27947. this.bindings = bindings;
  27948. this.id = _id$3 ++;
  27949. }
  27950. }
  27951. const rendererCache = new WeakMap();
  27952. const typeFromLength = new Map( [
  27953. [ 2, 'vec2' ],
  27954. [ 3, 'vec3' ],
  27955. [ 4, 'vec4' ],
  27956. [ 9, 'mat3' ],
  27957. [ 16, 'mat4' ]
  27958. ] );
  27959. const typeFromArray = new Map( [
  27960. [ Int8Array, 'int' ],
  27961. [ Int16Array, 'int' ],
  27962. [ Int32Array, 'int' ],
  27963. [ Uint8Array, 'uint' ],
  27964. [ Uint16Array, 'uint' ],
  27965. [ Uint32Array, 'uint' ],
  27966. [ Float32Array, 'float' ]
  27967. ] );
  27968. const toFloat = ( value ) => {
  27969. value = Number( value );
  27970. return value + ( value % 1 ? '' : '.0' );
  27971. };
  27972. class NodeBuilder {
  27973. constructor( object, renderer, parser ) {
  27974. this.object = object;
  27975. this.material = ( object && object.material ) || null;
  27976. this.geometry = ( object && object.geometry ) || null;
  27977. this.renderer = renderer;
  27978. this.parser = parser;
  27979. this.scene = null;
  27980. this.camera = null;
  27981. this.nodes = [];
  27982. this.updateNodes = [];
  27983. this.updateBeforeNodes = [];
  27984. this.updateAfterNodes = [];
  27985. this.hashNodes = {};
  27986. this.lightsNode = null;
  27987. this.environmentNode = null;
  27988. this.fogNode = null;
  27989. this.clippingContext = null;
  27990. this.vertexShader = null;
  27991. this.fragmentShader = null;
  27992. this.computeShader = null;
  27993. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  27994. this.flowCode = { vertex: '', fragment: '', compute: '' };
  27995. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  27996. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  27997. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  27998. this.bindingsIndexes = {};
  27999. this.bindGroups = null;
  28000. this.attributes = [];
  28001. this.bufferAttributes = [];
  28002. this.varyings = [];
  28003. this.codes = {};
  28004. this.vars = {};
  28005. this.flow = { code: '' };
  28006. this.chaining = [];
  28007. this.stack = stack();
  28008. this.stacks = [];
  28009. this.tab = '\t';
  28010. this.instanceBindGroups = true;
  28011. this.currentFunctionNode = null;
  28012. this.context = {
  28013. keywords: new NodeKeywords(),
  28014. material: this.material
  28015. };
  28016. this.cache = new NodeCache();
  28017. this.globalCache = this.cache;
  28018. this.flowsData = new WeakMap();
  28019. this.shaderStage = null;
  28020. this.buildStage = null;
  28021. }
  28022. getBingGroupsCache() {
  28023. let bindGroupsCache = rendererCache.get( this.renderer );
  28024. if ( bindGroupsCache === undefined ) {
  28025. bindGroupsCache = new ChainMap();
  28026. rendererCache.set( this.renderer, bindGroupsCache );
  28027. }
  28028. return bindGroupsCache;
  28029. }
  28030. createRenderTarget( width, height, options ) {
  28031. return new RenderTarget( width, height, options );
  28032. }
  28033. createCubeRenderTarget( size, options ) {
  28034. return new CubeRenderTarget( size, options );
  28035. }
  28036. createPMREMGenerator() {
  28037. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  28038. return new PMREMGenerator( this.renderer );
  28039. }
  28040. includes( node ) {
  28041. return this.nodes.includes( node );
  28042. }
  28043. _getBindGroup( groupName, bindings ) {
  28044. const bindGroupsCache = this.getBingGroupsCache();
  28045. // cache individual uniforms group
  28046. const bindingsArray = [];
  28047. let sharedGroup = true;
  28048. for ( const binding of bindings ) {
  28049. if ( binding.groupNode.shared === true ) {
  28050. // nodes is the chainmap key
  28051. const nodes = binding.getNodes();
  28052. let sharedBinding = bindGroupsCache.get( nodes );
  28053. if ( sharedBinding === undefined ) {
  28054. bindGroupsCache.set( nodes, binding );
  28055. sharedBinding = binding;
  28056. }
  28057. bindingsArray.push( sharedBinding );
  28058. } else {
  28059. bindingsArray.push( binding );
  28060. sharedGroup = false;
  28061. }
  28062. }
  28063. //
  28064. let bindGroup;
  28065. if ( sharedGroup ) {
  28066. bindGroup = bindGroupsCache.get( bindingsArray );
  28067. if ( bindGroup === undefined ) {
  28068. bindGroup = new BindGroup( groupName, bindingsArray );
  28069. bindGroupsCache.set( bindingsArray, bindGroup );
  28070. }
  28071. } else {
  28072. bindGroup = new BindGroup( groupName, bindingsArray );
  28073. }
  28074. return bindGroup;
  28075. }
  28076. getBindGroupArray( groupName, shaderStage ) {
  28077. const bindings = this.bindings[ shaderStage ];
  28078. let bindGroup = bindings[ groupName ];
  28079. if ( bindGroup === undefined ) {
  28080. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  28081. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  28082. }
  28083. bindings[ groupName ] = bindGroup = [];
  28084. }
  28085. return bindGroup;
  28086. }
  28087. getBindings() {
  28088. let bindingsGroups = this.bindGroups;
  28089. if ( bindingsGroups === null ) {
  28090. const groups = {};
  28091. const bindings = this.bindings;
  28092. for ( const shaderStage of shaderStages ) {
  28093. for ( const groupName in bindings[ shaderStage ] ) {
  28094. const uniforms = bindings[ shaderStage ][ groupName ];
  28095. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  28096. groupUniforms.push( ...uniforms );
  28097. }
  28098. }
  28099. bindingsGroups = [];
  28100. for ( const groupName in groups ) {
  28101. const group = groups[ groupName ];
  28102. const bindingsGroup = this._getBindGroup( groupName, group );
  28103. bindingsGroups.push( bindingsGroup );
  28104. }
  28105. this.bindGroups = bindingsGroups;
  28106. }
  28107. return bindingsGroups;
  28108. }
  28109. setHashNode( node, hash ) {
  28110. this.hashNodes[ hash ] = node;
  28111. }
  28112. addNode( node ) {
  28113. if ( this.nodes.includes( node ) === false ) {
  28114. this.nodes.push( node );
  28115. this.setHashNode( node, node.getHash( this ) );
  28116. }
  28117. }
  28118. buildUpdateNodes() {
  28119. for ( const node of this.nodes ) {
  28120. const updateType = node.getUpdateType();
  28121. const updateBeforeType = node.getUpdateBeforeType();
  28122. const updateAfterType = node.getUpdateAfterType();
  28123. if ( updateType !== NodeUpdateType.NONE ) {
  28124. this.updateNodes.push( node.getSelf() );
  28125. }
  28126. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  28127. this.updateBeforeNodes.push( node );
  28128. }
  28129. if ( updateAfterType !== NodeUpdateType.NONE ) {
  28130. this.updateAfterNodes.push( node );
  28131. }
  28132. }
  28133. }
  28134. get currentNode() {
  28135. return this.chaining[ this.chaining.length - 1 ];
  28136. }
  28137. isFilteredTexture( texture ) {
  28138. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  28139. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  28140. }
  28141. addChain( node ) {
  28142. /*
  28143. if ( this.chaining.indexOf( node ) !== - 1 ) {
  28144. console.warn( 'Recursive node: ', node );
  28145. }
  28146. */
  28147. this.chaining.push( node );
  28148. }
  28149. removeChain( node ) {
  28150. const lastChain = this.chaining.pop();
  28151. if ( lastChain !== node ) {
  28152. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  28153. }
  28154. }
  28155. getMethod( method ) {
  28156. return method;
  28157. }
  28158. getNodeFromHash( hash ) {
  28159. return this.hashNodes[ hash ];
  28160. }
  28161. addFlow( shaderStage, node ) {
  28162. this.flowNodes[ shaderStage ].push( node );
  28163. return node;
  28164. }
  28165. setContext( context ) {
  28166. this.context = context;
  28167. }
  28168. getContext() {
  28169. return this.context;
  28170. }
  28171. setCache( cache ) {
  28172. this.cache = cache;
  28173. }
  28174. getCache() {
  28175. return this.cache;
  28176. }
  28177. getCacheFromNode( node, parent = true ) {
  28178. const data = this.getDataFromNode( node );
  28179. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  28180. return data.cache;
  28181. }
  28182. isAvailable( /*name*/ ) {
  28183. return false;
  28184. }
  28185. getVertexIndex() {
  28186. console.warn( 'Abstract function.' );
  28187. }
  28188. getInstanceIndex() {
  28189. console.warn( 'Abstract function.' );
  28190. }
  28191. getDrawIndex() {
  28192. console.warn( 'Abstract function.' );
  28193. }
  28194. getFrontFacing() {
  28195. console.warn( 'Abstract function.' );
  28196. }
  28197. getFragCoord() {
  28198. console.warn( 'Abstract function.' );
  28199. }
  28200. isFlipY() {
  28201. return false;
  28202. }
  28203. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  28204. console.warn( 'Abstract function.' );
  28205. }
  28206. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  28207. console.warn( 'Abstract function.' );
  28208. }
  28209. generateConst( type, value = null ) {
  28210. if ( value === null ) {
  28211. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  28212. else if ( type === 'bool' ) value = false;
  28213. else if ( type === 'color' ) value = new Color();
  28214. else if ( type === 'vec2' ) value = new Vector2();
  28215. else if ( type === 'vec3' ) value = new Vector3();
  28216. else if ( type === 'vec4' ) value = new Vector4();
  28217. }
  28218. if ( type === 'float' ) return toFloat( value );
  28219. if ( type === 'int' ) return `${ Math.round( value ) }`;
  28220. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  28221. if ( type === 'bool' ) return value ? 'true' : 'false';
  28222. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  28223. const typeLength = this.getTypeLength( type );
  28224. const componentType = this.getComponentType( type );
  28225. const generateConst = value => this.generateConst( componentType, value );
  28226. if ( typeLength === 2 ) {
  28227. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  28228. } else if ( typeLength === 3 ) {
  28229. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  28230. } else if ( typeLength === 4 ) {
  28231. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  28232. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  28233. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  28234. } else if ( typeLength > 4 ) {
  28235. return `${ this.getType( type ) }()`;
  28236. }
  28237. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  28238. }
  28239. getType( type ) {
  28240. if ( type === 'color' ) return 'vec3';
  28241. return type;
  28242. }
  28243. hasGeometryAttribute( name ) {
  28244. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  28245. }
  28246. getAttribute( name, type ) {
  28247. const attributes = this.attributes;
  28248. // find attribute
  28249. for ( const attribute of attributes ) {
  28250. if ( attribute.name === name ) {
  28251. return attribute;
  28252. }
  28253. }
  28254. // create a new if no exist
  28255. const attribute = new NodeAttribute( name, type );
  28256. attributes.push( attribute );
  28257. return attribute;
  28258. }
  28259. getPropertyName( node/*, shaderStage*/ ) {
  28260. return node.name;
  28261. }
  28262. isVector( type ) {
  28263. return /vec\d/.test( type );
  28264. }
  28265. isMatrix( type ) {
  28266. return /mat\d/.test( type );
  28267. }
  28268. isReference( type ) {
  28269. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  28270. }
  28271. needsColorSpaceToLinear( /*texture*/ ) {
  28272. return false;
  28273. }
  28274. getComponentTypeFromTexture( texture ) {
  28275. const type = texture.type;
  28276. if ( texture.isDataTexture ) {
  28277. if ( type === IntType ) return 'int';
  28278. if ( type === UnsignedIntType ) return 'uint';
  28279. }
  28280. return 'float';
  28281. }
  28282. getElementType( type ) {
  28283. if ( type === 'mat2' ) return 'vec2';
  28284. if ( type === 'mat3' ) return 'vec3';
  28285. if ( type === 'mat4' ) return 'vec4';
  28286. return this.getComponentType( type );
  28287. }
  28288. getComponentType( type ) {
  28289. type = this.getVectorType( type );
  28290. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  28291. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  28292. if ( componentType === null ) return null;
  28293. if ( componentType[ 1 ] === 'b' ) return 'bool';
  28294. if ( componentType[ 1 ] === 'i' ) return 'int';
  28295. if ( componentType[ 1 ] === 'u' ) return 'uint';
  28296. return 'float';
  28297. }
  28298. getVectorType( type ) {
  28299. if ( type === 'color' ) return 'vec3';
  28300. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  28301. return type;
  28302. }
  28303. getTypeFromLength( length, componentType = 'float' ) {
  28304. if ( length === 1 ) return componentType;
  28305. const baseType = typeFromLength.get( length );
  28306. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  28307. return prefix + baseType;
  28308. }
  28309. getTypeFromArray( array ) {
  28310. return typeFromArray.get( array.constructor );
  28311. }
  28312. getTypeFromAttribute( attribute ) {
  28313. let dataAttribute = attribute;
  28314. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  28315. const array = dataAttribute.array;
  28316. const itemSize = attribute.itemSize;
  28317. const normalized = attribute.normalized;
  28318. let arrayType;
  28319. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  28320. arrayType = this.getTypeFromArray( array );
  28321. }
  28322. return this.getTypeFromLength( itemSize, arrayType );
  28323. }
  28324. getTypeLength( type ) {
  28325. const vecType = this.getVectorType( type );
  28326. const vecNum = /vec([2-4])/.exec( vecType );
  28327. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  28328. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  28329. if ( /mat2/.test( type ) === true ) return 4;
  28330. if ( /mat3/.test( type ) === true ) return 9;
  28331. if ( /mat4/.test( type ) === true ) return 16;
  28332. return 0;
  28333. }
  28334. getVectorFromMatrix( type ) {
  28335. return type.replace( 'mat', 'vec' );
  28336. }
  28337. changeComponentType( type, newComponentType ) {
  28338. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  28339. }
  28340. getIntegerType( type ) {
  28341. const componentType = this.getComponentType( type );
  28342. if ( componentType === 'int' || componentType === 'uint' ) return type;
  28343. return this.changeComponentType( type, 'int' );
  28344. }
  28345. addStack() {
  28346. this.stack = stack( this.stack );
  28347. this.stacks.push( getCurrentStack() || this.stack );
  28348. setCurrentStack( this.stack );
  28349. return this.stack;
  28350. }
  28351. removeStack() {
  28352. const lastStack = this.stack;
  28353. this.stack = lastStack.parent;
  28354. setCurrentStack( this.stacks.pop() );
  28355. return lastStack;
  28356. }
  28357. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  28358. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  28359. let nodeData = cache.getData( node );
  28360. if ( nodeData === undefined ) {
  28361. nodeData = {};
  28362. cache.setData( node, nodeData );
  28363. }
  28364. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  28365. return nodeData[ shaderStage ];
  28366. }
  28367. getNodeProperties( node, shaderStage = 'any' ) {
  28368. const nodeData = this.getDataFromNode( node, shaderStage );
  28369. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  28370. }
  28371. getBufferAttributeFromNode( node, type ) {
  28372. const nodeData = this.getDataFromNode( node );
  28373. let bufferAttribute = nodeData.bufferAttribute;
  28374. if ( bufferAttribute === undefined ) {
  28375. const index = this.uniforms.index ++;
  28376. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  28377. this.bufferAttributes.push( bufferAttribute );
  28378. nodeData.bufferAttribute = bufferAttribute;
  28379. }
  28380. return bufferAttribute;
  28381. }
  28382. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  28383. const nodeData = this.getDataFromNode( node, shaderStage );
  28384. if ( nodeData.structType === undefined ) {
  28385. const index = this.structs.index ++;
  28386. node.name = `StructType${ index }`;
  28387. this.structs[ shaderStage ].push( node );
  28388. nodeData.structType = node;
  28389. }
  28390. return node;
  28391. }
  28392. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  28393. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  28394. let nodeUniform = nodeData.uniform;
  28395. if ( nodeUniform === undefined ) {
  28396. const index = this.uniforms.index ++;
  28397. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  28398. this.uniforms[ shaderStage ].push( nodeUniform );
  28399. nodeData.uniform = nodeUniform;
  28400. }
  28401. return nodeUniform;
  28402. }
  28403. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  28404. const nodeData = this.getDataFromNode( node, shaderStage );
  28405. let nodeVar = nodeData.variable;
  28406. if ( nodeVar === undefined ) {
  28407. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  28408. if ( name === null ) name = 'nodeVar' + vars.length;
  28409. nodeVar = new NodeVar( name, type );
  28410. vars.push( nodeVar );
  28411. nodeData.variable = nodeVar;
  28412. }
  28413. return nodeVar;
  28414. }
  28415. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  28416. const nodeData = this.getDataFromNode( node, 'any' );
  28417. let nodeVarying = nodeData.varying;
  28418. if ( nodeVarying === undefined ) {
  28419. const varyings = this.varyings;
  28420. const index = varyings.length;
  28421. if ( name === null ) name = 'nodeVarying' + index;
  28422. nodeVarying = new NodeVarying( name, type );
  28423. varyings.push( nodeVarying );
  28424. nodeData.varying = nodeVarying;
  28425. }
  28426. return nodeVarying;
  28427. }
  28428. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  28429. const nodeData = this.getDataFromNode( node );
  28430. let nodeCode = nodeData.code;
  28431. if ( nodeCode === undefined ) {
  28432. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  28433. const index = codes.length;
  28434. nodeCode = new NodeCode( 'nodeCode' + index, type );
  28435. codes.push( nodeCode );
  28436. nodeData.code = nodeCode;
  28437. }
  28438. return nodeCode;
  28439. }
  28440. addLineFlowCode( code ) {
  28441. if ( code === '' ) return this;
  28442. code = this.tab + code;
  28443. if ( ! /;\s*$/.test( code ) ) {
  28444. code = code + ';\n';
  28445. }
  28446. this.flow.code += code;
  28447. return this;
  28448. }
  28449. addFlowCode( code ) {
  28450. this.flow.code += code;
  28451. return this;
  28452. }
  28453. addFlowTab() {
  28454. this.tab += '\t';
  28455. return this;
  28456. }
  28457. removeFlowTab() {
  28458. this.tab = this.tab.slice( 0, - 1 );
  28459. return this;
  28460. }
  28461. getFlowData( node/*, shaderStage*/ ) {
  28462. return this.flowsData.get( node );
  28463. }
  28464. flowNode( node ) {
  28465. const output = node.getNodeType( this );
  28466. const flowData = this.flowChildNode( node, output );
  28467. this.flowsData.set( node, flowData );
  28468. return flowData;
  28469. }
  28470. buildFunctionNode( shaderNode ) {
  28471. const fn = new FunctionNode();
  28472. const previous = this.currentFunctionNode;
  28473. this.currentFunctionNode = fn;
  28474. fn.code = this.buildFunctionCode( shaderNode );
  28475. this.currentFunctionNode = previous;
  28476. return fn;
  28477. }
  28478. flowShaderNode( shaderNode ) {
  28479. const layout = shaderNode.layout;
  28480. let inputs;
  28481. if ( shaderNode.isArrayInput ) {
  28482. inputs = [];
  28483. for ( const input of layout.inputs ) {
  28484. inputs.push( new ParameterNode( input.type, input.name ) );
  28485. }
  28486. } else {
  28487. inputs = {};
  28488. for ( const input of layout.inputs ) {
  28489. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  28490. }
  28491. }
  28492. //
  28493. shaderNode.layout = null;
  28494. const callNode = shaderNode.call( inputs );
  28495. const flowData = this.flowStagesNode( callNode, layout.type );
  28496. shaderNode.layout = layout;
  28497. return flowData;
  28498. }
  28499. flowStagesNode( node, output = null ) {
  28500. const previousFlow = this.flow;
  28501. const previousVars = this.vars;
  28502. const previousCache = this.cache;
  28503. const previousBuildStage = this.buildStage;
  28504. const previousStack = this.stack;
  28505. const flow = {
  28506. code: ''
  28507. };
  28508. this.flow = flow;
  28509. this.vars = {};
  28510. this.cache = new NodeCache();
  28511. this.stack = stack();
  28512. for ( const buildStage of defaultBuildStages ) {
  28513. this.setBuildStage( buildStage );
  28514. flow.result = node.build( this, output );
  28515. }
  28516. flow.vars = this.getVars( this.shaderStage );
  28517. this.flow = previousFlow;
  28518. this.vars = previousVars;
  28519. this.cache = previousCache;
  28520. this.stack = previousStack;
  28521. this.setBuildStage( previousBuildStage );
  28522. return flow;
  28523. }
  28524. getFunctionOperator() {
  28525. return null;
  28526. }
  28527. flowChildNode( node, output = null ) {
  28528. const previousFlow = this.flow;
  28529. const flow = {
  28530. code: ''
  28531. };
  28532. this.flow = flow;
  28533. flow.result = node.build( this, output );
  28534. this.flow = previousFlow;
  28535. return flow;
  28536. }
  28537. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  28538. const previousShaderStage = this.shaderStage;
  28539. this.setShaderStage( shaderStage );
  28540. const flowData = this.flowChildNode( node, output );
  28541. if ( propertyName !== null ) {
  28542. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  28543. }
  28544. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  28545. this.setShaderStage( previousShaderStage );
  28546. return flowData;
  28547. }
  28548. getAttributesArray() {
  28549. return this.attributes.concat( this.bufferAttributes );
  28550. }
  28551. getAttributes( /*shaderStage*/ ) {
  28552. console.warn( 'Abstract function.' );
  28553. }
  28554. getVaryings( /*shaderStage*/ ) {
  28555. console.warn( 'Abstract function.' );
  28556. }
  28557. getVar( type, name ) {
  28558. return `${ this.getType( type ) } ${ name }`;
  28559. }
  28560. getVars( shaderStage ) {
  28561. let snippet = '';
  28562. const vars = this.vars[ shaderStage ];
  28563. if ( vars !== undefined ) {
  28564. for ( const variable of vars ) {
  28565. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  28566. }
  28567. }
  28568. return snippet;
  28569. }
  28570. getUniforms( /*shaderStage*/ ) {
  28571. console.warn( 'Abstract function.' );
  28572. }
  28573. getCodes( shaderStage ) {
  28574. const codes = this.codes[ shaderStage ];
  28575. let code = '';
  28576. if ( codes !== undefined ) {
  28577. for ( const nodeCode of codes ) {
  28578. code += nodeCode.code + '\n';
  28579. }
  28580. }
  28581. return code;
  28582. }
  28583. getHash() {
  28584. return this.vertexShader + this.fragmentShader + this.computeShader;
  28585. }
  28586. setShaderStage( shaderStage ) {
  28587. this.shaderStage = shaderStage;
  28588. }
  28589. getShaderStage() {
  28590. return this.shaderStage;
  28591. }
  28592. setBuildStage( buildStage ) {
  28593. this.buildStage = buildStage;
  28594. }
  28595. getBuildStage() {
  28596. return this.buildStage;
  28597. }
  28598. buildCode() {
  28599. console.warn( 'Abstract function.' );
  28600. }
  28601. build() {
  28602. const { object, material } = this;
  28603. if ( material !== null ) {
  28604. NodeMaterial.fromMaterial( material ).build( this );
  28605. } else {
  28606. this.addFlow( 'compute', object );
  28607. }
  28608. // setup() -> stage 1: create possible new nodes and returns an output reference node
  28609. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  28610. // generate() -> stage 3: generate shader
  28611. for ( const buildStage of defaultBuildStages ) {
  28612. this.setBuildStage( buildStage );
  28613. if ( this.context.vertex && this.context.vertex.isNode ) {
  28614. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  28615. }
  28616. for ( const shaderStage of shaderStages ) {
  28617. this.setShaderStage( shaderStage );
  28618. const flowNodes = this.flowNodes[ shaderStage ];
  28619. for ( const node of flowNodes ) {
  28620. if ( buildStage === 'generate' ) {
  28621. this.flowNode( node );
  28622. } else {
  28623. node.build( this );
  28624. }
  28625. }
  28626. }
  28627. }
  28628. this.setBuildStage( null );
  28629. this.setShaderStage( null );
  28630. // stage 4: build code for a specific output
  28631. this.buildCode();
  28632. this.buildUpdateNodes();
  28633. return this;
  28634. }
  28635. getNodeUniform( uniformNode, type ) {
  28636. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  28637. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  28638. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  28639. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  28640. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  28641. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  28642. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  28643. throw new Error( `Uniform "${type}" not declared.` );
  28644. }
  28645. createNodeMaterial( type = 'NodeMaterial' ) {
  28646. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  28647. return createNodeMaterialFromType( type );
  28648. }
  28649. format( snippet, fromType, toType ) {
  28650. fromType = this.getVectorType( fromType );
  28651. toType = this.getVectorType( toType );
  28652. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  28653. return snippet;
  28654. }
  28655. const fromTypeLength = this.getTypeLength( fromType );
  28656. const toTypeLength = this.getTypeLength( toType );
  28657. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  28658. // @TODO: ignore for now
  28659. return snippet;
  28660. }
  28661. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  28662. // @TODO: ignore for now
  28663. return snippet;
  28664. }
  28665. if ( fromTypeLength === toTypeLength ) {
  28666. return `${ this.getType( toType ) }( ${ snippet } )`;
  28667. }
  28668. if ( fromTypeLength > toTypeLength ) {
  28669. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  28670. }
  28671. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  28672. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  28673. }
  28674. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  28675. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  28676. }
  28677. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  28678. // convert a number value to vector type, e.g:
  28679. // vec3( 1u ) -> vec3( float( 1u ) )
  28680. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  28681. }
  28682. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  28683. }
  28684. getSignature() {
  28685. return `// Three.js r${ REVISION } - Node System\n`;
  28686. }
  28687. }
  28688. class NodeFrame {
  28689. constructor() {
  28690. this.time = 0;
  28691. this.deltaTime = 0;
  28692. this.frameId = 0;
  28693. this.renderId = 0;
  28694. this.startTime = null;
  28695. this.updateMap = new WeakMap();
  28696. this.updateBeforeMap = new WeakMap();
  28697. this.updateAfterMap = new WeakMap();
  28698. this.renderer = null;
  28699. this.material = null;
  28700. this.camera = null;
  28701. this.object = null;
  28702. this.scene = null;
  28703. }
  28704. _getMaps( referenceMap, nodeRef ) {
  28705. let maps = referenceMap.get( nodeRef );
  28706. if ( maps === undefined ) {
  28707. maps = {
  28708. renderMap: new WeakMap(),
  28709. frameMap: new WeakMap()
  28710. };
  28711. referenceMap.set( nodeRef, maps );
  28712. }
  28713. return maps;
  28714. }
  28715. updateBeforeNode( node ) {
  28716. const updateType = node.getUpdateBeforeType();
  28717. const reference = node.updateReference( this );
  28718. if ( updateType === NodeUpdateType.FRAME ) {
  28719. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  28720. if ( frameMap.get( reference ) !== this.frameId ) {
  28721. if ( node.updateBefore( this ) !== false ) {
  28722. frameMap.set( reference, this.frameId );
  28723. }
  28724. }
  28725. } else if ( updateType === NodeUpdateType.RENDER ) {
  28726. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  28727. if ( renderMap.get( reference ) !== this.renderId ) {
  28728. if ( node.updateBefore( this ) !== false ) {
  28729. renderMap.set( reference, this.renderId );
  28730. }
  28731. }
  28732. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28733. node.updateBefore( this );
  28734. }
  28735. }
  28736. updateAfterNode( node ) {
  28737. const updateType = node.getUpdateAfterType();
  28738. const reference = node.updateReference( this );
  28739. if ( updateType === NodeUpdateType.FRAME ) {
  28740. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  28741. if ( frameMap.get( reference ) !== this.frameId ) {
  28742. if ( node.updateAfter( this ) !== false ) {
  28743. frameMap.set( reference, this.frameId );
  28744. }
  28745. }
  28746. } else if ( updateType === NodeUpdateType.RENDER ) {
  28747. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  28748. if ( renderMap.get( reference ) !== this.renderId ) {
  28749. if ( node.updateAfter( this ) !== false ) {
  28750. renderMap.set( reference, this.renderId );
  28751. }
  28752. }
  28753. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28754. node.updateAfter( this );
  28755. }
  28756. }
  28757. updateNode( node ) {
  28758. const updateType = node.getUpdateType();
  28759. const reference = node.updateReference( this );
  28760. if ( updateType === NodeUpdateType.FRAME ) {
  28761. const { frameMap } = this._getMaps( this.updateMap, reference );
  28762. if ( frameMap.get( reference ) !== this.frameId ) {
  28763. if ( node.update( this ) !== false ) {
  28764. frameMap.set( reference, this.frameId );
  28765. }
  28766. }
  28767. } else if ( updateType === NodeUpdateType.RENDER ) {
  28768. const { renderMap } = this._getMaps( this.updateMap, reference );
  28769. if ( renderMap.get( reference ) !== this.renderId ) {
  28770. if ( node.update( this ) !== false ) {
  28771. renderMap.set( reference, this.renderId );
  28772. }
  28773. }
  28774. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28775. node.update( this );
  28776. }
  28777. }
  28778. update() {
  28779. this.frameId ++;
  28780. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  28781. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  28782. this.lastTime = performance.now();
  28783. this.time += this.deltaTime;
  28784. }
  28785. }
  28786. class NodeFunctionInput {
  28787. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  28788. this.type = type;
  28789. this.name = name;
  28790. this.count = count;
  28791. this.qualifier = qualifier;
  28792. this.isConst = isConst;
  28793. }
  28794. }
  28795. NodeFunctionInput.isNodeFunctionInput = true;
  28796. class StructTypeNode extends Node {
  28797. constructor( types ) {
  28798. super();
  28799. this.types = types;
  28800. this.isStructTypeNode = true;
  28801. }
  28802. getMemberTypes() {
  28803. return this.types;
  28804. }
  28805. }
  28806. addNodeClass( 'StructTypeNode', StructTypeNode );
  28807. class OutputStructNode extends Node {
  28808. constructor( ...members ) {
  28809. super();
  28810. this.members = members;
  28811. this.isOutputStructNode = true;
  28812. }
  28813. setup( builder ) {
  28814. super.setup( builder );
  28815. const members = this.members;
  28816. const types = [];
  28817. for ( let i = 0; i < members.length; i ++ ) {
  28818. types.push( members[ i ].getNodeType( builder ) );
  28819. }
  28820. this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name;
  28821. }
  28822. generate( builder, output ) {
  28823. const propertyName = builder.getOutputStructName();
  28824. const members = this.members;
  28825. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  28826. for ( let i = 0; i < members.length; i ++ ) {
  28827. const snippet = members[ i ].build( builder, output );
  28828. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }` );
  28829. }
  28830. return propertyName;
  28831. }
  28832. }
  28833. const outputStruct = nodeProxy( OutputStructNode );
  28834. addNodeClass( 'OutputStructNode', OutputStructNode );
  28835. class HashNode extends Node {
  28836. constructor( seedNode ) {
  28837. super();
  28838. this.seedNode = seedNode;
  28839. }
  28840. setup( /*builder*/ ) {
  28841. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  28842. const state = this.seedNode.toUint().mul( 747796405 ).add( 2891336453 );
  28843. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  28844. const result = word.shiftRight( 22 ).bitXor( word );
  28845. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  28846. }
  28847. }
  28848. const hash = nodeProxy( HashNode );
  28849. addNodeElement( 'hash', hash );
  28850. addNodeClass( 'HashNode', HashNode );
  28851. // remapping functions https://iquilezles.org/articles/functions/
  28852. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  28853. 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 ) );
  28854. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  28855. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  28856. addNodeElement( 'parabola', parabola );
  28857. addNodeElement( 'gain', gain );
  28858. addNodeElement( 'pcurve', pcurve );
  28859. addNodeElement( 'sinc', sinc );
  28860. // https://github.com/cabbibo/glsl-tri-noise-3d
  28861. const tri = tslFn( ( [ x ] ) => {
  28862. return x.fract().sub( .5 ).abs();
  28863. } );
  28864. const tri3 = tslFn( ( [ p ] ) => {
  28865. 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. ) ) ) ) );
  28866. } );
  28867. const triNoise3D = tslFn( ( [ p_immutable, spd, time ] ) => {
  28868. const p = vec3( p_immutable ).toVar();
  28869. const z = float( 1.4 ).toVar();
  28870. const rz = float( 0.0 ).toVar();
  28871. const bp = vec3( p ).toVar();
  28872. loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  28873. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  28874. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  28875. bp.mulAssign( 1.8 );
  28876. z.mulAssign( 1.5 );
  28877. p.mulAssign( 1.2 );
  28878. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  28879. rz.addAssign( t.div( z ) );
  28880. bp.addAssign( 0.14 );
  28881. } );
  28882. return rz;
  28883. } );
  28884. // layouts
  28885. tri.setLayout( {
  28886. name: 'tri',
  28887. type: 'float',
  28888. inputs: [
  28889. { name: 'x', type: 'float' }
  28890. ]
  28891. } );
  28892. tri3.setLayout( {
  28893. name: 'tri3',
  28894. type: 'vec3',
  28895. inputs: [
  28896. { name: 'p', type: 'vec3' }
  28897. ]
  28898. } );
  28899. triNoise3D.setLayout( {
  28900. name: 'triNoise3D',
  28901. type: 'float',
  28902. inputs: [
  28903. { name: 'p', type: 'vec3' },
  28904. { name: 'spd', type: 'float' },
  28905. { name: 'time', type: 'float' }
  28906. ]
  28907. } );
  28908. let discardExpression;
  28909. class DiscardNode extends CondNode {
  28910. constructor( condNode ) {
  28911. discardExpression = discardExpression || expression( 'discard' );
  28912. super( condNode, discardExpression );
  28913. }
  28914. }
  28915. const inlineDiscard = nodeProxy( DiscardNode );
  28916. const discard = ( condNode ) => inlineDiscard( condNode ).append();
  28917. const Return = () => expression( 'return' ).append();
  28918. addNodeElement( 'discard', discard ); // @TODO: Check... this cause a little confusing using in chaining
  28919. addNodeClass( 'DiscardNode', DiscardNode );
  28920. class FunctionOverloadingNode extends Node {
  28921. constructor( functionNodes = [], ...parametersNodes ) {
  28922. super();
  28923. this.functionNodes = functionNodes;
  28924. this.parametersNodes = parametersNodes;
  28925. this._candidateFnCall = null;
  28926. this.global = true;
  28927. }
  28928. getNodeType() {
  28929. return this.functionNodes[ 0 ].shaderNode.layout.type;
  28930. }
  28931. setup( builder ) {
  28932. const params = this.parametersNodes;
  28933. let candidateFnCall = this._candidateFnCall;
  28934. if ( candidateFnCall === null ) {
  28935. let candidateFn = null;
  28936. let candidateScore = - 1;
  28937. for ( const functionNode of this.functionNodes ) {
  28938. const shaderNode = functionNode.shaderNode;
  28939. const layout = shaderNode.layout;
  28940. if ( layout === null ) {
  28941. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  28942. }
  28943. const inputs = layout.inputs;
  28944. if ( params.length === inputs.length ) {
  28945. let score = 0;
  28946. for ( let i = 0; i < params.length; i ++ ) {
  28947. const param = params[ i ];
  28948. const input = inputs[ i ];
  28949. if ( param.getNodeType( builder ) === input.type ) {
  28950. score ++;
  28951. } else {
  28952. score = 0;
  28953. }
  28954. }
  28955. if ( score > candidateScore ) {
  28956. candidateFn = functionNode;
  28957. candidateScore = score;
  28958. }
  28959. }
  28960. }
  28961. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  28962. }
  28963. return candidateFnCall;
  28964. }
  28965. }
  28966. const overloadingBaseFn = nodeProxy( FunctionOverloadingNode );
  28967. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  28968. addNodeClass( 'FunctionOverloadingNode', FunctionOverloadingNode );
  28969. class MatcapUVNode extends TempNode {
  28970. constructor() {
  28971. super( 'vec2' );
  28972. }
  28973. setup() {
  28974. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  28975. const y = positionViewDirection.cross( x );
  28976. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  28977. }
  28978. }
  28979. const matcapUV = nodeImmutable( MatcapUVNode );
  28980. addNodeClass( 'MatcapUVNode', MatcapUVNode );
  28981. class TimerNode extends UniformNode {
  28982. constructor( scope = TimerNode.LOCAL, scale = 1, value = 0 ) {
  28983. super( value );
  28984. this.scope = scope;
  28985. this.scale = scale;
  28986. this.updateType = NodeUpdateType.FRAME;
  28987. }
  28988. /*
  28989. @TODO:
  28990. getNodeType( builder ) {
  28991. const scope = this.scope;
  28992. if ( scope === TimerNode.FRAME ) {
  28993. return 'uint';
  28994. }
  28995. return 'float';
  28996. }
  28997. */
  28998. update( frame ) {
  28999. const scope = this.scope;
  29000. const scale = this.scale;
  29001. if ( scope === TimerNode.LOCAL ) {
  29002. this.value += frame.deltaTime * scale;
  29003. } else if ( scope === TimerNode.DELTA ) {
  29004. this.value = frame.deltaTime * scale;
  29005. } else if ( scope === TimerNode.FRAME ) {
  29006. this.value = frame.frameId;
  29007. } else {
  29008. // global
  29009. this.value = frame.time * scale;
  29010. }
  29011. }
  29012. serialize( data ) {
  29013. super.serialize( data );
  29014. data.scope = this.scope;
  29015. data.scale = this.scale;
  29016. }
  29017. deserialize( data ) {
  29018. super.deserialize( data );
  29019. this.scope = data.scope;
  29020. this.scale = data.scale;
  29021. }
  29022. }
  29023. TimerNode.LOCAL = 'local';
  29024. TimerNode.GLOBAL = 'global';
  29025. TimerNode.DELTA = 'delta';
  29026. TimerNode.FRAME = 'frame';
  29027. // @TODO: add support to use node in timeScale
  29028. const timerLocal = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.LOCAL, timeScale, value ) );
  29029. const timerGlobal = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.GLOBAL, timeScale, value ) );
  29030. const timerDelta = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.DELTA, timeScale, value ) );
  29031. const frameId = nodeImmutable( TimerNode, TimerNode.FRAME ).toUint();
  29032. addNodeClass( 'TimerNode', TimerNode );
  29033. class OscNode extends Node {
  29034. constructor( method = OscNode.SINE, timeNode = timerLocal() ) {
  29035. super();
  29036. this.method = method;
  29037. this.timeNode = timeNode;
  29038. }
  29039. getNodeType( builder ) {
  29040. return this.timeNode.getNodeType( builder );
  29041. }
  29042. setup() {
  29043. const method = this.method;
  29044. const timeNode = nodeObject( this.timeNode );
  29045. let outputNode = null;
  29046. if ( method === OscNode.SINE ) {
  29047. outputNode = timeNode.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  29048. } else if ( method === OscNode.SQUARE ) {
  29049. outputNode = timeNode.fract().round();
  29050. } else if ( method === OscNode.TRIANGLE ) {
  29051. outputNode = timeNode.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  29052. } else if ( method === OscNode.SAWTOOTH ) {
  29053. outputNode = timeNode.fract();
  29054. }
  29055. return outputNode;
  29056. }
  29057. serialize( data ) {
  29058. super.serialize( data );
  29059. data.method = this.method;
  29060. }
  29061. deserialize( data ) {
  29062. super.deserialize( data );
  29063. this.method = data.method;
  29064. }
  29065. }
  29066. OscNode.SINE = 'sine';
  29067. OscNode.SQUARE = 'square';
  29068. OscNode.TRIANGLE = 'triangle';
  29069. OscNode.SAWTOOTH = 'sawtooth';
  29070. const oscSine = nodeProxy( OscNode, OscNode.SINE );
  29071. const oscSquare = nodeProxy( OscNode, OscNode.SQUARE );
  29072. const oscTriangle = nodeProxy( OscNode, OscNode.TRIANGLE );
  29073. const oscSawtooth = nodeProxy( OscNode, OscNode.SAWTOOTH );
  29074. addNodeClass( 'OscNode', OscNode );
  29075. class PackingNode extends TempNode {
  29076. constructor( scope, node ) {
  29077. super();
  29078. this.scope = scope;
  29079. this.node = node;
  29080. }
  29081. getNodeType( builder ) {
  29082. return this.node.getNodeType( builder );
  29083. }
  29084. setup() {
  29085. const { scope, node } = this;
  29086. let result = null;
  29087. if ( scope === PackingNode.DIRECTION_TO_COLOR ) {
  29088. result = node.mul( 0.5 ).add( 0.5 );
  29089. } else if ( scope === PackingNode.COLOR_TO_DIRECTION ) {
  29090. result = node.mul( 2.0 ).sub( 1 );
  29091. }
  29092. return result;
  29093. }
  29094. }
  29095. PackingNode.DIRECTION_TO_COLOR = 'directionToColor';
  29096. PackingNode.COLOR_TO_DIRECTION = 'colorToDirection';
  29097. const directionToColor = nodeProxy( PackingNode, PackingNode.DIRECTION_TO_COLOR );
  29098. const colorToDirection = nodeProxy( PackingNode, PackingNode.COLOR_TO_DIRECTION );
  29099. addNodeElement( 'directionToColor', directionToColor );
  29100. addNodeElement( 'colorToDirection', colorToDirection );
  29101. addNodeClass( 'PackingNode', PackingNode );
  29102. class RemapNode extends Node {
  29103. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  29104. super();
  29105. this.node = node;
  29106. this.inLowNode = inLowNode;
  29107. this.inHighNode = inHighNode;
  29108. this.outLowNode = outLowNode;
  29109. this.outHighNode = outHighNode;
  29110. this.doClamp = true;
  29111. }
  29112. setup() {
  29113. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  29114. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  29115. if ( doClamp === true ) t = t.clamp();
  29116. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  29117. }
  29118. }
  29119. const remap = nodeProxy( RemapNode, null, null, { doClamp: false } );
  29120. const remapClamp = nodeProxy( RemapNode );
  29121. addNodeElement( 'remap', remap );
  29122. addNodeElement( 'remapClamp', remapClamp );
  29123. addNodeClass( 'RemapNode', RemapNode );
  29124. class RotateUVNode extends TempNode {
  29125. constructor( uvNode, rotationNode, centerNode = vec2( 0.5 ) ) {
  29126. super( 'vec2' );
  29127. this.uvNode = uvNode;
  29128. this.rotationNode = rotationNode;
  29129. this.centerNode = centerNode;
  29130. }
  29131. setup() {
  29132. const { uvNode, rotationNode, centerNode } = this;
  29133. const vector = uvNode.sub( centerNode );
  29134. return vector.rotate( rotationNode ).add( centerNode );
  29135. }
  29136. }
  29137. const rotateUV = nodeProxy( RotateUVNode );
  29138. addNodeElement( 'rotateUV', rotateUV );
  29139. addNodeClass( 'RotateUVNode', RotateUVNode );
  29140. class RotateNode extends TempNode {
  29141. constructor( positionNode, rotationNode ) {
  29142. super();
  29143. this.positionNode = positionNode;
  29144. this.rotationNode = rotationNode;
  29145. }
  29146. getNodeType( builder ) {
  29147. return this.positionNode.getNodeType( builder );
  29148. }
  29149. setup( builder ) {
  29150. const { rotationNode, positionNode } = this;
  29151. const nodeType = this.getNodeType( builder );
  29152. if ( nodeType === 'vec2' ) {
  29153. const cosAngle = rotationNode.cos();
  29154. const sinAngle = rotationNode.sin();
  29155. const rotationMatrix = mat2(
  29156. cosAngle, sinAngle,
  29157. sinAngle.negate(), cosAngle
  29158. );
  29159. return rotationMatrix.mul( positionNode );
  29160. } else {
  29161. const rotation = rotationNode;
  29162. 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 ) );
  29163. 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 ) );
  29164. 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 ) );
  29165. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  29166. }
  29167. }
  29168. }
  29169. const rotate = nodeProxy( RotateNode );
  29170. addNodeElement( 'rotate', rotate );
  29171. addNodeClass( 'RotateNode', RotateNode );
  29172. class SpriteSheetUVNode extends Node {
  29173. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  29174. super( 'vec2' );
  29175. this.countNode = countNode;
  29176. this.uvNode = uvNode;
  29177. this.frameNode = frameNode;
  29178. }
  29179. setup() {
  29180. const { frameNode, uvNode, countNode } = this;
  29181. const { width, height } = countNode;
  29182. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  29183. const column = frameNum.mod( width );
  29184. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  29185. const scale = countNode.reciprocal();
  29186. const uvFrameOffset = vec2( column, row );
  29187. return uvNode.add( uvFrameOffset ).mul( scale );
  29188. }
  29189. }
  29190. const spritesheetUV = nodeProxy( SpriteSheetUVNode );
  29191. addNodeClass( 'SpriteSheetUVNode', SpriteSheetUVNode );
  29192. class StorageArrayElementNode extends ArrayElementNode {
  29193. constructor( storageBufferNode, indexNode ) {
  29194. super( storageBufferNode, indexNode );
  29195. this.isStorageArrayElementNode = true;
  29196. }
  29197. set storageBufferNode( value ) {
  29198. this.node = value;
  29199. }
  29200. get storageBufferNode() {
  29201. return this.node;
  29202. }
  29203. setup( builder ) {
  29204. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  29205. if ( ! this.node.instanceIndex && this.node.bufferObject === true ) {
  29206. builder.setupPBO( this.node );
  29207. }
  29208. }
  29209. return super.setup( builder );
  29210. }
  29211. generate( builder, output ) {
  29212. let snippet;
  29213. const isAssignContext = builder.context.assign;
  29214. //
  29215. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  29216. const { node } = this;
  29217. if ( ! node.instanceIndex && this.node.bufferObject === true && isAssignContext !== true ) {
  29218. snippet = builder.generatePBO( this );
  29219. } else {
  29220. snippet = node.build( builder );
  29221. }
  29222. } else {
  29223. snippet = super.generate( builder );
  29224. }
  29225. if ( isAssignContext !== true ) {
  29226. const type = this.getNodeType( builder );
  29227. snippet = builder.format( snippet, type, output );
  29228. }
  29229. return snippet;
  29230. }
  29231. }
  29232. const storageElement = nodeProxy( StorageArrayElementNode );
  29233. addNodeElement( 'storageElement', storageElement );
  29234. addNodeClass( 'StorageArrayElementNode', StorageArrayElementNode );
  29235. class TriplanarTexturesNode extends Node {
  29236. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  29237. super( 'vec4' );
  29238. this.textureXNode = textureXNode;
  29239. this.textureYNode = textureYNode;
  29240. this.textureZNode = textureZNode;
  29241. this.scaleNode = scaleNode;
  29242. this.positionNode = positionNode;
  29243. this.normalNode = normalNode;
  29244. }
  29245. setup() {
  29246. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  29247. // Ref: https://github.com/keijiro/StandardTriplanar
  29248. // Blending factor of triplanar mapping
  29249. let bf = normalNode.abs().normalize();
  29250. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  29251. // Triplanar mapping
  29252. const tx = positionNode.yz.mul( scaleNode );
  29253. const ty = positionNode.zx.mul( scaleNode );
  29254. const tz = positionNode.xy.mul( scaleNode );
  29255. // Base color
  29256. const textureX = textureXNode.value;
  29257. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  29258. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  29259. const cx = texture( textureX, tx ).mul( bf.x );
  29260. const cy = texture( textureY, ty ).mul( bf.y );
  29261. const cz = texture( textureZ, tz ).mul( bf.z );
  29262. return add( cx, cy, cz );
  29263. }
  29264. }
  29265. const triplanarTextures = nodeProxy( TriplanarTexturesNode );
  29266. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  29267. addNodeElement( 'triplanarTexture', triplanarTexture );
  29268. addNodeClass( 'TriplanarTexturesNode', TriplanarTexturesNode );
  29269. const _reflectorPlane = new Plane();
  29270. const _normal = new Vector3();
  29271. const _reflectorWorldPosition = new Vector3();
  29272. const _cameraWorldPosition = new Vector3();
  29273. const _rotationMatrix = new Matrix4();
  29274. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  29275. const clipPlane = new Vector4();
  29276. const _view = new Vector3();
  29277. const _target = new Vector3();
  29278. const _q = new Vector4();
  29279. const _size$3 = new Vector2();
  29280. const _defaultRT = new RenderTarget();
  29281. const _defaultUV = vec2( viewportTopLeft.x.oneMinus(), viewportTopLeft.y );
  29282. let _inReflector = false;
  29283. class ReflectorNode extends TextureNode {
  29284. constructor( parameters = {} ) {
  29285. super( _defaultRT.texture, _defaultUV );
  29286. const {
  29287. target = new Object3D(),
  29288. resolution = 1,
  29289. generateMipmaps = false,
  29290. bounces = true
  29291. } = parameters;
  29292. //
  29293. this.target = target;
  29294. this.resolution = resolution;
  29295. this.generateMipmaps = generateMipmaps;
  29296. this.bounces = bounces;
  29297. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  29298. this.virtualCameras = new WeakMap();
  29299. this.renderTargets = new WeakMap();
  29300. }
  29301. _updateResolution( renderTarget, renderer ) {
  29302. const resolution = this.resolution;
  29303. renderer.getDrawingBufferSize( _size$3 );
  29304. renderTarget.setSize( Math.round( _size$3.width * resolution ), Math.round( _size$3.height * resolution ) );
  29305. }
  29306. setup( builder ) {
  29307. this._updateResolution( _defaultRT, builder.renderer );
  29308. return super.setup( builder );
  29309. }
  29310. getTextureNode() {
  29311. return this.textureNode;
  29312. }
  29313. getVirtualCamera( camera ) {
  29314. let virtualCamera = this.virtualCameras.get( camera );
  29315. if ( virtualCamera === undefined ) {
  29316. virtualCamera = camera.clone();
  29317. this.virtualCameras.set( camera, virtualCamera );
  29318. }
  29319. return virtualCamera;
  29320. }
  29321. getRenderTarget( camera ) {
  29322. let renderTarget = this.renderTargets.get( camera );
  29323. if ( renderTarget === undefined ) {
  29324. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  29325. if ( this.generateMipmaps === true ) {
  29326. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  29327. renderTarget.texture.generateMipmaps = true;
  29328. }
  29329. this.renderTargets.set( camera, renderTarget );
  29330. }
  29331. return renderTarget;
  29332. }
  29333. updateBefore( frame ) {
  29334. if ( this.bounces === false && _inReflector ) return false;
  29335. _inReflector = true;
  29336. const { scene, camera, renderer, material } = frame;
  29337. const { target } = this;
  29338. const virtualCamera = this.getVirtualCamera( camera );
  29339. const renderTarget = this.getRenderTarget( virtualCamera );
  29340. renderer.getDrawingBufferSize( _size$3 );
  29341. this._updateResolution( renderTarget, renderer );
  29342. //
  29343. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  29344. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  29345. _rotationMatrix.extractRotation( target.matrixWorld );
  29346. _normal.set( 0, 0, 1 );
  29347. _normal.applyMatrix4( _rotationMatrix );
  29348. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  29349. // Avoid rendering when reflector is facing away
  29350. if ( _view.dot( _normal ) > 0 ) return;
  29351. _view.reflect( _normal ).negate();
  29352. _view.add( _reflectorWorldPosition );
  29353. _rotationMatrix.extractRotation( camera.matrixWorld );
  29354. _lookAtPosition.set( 0, 0, - 1 );
  29355. _lookAtPosition.applyMatrix4( _rotationMatrix );
  29356. _lookAtPosition.add( _cameraWorldPosition );
  29357. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  29358. _target.reflect( _normal ).negate();
  29359. _target.add( _reflectorWorldPosition );
  29360. //
  29361. virtualCamera.coordinateSystem = camera.coordinateSystem;
  29362. virtualCamera.position.copy( _view );
  29363. virtualCamera.up.set( 0, 1, 0 );
  29364. virtualCamera.up.applyMatrix4( _rotationMatrix );
  29365. virtualCamera.up.reflect( _normal );
  29366. virtualCamera.lookAt( _target );
  29367. virtualCamera.near = camera.near;
  29368. virtualCamera.far = camera.far;
  29369. virtualCamera.updateMatrixWorld();
  29370. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  29371. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  29372. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  29373. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  29374. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  29375. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  29376. const projectionMatrix = virtualCamera.projectionMatrix;
  29377. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  29378. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  29379. _q.z = - 1.0;
  29380. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  29381. // Calculate the scaled plane vector
  29382. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  29383. const clipBias = 0;
  29384. // Replacing the third row of the projection matrix
  29385. projectionMatrix.elements[ 2 ] = clipPlane.x;
  29386. projectionMatrix.elements[ 6 ] = clipPlane.y;
  29387. projectionMatrix.elements[ 10 ] = clipPlane.z - clipBias;
  29388. projectionMatrix.elements[ 14 ] = clipPlane.w;
  29389. //
  29390. this.value = renderTarget.texture;
  29391. material.visible = false;
  29392. const currentRenderTarget = renderer.getRenderTarget();
  29393. renderer.setRenderTarget( renderTarget );
  29394. renderer.render( scene, virtualCamera );
  29395. renderer.setRenderTarget( currentRenderTarget );
  29396. material.visible = true;
  29397. _inReflector = false;
  29398. }
  29399. }
  29400. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  29401. class VertexColorNode extends AttributeNode {
  29402. constructor( index = 0 ) {
  29403. super( null, 'vec4' );
  29404. this.isVertexColorNode = true;
  29405. this.index = index;
  29406. }
  29407. getAttributeName( /*builder*/ ) {
  29408. const index = this.index;
  29409. return 'color' + ( index > 0 ? index : '' );
  29410. }
  29411. generate( builder ) {
  29412. const attributeName = this.getAttributeName( builder );
  29413. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  29414. let result;
  29415. if ( geometryAttribute === true ) {
  29416. result = super.generate( builder );
  29417. } else {
  29418. // Vertex color fallback should be white
  29419. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  29420. }
  29421. return result;
  29422. }
  29423. serialize( data ) {
  29424. super.serialize( data );
  29425. data.index = this.index;
  29426. }
  29427. deserialize( data ) {
  29428. super.deserialize( data );
  29429. this.index = data.index;
  29430. }
  29431. }
  29432. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  29433. addNodeClass( 'VertexColorNode', VertexColorNode );
  29434. class RendererReferenceNode extends ReferenceNode {
  29435. constructor( property, inputType, renderer = null ) {
  29436. super( property, inputType, renderer );
  29437. this.renderer = renderer;
  29438. }
  29439. updateReference( state ) {
  29440. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  29441. return this.reference;
  29442. }
  29443. }
  29444. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  29445. addNodeClass( 'RendererReferenceNode', RendererReferenceNode );
  29446. // Mipped Bicubic Texture Filtering by N8
  29447. // https://www.shadertoy.com/view/Dl2SDW
  29448. const bC = 1.0 / 6.0;
  29449. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  29450. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  29451. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  29452. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  29453. const g0 = ( a ) => w0( a ).add( w1( a ) );
  29454. const g1 = ( a ) => w2( a ).add( w3( a ) );
  29455. // h0 and h1 are the two offset functions
  29456. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  29457. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  29458. const bicubic = ( textureNode, texelSize, lod ) => {
  29459. const uv = textureNode.uvNode;
  29460. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  29461. const iuv = floor( uvScaled );
  29462. const fuv = fract( uvScaled );
  29463. const g0x = g0( fuv.x );
  29464. const g1x = g1( fuv.x );
  29465. const h0x = h0( fuv.x );
  29466. const h1x = h1( fuv.x );
  29467. const h0y = h0( fuv.y );
  29468. const h1y = h1( fuv.y );
  29469. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  29470. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  29471. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  29472. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  29473. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.uv( p0 ).level( lod ) ), g1x.mul( textureNode.uv( p1 ).level( lod ) ) ) );
  29474. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.uv( p2 ).level( lod ) ), g1x.mul( textureNode.uv( p3 ).level( lod ) ) ) );
  29475. return a.add( b );
  29476. };
  29477. const textureBicubicMethod = ( textureNode, lodNode ) => {
  29478. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  29479. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  29480. const fLodSizeInv = div( 1.0, fLodSize );
  29481. const cLodSizeInv = div( 1.0, cLodSize );
  29482. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  29483. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  29484. return fract( lodNode ).mix( fSample, cSample );
  29485. };
  29486. class TextureBicubicNode extends TempNode {
  29487. constructor( textureNode, blurNode = float( 3 ) ) {
  29488. super( 'vec4' );
  29489. this.textureNode = textureNode;
  29490. this.blurNode = blurNode;
  29491. }
  29492. setup() {
  29493. return textureBicubicMethod( this.textureNode, this.blurNode );
  29494. }
  29495. }
  29496. const textureBicubic = nodeProxy( TextureBicubicNode );
  29497. addNodeElement( 'bicubic', textureBicubic );
  29498. addNodeClass( 'TextureBicubicNode', TextureBicubicNode );
  29499. class PointUVNode extends Node {
  29500. constructor() {
  29501. super( 'vec2' );
  29502. this.isPointUVNode = true;
  29503. }
  29504. generate( /*builder*/ ) {
  29505. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  29506. }
  29507. }
  29508. const pointUV = nodeImmutable( PointUVNode );
  29509. addNodeClass( 'PointUVNode', PointUVNode );
  29510. class SceneNode extends Node {
  29511. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  29512. super();
  29513. this.scope = scope;
  29514. this.scene = scene;
  29515. }
  29516. setup( builder ) {
  29517. const scope = this.scope;
  29518. const scene = this.scene !== null ? this.scene : builder.scene;
  29519. let output;
  29520. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  29521. output = reference( 'backgroundBlurriness', 'float', scene );
  29522. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  29523. output = reference( 'backgroundIntensity', 'float', scene );
  29524. } else {
  29525. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  29526. }
  29527. return output;
  29528. }
  29529. }
  29530. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  29531. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  29532. const backgroundBlurriness = nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  29533. const backgroundIntensity = nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  29534. addNodeClass( 'SceneNode', SceneNode );
  29535. const GPUPrimitiveTopology = {
  29536. PointList: 'point-list',
  29537. LineList: 'line-list',
  29538. LineStrip: 'line-strip',
  29539. TriangleList: 'triangle-list',
  29540. TriangleStrip: 'triangle-strip',
  29541. };
  29542. const GPUCompareFunction = {
  29543. Never: 'never',
  29544. Less: 'less',
  29545. Equal: 'equal',
  29546. LessEqual: 'less-equal',
  29547. Greater: 'greater',
  29548. NotEqual: 'not-equal',
  29549. GreaterEqual: 'greater-equal',
  29550. Always: 'always'
  29551. };
  29552. const GPUStoreOp = {
  29553. Store: 'store',
  29554. Discard: 'discard'
  29555. };
  29556. const GPULoadOp = {
  29557. Load: 'load',
  29558. Clear: 'clear'
  29559. };
  29560. const GPUFrontFace = {
  29561. CCW: 'ccw',
  29562. CW: 'cw'
  29563. };
  29564. const GPUCullMode = {
  29565. None: 'none',
  29566. Front: 'front',
  29567. Back: 'back'
  29568. };
  29569. const GPUIndexFormat = {
  29570. Uint16: 'uint16',
  29571. Uint32: 'uint32'
  29572. };
  29573. const GPUTextureFormat = {
  29574. // 8-bit formats
  29575. R8Unorm: 'r8unorm',
  29576. R8Snorm: 'r8snorm',
  29577. R8Uint: 'r8uint',
  29578. R8Sint: 'r8sint',
  29579. // 16-bit formats
  29580. R16Uint: 'r16uint',
  29581. R16Sint: 'r16sint',
  29582. R16Float: 'r16float',
  29583. RG8Unorm: 'rg8unorm',
  29584. RG8Snorm: 'rg8snorm',
  29585. RG8Uint: 'rg8uint',
  29586. RG8Sint: 'rg8sint',
  29587. // 32-bit formats
  29588. R32Uint: 'r32uint',
  29589. R32Sint: 'r32sint',
  29590. R32Float: 'r32float',
  29591. RG16Uint: 'rg16uint',
  29592. RG16Sint: 'rg16sint',
  29593. RG16Float: 'rg16float',
  29594. RGBA8Unorm: 'rgba8unorm',
  29595. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  29596. RGBA8Snorm: 'rgba8snorm',
  29597. RGBA8Uint: 'rgba8uint',
  29598. RGBA8Sint: 'rgba8sint',
  29599. BGRA8Unorm: 'bgra8unorm',
  29600. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  29601. // Packed 32-bit formats
  29602. RGB9E5UFloat: 'rgb9e5ufloat',
  29603. RGB10A2Unorm: 'rgb10a2unorm',
  29604. RG11B10uFloat: 'rgb10a2unorm',
  29605. // 64-bit formats
  29606. RG32Uint: 'rg32uint',
  29607. RG32Sint: 'rg32sint',
  29608. RG32Float: 'rg32float',
  29609. RGBA16Uint: 'rgba16uint',
  29610. RGBA16Sint: 'rgba16sint',
  29611. RGBA16Float: 'rgba16float',
  29612. // 128-bit formats
  29613. RGBA32Uint: 'rgba32uint',
  29614. RGBA32Sint: 'rgba32sint',
  29615. RGBA32Float: 'rgba32float',
  29616. // Depth and stencil formats
  29617. Stencil8: 'stencil8',
  29618. Depth16Unorm: 'depth16unorm',
  29619. Depth24Plus: 'depth24plus',
  29620. Depth24PlusStencil8: 'depth24plus-stencil8',
  29621. Depth32Float: 'depth32float',
  29622. // 'depth32float-stencil8' extension
  29623. Depth32FloatStencil8: 'depth32float-stencil8',
  29624. // BC compressed formats usable if 'texture-compression-bc' is both
  29625. // supported by the device/user agent and enabled in requestDevice.
  29626. BC1RGBAUnorm: 'bc1-rgba-unorm',
  29627. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  29628. BC2RGBAUnorm: 'bc2-rgba-unorm',
  29629. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  29630. BC3RGBAUnorm: 'bc3-rgba-unorm',
  29631. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  29632. BC4RUnorm: 'bc4-r-unorm',
  29633. BC4RSnorm: 'bc4-r-snorm',
  29634. BC5RGUnorm: 'bc5-rg-unorm',
  29635. BC5RGSnorm: 'bc5-rg-snorm',
  29636. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  29637. BC6HRGBFloat: 'bc6h-rgb-float',
  29638. BC7RGBAUnorm: 'bc7-rgba-unorm',
  29639. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  29640. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  29641. // supported by the device/user agent and enabled in requestDevice.
  29642. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  29643. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  29644. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  29645. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  29646. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  29647. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  29648. EACR11Unorm: 'eac-r11unorm',
  29649. EACR11Snorm: 'eac-r11snorm',
  29650. EACRG11Unorm: 'eac-rg11unorm',
  29651. EACRG11Snorm: 'eac-rg11snorm',
  29652. // ASTC compressed formats usable if 'texture-compression-astc' is both
  29653. // supported by the device/user agent and enabled in requestDevice.
  29654. ASTC4x4Unorm: 'astc-4x4-unorm',
  29655. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  29656. ASTC5x4Unorm: 'astc-5x4-unorm',
  29657. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  29658. ASTC5x5Unorm: 'astc-5x5-unorm',
  29659. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  29660. ASTC6x5Unorm: 'astc-6x5-unorm',
  29661. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  29662. ASTC6x6Unorm: 'astc-6x6-unorm',
  29663. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  29664. ASTC8x5Unorm: 'astc-8x5-unorm',
  29665. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  29666. ASTC8x6Unorm: 'astc-8x6-unorm',
  29667. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  29668. ASTC8x8Unorm: 'astc-8x8-unorm',
  29669. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  29670. ASTC10x5Unorm: 'astc-10x5-unorm',
  29671. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  29672. ASTC10x6Unorm: 'astc-10x6-unorm',
  29673. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  29674. ASTC10x8Unorm: 'astc-10x8-unorm',
  29675. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  29676. ASTC10x10Unorm: 'astc-10x10-unorm',
  29677. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  29678. ASTC12x10Unorm: 'astc-12x10-unorm',
  29679. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  29680. ASTC12x12Unorm: 'astc-12x12-unorm',
  29681. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  29682. };
  29683. const GPUAddressMode = {
  29684. ClampToEdge: 'clamp-to-edge',
  29685. Repeat: 'repeat',
  29686. MirrorRepeat: 'mirror-repeat'
  29687. };
  29688. const GPUFilterMode = {
  29689. Linear: 'linear',
  29690. Nearest: 'nearest'
  29691. };
  29692. const GPUBlendFactor = {
  29693. Zero: 'zero',
  29694. One: 'one',
  29695. Src: 'src',
  29696. OneMinusSrc: 'one-minus-src',
  29697. SrcAlpha: 'src-alpha',
  29698. OneMinusSrcAlpha: 'one-minus-src-alpha',
  29699. Dst: 'dst',
  29700. OneMinusDstColor: 'one-minus-dst',
  29701. DstAlpha: 'dst-alpha',
  29702. OneMinusDstAlpha: 'one-minus-dst-alpha',
  29703. SrcAlphaSaturated: 'src-alpha-saturated',
  29704. Constant: 'constant',
  29705. OneMinusConstant: 'one-minus-constant'
  29706. };
  29707. const GPUBlendOperation = {
  29708. Add: 'add',
  29709. Subtract: 'subtract',
  29710. ReverseSubtract: 'reverse-subtract',
  29711. Min: 'min',
  29712. Max: 'max'
  29713. };
  29714. const GPUColorWriteFlags = {
  29715. None: 0,
  29716. Red: 0x1,
  29717. Green: 0x2,
  29718. Blue: 0x4,
  29719. Alpha: 0x8,
  29720. All: 0xF
  29721. };
  29722. const GPUStencilOperation = {
  29723. Keep: 'keep',
  29724. Zero: 'zero',
  29725. Replace: 'replace',
  29726. Invert: 'invert',
  29727. IncrementClamp: 'increment-clamp',
  29728. DecrementClamp: 'decrement-clamp',
  29729. IncrementWrap: 'increment-wrap',
  29730. DecrementWrap: 'decrement-wrap'
  29731. };
  29732. const GPUBufferBindingType = {
  29733. Uniform: 'uniform',
  29734. Storage: 'storage',
  29735. ReadOnlyStorage: 'read-only-storage'
  29736. };
  29737. const GPUStorageTextureAccess = {
  29738. WriteOnly: 'write-only',
  29739. ReadOnly: 'read-only',
  29740. ReadWrite: 'read-write',
  29741. };
  29742. const GPUTextureSampleType = {
  29743. Float: 'float',
  29744. UnfilterableFloat: 'unfilterable-float',
  29745. Depth: 'depth',
  29746. SInt: 'sint',
  29747. UInt: 'uint'
  29748. };
  29749. const GPUTextureDimension = {
  29750. OneD: '1d',
  29751. TwoD: '2d',
  29752. ThreeD: '3d'
  29753. };
  29754. const GPUTextureViewDimension = {
  29755. OneD: '1d',
  29756. TwoD: '2d',
  29757. TwoDArray: '2d-array',
  29758. Cube: 'cube',
  29759. CubeArray: 'cube-array',
  29760. ThreeD: '3d'
  29761. };
  29762. const GPUTextureAspect = {
  29763. All: 'all',
  29764. StencilOnly: 'stencil-only',
  29765. DepthOnly: 'depth-only'
  29766. };
  29767. const GPUInputStepMode = {
  29768. Vertex: 'vertex',
  29769. Instance: 'instance'
  29770. };
  29771. const GPUFeatureName = {
  29772. DepthClipControl: 'depth-clip-control',
  29773. Depth32FloatStencil8: 'depth32float-stencil8',
  29774. TextureCompressionBC: 'texture-compression-bc',
  29775. TextureCompressionETC2: 'texture-compression-etc2',
  29776. TextureCompressionASTC: 'texture-compression-astc',
  29777. TimestampQuery: 'timestamp-query',
  29778. IndirectFirstInstance: 'indirect-first-instance',
  29779. ShaderF16: 'shader-f16',
  29780. RG11B10UFloat: 'rg11b10ufloat-renderable',
  29781. BGRA8UNormStorage: 'bgra8unorm-storage',
  29782. Float32Filterable: 'float32-filterable'
  29783. };
  29784. class StorageBufferNode extends BufferNode {
  29785. constructor( value, bufferType, bufferCount = 0 ) {
  29786. super( value, bufferType, bufferCount );
  29787. this.isStorageBufferNode = true;
  29788. this.access = GPUBufferBindingType.Storage;
  29789. this.bufferObject = false;
  29790. this.bufferCount = bufferCount;
  29791. this._attribute = null;
  29792. this._varying = null;
  29793. this.global = true;
  29794. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  29795. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  29796. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  29797. else value.isStorageBufferAttribute = true;
  29798. }
  29799. }
  29800. getHash( builder ) {
  29801. if ( this.bufferCount === 0 ) {
  29802. let bufferData = builder.globalCache.getData( this.value );
  29803. if ( bufferData === undefined ) {
  29804. bufferData = {
  29805. node: this
  29806. };
  29807. builder.globalCache.setData( this.value, bufferData );
  29808. }
  29809. return bufferData.node.uuid;
  29810. }
  29811. return this.uuid;
  29812. }
  29813. getInputType( /*builder*/ ) {
  29814. return 'storageBuffer';
  29815. }
  29816. element( indexNode ) {
  29817. return storageElement( this, indexNode );
  29818. }
  29819. setBufferObject( value ) {
  29820. this.bufferObject = value;
  29821. return this;
  29822. }
  29823. setAccess( value ) {
  29824. this.access = value;
  29825. return this;
  29826. }
  29827. toReadOnly() {
  29828. return this.setAccess( GPUBufferBindingType.ReadOnlyStorage );
  29829. }
  29830. generate( builder ) {
  29831. if ( builder.isAvailable( 'storageBuffer' ) ) {
  29832. return super.generate( builder );
  29833. }
  29834. const nodeType = this.getNodeType( builder );
  29835. if ( this._attribute === null ) {
  29836. this._attribute = bufferAttribute( this.value );
  29837. this._varying = varying( this._attribute );
  29838. }
  29839. const output = this._varying.build( builder, nodeType );
  29840. builder.registerTransform( output, this._attribute );
  29841. return output;
  29842. }
  29843. }
  29844. // Read-Write Storage
  29845. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  29846. const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) );
  29847. addNodeClass( 'StorageBufferNode', StorageBufferNode );
  29848. class StorageTextureNode extends TextureNode {
  29849. constructor( value, uvNode, storeNode = null ) {
  29850. super( value, uvNode );
  29851. this.storeNode = storeNode;
  29852. this.isStorageTextureNode = true;
  29853. this.access = GPUStorageTextureAccess.WriteOnly;
  29854. }
  29855. getInputType( /*builder*/ ) {
  29856. return 'storageTexture';
  29857. }
  29858. setup( builder ) {
  29859. super.setup( builder );
  29860. const properties = builder.getNodeProperties( this );
  29861. properties.storeNode = this.storeNode;
  29862. }
  29863. setAccess( value ) {
  29864. this.access = value;
  29865. return this;
  29866. }
  29867. generate( builder, output ) {
  29868. let snippet;
  29869. if ( this.storeNode !== null ) {
  29870. snippet = this.generateStore( builder );
  29871. } else {
  29872. snippet = super.generate( builder, output );
  29873. }
  29874. return snippet;
  29875. }
  29876. toReadOnly() {
  29877. return this.setAccess( GPUStorageTextureAccess.ReadOnly );
  29878. }
  29879. toWriteOnly() {
  29880. return this.setAccess( GPUStorageTextureAccess.WriteOnly );
  29881. }
  29882. generateStore( builder ) {
  29883. const properties = builder.getNodeProperties( this );
  29884. const { uvNode, storeNode } = properties;
  29885. const textureProperty = super.generate( builder, 'property' );
  29886. const uvSnippet = uvNode.build( builder, 'uvec2' );
  29887. const storeSnippet = storeNode.build( builder, 'vec4' );
  29888. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  29889. builder.addLineFlowCode( snippet );
  29890. }
  29891. }
  29892. const storageTexture = nodeProxy( StorageTextureNode );
  29893. const textureStore = ( value, uvNode, storeNode ) => {
  29894. const node = storageTexture( value, uvNode, storeNode );
  29895. if ( storeNode !== null ) node.append();
  29896. return node;
  29897. };
  29898. addNodeClass( 'StorageTextureNode', StorageTextureNode );
  29899. const normal = tslFn( ( { texture, uv } ) => {
  29900. const epsilon = 0.0001;
  29901. const ret = vec3().temp();
  29902. If( uv.x.lessThan( epsilon ), () => {
  29903. ret.assign( vec3( 1, 0, 0 ) );
  29904. } ).elseif( uv.y.lessThan( epsilon ), () => {
  29905. ret.assign( vec3( 0, 1, 0 ) );
  29906. } ).elseif( uv.z.lessThan( epsilon ), () => {
  29907. ret.assign( vec3( 0, 0, 1 ) );
  29908. } ).elseif( uv.x.greaterThan( 1 - epsilon ), () => {
  29909. ret.assign( vec3( - 1, 0, 0 ) );
  29910. } ).elseif( uv.y.greaterThan( 1 - epsilon ), () => {
  29911. ret.assign( vec3( 0, - 1, 0 ) );
  29912. } ).elseif( uv.z.greaterThan( 1 - epsilon ), () => {
  29913. ret.assign( vec3( 0, 0, - 1 ) );
  29914. } ).else( () => {
  29915. const step = 0.01;
  29916. 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 );
  29917. 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 );
  29918. 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 );
  29919. ret.assign( vec3( x, y, z ) );
  29920. } );
  29921. return ret.normalize();
  29922. } );
  29923. class Texture3DNode extends TextureNode {
  29924. constructor( value, uvNode = null, levelNode = null ) {
  29925. super( value, uvNode, levelNode );
  29926. this.isTexture3DNode = true;
  29927. }
  29928. getInputType( /*builder*/ ) {
  29929. return 'texture3D';
  29930. }
  29931. getDefaultUV() {
  29932. return vec3( 0.5, 0.5, 0.5 );
  29933. }
  29934. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  29935. setupUV( builder, uvNode ) {
  29936. return uvNode;
  29937. }
  29938. generateUV( builder, uvNode ) {
  29939. return uvNode.build( builder, 'vec3' );
  29940. }
  29941. normal( uvNode ) {
  29942. return normal( { texture: this, uv: uvNode } );
  29943. }
  29944. }
  29945. const texture3D = nodeProxy( Texture3DNode );
  29946. addNodeClass( 'Texture3DNode', Texture3DNode );
  29947. class UserDataNode extends ReferenceNode {
  29948. constructor( property, inputType, userData = null ) {
  29949. super( property, inputType, userData );
  29950. this.userData = userData;
  29951. }
  29952. update( frame ) {
  29953. this.reference = this.userData !== null ? this.userData : frame.object.userData;
  29954. super.update( frame );
  29955. }
  29956. }
  29957. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  29958. addNodeClass( 'UserDataNode', UserDataNode );
  29959. const BurnNode = tslFn( ( { base, blend } ) => {
  29960. const fn = ( c ) => blend[ c ].lessThan( EPSILON ).cond( blend[ c ], base[ c ].oneMinus().div( blend[ c ] ).oneMinus().max( 0 ) );
  29961. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  29962. } ).setLayout( {
  29963. name: 'burnColor',
  29964. type: 'vec3',
  29965. inputs: [
  29966. { name: 'base', type: 'vec3' },
  29967. { name: 'blend', type: 'vec3' }
  29968. ]
  29969. } );
  29970. const DodgeNode = tslFn( ( { base, blend } ) => {
  29971. const fn = ( c ) => blend[ c ].equal( 1.0 ).cond( blend[ c ], base[ c ].div( blend[ c ].oneMinus() ).max( 0 ) );
  29972. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  29973. } ).setLayout( {
  29974. name: 'dodgeColor',
  29975. type: 'vec3',
  29976. inputs: [
  29977. { name: 'base', type: 'vec3' },
  29978. { name: 'blend', type: 'vec3' }
  29979. ]
  29980. } );
  29981. const ScreenNode = tslFn( ( { base, blend } ) => {
  29982. const fn = ( c ) => base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus();
  29983. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  29984. } ).setLayout( {
  29985. name: 'screenColor',
  29986. type: 'vec3',
  29987. inputs: [
  29988. { name: 'base', type: 'vec3' },
  29989. { name: 'blend', type: 'vec3' }
  29990. ]
  29991. } );
  29992. const OverlayNode = tslFn( ( { base, blend } ) => {
  29993. const fn = ( c ) => base[ c ].lessThan( 0.5 ).cond( base[ c ].mul( blend[ c ], 2.0 ), base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus() );
  29994. //const fn = ( c ) => mix( base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus(), base[ c ].mul( blend[ c ], 2.0 ), step( base[ c ], 0.5 ) );
  29995. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  29996. } ).setLayout( {
  29997. name: 'overlayColor',
  29998. type: 'vec3',
  29999. inputs: [
  30000. { name: 'base', type: 'vec3' },
  30001. { name: 'blend', type: 'vec3' }
  30002. ]
  30003. } );
  30004. class BlendModeNode extends TempNode {
  30005. constructor( blendMode, baseNode, blendNode ) {
  30006. super();
  30007. this.blendMode = blendMode;
  30008. this.baseNode = baseNode;
  30009. this.blendNode = blendNode;
  30010. }
  30011. setup() {
  30012. const { blendMode, baseNode, blendNode } = this;
  30013. const params = { base: baseNode, blend: blendNode };
  30014. let outputNode = null;
  30015. if ( blendMode === BlendModeNode.BURN ) {
  30016. outputNode = BurnNode( params );
  30017. } else if ( blendMode === BlendModeNode.DODGE ) {
  30018. outputNode = DodgeNode( params );
  30019. } else if ( blendMode === BlendModeNode.SCREEN ) {
  30020. outputNode = ScreenNode( params );
  30021. } else if ( blendMode === BlendModeNode.OVERLAY ) {
  30022. outputNode = OverlayNode( params );
  30023. }
  30024. return outputNode;
  30025. }
  30026. }
  30027. BlendModeNode.BURN = 'burn';
  30028. BlendModeNode.DODGE = 'dodge';
  30029. BlendModeNode.SCREEN = 'screen';
  30030. BlendModeNode.OVERLAY = 'overlay';
  30031. const burn = nodeProxy( BlendModeNode, BlendModeNode.BURN );
  30032. const dodge = nodeProxy( BlendModeNode, BlendModeNode.DODGE );
  30033. const overlay = nodeProxy( BlendModeNode, BlendModeNode.OVERLAY );
  30034. const screen = nodeProxy( BlendModeNode, BlendModeNode.SCREEN );
  30035. addNodeElement( 'burn', burn );
  30036. addNodeElement( 'dodge', dodge );
  30037. addNodeElement( 'overlay', overlay );
  30038. addNodeElement( 'screen', screen );
  30039. addNodeClass( 'BlendModeNode', BlendModeNode );
  30040. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  30041. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  30042. const dHdxy_fwd = tslFn( ( { textureNode, bumpScale } ) => {
  30043. // It's used to preserve the same TextureNode instance
  30044. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  30045. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  30046. return vec2(
  30047. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  30048. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  30049. ).mul( bumpScale );
  30050. } );
  30051. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  30052. const perturbNormalArb = tslFn( ( inputs ) => {
  30053. const { surf_pos, surf_norm, dHdxy } = inputs;
  30054. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  30055. const vSigmaX = surf_pos.dFdx().normalize();
  30056. const vSigmaY = surf_pos.dFdy().normalize();
  30057. const vN = surf_norm; // normalized
  30058. const R1 = vSigmaY.cross( vN );
  30059. const R2 = vN.cross( vSigmaX );
  30060. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  30061. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  30062. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  30063. } );
  30064. class BumpMapNode extends TempNode {
  30065. constructor( textureNode, scaleNode = null ) {
  30066. super( 'vec3' );
  30067. this.textureNode = textureNode;
  30068. this.scaleNode = scaleNode;
  30069. }
  30070. setup() {
  30071. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  30072. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  30073. return perturbNormalArb( {
  30074. surf_pos: positionView,
  30075. surf_norm: normalView,
  30076. dHdxy
  30077. } );
  30078. }
  30079. }
  30080. const bumpMap = nodeProxy( BumpMapNode );
  30081. addNodeElement( 'bumpMap', bumpMap );
  30082. addNodeClass( 'BumpMapNode', BumpMapNode );
  30083. const saturationNode = tslFn( ( { color, adjustment } ) => {
  30084. return adjustment.mix( luminance( color.rgb ), color.rgb );
  30085. } );
  30086. const vibranceNode = tslFn( ( { color, adjustment } ) => {
  30087. const average = add( color.r, color.g, color.b ).div( 3.0 );
  30088. const mx = color.r.max( color.g.max( color.b ) );
  30089. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  30090. return mix( color.rgb, mx, amt );
  30091. } );
  30092. const hueNode = tslFn( ( { color, adjustment } ) => {
  30093. const k = vec3( 0.57735, 0.57735, 0.57735 );
  30094. const cosAngle = adjustment.cos();
  30095. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  30096. } );
  30097. class ColorAdjustmentNode extends TempNode {
  30098. constructor( method, colorNode, adjustmentNode = float( 1 ) ) {
  30099. super( 'vec3' );
  30100. this.method = method;
  30101. this.colorNode = colorNode;
  30102. this.adjustmentNode = adjustmentNode;
  30103. }
  30104. setup() {
  30105. const { method, colorNode, adjustmentNode } = this;
  30106. const callParams = { color: colorNode, adjustment: adjustmentNode };
  30107. let outputNode = null;
  30108. if ( method === ColorAdjustmentNode.SATURATION ) {
  30109. outputNode = saturationNode( callParams );
  30110. } else if ( method === ColorAdjustmentNode.VIBRANCE ) {
  30111. outputNode = vibranceNode( callParams );
  30112. } else if ( method === ColorAdjustmentNode.HUE ) {
  30113. outputNode = hueNode( callParams );
  30114. } else {
  30115. console.error( `${ this.type }: Method "${ this.method }" not supported!` );
  30116. }
  30117. return outputNode;
  30118. }
  30119. }
  30120. ColorAdjustmentNode.SATURATION = 'saturation';
  30121. ColorAdjustmentNode.VIBRANCE = 'vibrance';
  30122. ColorAdjustmentNode.HUE = 'hue';
  30123. const saturation = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.SATURATION );
  30124. const vibrance = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.VIBRANCE );
  30125. const hue = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.HUE );
  30126. const lumaCoeffs = vec3( 0.2125, 0.7154, 0.0721 );
  30127. const luminance = ( color, luma = lumaCoeffs ) => dot( color, luma );
  30128. const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) );
  30129. addNodeElement( 'saturation', saturation );
  30130. addNodeElement( 'vibrance', vibrance );
  30131. addNodeElement( 'hue', hue );
  30132. addNodeElement( 'threshold', threshold );
  30133. addNodeClass( 'ColorAdjustmentNode', ColorAdjustmentNode );
  30134. // Normal Mapping Without Precomputed Tangents
  30135. // http://www.thetenthplanet.de/archives/1180
  30136. const perturbNormal2Arb = tslFn( ( inputs ) => {
  30137. const { eye_pos, surf_norm, mapN, uv } = inputs;
  30138. const q0 = eye_pos.dFdx();
  30139. const q1 = eye_pos.dFdy();
  30140. const st0 = uv.dFdx();
  30141. const st1 = uv.dFdy();
  30142. const N = surf_norm; // normalized
  30143. const q1perp = q1.cross( N );
  30144. const q0perp = N.cross( q0 );
  30145. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  30146. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  30147. const det = T.dot( T ).max( B.dot( B ) );
  30148. const scale = faceDirection.mul( det.inverseSqrt() );
  30149. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  30150. } );
  30151. class NormalMapNode extends TempNode {
  30152. constructor( node, scaleNode = null ) {
  30153. super( 'vec3' );
  30154. this.node = node;
  30155. this.scaleNode = scaleNode;
  30156. this.normalMapType = TangentSpaceNormalMap;
  30157. }
  30158. setup( builder ) {
  30159. const { normalMapType, scaleNode } = this;
  30160. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  30161. if ( scaleNode !== null ) {
  30162. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  30163. }
  30164. let outputNode = null;
  30165. if ( normalMapType === ObjectSpaceNormalMap ) {
  30166. outputNode = modelNormalMatrix.mul( normalMap ).normalize();
  30167. } else if ( normalMapType === TangentSpaceNormalMap ) {
  30168. const tangent = builder.hasGeometryAttribute( 'tangent' );
  30169. if ( tangent === true ) {
  30170. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  30171. } else {
  30172. outputNode = perturbNormal2Arb( {
  30173. eye_pos: positionView,
  30174. surf_norm: normalView,
  30175. mapN: normalMap,
  30176. uv: uv()
  30177. } );
  30178. }
  30179. }
  30180. return outputNode;
  30181. }
  30182. }
  30183. const normalMap = nodeProxy( NormalMapNode );
  30184. addNodeElement( 'normalMap', normalMap );
  30185. addNodeClass( 'NormalMapNode', NormalMapNode );
  30186. class PosterizeNode extends TempNode {
  30187. constructor( sourceNode, stepsNode ) {
  30188. super();
  30189. this.sourceNode = sourceNode;
  30190. this.stepsNode = stepsNode;
  30191. }
  30192. setup() {
  30193. const { sourceNode, stepsNode } = this;
  30194. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  30195. }
  30196. }
  30197. const posterize = nodeProxy( PosterizeNode );
  30198. addNodeElement( 'posterize', posterize );
  30199. addNodeClass( 'PosterizeNode', PosterizeNode );
  30200. // exposure only
  30201. const LinearToneMappingNode = tslFn( ( { color, exposure } ) => {
  30202. return color.mul( exposure ).clamp();
  30203. } );
  30204. // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
  30205. const ReinhardToneMappingNode = tslFn( ( { color, exposure } ) => {
  30206. color = color.mul( exposure );
  30207. return color.div( color.add( 1.0 ) ).clamp();
  30208. } );
  30209. // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
  30210. const OptimizedCineonToneMappingNode = tslFn( ( { color, exposure } ) => {
  30211. // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson
  30212. color = color.mul( exposure );
  30213. color = color.sub( 0.004 ).max( 0.0 );
  30214. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  30215. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  30216. return a.div( b ).pow( 2.2 );
  30217. } );
  30218. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  30219. const RRTAndODTFit = tslFn( ( { color } ) => {
  30220. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  30221. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  30222. return a.div( b );
  30223. } );
  30224. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  30225. const ACESFilmicToneMappingNode = tslFn( ( { color, exposure } ) => {
  30226. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  30227. const ACESInputMat = mat3(
  30228. 0.59719, 0.35458, 0.04823,
  30229. 0.07600, 0.90834, 0.01566,
  30230. 0.02840, 0.13383, 0.83777
  30231. );
  30232. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  30233. const ACESOutputMat = mat3(
  30234. 1.60475, - 0.53108, - 0.07367,
  30235. - 0.10208, 1.10813, - 0.00605,
  30236. - 0.00327, - 0.07276, 1.07602
  30237. );
  30238. color = color.mul( exposure ).div( 0.6 );
  30239. color = ACESInputMat.mul( color );
  30240. // Apply RRT and ODT
  30241. color = RRTAndODTFit( { color } );
  30242. color = ACESOutputMat.mul( color );
  30243. // Clamp to [0, 1]
  30244. return color.clamp();
  30245. } );
  30246. 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 ) );
  30247. 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 ) );
  30248. const agxDefaultContrastApprox = tslFn( ( [ x_immutable ] ) => {
  30249. const x = vec3( x_immutable ).toVar();
  30250. const x2 = vec3( x.mul( x ) ).toVar();
  30251. const x4 = vec3( x2.mul( x2 ) ).toVar();
  30252. 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 ) ) ) );
  30253. } );
  30254. const AGXToneMappingNode = tslFn( ( { color, exposure } ) => {
  30255. const colortone = vec3( color ).toVar();
  30256. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  30257. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  30258. const AgxMinEv = float( - 12.47393 );
  30259. const AgxMaxEv = float( 4.026069 );
  30260. colortone.mulAssign( exposure );
  30261. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  30262. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  30263. colortone.assign( max$1( colortone, 1e-10 ) );
  30264. colortone.assign( log2( colortone ) );
  30265. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  30266. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  30267. colortone.assign( agxDefaultContrastApprox( colortone ) );
  30268. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  30269. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  30270. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  30271. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  30272. return colortone;
  30273. } );
  30274. // https://modelviewer.dev/examples/tone-mapping
  30275. const NeutralToneMappingNode = tslFn( ( { color, exposure } ) => {
  30276. const StartCompression = float( 0.8 - 0.04 );
  30277. const Desaturation = float( 0.15 );
  30278. color = color.mul( exposure );
  30279. const x = min$1( color.r, min$1( color.g, color.b ) );
  30280. const offset = cond( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  30281. color.subAssign( offset );
  30282. const peak = max$1( color.r, max$1( color.g, color.b ) );
  30283. If( peak.lessThan( StartCompression ), () => {
  30284. return color;
  30285. } );
  30286. const d = sub( 1, StartCompression );
  30287. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  30288. color.mulAssign( newPeak.div( peak ) );
  30289. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  30290. return mix( color, vec3( newPeak ), g );
  30291. } ).setLayout( {
  30292. name: 'NeutralToneMapping',
  30293. type: 'vec3',
  30294. inputs: [
  30295. { name: 'color', type: 'vec3' },
  30296. { name: 'exposure', type: 'float' }
  30297. ]
  30298. } );
  30299. const toneMappingLib = {
  30300. [ LinearToneMapping ]: LinearToneMappingNode,
  30301. [ ReinhardToneMapping ]: ReinhardToneMappingNode,
  30302. [ CineonToneMapping ]: OptimizedCineonToneMappingNode,
  30303. [ ACESFilmicToneMapping ]: ACESFilmicToneMappingNode,
  30304. [ AgXToneMapping ]: AGXToneMappingNode,
  30305. [ NeutralToneMapping ]: NeutralToneMappingNode
  30306. };
  30307. class ToneMappingNode extends TempNode {
  30308. constructor( toneMapping = NoToneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  30309. super( 'vec3' );
  30310. this.toneMapping = toneMapping;
  30311. this.exposureNode = exposureNode;
  30312. this.colorNode = colorNode;
  30313. }
  30314. getCacheKey() {
  30315. let cacheKey = super.getCacheKey();
  30316. cacheKey = '{toneMapping:' + this.toneMapping + ',nodes:' + cacheKey + '}';
  30317. return cacheKey;
  30318. }
  30319. setup( builder ) {
  30320. const colorNode = this.colorNode || builder.context.color;
  30321. const toneMapping = this.toneMapping;
  30322. if ( toneMapping === NoToneMapping ) return colorNode;
  30323. const toneMappingParams = { exposure: this.exposureNode, color: colorNode };
  30324. const toneMappingNode = toneMappingLib[ toneMapping ];
  30325. let outputNode = null;
  30326. if ( toneMappingNode ) {
  30327. outputNode = toneMappingNode( toneMappingParams );
  30328. } else {
  30329. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  30330. outputNode = colorNode;
  30331. }
  30332. return outputNode;
  30333. }
  30334. }
  30335. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  30336. const toneMappingExposure = rendererReference( 'toneMappingExposure', 'float' );
  30337. addNodeElement( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  30338. addNodeClass( 'ToneMappingNode', ToneMappingNode );
  30339. let _sharedFramebuffer = null;
  30340. class ViewportSharedTextureNode extends ViewportTextureNode {
  30341. constructor( uvNode = viewportTopLeft, levelNode = null ) {
  30342. if ( _sharedFramebuffer === null ) {
  30343. _sharedFramebuffer = new FramebufferTexture();
  30344. }
  30345. super( uvNode, levelNode, _sharedFramebuffer );
  30346. }
  30347. updateReference() {
  30348. return this;
  30349. }
  30350. }
  30351. const viewportSharedTexture = nodeProxy( ViewportSharedTextureNode );
  30352. addNodeElement( 'viewportSharedTexture', viewportSharedTexture );
  30353. addNodeClass( 'ViewportSharedTextureNode', ViewportSharedTextureNode );
  30354. const _size$2 = new Vector2();
  30355. class PassTextureNode extends TextureNode {
  30356. constructor( passNode, texture ) {
  30357. super( texture );
  30358. this.passNode = passNode;
  30359. this.setUpdateMatrix( false );
  30360. }
  30361. setup( builder ) {
  30362. this.passNode.build( builder );
  30363. return super.setup( builder );
  30364. }
  30365. clone() {
  30366. return new this.constructor( this.passNode, this.value );
  30367. }
  30368. }
  30369. class PassNode extends TempNode {
  30370. constructor( scope, scene, camera ) {
  30371. super( 'vec4' );
  30372. this.scope = scope;
  30373. this.scene = scene;
  30374. this.camera = camera;
  30375. this._pixelRatio = 1;
  30376. this._width = 1;
  30377. this._height = 1;
  30378. const depthTexture = new DepthTexture();
  30379. depthTexture.isRenderTargetTexture = true;
  30380. //depthTexture.type = FloatType;
  30381. depthTexture.name = 'PostProcessingDepth';
  30382. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType } );
  30383. renderTarget.texture.name = 'PostProcessing';
  30384. renderTarget.depthTexture = depthTexture;
  30385. this.renderTarget = renderTarget;
  30386. this.updateBeforeType = NodeUpdateType.FRAME;
  30387. this._textureNode = nodeObject( new PassTextureNode( this, renderTarget.texture ) );
  30388. this._depthTextureNode = nodeObject( new PassTextureNode( this, depthTexture ) );
  30389. this._linearDepthNode = null;
  30390. this._viewZNode = null;
  30391. this._cameraNear = uniform( 0 );
  30392. this._cameraFar = uniform( 0 );
  30393. this.isPassNode = true;
  30394. }
  30395. isGlobal() {
  30396. return true;
  30397. }
  30398. getTextureNode() {
  30399. return this._textureNode;
  30400. }
  30401. getTextureDepthNode() {
  30402. return this._depthTextureNode;
  30403. }
  30404. getViewZNode() {
  30405. if ( this._viewZNode === null ) {
  30406. const cameraNear = this._cameraNear;
  30407. const cameraFar = this._cameraFar;
  30408. this._viewZNode = perspectiveDepthToViewZ( this._depthTextureNode, cameraNear, cameraFar );
  30409. }
  30410. return this._viewZNode;
  30411. }
  30412. getLinearDepthNode() {
  30413. if ( this._linearDepthNode === null ) {
  30414. const cameraNear = this._cameraNear;
  30415. const cameraFar = this._cameraFar;
  30416. // TODO: just if ( builder.camera.isPerspectiveCamera )
  30417. this._linearDepthNode = viewZToOrthographicDepth( this.getViewZNode(), cameraNear, cameraFar );
  30418. }
  30419. return this._linearDepthNode;
  30420. }
  30421. setup() {
  30422. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  30423. }
  30424. updateBefore( frame ) {
  30425. const { renderer } = frame;
  30426. const { scene, camera } = this;
  30427. this._pixelRatio = renderer.getPixelRatio();
  30428. const size = renderer.getSize( _size$2 );
  30429. this.setSize( size.width, size.height );
  30430. const currentToneMapping = renderer.toneMapping;
  30431. const currentToneMappingNode = renderer.toneMappingNode;
  30432. const currentRenderTarget = renderer.getRenderTarget();
  30433. this._cameraNear.value = camera.near;
  30434. this._cameraFar.value = camera.far;
  30435. renderer.toneMapping = NoToneMapping;
  30436. renderer.toneMappingNode = null;
  30437. renderer.setRenderTarget( this.renderTarget );
  30438. renderer.render( scene, camera );
  30439. renderer.toneMapping = currentToneMapping;
  30440. renderer.toneMappingNode = currentToneMappingNode;
  30441. renderer.setRenderTarget( currentRenderTarget );
  30442. }
  30443. setSize( width, height ) {
  30444. this._width = width;
  30445. this._height = height;
  30446. const effectiveWidth = this._width * this._pixelRatio;
  30447. const effectiveHeight = this._height * this._pixelRatio;
  30448. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  30449. }
  30450. setPixelRatio( pixelRatio ) {
  30451. this._pixelRatio = pixelRatio;
  30452. this.setSize( this._width, this._height );
  30453. }
  30454. dispose() {
  30455. this.renderTarget.dispose();
  30456. }
  30457. }
  30458. PassNode.COLOR = 'color';
  30459. PassNode.DEPTH = 'depth';
  30460. const pass = ( scene, camera ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera ) );
  30461. const texturePass = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  30462. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  30463. addNodeClass( 'PassNode', PassNode );
  30464. // Helper for passes that need to fill the viewport with a single quad.
  30465. const _camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  30466. // https://github.com/mrdoob/three.js/pull/21358
  30467. class QuadGeometry extends BufferGeometry {
  30468. constructor( flipY = false ) {
  30469. super();
  30470. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  30471. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  30472. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  30473. }
  30474. }
  30475. const _geometry = new QuadGeometry();
  30476. class QuadMesh extends Mesh {
  30477. constructor( material = null ) {
  30478. super( _geometry, material );
  30479. this.camera = _camera;
  30480. }
  30481. renderAsync( renderer ) {
  30482. return renderer.renderAsync( this, _camera );
  30483. }
  30484. render( renderer ) {
  30485. renderer.render( this, _camera );
  30486. }
  30487. }
  30488. // WebGPU: The use of a single QuadMesh for both gaussian blur passes results in a single RenderObject with a SampledTexture binding that
  30489. // alternates between source textures and triggers creation of new BindGroups and BindGroupLayouts every frame.
  30490. const quadMesh1 = new QuadMesh();
  30491. const quadMesh2 = new QuadMesh();
  30492. class GaussianBlurNode extends TempNode {
  30493. constructor( textureNode, sigma = 2 ) {
  30494. super( 'vec4' );
  30495. this.textureNode = textureNode;
  30496. this.sigma = sigma;
  30497. this.directionNode = vec2( 1 );
  30498. this._invSize = uniform( new Vector2() );
  30499. this._passDirection = uniform( new Vector2() );
  30500. this._horizontalRT = new RenderTarget();
  30501. this._horizontalRT.texture.name = 'GaussianBlurNode.horizontal';
  30502. this._verticalRT = new RenderTarget();
  30503. this._verticalRT.texture.name = 'GaussianBlurNode.vertical';
  30504. this._textureNode = texturePass( this, this._verticalRT.texture );
  30505. this.updateBeforeType = NodeUpdateType.RENDER;
  30506. this.resolution = new Vector2( 1, 1 );
  30507. }
  30508. setSize( width, height ) {
  30509. width = Math.max( Math.round( width * this.resolution.x ), 1 );
  30510. height = Math.max( Math.round( height * this.resolution.y ), 1 );
  30511. this._invSize.value.set( 1 / width, 1 / height );
  30512. this._horizontalRT.setSize( width, height );
  30513. this._verticalRT.setSize( width, height );
  30514. }
  30515. updateBefore( frame ) {
  30516. const { renderer } = frame;
  30517. const textureNode = this.textureNode;
  30518. const map = textureNode.value;
  30519. const currentRenderTarget = renderer.getRenderTarget();
  30520. const currentTexture = textureNode.value;
  30521. quadMesh1.material = this._material;
  30522. quadMesh2.material = this._material;
  30523. this.setSize( map.image.width, map.image.height );
  30524. const textureType = map.type;
  30525. this._horizontalRT.texture.type = textureType;
  30526. this._verticalRT.texture.type = textureType;
  30527. // horizontal
  30528. renderer.setRenderTarget( this._horizontalRT );
  30529. this._passDirection.value.set( 1, 0 );
  30530. quadMesh1.render( renderer );
  30531. // vertical
  30532. textureNode.value = this._horizontalRT.texture;
  30533. renderer.setRenderTarget( this._verticalRT );
  30534. this._passDirection.value.set( 0, 1 );
  30535. quadMesh2.render( renderer );
  30536. // restore
  30537. renderer.setRenderTarget( currentRenderTarget );
  30538. textureNode.value = currentTexture;
  30539. }
  30540. getTextureNode() {
  30541. return this._textureNode;
  30542. }
  30543. setup( builder ) {
  30544. const textureNode = this.textureNode;
  30545. if ( textureNode.isTextureNode !== true ) {
  30546. console.error( 'GaussianBlurNode requires a TextureNode.' );
  30547. return vec4();
  30548. }
  30549. //
  30550. const uvNode = textureNode.uvNode || uv();
  30551. const sampleTexture = ( uv ) => textureNode.cache().context( { getUV: () => uv, forceUVContext: true } );
  30552. const blur = tslFn( () => {
  30553. const kernelSize = 3 + ( 2 * this.sigma );
  30554. const gaussianCoefficients = this._getCoefficients( kernelSize );
  30555. const invSize = this._invSize;
  30556. const direction = vec2( this.directionNode ).mul( this._passDirection );
  30557. const weightSum = float( gaussianCoefficients[ 0 ] ).toVar();
  30558. const diffuseSum = vec4( sampleTexture( uvNode ).mul( weightSum ) ).toVar();
  30559. for ( let i = 1; i < kernelSize; i ++ ) {
  30560. const x = float( i );
  30561. const w = float( gaussianCoefficients[ i ] );
  30562. const uvOffset = vec2( direction.mul( invSize.mul( x ) ) ).toVar();
  30563. const sample1 = vec4( sampleTexture( uvNode.add( uvOffset ) ) );
  30564. const sample2 = vec4( sampleTexture( uvNode.sub( uvOffset ) ) );
  30565. diffuseSum.addAssign( sample1.add( sample2 ).mul( w ) );
  30566. weightSum.addAssign( mul( 2.0, w ) );
  30567. }
  30568. return diffuseSum.div( weightSum );
  30569. } );
  30570. //
  30571. const material = this._material || ( this._material = builder.createNodeMaterial() );
  30572. material.fragmentNode = blur();
  30573. //
  30574. const properties = builder.getNodeProperties( this );
  30575. properties.textureNode = textureNode;
  30576. //
  30577. return this._textureNode;
  30578. }
  30579. _getCoefficients( kernelRadius ) {
  30580. const coefficients = [];
  30581. for ( let i = 0; i < kernelRadius; i ++ ) {
  30582. coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( kernelRadius * kernelRadius ) ) / kernelRadius );
  30583. }
  30584. return coefficients;
  30585. }
  30586. }
  30587. const gaussianBlur = ( node, sigma ) => nodeObject( new GaussianBlurNode( nodeObject( node ), sigma ) );
  30588. addNodeElement( 'gaussianBlur', gaussianBlur );
  30589. const _size$1 = new Vector2();
  30590. const quadMeshComp = new QuadMesh();
  30591. class AfterImageNode extends TempNode {
  30592. constructor( textureNode, damp = 0.96 ) {
  30593. super( textureNode );
  30594. this.textureNode = textureNode;
  30595. this.textureNodeOld = texture();
  30596. this.damp = uniform( damp );
  30597. this._compRT = new RenderTarget();
  30598. this._compRT.texture.name = 'AfterImageNode.comp';
  30599. this._oldRT = new RenderTarget();
  30600. this._oldRT.texture.name = 'AfterImageNode.old';
  30601. this._textureNode = texturePass( this, this._compRT.texture );
  30602. this.updateBeforeType = NodeUpdateType.RENDER;
  30603. }
  30604. getTextureNode() {
  30605. return this._textureNode;
  30606. }
  30607. setSize( width, height ) {
  30608. this._compRT.setSize( width, height );
  30609. this._oldRT.setSize( width, height );
  30610. }
  30611. updateBefore( frame ) {
  30612. const { renderer } = frame;
  30613. const textureNode = this.textureNode;
  30614. const map = textureNode.value;
  30615. const textureType = map.type;
  30616. this._compRT.texture.type = textureType;
  30617. this._oldRT.texture.type = textureType;
  30618. renderer.getDrawingBufferSize( _size$1 );
  30619. this.setSize( _size$1.x, _size$1.y );
  30620. const currentToneMapping = renderer.toneMapping;
  30621. const currentToneMappingNode = renderer.toneMappingNode;
  30622. const currentRenderTarget = renderer.getRenderTarget();
  30623. const currentTexture = textureNode.value;
  30624. this.textureNodeOld.value = this._oldRT.texture;
  30625. // comp
  30626. renderer.toneMapping = NoToneMapping;
  30627. renderer.toneMappingNode = null;
  30628. renderer.setRenderTarget( this._compRT );
  30629. quadMeshComp.render( renderer );
  30630. // Swap the textures
  30631. const temp = this._oldRT;
  30632. this._oldRT = this._compRT;
  30633. this._compRT = temp;
  30634. renderer.toneMapping = currentToneMapping;
  30635. renderer.toneMappingNode = currentToneMappingNode;
  30636. renderer.setRenderTarget( currentRenderTarget );
  30637. textureNode.value = currentTexture;
  30638. }
  30639. setup( builder ) {
  30640. const textureNode = this.textureNode;
  30641. const textureNodeOld = this.textureNodeOld;
  30642. if ( textureNode.isTextureNode !== true ) {
  30643. console.error( 'AfterImageNode requires a TextureNode.' );
  30644. return vec4();
  30645. }
  30646. //
  30647. const uvNode = textureNode.uvNode || uv();
  30648. textureNodeOld.uvNode = uvNode;
  30649. const sampleTexture = ( uv ) => textureNode.cache().context( { getUV: () => uv, forceUVContext: true } );
  30650. const when_gt = tslFn( ( [ x_immutable, y_immutable ] ) => {
  30651. const y = float( y_immutable ).toVar();
  30652. const x = vec4( x_immutable ).toVar();
  30653. return max$1( sign( x.sub( y ) ), 0.0 );
  30654. } );
  30655. const afterImg = tslFn( () => {
  30656. const texelOld = vec4( textureNodeOld );
  30657. const texelNew = vec4( sampleTexture( uvNode ) );
  30658. texelOld.mulAssign( this.damp.mul( when_gt( texelOld, 0.1 ) ) );
  30659. return max$1( texelNew, texelOld );
  30660. } );
  30661. //
  30662. const materialComposed = this._materialComposed || ( this._materialComposed = builder.createNodeMaterial() );
  30663. materialComposed.fragmentNode = afterImg();
  30664. quadMeshComp.material = materialComposed;
  30665. //
  30666. const properties = builder.getNodeProperties( this );
  30667. properties.textureNode = textureNode;
  30668. //
  30669. return this._textureNode;
  30670. }
  30671. }
  30672. const afterImage = ( node, damp ) => nodeObject( new AfterImageNode( nodeObject( node ), damp ) );
  30673. addNodeElement( 'afterImage', afterImage );
  30674. const quadMesh$2 = new QuadMesh();
  30675. class AnamorphicNode extends TempNode {
  30676. constructor( textureNode, tresholdNode, scaleNode, samples ) {
  30677. super( 'vec4' );
  30678. this.textureNode = textureNode;
  30679. this.tresholdNode = tresholdNode;
  30680. this.scaleNode = scaleNode;
  30681. this.colorNode = vec3( 0.1, 0.0, 1.0 );
  30682. this.samples = samples;
  30683. this.resolution = new Vector2( 1, 1 );
  30684. this._renderTarget = new RenderTarget();
  30685. this._renderTarget.texture.name = 'anamorphic';
  30686. this._invSize = uniform( new Vector2() );
  30687. this._textureNode = texturePass( this, this._renderTarget.texture );
  30688. this.updateBeforeType = NodeUpdateType.RENDER;
  30689. }
  30690. getTextureNode() {
  30691. return this._textureNode;
  30692. }
  30693. setSize( width, height ) {
  30694. this._invSize.value.set( 1 / width, 1 / height );
  30695. width = Math.max( Math.round( width * this.resolution.x ), 1 );
  30696. height = Math.max( Math.round( height * this.resolution.y ), 1 );
  30697. this._renderTarget.setSize( width, height );
  30698. }
  30699. updateBefore( frame ) {
  30700. const { renderer } = frame;
  30701. const textureNode = this.textureNode;
  30702. const map = textureNode.value;
  30703. this._renderTarget.texture.type = map.type;
  30704. const currentRenderTarget = renderer.getRenderTarget();
  30705. const currentTexture = textureNode.value;
  30706. quadMesh$2.material = this._material;
  30707. this.setSize( map.image.width, map.image.height );
  30708. // render
  30709. renderer.setRenderTarget( this._renderTarget );
  30710. quadMesh$2.render( renderer );
  30711. // restore
  30712. renderer.setRenderTarget( currentRenderTarget );
  30713. textureNode.value = currentTexture;
  30714. }
  30715. setup( builder ) {
  30716. const textureNode = this.textureNode;
  30717. if ( textureNode.isTextureNode !== true ) {
  30718. console.error( 'AnamorphNode requires a TextureNode.' );
  30719. return vec4();
  30720. }
  30721. //
  30722. const uvNode = textureNode.uvNode || uv();
  30723. const sampleTexture = ( uv ) => textureNode.cache().context( { getUV: () => uv, forceUVContext: true } );
  30724. const anamorph = tslFn( () => {
  30725. const samples = this.samples;
  30726. const halfSamples = Math.floor( samples / 2 );
  30727. const total = vec3( 0 ).toVar();
  30728. loop( { start: - halfSamples, end: halfSamples }, ( { i } ) => {
  30729. const softness = float( i ).abs().div( halfSamples ).oneMinus();
  30730. const uv = vec2( uvNode.x.add( this._invSize.x.mul( i ).mul( this.scaleNode ) ), uvNode.y );
  30731. const color = sampleTexture( uv );
  30732. const pass = threshold( color, this.tresholdNode ).mul( softness );
  30733. total.addAssign( pass );
  30734. } );
  30735. return total.mul( this.colorNode );
  30736. } );
  30737. //
  30738. const material = this._material || ( this._material = builder.createNodeMaterial() );
  30739. material.fragmentNode = anamorph();
  30740. //
  30741. const properties = builder.getNodeProperties( this );
  30742. properties.textureNode = textureNode;
  30743. //
  30744. return this._textureNode;
  30745. }
  30746. }
  30747. const anamorphic = ( node, threshold = .9, scale = 3, samples = 32 ) => nodeObject( new AnamorphicNode( nodeObject( node ), nodeObject( threshold ), nodeObject( scale ), samples ) );
  30748. addNodeElement( 'anamorphic', anamorphic );
  30749. class SobelOperatorNode extends TempNode {
  30750. constructor( textureNode ) {
  30751. super();
  30752. this.textureNode = textureNode;
  30753. this.updateBeforeType = NodeUpdateType.RENDER;
  30754. this._invSize = uniform( new Vector2() );
  30755. }
  30756. updateBefore() {
  30757. const map = this.textureNode.value;
  30758. this._invSize.value.set( 1 / map.image.width, 1 / map.image.height );
  30759. }
  30760. setup() {
  30761. const { textureNode } = this;
  30762. const uvNode = textureNode.uvNode || uv();
  30763. const sampleTexture = ( uv ) => this.textureNode.cache().context( { getUV: () => uv, forceUVContext: true } );
  30764. const sobel = tslFn( () => {
  30765. // Sobel Edge Detection (see https://youtu.be/uihBwtPIBxM)
  30766. const texel = this._invSize;
  30767. // kernel definition (in glsl matrices are filled in column-major order)
  30768. const Gx = mat3( - 1, - 2, - 1, 0, 0, 0, 1, 2, 1 ); // x direction kernel
  30769. const Gy = mat3( - 1, 0, 1, - 2, 0, 2, - 1, 0, 1 ); // y direction kernel
  30770. // fetch the 3x3 neighbourhood of a fragment
  30771. // first column
  30772. const tx0y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, - 1 ) ) ) ).xyz );
  30773. const tx0y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, 0 ) ) ) ).xyz );
  30774. const tx0y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, 1 ) ) ) ).xyz );
  30775. // second column
  30776. const tx1y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, - 1 ) ) ) ).xyz );
  30777. const tx1y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, 0 ) ) ) ).xyz );
  30778. const tx1y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, 1 ) ) ) ).xyz );
  30779. // third column
  30780. const tx2y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, - 1 ) ) ) ).xyz );
  30781. const tx2y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, 0 ) ) ) ).xyz );
  30782. const tx2y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, 1 ) ) ) ).xyz );
  30783. // gradient value in x direction
  30784. const valueGx = add(
  30785. Gx[ 0 ][ 0 ].mul( tx0y0 ),
  30786. Gx[ 1 ][ 0 ].mul( tx1y0 ),
  30787. Gx[ 2 ][ 0 ].mul( tx2y0 ),
  30788. Gx[ 0 ][ 1 ].mul( tx0y1 ),
  30789. Gx[ 1 ][ 1 ].mul( tx1y1 ),
  30790. Gx[ 2 ][ 1 ].mul( tx2y1 ),
  30791. Gx[ 0 ][ 2 ].mul( tx0y2 ),
  30792. Gx[ 1 ][ 2 ].mul( tx1y2 ),
  30793. Gx[ 2 ][ 2 ].mul( tx2y2 )
  30794. );
  30795. // gradient value in y direction
  30796. const valueGy = add(
  30797. Gy[ 0 ][ 0 ].mul( tx0y0 ),
  30798. Gy[ 1 ][ 0 ].mul( tx1y0 ),
  30799. Gy[ 2 ][ 0 ].mul( tx2y0 ),
  30800. Gy[ 0 ][ 1 ].mul( tx0y1 ),
  30801. Gy[ 1 ][ 1 ].mul( tx1y1 ),
  30802. Gy[ 2 ][ 1 ].mul( tx2y1 ),
  30803. Gy[ 0 ][ 2 ].mul( tx0y2 ),
  30804. Gy[ 1 ][ 2 ].mul( tx1y2 ),
  30805. Gy[ 2 ][ 2 ].mul( tx2y2 )
  30806. );
  30807. // magnitute of the total gradient
  30808. const G = valueGx.mul( valueGx ).add( valueGy.mul( valueGy ) ).sqrt();
  30809. return vec4( vec3( G ), 1 );
  30810. } );
  30811. const outputNode = sobel();
  30812. return outputNode;
  30813. }
  30814. }
  30815. const sobel = ( node ) => nodeObject( new SobelOperatorNode( nodeObject( node ) ) );
  30816. addNodeElement( 'sobel', sobel );
  30817. class DepthOfFieldNode extends TempNode {
  30818. constructor( textureNode, viewZNode, focus = 1, aperture = 0.025, maxblur = 1 ) {
  30819. super();
  30820. this.textureNode = textureNode;
  30821. this.viewZNode = viewZNode;
  30822. this.focus = uniform( focus );
  30823. this.aperture = uniform( aperture );
  30824. this.maxblur = uniform( maxblur );
  30825. this._aspect = uniform( 0 );
  30826. this.updateBeforeType = NodeUpdateType.RENDER;
  30827. }
  30828. updateBefore() {
  30829. const map = this.textureNode.value;
  30830. this._aspect.value = map.image.width / map.image.height;
  30831. }
  30832. setup() {
  30833. const { textureNode } = this;
  30834. const uvNode = textureNode.uvNode || uv();
  30835. const sampleTexture = ( uv ) => this.textureNode.uv( uv );
  30836. const dof = tslFn( () => {
  30837. const aspectcorrect = vec2( 1.0, this._aspect );
  30838. const factor = this.focus.add( this.viewZNode );
  30839. const dofblur = vec2( clamp( factor.mul( this.aperture ), this.maxblur.negate(), this.maxblur ) );
  30840. const dofblur9 = dofblur.mul( 0.9 );
  30841. const dofblur7 = dofblur.mul( 0.7 );
  30842. const dofblur4 = dofblur.mul( 0.4 );
  30843. let col = vec4( 0.0 );
  30844. col = col.add( sampleTexture( uvNode ) );
  30845. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30846. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30847. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30848. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30849. col = col.add( sampleTexture( uvNode.add( vec2( 0.40, 0.0 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30850. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30851. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30852. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30853. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30854. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30855. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30856. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30857. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30858. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30859. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30860. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30861. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30862. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30863. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30864. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30865. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30866. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30867. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30868. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30869. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30870. col = col.add( sampleTexture( uvNode.add( vec2( 0.40, 0.0 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30871. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30872. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30873. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30874. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30875. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30876. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30877. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30878. col = col.add( sampleTexture( uvNode.add( vec2( 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30879. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30880. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30881. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30882. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30883. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30884. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30885. col = col.div( 41 );
  30886. col.a = 1;
  30887. return vec4( col );
  30888. } );
  30889. const outputNode = dof();
  30890. return outputNode;
  30891. }
  30892. }
  30893. const dof = ( node, viewZNode, focus, apeture, maxblur ) => nodeObject( new DepthOfFieldNode( nodeObject( node ), nodeObject( viewZNode ), focus, apeture, maxblur ) );
  30894. addNodeElement( 'dof', dof );
  30895. const quadMesh$1 = new QuadMesh();
  30896. class DotScreenNode extends TempNode {
  30897. constructor( colorNode, center = new Vector2( 0.5, 0.5 ), angle = 1.57, scale = 1 ) {
  30898. super( 'vec4' );
  30899. this.colorNode = colorNode;
  30900. this.center = uniform( center );
  30901. this.angle = uniform( angle );
  30902. this.scale = uniform( scale );
  30903. this._renderTarget = new RenderTarget();
  30904. this._renderTarget.texture.name = 'dotScreen';
  30905. this._size = uniform( new Vector2() );
  30906. this._textureNode = texturePass( this, this._renderTarget.texture );
  30907. this.updateBeforeType = NodeUpdateType.RENDER;
  30908. }
  30909. getTextureNode() {
  30910. return this._textureNode;
  30911. }
  30912. setSize( width, height ) {
  30913. this._size.value.set( width, height );
  30914. this._renderTarget.setSize( width, height );
  30915. }
  30916. updateBefore( frame ) {
  30917. const { renderer } = frame;
  30918. const colorNode = this.colorNode;
  30919. const map = colorNode.value;
  30920. this._renderTarget.texture.type = map.type;
  30921. const currentRenderTarget = renderer.getRenderTarget();
  30922. const currentTexture = colorNode.value;
  30923. quadMesh$1.material = this._material;
  30924. this.setSize( map.image.width, map.image.height );
  30925. // render
  30926. renderer.setRenderTarget( this._renderTarget );
  30927. quadMesh$1.render( renderer );
  30928. // restore
  30929. renderer.setRenderTarget( currentRenderTarget );
  30930. colorNode.value = currentTexture;
  30931. }
  30932. setup( builder ) {
  30933. const colorNode = this.colorNode;
  30934. const pattern = tslFn( () => {
  30935. const s = sin( this.angle );
  30936. const c = cos( this.angle );
  30937. const tex = uv().mul( this._size ).sub( this.center );
  30938. const point = vec2( c.mul( tex.x ).sub( s.mul( tex.y ) ), s.mul( tex.x ).add( c.mul( tex.y ) ) ).mul( this.scale );
  30939. return sin( point.x ).mul( sin( point.y ) ).mul( 4 );
  30940. } );
  30941. const dotScreen = tslFn( () => {
  30942. const color = colorNode;
  30943. const average = add( color.r, color.g, color.b ).div( 3 );
  30944. return vec4( vec3( average.mul( 10 ).sub( 5 ).add( pattern() ) ), color.a );
  30945. } );
  30946. //
  30947. const material = this._material || ( this._material = builder.createNodeMaterial() );
  30948. material.fragmentNode = dotScreen();
  30949. //
  30950. const properties = builder.getNodeProperties( this );
  30951. properties.textureNode = colorNode;
  30952. //
  30953. return this._textureNode;
  30954. }
  30955. }
  30956. const dotScreen = ( node, center, angle, scale ) => nodeObject( new DotScreenNode( nodeObject( node ), center, angle, scale ) );
  30957. addNodeElement( 'dotScreen', dotScreen );
  30958. class RGBShiftNode extends TempNode {
  30959. constructor( textureNode, amount = 0.005, angle = 0 ) {
  30960. super( 'vec4' );
  30961. this.textureNode = textureNode;
  30962. this.amount = uniform( amount );
  30963. this.angle = uniform( angle );
  30964. this.updateBeforeType = NodeUpdateType.RENDER;
  30965. }
  30966. updateBefore() {
  30967. }
  30968. setup() {
  30969. const { textureNode } = this;
  30970. const uvNode = textureNode.uvNode || uv();
  30971. const sampleTexture = ( uv ) => this.textureNode.uv( uv );
  30972. const rgbShift = tslFn( () => {
  30973. const offset = vec2( cos( this.angle ), sin( this.angle ) ).mul( this.amount );
  30974. const cr = sampleTexture( uvNode.add( offset ) );
  30975. const cga = sampleTexture( uvNode );
  30976. const cb = sampleTexture( uvNode.sub( offset ) );
  30977. return vec4( cr.r, cga.g, cb.b, cga.a );
  30978. } );
  30979. return rgbShift();
  30980. }
  30981. }
  30982. const rgbShift = ( node, amount, angle ) => nodeObject( new RGBShiftNode( nodeObject( node ), amount, angle ) );
  30983. addNodeElement( 'rgbShift', rgbShift );
  30984. class FunctionCallNode extends TempNode {
  30985. constructor( functionNode = null, parameters = {} ) {
  30986. super();
  30987. this.functionNode = functionNode;
  30988. this.parameters = parameters;
  30989. }
  30990. setParameters( parameters ) {
  30991. this.parameters = parameters;
  30992. return this;
  30993. }
  30994. getParameters() {
  30995. return this.parameters;
  30996. }
  30997. getNodeType( builder ) {
  30998. return this.functionNode.getNodeType( builder );
  30999. }
  31000. generate( builder ) {
  31001. const params = [];
  31002. const functionNode = this.functionNode;
  31003. const inputs = functionNode.getInputs( builder );
  31004. const parameters = this.parameters;
  31005. if ( Array.isArray( parameters ) ) {
  31006. for ( let i = 0; i < parameters.length; i ++ ) {
  31007. const inputNode = inputs[ i ];
  31008. const node = parameters[ i ];
  31009. params.push( node.build( builder, inputNode.type ) );
  31010. }
  31011. } else {
  31012. for ( const inputNode of inputs ) {
  31013. const node = parameters[ inputNode.name ];
  31014. if ( node !== undefined ) {
  31015. params.push( node.build( builder, inputNode.type ) );
  31016. } else {
  31017. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  31018. }
  31019. }
  31020. }
  31021. const functionName = functionNode.build( builder, 'property' );
  31022. return `${functionName}( ${params.join( ', ' )} )`;
  31023. }
  31024. }
  31025. const call = ( func, ...params ) => {
  31026. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  31027. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  31028. };
  31029. addNodeElement( 'call', call );
  31030. addNodeClass( 'FunctionCallNode', FunctionCallNode );
  31031. class ScriptableValueNode extends Node {
  31032. constructor( value = null ) {
  31033. super();
  31034. this._value = value;
  31035. this._cache = null;
  31036. this.inputType = null;
  31037. this.outpuType = null;
  31038. this.events = new EventDispatcher();
  31039. this.isScriptableValueNode = true;
  31040. }
  31041. get isScriptableOutputNode() {
  31042. return this.outputType !== null;
  31043. }
  31044. set value( val ) {
  31045. if ( this._value === val ) return;
  31046. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  31047. URL.revokeObjectURL( this._cache );
  31048. this._cache = null;
  31049. }
  31050. this._value = val;
  31051. this.events.dispatchEvent( { type: 'change' } );
  31052. this.refresh();
  31053. }
  31054. get value() {
  31055. return this._value;
  31056. }
  31057. refresh() {
  31058. this.events.dispatchEvent( { type: 'refresh' } );
  31059. }
  31060. getValue() {
  31061. const value = this.value;
  31062. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  31063. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  31064. } else if ( value && value.value !== null && value.value !== undefined && (
  31065. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  31066. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  31067. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  31068. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  31069. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  31070. ( this.inputType === 'Color' && value.value.isColor ) ||
  31071. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  31072. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  31073. ) ) {
  31074. return value.value;
  31075. }
  31076. return this._cache || value;
  31077. }
  31078. getNodeType( builder ) {
  31079. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  31080. }
  31081. setup() {
  31082. return this.value && this.value.isNode ? this.value : float();
  31083. }
  31084. serialize( data ) {
  31085. super.serialize( data );
  31086. if ( this.value !== null ) {
  31087. if ( this.inputType === 'ArrayBuffer' ) {
  31088. data.value = arrayBufferToBase64( this.value );
  31089. } else {
  31090. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  31091. }
  31092. } else {
  31093. data.value = null;
  31094. }
  31095. data.inputType = this.inputType;
  31096. data.outputType = this.outputType;
  31097. }
  31098. deserialize( data ) {
  31099. super.deserialize( data );
  31100. let value = null;
  31101. if ( data.value !== null ) {
  31102. if ( data.inputType === 'ArrayBuffer' ) {
  31103. value = base64ToArrayBuffer( data.value );
  31104. } else if ( data.inputType === 'Texture' ) {
  31105. value = data.meta.textures[ data.value ];
  31106. } else {
  31107. value = data.meta.nodes[ data.value ] || null;
  31108. }
  31109. }
  31110. this.value = value;
  31111. this.inputType = data.inputType;
  31112. this.outputType = data.outputType;
  31113. }
  31114. }
  31115. const scriptableValue = nodeProxy( ScriptableValueNode );
  31116. addNodeElement( 'scriptableValue', scriptableValue );
  31117. addNodeClass( 'ScriptableValueNode', ScriptableValueNode );
  31118. class Resources extends Map {
  31119. get( key, callback = null, ...params ) {
  31120. if ( this.has( key ) ) return super.get( key );
  31121. if ( callback !== null ) {
  31122. const value = callback( ...params );
  31123. this.set( key, value );
  31124. return value;
  31125. }
  31126. }
  31127. }
  31128. class Parameters {
  31129. constructor( scriptableNode ) {
  31130. this.scriptableNode = scriptableNode;
  31131. }
  31132. get parameters() {
  31133. return this.scriptableNode.parameters;
  31134. }
  31135. get layout() {
  31136. return this.scriptableNode.getLayout();
  31137. }
  31138. getInputLayout( id ) {
  31139. return this.scriptableNode.getInputLayout( id );
  31140. }
  31141. get( name ) {
  31142. const param = this.parameters[ name ];
  31143. const value = param ? param.getValue() : null;
  31144. return value;
  31145. }
  31146. }
  31147. const global = new Resources();
  31148. class ScriptableNode extends Node {
  31149. constructor( codeNode = null, parameters = {} ) {
  31150. super();
  31151. this.codeNode = codeNode;
  31152. this.parameters = parameters;
  31153. this._local = new Resources();
  31154. this._output = scriptableValue();
  31155. this._outputs = {};
  31156. this._source = this.source;
  31157. this._method = null;
  31158. this._object = null;
  31159. this._value = null;
  31160. this._needsOutputUpdate = true;
  31161. this.onRefresh = this.onRefresh.bind( this );
  31162. this.isScriptableNode = true;
  31163. }
  31164. get source() {
  31165. return this.codeNode ? this.codeNode.code : '';
  31166. }
  31167. setLocal( name, value ) {
  31168. return this._local.set( name, value );
  31169. }
  31170. getLocal( name ) {
  31171. return this._local.get( name );
  31172. }
  31173. onRefresh() {
  31174. this._refresh();
  31175. }
  31176. getInputLayout( id ) {
  31177. for ( const element of this.getLayout() ) {
  31178. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  31179. return element;
  31180. }
  31181. }
  31182. }
  31183. getOutputLayout( id ) {
  31184. for ( const element of this.getLayout() ) {
  31185. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  31186. return element;
  31187. }
  31188. }
  31189. }
  31190. setOutput( name, value ) {
  31191. const outputs = this._outputs;
  31192. if ( outputs[ name ] === undefined ) {
  31193. outputs[ name ] = scriptableValue( value );
  31194. } else {
  31195. outputs[ name ].value = value;
  31196. }
  31197. return this;
  31198. }
  31199. getOutput( name ) {
  31200. return this._outputs[ name ];
  31201. }
  31202. getParameter( name ) {
  31203. return this.parameters[ name ];
  31204. }
  31205. setParameter( name, value ) {
  31206. const parameters = this.parameters;
  31207. if ( value && value.isScriptableNode ) {
  31208. this.deleteParameter( name );
  31209. parameters[ name ] = value;
  31210. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  31211. } else if ( value && value.isScriptableValueNode ) {
  31212. this.deleteParameter( name );
  31213. parameters[ name ] = value;
  31214. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  31215. } else if ( parameters[ name ] === undefined ) {
  31216. parameters[ name ] = scriptableValue( value );
  31217. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  31218. } else {
  31219. parameters[ name ].value = value;
  31220. }
  31221. return this;
  31222. }
  31223. getValue() {
  31224. return this.getDefaultOutput().getValue();
  31225. }
  31226. deleteParameter( name ) {
  31227. let valueNode = this.parameters[ name ];
  31228. if ( valueNode ) {
  31229. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  31230. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  31231. }
  31232. return this;
  31233. }
  31234. clearParameters() {
  31235. for ( const name of Object.keys( this.parameters ) ) {
  31236. this.deleteParameter( name );
  31237. }
  31238. this.needsUpdate = true;
  31239. return this;
  31240. }
  31241. call( name, ...params ) {
  31242. const object = this.getObject();
  31243. const method = object[ name ];
  31244. if ( typeof method === 'function' ) {
  31245. return method( ...params );
  31246. }
  31247. }
  31248. async callAsync( name, ...params ) {
  31249. const object = this.getObject();
  31250. const method = object[ name ];
  31251. if ( typeof method === 'function' ) {
  31252. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  31253. }
  31254. }
  31255. getNodeType( builder ) {
  31256. return this.getDefaultOutputNode().getNodeType( builder );
  31257. }
  31258. refresh( output = null ) {
  31259. if ( output !== null ) {
  31260. this.getOutput( output ).refresh();
  31261. } else {
  31262. this._refresh();
  31263. }
  31264. }
  31265. getObject() {
  31266. if ( this.needsUpdate ) this.dispose();
  31267. if ( this._object !== null ) return this._object;
  31268. //
  31269. const refresh = () => this.refresh();
  31270. const setOutput = ( id, value ) => this.setOutput( id, value );
  31271. const parameters = new Parameters( this );
  31272. const THREE = global.get( 'THREE' );
  31273. const TSL = global.get( 'TSL' );
  31274. const method = this.getMethod( this.codeNode );
  31275. const params = [ parameters, this._local, global, refresh, setOutput, THREE, TSL ];
  31276. this._object = method( ...params );
  31277. const layout = this._object.layout;
  31278. if ( layout ) {
  31279. if ( layout.cache === false ) {
  31280. this._local.clear();
  31281. }
  31282. // default output
  31283. this._output.outputType = layout.outputType || null;
  31284. if ( Array.isArray( layout.elements ) ) {
  31285. for ( const element of layout.elements ) {
  31286. const id = element.id || element.name;
  31287. if ( element.inputType ) {
  31288. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  31289. this.getParameter( id ).inputType = element.inputType;
  31290. }
  31291. if ( element.outputType ) {
  31292. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  31293. this.getOutput( id ).outputType = element.outputType;
  31294. }
  31295. }
  31296. }
  31297. }
  31298. return this._object;
  31299. }
  31300. deserialize( data ) {
  31301. super.deserialize( data );
  31302. for ( const name in this.parameters ) {
  31303. let valueNode = this.parameters[ name ];
  31304. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  31305. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  31306. }
  31307. }
  31308. getLayout() {
  31309. return this.getObject().layout;
  31310. }
  31311. getDefaultOutputNode() {
  31312. const output = this.getDefaultOutput().value;
  31313. if ( output && output.isNode ) {
  31314. return output;
  31315. }
  31316. return float();
  31317. }
  31318. getDefaultOutput() {
  31319. return this._exec()._output;
  31320. }
  31321. getMethod() {
  31322. if ( this.needsUpdate ) this.dispose();
  31323. if ( this._method !== null ) return this._method;
  31324. //
  31325. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  31326. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  31327. const properties = interfaceProps.join( ', ' );
  31328. const declarations = 'var ' + properties + '; var output = {};\n';
  31329. const returns = '\nreturn { ...output, ' + properties + ' };';
  31330. const code = declarations + this.codeNode.code + returns;
  31331. //
  31332. this._method = new Function( ...parametersProps, code );
  31333. return this._method;
  31334. }
  31335. dispose() {
  31336. if ( this._method === null ) return;
  31337. if ( this._object && typeof this._object.dispose === 'function' ) {
  31338. this._object.dispose();
  31339. }
  31340. this._method = null;
  31341. this._object = null;
  31342. this._source = null;
  31343. this._value = null;
  31344. this._needsOutputUpdate = true;
  31345. this._output.value = null;
  31346. this._outputs = {};
  31347. }
  31348. setup() {
  31349. return this.getDefaultOutputNode();
  31350. }
  31351. set needsUpdate( value ) {
  31352. if ( value === true ) this.dispose();
  31353. }
  31354. get needsUpdate() {
  31355. return this.source !== this._source;
  31356. }
  31357. _exec() {
  31358. if ( this.codeNode === null ) return this;
  31359. if ( this._needsOutputUpdate === true ) {
  31360. this._value = this.call( 'main' );
  31361. this._needsOutputUpdate = false;
  31362. }
  31363. this._output.value = this._value;
  31364. return this;
  31365. }
  31366. _refresh() {
  31367. this.needsUpdate = true;
  31368. this._exec();
  31369. this._output.refresh();
  31370. }
  31371. }
  31372. const scriptable = nodeProxy( ScriptableNode );
  31373. addNodeElement( 'scriptable', scriptable );
  31374. addNodeClass( 'ScriptableNode', ScriptableNode );
  31375. class FogNode extends Node {
  31376. constructor( colorNode, factorNode ) {
  31377. super( 'float' );
  31378. this.isFogNode = true;
  31379. this.colorNode = colorNode;
  31380. this.factorNode = factorNode;
  31381. }
  31382. getViewZNode( builder ) {
  31383. let viewZ;
  31384. const getViewZ = builder.context.getViewZ;
  31385. if ( getViewZ !== undefined ) {
  31386. viewZ = getViewZ( this );
  31387. }
  31388. return ( viewZ || positionView.z ).negate();
  31389. }
  31390. setup() {
  31391. return this.factorNode;
  31392. }
  31393. }
  31394. const fog = nodeProxy( FogNode );
  31395. addNodeElement( 'fog', fog );
  31396. addNodeClass( 'FogNode', FogNode );
  31397. class FogRangeNode extends FogNode {
  31398. constructor( colorNode, nearNode, farNode ) {
  31399. super( colorNode );
  31400. this.isFogRangeNode = true;
  31401. this.nearNode = nearNode;
  31402. this.farNode = farNode;
  31403. }
  31404. setup( builder ) {
  31405. const viewZ = this.getViewZNode( builder );
  31406. return smoothstep( this.nearNode, this.farNode, viewZ );
  31407. }
  31408. }
  31409. const rangeFog = nodeProxy( FogRangeNode );
  31410. addNodeElement( 'rangeFog', rangeFog );
  31411. addNodeClass( 'FogRangeNode', FogRangeNode );
  31412. class FogExp2Node extends FogNode {
  31413. constructor( colorNode, densityNode ) {
  31414. super( colorNode );
  31415. this.isFogExp2Node = true;
  31416. this.densityNode = densityNode;
  31417. }
  31418. setup( builder ) {
  31419. const viewZ = this.getViewZNode( builder );
  31420. const density = this.densityNode;
  31421. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  31422. }
  31423. }
  31424. const densityFog = nodeProxy( FogExp2Node );
  31425. addNodeElement( 'densityFog', densityFog );
  31426. addNodeClass( 'FogExp2Node', FogExp2Node );
  31427. let min = null;
  31428. let max = null;
  31429. class RangeNode extends Node {
  31430. constructor( minNode = float(), maxNode = float() ) {
  31431. super();
  31432. this.minNode = minNode;
  31433. this.maxNode = maxNode;
  31434. }
  31435. getVectorLength( builder ) {
  31436. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  31437. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  31438. return minLength > maxLength ? minLength : maxLength;
  31439. }
  31440. getNodeType( builder ) {
  31441. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  31442. }
  31443. setup( builder ) {
  31444. const object = builder.object;
  31445. let output = null;
  31446. if ( object.count > 1 ) {
  31447. const minValue = this.minNode.value;
  31448. const maxValue = this.maxNode.value;
  31449. const minLength = builder.getTypeLength( getValueType( minValue ) );
  31450. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  31451. min = min || new Vector4();
  31452. max = max || new Vector4();
  31453. min.setScalar( 0 );
  31454. max.setScalar( 0 );
  31455. if ( minLength === 1 ) min.setScalar( minValue );
  31456. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  31457. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  31458. if ( maxLength === 1 ) max.setScalar( maxValue );
  31459. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  31460. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  31461. const stride = 4;
  31462. const length = stride * object.count;
  31463. const array = new Float32Array( length );
  31464. for ( let i = 0; i < length; i ++ ) {
  31465. const index = i % stride;
  31466. const minElementValue = min.getComponent( index );
  31467. const maxElementValue = max.getComponent( index );
  31468. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  31469. }
  31470. const nodeType = this.getNodeType( builder );
  31471. if ( object.count <= 4096 ) {
  31472. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  31473. } else {
  31474. // TODO: Improve anonymous buffer attribute creation removing this part
  31475. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  31476. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  31477. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  31478. }
  31479. } else {
  31480. output = float( 0 );
  31481. }
  31482. return output;
  31483. }
  31484. }
  31485. const range = nodeProxy( RangeNode );
  31486. addNodeClass( 'RangeNode', RangeNode );
  31487. class ComputeNode extends Node {
  31488. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  31489. super( 'void' );
  31490. this.isComputeNode = true;
  31491. this.computeNode = computeNode;
  31492. this.count = count;
  31493. this.workgroupSize = workgroupSize;
  31494. this.dispatchCount = 0;
  31495. this.version = 1;
  31496. this.updateBeforeType = NodeUpdateType.OBJECT;
  31497. this.updateDispatchCount();
  31498. }
  31499. dispose() {
  31500. this.dispatchEvent( { type: 'dispose' } );
  31501. }
  31502. set needsUpdate( value ) {
  31503. if ( value === true ) this.version ++;
  31504. }
  31505. updateDispatchCount() {
  31506. const { count, workgroupSize } = this;
  31507. let size = workgroupSize[ 0 ];
  31508. for ( let i = 1; i < workgroupSize.length; i ++ )
  31509. size *= workgroupSize[ i ];
  31510. this.dispatchCount = Math.ceil( count / size );
  31511. }
  31512. onInit() { }
  31513. updateBefore( { renderer } ) {
  31514. renderer.compute( this );
  31515. }
  31516. generate( builder ) {
  31517. const { shaderStage } = builder;
  31518. if ( shaderStage === 'compute' ) {
  31519. const snippet = this.computeNode.build( builder, 'void' );
  31520. if ( snippet !== '' ) {
  31521. builder.addLineFlowCode( snippet );
  31522. }
  31523. }
  31524. }
  31525. }
  31526. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  31527. addNodeElement( 'compute', compute );
  31528. addNodeClass( 'ComputeNode', ComputeNode );
  31529. class LightNode extends Node {
  31530. constructor( scope = LightNode.TARGET_DIRECTION, light = null ) {
  31531. super();
  31532. this.scope = scope;
  31533. this.light = light;
  31534. }
  31535. setup() {
  31536. const { scope, light } = this;
  31537. let output = null;
  31538. if ( scope === LightNode.TARGET_DIRECTION ) {
  31539. output = cameraViewMatrix.transformDirection( objectPosition( light ).sub( objectPosition( light.target ) ) );
  31540. }
  31541. return output;
  31542. }
  31543. serialize( data ) {
  31544. super.serialize( data );
  31545. data.scope = this.scope;
  31546. }
  31547. deserialize( data ) {
  31548. super.deserialize( data );
  31549. this.scope = data.scope;
  31550. }
  31551. }
  31552. LightNode.TARGET_DIRECTION = 'targetDirection';
  31553. const lightTargetDirection = nodeProxy( LightNode, LightNode.TARGET_DIRECTION );
  31554. addNodeClass( 'LightNode', LightNode );
  31555. const getDistanceAttenuation = tslFn( ( inputs ) => {
  31556. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  31557. // based upon Frostbite 3 Moving to Physically-based Rendering
  31558. // page 32, equation 26: E[window1]
  31559. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  31560. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  31561. return cutoffDistance.greaterThan( 0 ).cond(
  31562. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  31563. distanceFalloff
  31564. );
  31565. } ); // validated
  31566. class PointLightNode extends AnalyticLightNode {
  31567. constructor( light = null ) {
  31568. super( light );
  31569. this.cutoffDistanceNode = uniform( 0 );
  31570. this.decayExponentNode = uniform( 0 );
  31571. }
  31572. update( frame ) {
  31573. const { light } = this;
  31574. super.update( frame );
  31575. this.cutoffDistanceNode.value = light.distance;
  31576. this.decayExponentNode.value = light.decay;
  31577. }
  31578. setup( builder ) {
  31579. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  31580. const lightingModel = builder.context.lightingModel;
  31581. const lVector = objectViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  31582. const lightDirection = lVector.normalize();
  31583. const lightDistance = lVector.length();
  31584. const lightAttenuation = getDistanceAttenuation( {
  31585. lightDistance,
  31586. cutoffDistance: cutoffDistanceNode,
  31587. decayExponent: decayExponentNode
  31588. } );
  31589. const lightColor = colorNode.mul( lightAttenuation );
  31590. const reflectedLight = builder.context.reflectedLight;
  31591. lightingModel.direct( {
  31592. lightDirection,
  31593. lightColor,
  31594. reflectedLight,
  31595. shadowMask: this.shadowMaskNode
  31596. }, builder.stack, builder );
  31597. }
  31598. }
  31599. addNodeClass( 'PointLightNode', PointLightNode );
  31600. addLightNode( PointLight, PointLightNode );
  31601. class DirectionalLightNode extends AnalyticLightNode {
  31602. constructor( light = null ) {
  31603. super( light );
  31604. }
  31605. setup( builder ) {
  31606. super.setup( builder );
  31607. const lightingModel = builder.context.lightingModel;
  31608. const lightColor = this.colorNode;
  31609. const lightDirection = lightTargetDirection( this.light );
  31610. const reflectedLight = builder.context.reflectedLight;
  31611. lightingModel.direct( {
  31612. lightDirection,
  31613. lightColor,
  31614. reflectedLight,
  31615. shadowMask: this.shadowMaskNode
  31616. }, builder.stack, builder );
  31617. }
  31618. }
  31619. addNodeClass( 'DirectionalLightNode', DirectionalLightNode );
  31620. addLightNode( DirectionalLight, DirectionalLightNode );
  31621. const _matrix41 = new Matrix4();
  31622. const _matrix42 = new Matrix4();
  31623. let ltcLib = null;
  31624. class RectAreaLightNode extends AnalyticLightNode {
  31625. constructor( light = null ) {
  31626. super( light );
  31627. this.halfHeight = uniform( new Vector3() );
  31628. this.halfWidth = uniform( new Vector3() );
  31629. }
  31630. update( frame ) {
  31631. super.update( frame );
  31632. const { light } = this;
  31633. const viewMatrix = frame.camera.matrixWorldInverse;
  31634. _matrix42.identity();
  31635. _matrix41.copy( light.matrixWorld );
  31636. _matrix41.premultiply( viewMatrix );
  31637. _matrix42.extractRotation( _matrix41 );
  31638. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  31639. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  31640. this.halfWidth.value.applyMatrix4( _matrix42 );
  31641. this.halfHeight.value.applyMatrix4( _matrix42 );
  31642. }
  31643. setup( builder ) {
  31644. super.setup( builder );
  31645. let ltc_1, ltc_2;
  31646. if ( builder.isAvailable( 'float32Filterable' ) ) {
  31647. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  31648. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  31649. } else {
  31650. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  31651. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  31652. }
  31653. const { colorNode, light } = this;
  31654. const lightingModel = builder.context.lightingModel;
  31655. const lightPosition = objectViewPosition( light );
  31656. const reflectedLight = builder.context.reflectedLight;
  31657. lightingModel.directRectArea( {
  31658. lightColor: colorNode,
  31659. lightPosition,
  31660. halfWidth: this.halfWidth,
  31661. halfHeight: this.halfHeight,
  31662. reflectedLight,
  31663. ltc_1,
  31664. ltc_2
  31665. }, builder.stack, builder );
  31666. }
  31667. static setLTC( ltc ) {
  31668. ltcLib = ltc;
  31669. }
  31670. }
  31671. addNodeClass( 'RectAreaLightNode', RectAreaLightNode );
  31672. addLightNode( RectAreaLight, RectAreaLightNode );
  31673. class SpotLightNode extends AnalyticLightNode {
  31674. constructor( light = null ) {
  31675. super( light );
  31676. this.coneCosNode = uniform( 0 );
  31677. this.penumbraCosNode = uniform( 0 );
  31678. this.cutoffDistanceNode = uniform( 0 );
  31679. this.decayExponentNode = uniform( 0 );
  31680. }
  31681. update( frame ) {
  31682. super.update( frame );
  31683. const { light } = this;
  31684. this.coneCosNode.value = Math.cos( light.angle );
  31685. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  31686. this.cutoffDistanceNode.value = light.distance;
  31687. this.decayExponentNode.value = light.decay;
  31688. }
  31689. getSpotAttenuation( angleCosine ) {
  31690. const { coneCosNode, penumbraCosNode } = this;
  31691. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  31692. }
  31693. setup( builder ) {
  31694. super.setup( builder );
  31695. const lightingModel = builder.context.lightingModel;
  31696. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  31697. const lVector = objectViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  31698. const lightDirection = lVector.normalize();
  31699. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  31700. const spotAttenuation = this.getSpotAttenuation( angleCos );
  31701. const lightDistance = lVector.length();
  31702. const lightAttenuation = getDistanceAttenuation( {
  31703. lightDistance,
  31704. cutoffDistance: cutoffDistanceNode,
  31705. decayExponent: decayExponentNode
  31706. } );
  31707. const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  31708. const reflectedLight = builder.context.reflectedLight;
  31709. lightingModel.direct( {
  31710. lightDirection,
  31711. lightColor,
  31712. reflectedLight,
  31713. shadowMask: this.shadowMaskNode
  31714. }, builder.stack, builder );
  31715. }
  31716. }
  31717. addNodeClass( 'SpotLightNode', SpotLightNode );
  31718. addLightNode( SpotLight, SpotLightNode );
  31719. class IESSpotLight extends SpotLight {
  31720. constructor( color, intensity, distance, angle, penumbra, decay ) {
  31721. super( color, intensity, distance, angle, penumbra, decay );
  31722. this.iesMap = null;
  31723. }
  31724. copy( source, recursive ) {
  31725. super.copy( source, recursive );
  31726. this.iesMap = source.iesMap;
  31727. return this;
  31728. }
  31729. }
  31730. class IESSpotLightNode extends SpotLightNode {
  31731. getSpotAttenuation( angleCosine ) {
  31732. const iesMap = this.light.iesMap;
  31733. let spotAttenuation = null;
  31734. if ( iesMap && iesMap.isTexture === true ) {
  31735. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  31736. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  31737. } else {
  31738. spotAttenuation = super.getSpotAttenuation( angleCosine );
  31739. }
  31740. return spotAttenuation;
  31741. }
  31742. }
  31743. addNodeClass( 'IESSpotLightNode', IESSpotLightNode );
  31744. addLightNode( IESSpotLight, IESSpotLightNode );
  31745. class AmbientLightNode extends AnalyticLightNode {
  31746. constructor( light = null ) {
  31747. super( light );
  31748. }
  31749. setup( { context } ) {
  31750. context.irradiance.addAssign( this.colorNode );
  31751. }
  31752. }
  31753. addNodeClass( 'AmbientLightNode', AmbientLightNode );
  31754. addLightNode( AmbientLight, AmbientLightNode );
  31755. class HemisphereLightNode extends AnalyticLightNode {
  31756. constructor( light = null ) {
  31757. super( light );
  31758. this.lightPositionNode = objectPosition( light );
  31759. this.lightDirectionNode = this.lightPositionNode.normalize();
  31760. this.groundColorNode = uniform( new Color() );
  31761. }
  31762. update( frame ) {
  31763. const { light } = this;
  31764. super.update( frame );
  31765. this.lightPositionNode.object3d = light;
  31766. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  31767. }
  31768. setup( builder ) {
  31769. const { colorNode, groundColorNode, lightDirectionNode } = this;
  31770. const dotNL = normalView.dot( lightDirectionNode );
  31771. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  31772. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  31773. builder.context.irradiance.addAssign( irradiance );
  31774. }
  31775. }
  31776. addNodeClass( 'HemisphereLightNode', HemisphereLightNode );
  31777. addLightNode( HemisphereLight, HemisphereLightNode );
  31778. const checkerShaderNode = tslFn( ( inputs ) => {
  31779. const uv = inputs.uv.mul( 2.0 );
  31780. const cx = uv.x.floor();
  31781. const cy = uv.y.floor();
  31782. const result = cx.add( cy ).mod( 2.0 );
  31783. return result.sign();
  31784. } );
  31785. class CheckerNode extends TempNode {
  31786. constructor( uvNode = uv() ) {
  31787. super( 'float' );
  31788. this.uvNode = uvNode;
  31789. }
  31790. setup() {
  31791. return checkerShaderNode( { uv: this.uvNode } );
  31792. }
  31793. }
  31794. const checker = nodeProxy( CheckerNode );
  31795. addNodeElement( 'checker', checker );
  31796. addNodeClass( 'CheckerNode', CheckerNode );
  31797. class NodeLoader extends Loader {
  31798. constructor( manager ) {
  31799. super( manager );
  31800. this.textures = {};
  31801. }
  31802. load( url, onLoad, onProgress, onError ) {
  31803. const loader = new FileLoader( this.manager );
  31804. loader.setPath( this.path );
  31805. loader.setRequestHeader( this.requestHeader );
  31806. loader.setWithCredentials( this.withCredentials );
  31807. loader.load( url, ( text ) => {
  31808. try {
  31809. onLoad( this.parse( JSON.parse( text ) ) );
  31810. } catch ( e ) {
  31811. if ( onError ) {
  31812. onError( e );
  31813. } else {
  31814. console.error( e );
  31815. }
  31816. this.manager.itemError( url );
  31817. }
  31818. }, onProgress, onError );
  31819. }
  31820. parseNodes( json ) {
  31821. const nodes = {};
  31822. if ( json !== undefined ) {
  31823. for ( const nodeJSON of json ) {
  31824. const { uuid, type } = nodeJSON;
  31825. nodes[ uuid ] = nodeObject( createNodeFromType( type ) ); // @TODO: Maybe nodeObjectify the node in createNodeFromType?
  31826. nodes[ uuid ].uuid = uuid;
  31827. }
  31828. const meta = { nodes, textures: this.textures };
  31829. for ( const nodeJSON of json ) {
  31830. nodeJSON.meta = meta;
  31831. const node = nodes[ nodeJSON.uuid ];
  31832. node.deserialize( nodeJSON );
  31833. delete nodeJSON.meta;
  31834. }
  31835. }
  31836. return nodes;
  31837. }
  31838. parse( json ) {
  31839. const node = nodeObject( createNodeFromType( json.type ) );
  31840. node.uuid = json.uuid;
  31841. const nodes = this.parseNodes( json.nodes );
  31842. const meta = { nodes, textures: this.textures };
  31843. json.meta = meta;
  31844. node.deserialize( json );
  31845. delete json.meta;
  31846. return node;
  31847. }
  31848. setTextures( value ) {
  31849. this.textures = value;
  31850. return this;
  31851. }
  31852. }
  31853. const defaultValues$e = new PointsMaterial();
  31854. class InstancedPointsNodeMaterial extends NodeMaterial {
  31855. constructor( params = {} ) {
  31856. super();
  31857. this.normals = false;
  31858. this.lights = false;
  31859. this.useAlphaToCoverage = true;
  31860. this.useColor = params.vertexColors;
  31861. this.pointWidth = 1;
  31862. this.pointColorNode = null;
  31863. this.setDefaultValues( defaultValues$e );
  31864. this.setupShaders();
  31865. this.setValues( params );
  31866. }
  31867. setupShaders() {
  31868. const useAlphaToCoverage = this.alphaToCoverage;
  31869. const useColor = this.useColor;
  31870. this.vertexNode = tslFn( () => {
  31871. //vUv = uv;
  31872. varying( vec2(), 'vUv' ).assign( uv() ); // @TODO: Analyze other way to do this
  31873. const instancePosition = attribute( 'instancePosition' );
  31874. // camera space
  31875. const mvPos = property( 'vec4', 'mvPos' );
  31876. mvPos.assign( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  31877. const aspect = viewport.z.div( viewport.w );
  31878. // clip space
  31879. const clipPos = cameraProjectionMatrix.mul( mvPos );
  31880. // offset in ndc space
  31881. const offset = property( 'vec2', 'offset' );
  31882. offset.assign( positionGeometry.xy );
  31883. offset.assign( offset.mul( materialPointWidth ) );
  31884. offset.assign( offset.div( viewport.z ) );
  31885. offset.y.assign( offset.y.mul( aspect ) );
  31886. // back to clip space
  31887. offset.assign( offset.mul( clipPos.w ) );
  31888. //clipPos.xy += offset;
  31889. clipPos.assign( clipPos.add( vec4( offset, 0, 0 ) ) );
  31890. return clipPos;
  31891. //vec4 mvPosition = mvPos; // this was used for somethihng...
  31892. } )();
  31893. this.fragmentNode = tslFn( () => {
  31894. const vUv = varying( vec2(), 'vUv' );
  31895. // force assignment into correct place in flow
  31896. const alpha = property( 'float', 'alpha' );
  31897. alpha.assign( 1 );
  31898. const a = vUv.x;
  31899. const b = vUv.y;
  31900. const len2 = a.mul( a ).add( b.mul( b ) );
  31901. if ( useAlphaToCoverage ) {
  31902. // force assignment out of following 'if' statement - to avoid uniform control flow errors
  31903. const dlen = property( 'float', 'dlen' );
  31904. dlen.assign( len2.fwidth() );
  31905. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  31906. } else {
  31907. len2.greaterThan( 1.0 ).discard();
  31908. }
  31909. let pointColorNode;
  31910. if ( this.pointColorNode ) {
  31911. pointColorNode = this.pointColorNode;
  31912. } else {
  31913. if ( useColor ) {
  31914. const instanceColor = attribute( 'instanceColor' );
  31915. pointColorNode = instanceColor.mul( materialColor );
  31916. } else {
  31917. pointColorNode = materialColor;
  31918. }
  31919. }
  31920. return vec4( pointColorNode, alpha );
  31921. } )();
  31922. this.needsUpdate = true;
  31923. }
  31924. get alphaToCoverage() {
  31925. return this.useAlphaToCoverage;
  31926. }
  31927. set alphaToCoverage( value ) {
  31928. if ( this.useAlphaToCoverage !== value ) {
  31929. this.useAlphaToCoverage = value;
  31930. this.setupShaders();
  31931. }
  31932. }
  31933. }
  31934. addNodeMaterial( 'InstancedPointsNodeMaterial', InstancedPointsNodeMaterial );
  31935. const defaultValues$d = new LineBasicMaterial();
  31936. class LineBasicNodeMaterial extends NodeMaterial {
  31937. constructor( parameters ) {
  31938. super();
  31939. this.isLineBasicNodeMaterial = true;
  31940. this.lights = false;
  31941. this.normals = false;
  31942. this.setDefaultValues( defaultValues$d );
  31943. this.setValues( parameters );
  31944. }
  31945. }
  31946. addNodeMaterial( 'LineBasicNodeMaterial', LineBasicNodeMaterial );
  31947. const defaultValues$c = new LineDashedMaterial();
  31948. class LineDashedNodeMaterial extends NodeMaterial {
  31949. constructor( parameters ) {
  31950. super();
  31951. this.isLineDashedNodeMaterial = true;
  31952. this.lights = false;
  31953. this.normals = false;
  31954. this.setDefaultValues( defaultValues$c );
  31955. this.offsetNode = null;
  31956. this.dashScaleNode = null;
  31957. this.dashSizeNode = null;
  31958. this.gapSizeNode = null;
  31959. this.setValues( parameters );
  31960. }
  31961. setupVariants() {
  31962. const offsetNode = this.offsetNode;
  31963. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  31964. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  31965. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  31966. dashSize.assign( dashSizeNode );
  31967. gapSize.assign( gapSizeNode );
  31968. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  31969. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  31970. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  31971. }
  31972. }
  31973. addNodeMaterial( 'LineDashedNodeMaterial', LineDashedNodeMaterial );
  31974. const defaultValues$b = new LineDashedMaterial();
  31975. class Line2NodeMaterial extends NodeMaterial {
  31976. constructor( params = {} ) {
  31977. super();
  31978. this.normals = false;
  31979. this.lights = false;
  31980. this.setDefaultValues( defaultValues$b );
  31981. this.useAlphaToCoverage = true;
  31982. this.useColor = params.vertexColors;
  31983. this.useDash = params.dashed;
  31984. this.useWorldUnits = false;
  31985. this.dashOffset = 0;
  31986. this.lineWidth = 1;
  31987. this.lineColorNode = null;
  31988. this.offsetNode = null;
  31989. this.dashScaleNode = null;
  31990. this.dashSizeNode = null;
  31991. this.gapSizeNode = null;
  31992. this.setValues( params );
  31993. }
  31994. setup( builder ) {
  31995. this.setupShaders();
  31996. super.setup( builder );
  31997. }
  31998. setupShaders() {
  31999. const useAlphaToCoverage = this.alphaToCoverage;
  32000. const useColor = this.useColor;
  32001. const useDash = this.dashed;
  32002. const useWorldUnits = this.worldUnits;
  32003. const trimSegment = tslFn( ( { start, end } ) => {
  32004. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  32005. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  32006. const nearEstimate = b.mul( - 0.5 ).div( a );
  32007. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  32008. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  32009. } );
  32010. this.vertexNode = tslFn( () => {
  32011. varyingProperty( 'vec2', 'vUv' ).assign( uv() );
  32012. const instanceStart = attribute( 'instanceStart' );
  32013. const instanceEnd = attribute( 'instanceEnd' );
  32014. // camera space
  32015. const start = property( 'vec4', 'start' );
  32016. const end = property( 'vec4', 'end' );
  32017. start.assign( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ); // force assignment into correct place in flow
  32018. end.assign( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) );
  32019. if ( useWorldUnits ) {
  32020. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  32021. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  32022. }
  32023. const aspect = viewport.z.div( viewport.w );
  32024. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  32025. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  32026. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  32027. // perhaps there is a more elegant solution -- WestLangley
  32028. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  32029. If( perspective, () => {
  32030. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  32031. end.assign( trimSegment( { start: start, end: end } ) );
  32032. } ).elseif( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  32033. start.assign( trimSegment( { start: end, end: start } ) );
  32034. } );
  32035. } );
  32036. // clip space
  32037. const clipStart = cameraProjectionMatrix.mul( start );
  32038. const clipEnd = cameraProjectionMatrix.mul( end );
  32039. // ndc space
  32040. const ndcStart = clipStart.xyz.div( clipStart.w );
  32041. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  32042. // direction
  32043. const dir = ndcEnd.xy.sub( ndcStart.xy ).temp();
  32044. // account for clip-space aspect ratio
  32045. dir.x.assign( dir.x.mul( aspect ) );
  32046. dir.assign( dir.normalize() );
  32047. const clip = temp( vec4() );
  32048. if ( useWorldUnits ) {
  32049. // get the offset direction as perpendicular to the view vector
  32050. const worldDir = end.xyz.sub( start.xyz ).normalize();
  32051. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  32052. const worldUp = worldDir.cross( tmpFwd ).normalize();
  32053. const worldFwd = worldDir.cross( worldUp );
  32054. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  32055. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).cond( start, end ) );
  32056. // height offset
  32057. const hw = materialLineWidth.mul( 0.5 );
  32058. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).cond( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  32059. // don't extend the line if we're rendering dashes because we
  32060. // won't be rendering the endcaps
  32061. if ( ! useDash ) {
  32062. // cap extension
  32063. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).cond( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  32064. // add width to the box
  32065. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  32066. // endcaps
  32067. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  32068. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  32069. } );
  32070. }
  32071. // project the worldpos
  32072. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  32073. // shift the depth of the projected points so the line
  32074. // segments overlap neatly
  32075. const clipPose = temp( vec3() );
  32076. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).cond( ndcStart, ndcEnd ) );
  32077. clip.z.assign( clipPose.z.mul( clip.w ) );
  32078. } else {
  32079. const offset = property( 'vec2', 'offset' );
  32080. offset.assign( vec2( dir.y, dir.x.negate() ) );
  32081. // undo aspect ratio adjustment
  32082. dir.x.assign( dir.x.div( aspect ) );
  32083. offset.x.assign( offset.x.div( aspect ) );
  32084. // sign flip
  32085. offset.assign( positionGeometry.x.lessThan( 0.0 ).cond( offset.negate(), offset ) );
  32086. // endcaps
  32087. If( positionGeometry.y.lessThan( 0.0 ), () => {
  32088. offset.assign( offset.sub( dir ) );
  32089. } ).elseif( positionGeometry.y.greaterThan( 1.0 ), () => {
  32090. offset.assign( offset.add( dir ) );
  32091. } );
  32092. // adjust for linewidth
  32093. offset.assign( offset.mul( materialLineWidth ) );
  32094. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  32095. offset.assign( offset.div( viewport.w ) );
  32096. // select end
  32097. clip.assign( positionGeometry.y.lessThan( 0.5 ).cond( clipStart, clipEnd ) );
  32098. // back to clip space
  32099. offset.assign( offset.mul( clip.w ) );
  32100. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  32101. }
  32102. return clip;
  32103. } )();
  32104. const closestLineToLine = tslFn( ( { p1, p2, p3, p4 } ) => {
  32105. const p13 = p1.sub( p3 );
  32106. const p43 = p4.sub( p3 );
  32107. const p21 = p2.sub( p1 );
  32108. const d1343 = p13.dot( p43 );
  32109. const d4321 = p43.dot( p21 );
  32110. const d1321 = p13.dot( p21 );
  32111. const d4343 = p43.dot( p43 );
  32112. const d2121 = p21.dot( p21 );
  32113. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  32114. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  32115. const mua = numer.div( denom ).clamp();
  32116. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  32117. return vec2( mua, mub );
  32118. } );
  32119. this.fragmentNode = tslFn( () => {
  32120. const vUv = varyingProperty( 'vec2', 'vUv' );
  32121. if ( useDash ) {
  32122. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  32123. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  32124. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  32125. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  32126. dashSize.assign( dashSizeNode );
  32127. gapSize.assign( gapSizeNode );
  32128. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  32129. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  32130. const lineDistance = positionGeometry.y.lessThan( 0.5 ).cond( dashScaleNode.mul( instanceDistanceStart ), materialLineScale.mul( instanceDistanceEnd ) );
  32131. const vLineDistance = varying( lineDistance.add( materialLineDashOffset ) );
  32132. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  32133. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  32134. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  32135. }
  32136. // force assignment into correct place in flow
  32137. const alpha = property( 'float', 'alpha' );
  32138. alpha.assign( 1 );
  32139. if ( useWorldUnits ) {
  32140. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  32141. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  32142. // Find the closest points on the view ray and the line segment
  32143. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  32144. const lineDir = worldEnd.sub( worldStart );
  32145. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  32146. const p1 = worldStart.add( lineDir.mul( params.x ) );
  32147. const p2 = rayEnd.mul( params.y );
  32148. const delta = p1.sub( p2 );
  32149. const len = delta.length();
  32150. const norm = len.div( materialLineWidth );
  32151. if ( ! useDash ) {
  32152. if ( useAlphaToCoverage ) {
  32153. const dnorm = norm.fwidth();
  32154. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  32155. } else {
  32156. norm.greaterThan( 0.5 ).discard();
  32157. }
  32158. }
  32159. } else {
  32160. // round endcaps
  32161. if ( useAlphaToCoverage ) {
  32162. const a = vUv.x;
  32163. const b = vUv.y.greaterThan( 0.0 ).cond( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  32164. const len2 = a.mul( a ).add( b.mul( b ) );
  32165. // force assignment out of following 'if' statement - to avoid uniform control flow errors
  32166. const dlen = property( 'float', 'dlen' );
  32167. dlen.assign( len2.fwidth() );
  32168. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  32169. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  32170. } );
  32171. } else {
  32172. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  32173. const a = vUv.x;
  32174. const b = vUv.y.greaterThan( 0.0 ).cond( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  32175. const len2 = a.mul( a ).add( b.mul( b ) );
  32176. len2.greaterThan( 1.0 ).discard();
  32177. } );
  32178. }
  32179. }
  32180. let lineColorNode;
  32181. if ( this.lineColorNode ) {
  32182. lineColorNode = this.lineColorNode;
  32183. } else {
  32184. if ( useColor ) {
  32185. const instanceColorStart = attribute( 'instanceColorStart' );
  32186. const instanceColorEnd = attribute( 'instanceColorEnd' );
  32187. const instanceColor = positionGeometry.y.lessThan( 0.5 ).cond( instanceColorStart, instanceColorEnd );
  32188. lineColorNode = instanceColor.mul( materialColor );
  32189. } else {
  32190. lineColorNode = materialColor;
  32191. }
  32192. }
  32193. return vec4( lineColorNode, alpha );
  32194. } )();
  32195. }
  32196. get worldUnits() {
  32197. return this.useWorldUnits;
  32198. }
  32199. set worldUnits( value ) {
  32200. if ( this.useWorldUnits !== value ) {
  32201. this.useWorldUnits = value;
  32202. this.needsUpdate = true;
  32203. }
  32204. }
  32205. get dashed() {
  32206. return this.useDash;
  32207. }
  32208. set dashed( value ) {
  32209. if ( this.useDash !== value ) {
  32210. this.useDash = value;
  32211. this.needsUpdate = true;
  32212. }
  32213. }
  32214. get alphaToCoverage() {
  32215. return this.useAlphaToCoverage;
  32216. }
  32217. set alphaToCoverage( value ) {
  32218. if ( this.useAlphaToCoverage !== value ) {
  32219. this.useAlphaToCoverage = value;
  32220. this.needsUpdate = true;
  32221. }
  32222. }
  32223. }
  32224. addNodeMaterial( 'Line2NodeMaterial', Line2NodeMaterial );
  32225. const defaultValues$a = new MeshNormalMaterial();
  32226. class MeshNormalNodeMaterial extends NodeMaterial {
  32227. constructor( parameters ) {
  32228. super();
  32229. this.lights = false;
  32230. this.isMeshNormalNodeMaterial = true;
  32231. this.setDefaultValues( defaultValues$a );
  32232. this.setValues( parameters );
  32233. }
  32234. setupDiffuseColor() {
  32235. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  32236. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  32237. }
  32238. }
  32239. addNodeMaterial( 'MeshNormalNodeMaterial', MeshNormalNodeMaterial );
  32240. const defaultValues$9 = new MeshBasicMaterial();
  32241. class MeshBasicNodeMaterial extends NodeMaterial {
  32242. constructor( parameters ) {
  32243. super();
  32244. this.isMeshBasicNodeMaterial = true;
  32245. this.lights = false;
  32246. //this.normals = false; @TODO: normals usage by context
  32247. this.setDefaultValues( defaultValues$9 );
  32248. this.setValues( parameters );
  32249. }
  32250. }
  32251. addNodeMaterial( 'MeshBasicNodeMaterial', MeshBasicNodeMaterial );
  32252. const F_Schlick = tslFn( ( { f0, f90, dotVH } ) => {
  32253. // Original approximation by Christophe Schlick '94
  32254. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  32255. // Optimized variant (presented by Epic at SIGGRAPH '13)
  32256. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  32257. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  32258. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  32259. } ); // validated
  32260. const BRDF_Lambert = tslFn( ( inputs ) => {
  32261. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  32262. } ); // validated
  32263. const G_BlinnPhong_Implicit = () => float( 0.25 );
  32264. const D_BlinnPhong = tslFn( ( { dotNH } ) => {
  32265. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  32266. } );
  32267. const BRDF_BlinnPhong = tslFn( ( { lightDirection } ) => {
  32268. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  32269. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  32270. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  32271. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  32272. const G = G_BlinnPhong_Implicit();
  32273. const D = D_BlinnPhong( { dotNH } );
  32274. return F.mul( G ).mul( D );
  32275. } );
  32276. class PhongLightingModel extends LightingModel {
  32277. constructor( specular = true ) {
  32278. super();
  32279. this.specular = specular;
  32280. }
  32281. direct( { lightDirection, lightColor, reflectedLight } ) {
  32282. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  32283. const irradiance = dotNL.mul( lightColor );
  32284. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  32285. if ( this.specular === true ) {
  32286. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  32287. }
  32288. }
  32289. indirectDiffuse( { irradiance, reflectedLight } ) {
  32290. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  32291. }
  32292. }
  32293. const defaultValues$8 = new MeshLambertMaterial();
  32294. class MeshLambertNodeMaterial extends NodeMaterial {
  32295. constructor( parameters ) {
  32296. super();
  32297. this.isMeshLambertNodeMaterial = true;
  32298. this.lights = true;
  32299. this.setDefaultValues( defaultValues$8 );
  32300. this.setValues( parameters );
  32301. }
  32302. setupLightingModel( /*builder*/ ) {
  32303. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  32304. }
  32305. }
  32306. addNodeMaterial( 'MeshLambertNodeMaterial', MeshLambertNodeMaterial );
  32307. const defaultValues$7 = new MeshPhongMaterial();
  32308. class MeshPhongNodeMaterial extends NodeMaterial {
  32309. constructor( parameters ) {
  32310. super();
  32311. this.isMeshPhongNodeMaterial = true;
  32312. this.lights = true;
  32313. this.shininessNode = null;
  32314. this.specularNode = null;
  32315. this.setDefaultValues( defaultValues$7 );
  32316. this.setValues( parameters );
  32317. }
  32318. setupLightingModel( /*builder*/ ) {
  32319. return new PhongLightingModel();
  32320. }
  32321. setupVariants() {
  32322. // SHININESS
  32323. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  32324. shininess.assign( shininessNode );
  32325. // SPECULAR COLOR
  32326. const specularNode = this.specularNode || materialSpecular;
  32327. specularColor.assign( specularNode );
  32328. }
  32329. copy( source ) {
  32330. this.shininessNode = source.shininessNode;
  32331. this.specularNode = source.specularNode;
  32332. return super.copy( source );
  32333. }
  32334. }
  32335. addNodeMaterial( 'MeshPhongNodeMaterial', MeshPhongNodeMaterial );
  32336. const getGeometryRoughness = tslFn( () => {
  32337. const dxy = normalGeometry.dFdx().abs().max( normalGeometry.dFdy().abs() );
  32338. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  32339. return geometryRoughness;
  32340. } );
  32341. const getRoughness = tslFn( ( inputs ) => {
  32342. const { roughness } = inputs;
  32343. const geometryRoughness = getGeometryRoughness();
  32344. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  32345. roughnessFactor = roughnessFactor.add( geometryRoughness );
  32346. roughnessFactor = roughnessFactor.min( 1.0 );
  32347. return roughnessFactor;
  32348. } );
  32349. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  32350. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  32351. const V_GGX_SmithCorrelated = tslFn( ( { alpha, dotNL, dotNV } ) => {
  32352. const a2 = alpha.pow2();
  32353. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  32354. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  32355. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  32356. } ).setLayout( {
  32357. name: 'V_GGX_SmithCorrelated',
  32358. type: 'float',
  32359. inputs: [
  32360. { name: 'alpha', type: 'float' },
  32361. { name: 'dotNL', type: 'float' },
  32362. { name: 'dotNV', type: 'float' }
  32363. ]
  32364. } ); // validated
  32365. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  32366. const V_GGX_SmithCorrelated_Anisotropic = tslFn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  32367. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  32368. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  32369. const v = div( 0.5, gv.add( gl ) );
  32370. return v.saturate();
  32371. } ).setLayout( {
  32372. name: 'V_GGX_SmithCorrelated_Anisotropic',
  32373. type: 'float',
  32374. inputs: [
  32375. { name: 'alphaT', type: 'float', qualifier: 'in' },
  32376. { name: 'alphaB', type: 'float', qualifier: 'in' },
  32377. { name: 'dotTV', type: 'float', qualifier: 'in' },
  32378. { name: 'dotBV', type: 'float', qualifier: 'in' },
  32379. { name: 'dotTL', type: 'float', qualifier: 'in' },
  32380. { name: 'dotBL', type: 'float', qualifier: 'in' },
  32381. { name: 'dotNV', type: 'float', qualifier: 'in' },
  32382. { name: 'dotNL', type: 'float', qualifier: 'in' }
  32383. ]
  32384. } );
  32385. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  32386. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  32387. // alpha is "roughness squared" in Disney’s reparameterization
  32388. const D_GGX = tslFn( ( { alpha, dotNH } ) => {
  32389. const a2 = alpha.pow2();
  32390. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  32391. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  32392. } ).setLayout( {
  32393. name: 'D_GGX',
  32394. type: 'float',
  32395. inputs: [
  32396. { name: 'alpha', type: 'float' },
  32397. { name: 'dotNH', type: 'float' }
  32398. ]
  32399. } ); // validated
  32400. const RECIPROCAL_PI = float( 1 / Math.PI );
  32401. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  32402. const D_GGX_Anisotropic = tslFn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  32403. const a2 = alphaT.mul( alphaB );
  32404. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  32405. const v2 = v.dot( v );
  32406. const w2 = a2.div( v2 );
  32407. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  32408. } ).setLayout( {
  32409. name: 'D_GGX_Anisotropic',
  32410. type: 'float',
  32411. inputs: [
  32412. { name: 'alphaT', type: 'float', qualifier: 'in' },
  32413. { name: 'alphaB', type: 'float', qualifier: 'in' },
  32414. { name: 'dotNH', type: 'float', qualifier: 'in' },
  32415. { name: 'dotTH', type: 'float', qualifier: 'in' },
  32416. { name: 'dotBH', type: 'float', qualifier: 'in' }
  32417. ]
  32418. } );
  32419. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  32420. const BRDF_GGX = tslFn( ( inputs ) => {
  32421. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  32422. const normalView = inputs.normalView || transformedNormalView;
  32423. const alpha = roughness.pow2(); // UE4's roughness
  32424. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  32425. const dotNL = normalView.dot( lightDirection ).clamp();
  32426. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  32427. const dotNH = normalView.dot( halfDir ).clamp();
  32428. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  32429. let F = F_Schlick( { f0, f90, dotVH } );
  32430. let V, D;
  32431. if ( defined( USE_IRIDESCENCE ) ) {
  32432. F = iridescence.mix( F, f );
  32433. }
  32434. if ( defined( USE_ANISOTROPY ) ) {
  32435. const dotTL = anisotropyT.dot( lightDirection );
  32436. const dotTV = anisotropyT.dot( positionViewDirection );
  32437. const dotTH = anisotropyT.dot( halfDir );
  32438. const dotBL = anisotropyB.dot( lightDirection );
  32439. const dotBV = anisotropyB.dot( positionViewDirection );
  32440. const dotBH = anisotropyB.dot( halfDir );
  32441. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  32442. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  32443. } else {
  32444. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  32445. D = D_GGX( { alpha, dotNH } );
  32446. }
  32447. return F.mul( V ).mul( D );
  32448. } ); // validated
  32449. // Analytical approximation of the DFG LUT, one half of the
  32450. // split-sum approximation used in indirect specular lighting.
  32451. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  32452. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  32453. const DFGApprox = tslFn( ( { roughness, dotNV } ) => {
  32454. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  32455. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  32456. const r = roughness.mul( c0 ).add( c1 );
  32457. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  32458. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  32459. return fab;
  32460. } ).setLayout( {
  32461. name: 'DFGApprox',
  32462. type: 'vec2',
  32463. inputs: [
  32464. { name: 'roughness', type: 'float' },
  32465. { name: 'dotNV', type: 'vec3' }
  32466. ]
  32467. } );
  32468. const EnvironmentBRDF = tslFn( ( inputs ) => {
  32469. const { dotNV, specularColor, specularF90, roughness } = inputs;
  32470. const fab = DFGApprox( { dotNV, roughness } );
  32471. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  32472. } );
  32473. const Schlick_to_F0 = tslFn( ( { f, f90, dotVH } ) => {
  32474. const x = dotVH.oneMinus().saturate();
  32475. const x2 = x.mul( x );
  32476. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  32477. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  32478. } ).setLayout( {
  32479. name: 'Schlick_to_F0',
  32480. type: 'vec3',
  32481. inputs: [
  32482. { name: 'f', type: 'vec3' },
  32483. { name: 'f90', type: 'float' },
  32484. { name: 'dotVH', type: 'float' }
  32485. ]
  32486. } );
  32487. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  32488. const D_Charlie = tslFn( ( { roughness, dotNH } ) => {
  32489. const alpha = roughness.pow2();
  32490. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  32491. const invAlpha = float( 1.0 ).div( alpha );
  32492. const cos2h = dotNH.pow2();
  32493. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  32494. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  32495. } ).setLayout( {
  32496. name: 'D_Charlie',
  32497. type: 'float',
  32498. inputs: [
  32499. { name: 'roughness', type: 'float' },
  32500. { name: 'dotNH', type: 'float' }
  32501. ]
  32502. } );
  32503. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  32504. const V_Neubelt = tslFn( ( { dotNV, dotNL } ) => {
  32505. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  32506. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  32507. } ).setLayout( {
  32508. name: 'V_Neubelt',
  32509. type: 'float',
  32510. inputs: [
  32511. { name: 'dotNV', type: 'float' },
  32512. { name: 'dotNL', type: 'float' }
  32513. ]
  32514. } );
  32515. const BRDF_Sheen = tslFn( ( { lightDirection } ) => {
  32516. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  32517. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  32518. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  32519. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  32520. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  32521. const V = V_Neubelt( { dotNV, dotNL } );
  32522. return sheen.mul( D ).mul( V );
  32523. } );
  32524. // Rect Area Light
  32525. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  32526. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  32527. // code: https://github.com/selfshadow/ltc_code/
  32528. const LTC_Uv = tslFn( ( { N, V, roughness } ) => {
  32529. const LUT_SIZE = 64.0;
  32530. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  32531. const LUT_BIAS = 0.5 / LUT_SIZE;
  32532. const dotNV = N.dot( V ).saturate();
  32533. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  32534. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  32535. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  32536. return uv;
  32537. } ).setLayout( {
  32538. name: 'LTC_Uv',
  32539. type: 'vec2',
  32540. inputs: [
  32541. { name: 'N', type: 'vec3' },
  32542. { name: 'V', type: 'vec3' },
  32543. { name: 'roughness', type: 'float' }
  32544. ]
  32545. } );
  32546. const LTC_ClippedSphereFormFactor = tslFn( ( { f } ) => {
  32547. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  32548. // An approximation of the form factor of a horizon-clipped rectangle.
  32549. const l = f.length();
  32550. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  32551. } ).setLayout( {
  32552. name: 'LTC_ClippedSphereFormFactor',
  32553. type: 'float',
  32554. inputs: [
  32555. { name: 'f', type: 'vec3' }
  32556. ]
  32557. } );
  32558. const LTC_EdgeVectorFormFactor = tslFn( ( { v1, v2 } ) => {
  32559. const x = v1.dot( v2 );
  32560. const y = x.abs().toVar();
  32561. // rational polynomial approximation to theta / sin( theta ) / 2PI
  32562. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  32563. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  32564. const v = a.div( b );
  32565. const theta_sintheta = x.greaterThan( 0.0 ).cond( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  32566. return v1.cross( v2 ).mul( theta_sintheta );
  32567. } ).setLayout( {
  32568. name: 'LTC_EdgeVectorFormFactor',
  32569. type: 'vec3',
  32570. inputs: [
  32571. { name: 'v1', type: 'vec3' },
  32572. { name: 'v2', type: 'vec3' }
  32573. ]
  32574. } );
  32575. const LTC_Evaluate = tslFn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  32576. // bail if point is on back side of plane of light
  32577. // assumes ccw winding order of light vertices
  32578. const v1 = p1.sub( p0 ).toVar();
  32579. const v2 = p3.sub( p0 ).toVar();
  32580. const lightNormal = v1.cross( v2 );
  32581. const result = vec3().toVar();
  32582. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  32583. // construct orthonormal basis around N
  32584. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  32585. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  32586. // compute transform
  32587. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  32588. // transform rect
  32589. // & project rect onto sphere
  32590. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  32591. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  32592. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  32593. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  32594. // calculate vector form factor
  32595. const vectorFormFactor = vec3( 0 ).toVar();
  32596. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  32597. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  32598. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  32599. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  32600. // adjust for horizon clipping
  32601. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  32602. } );
  32603. return result;
  32604. } ).setLayout( {
  32605. name: 'LTC_Evaluate',
  32606. type: 'vec3',
  32607. inputs: [
  32608. { name: 'N', type: 'vec3' },
  32609. { name: 'V', type: 'vec3' },
  32610. { name: 'P', type: 'vec3' },
  32611. { name: 'mInv', type: 'mat3' },
  32612. { name: 'p0', type: 'vec3' },
  32613. { name: 'p1', type: 'vec3' },
  32614. { name: 'p2', type: 'vec3' },
  32615. { name: 'p3', type: 'vec3' }
  32616. ]
  32617. } );
  32618. //
  32619. // Transmission
  32620. //
  32621. const getVolumeTransmissionRay = tslFn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  32622. // Direction of refracted light.
  32623. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  32624. // Compute rotation-independant scaling of the model matrix.
  32625. const modelScale = vec3(
  32626. length( modelMatrix[ 0 ].xyz ),
  32627. length( modelMatrix[ 1 ].xyz ),
  32628. length( modelMatrix[ 2 ].xyz )
  32629. );
  32630. // The thickness is specified in local space.
  32631. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  32632. } ).setLayout( {
  32633. name: 'getVolumeTransmissionRay',
  32634. type: 'vec3',
  32635. inputs: [
  32636. { name: 'n', type: 'vec3' },
  32637. { name: 'v', type: 'vec3' },
  32638. { name: 'thickness', type: 'float' },
  32639. { name: 'ior', type: 'float' },
  32640. { name: 'modelMatrix', type: 'mat4' }
  32641. ]
  32642. } );
  32643. const applyIorToRoughness = tslFn( ( [ roughness, ior ] ) => {
  32644. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  32645. // an IOR of 1.5 results in the default amount of microfacet refraction.
  32646. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  32647. } ).setLayout( {
  32648. name: 'applyIorToRoughness',
  32649. type: 'float',
  32650. inputs: [
  32651. { name: 'roughness', type: 'float' },
  32652. { name: 'ior', type: 'float' }
  32653. ]
  32654. } );
  32655. const singleViewportMipTexture = viewportMipTexture();
  32656. const getTransmissionSample = tslFn( ( [ fragCoord, roughness, ior ] ) => {
  32657. const transmissionSample = singleViewportMipTexture.uv( fragCoord );
  32658. //const transmissionSample = viewportMipTexture( fragCoord );
  32659. const lod = log2( float( viewportResolution.x ) ).mul( applyIorToRoughness( roughness, ior ) );
  32660. return transmissionSample.bicubic( lod );
  32661. } );
  32662. const volumeAttenuation = tslFn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  32663. If( attenuationDistance.notEqual( 0 ), () => {
  32664. // Compute light attenuation using Beer's law.
  32665. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  32666. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  32667. return transmittance;
  32668. } );
  32669. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  32670. return vec3( 1.0 );
  32671. } ).setLayout( {
  32672. name: 'volumeAttenuation',
  32673. type: 'vec3',
  32674. inputs: [
  32675. { name: 'transmissionDistance', type: 'float' },
  32676. { name: 'attenuationColor', type: 'vec3' },
  32677. { name: 'attenuationDistance', type: 'float' }
  32678. ]
  32679. } );
  32680. const getIBLVolumeRefraction = tslFn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  32681. let transmittedLight, transmittance;
  32682. if ( dispersion ) {
  32683. transmittedLight = vec4().toVar();
  32684. transmittance = vec3().toVar();
  32685. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  32686. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  32687. loop( { start: 0, end: 3 }, ( { i } ) => {
  32688. const ior = iors.element( i );
  32689. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  32690. const refractedRayExit = position.add( transmissionRay );
  32691. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  32692. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  32693. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  32694. refractionCoords.addAssign( 1.0 );
  32695. refractionCoords.divAssign( 2.0 );
  32696. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  32697. // Sample framebuffer to get pixel the refracted ray hits.
  32698. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  32699. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  32700. transmittedLight.a.addAssign( transmissionSample.a );
  32701. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  32702. } );
  32703. transmittedLight.a.divAssign( 3.0 );
  32704. } else {
  32705. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  32706. const refractedRayExit = position.add( transmissionRay );
  32707. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  32708. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  32709. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  32710. refractionCoords.addAssign( 1.0 );
  32711. refractionCoords.divAssign( 2.0 );
  32712. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  32713. // Sample framebuffer to get pixel the refracted ray hits.
  32714. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  32715. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  32716. }
  32717. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  32718. const dotNV = n.dot( v ).clamp();
  32719. // Get the specular component.
  32720. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  32721. dotNV,
  32722. specularColor,
  32723. specularF90,
  32724. roughness
  32725. } ) );
  32726. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  32727. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  32728. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  32729. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  32730. } );
  32731. //
  32732. // Iridescence
  32733. //
  32734. // XYZ to linear-sRGB color space
  32735. const XYZ_TO_REC709 = mat3(
  32736. 3.2404542, - 0.9692660, 0.0556434,
  32737. - 1.5371385, 1.8760108, - 0.2040259,
  32738. - 0.4985314, 0.0415560, 1.0572252
  32739. );
  32740. // Assume air interface for top
  32741. // Note: We don't handle the case fresnel0 == 1
  32742. const Fresnel0ToIor = ( fresnel0 ) => {
  32743. const sqrtF0 = fresnel0.sqrt();
  32744. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  32745. };
  32746. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  32747. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  32748. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  32749. };
  32750. // Fresnel equations for dielectric/dielectric interfaces.
  32751. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  32752. // Evaluation XYZ sensitivity curves in Fourier space
  32753. const evalSensitivity = ( OPD, shift ) => {
  32754. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  32755. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  32756. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  32757. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  32758. 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() );
  32759. 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() );
  32760. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  32761. const rgb = XYZ_TO_REC709.mul( xyz );
  32762. return rgb;
  32763. };
  32764. const evalIridescence = tslFn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  32765. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  32766. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  32767. // Evaluate the cosTheta on the base layer (Snell law)
  32768. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( float( 1 ).sub( cosTheta1.pow2() ) );
  32769. // Handle TIR:
  32770. const cosTheta2Sq = float( 1 ).sub( sinTheta2Sq );
  32771. /*if ( cosTheta2Sq < 0.0 ) {
  32772. return vec3( 1.0 );
  32773. }*/
  32774. const cosTheta2 = cosTheta2Sq.sqrt();
  32775. // First interface
  32776. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  32777. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  32778. //const R21 = R12;
  32779. const T121 = R12.oneMinus();
  32780. const phi12 = iridescenceIOR.lessThan( outsideIOR ).cond( Math.PI, 0.0 );
  32781. const phi21 = float( Math.PI ).sub( phi12 );
  32782. // Second interface
  32783. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  32784. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  32785. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  32786. const phi23 = vec3(
  32787. baseIOR.x.lessThan( iridescenceIOR ).cond( Math.PI, 0.0 ),
  32788. baseIOR.y.lessThan( iridescenceIOR ).cond( Math.PI, 0.0 ),
  32789. baseIOR.z.lessThan( iridescenceIOR ).cond( Math.PI, 0.0 )
  32790. );
  32791. // Phase shift
  32792. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  32793. const phi = vec3( phi21 ).add( phi23 );
  32794. // Compound terms
  32795. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  32796. const r123 = R123.sqrt();
  32797. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  32798. // Reflectance term for m = 0 (DC term amplitude)
  32799. const C0 = R12.add( Rs );
  32800. let I = C0;
  32801. // Reflectance term for m > 0 (pairs of diracs)
  32802. let Cm = Rs.sub( T121 );
  32803. for ( let m = 1; m <= 2; ++ m ) {
  32804. Cm = Cm.mul( r123 );
  32805. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  32806. I = I.add( Cm.mul( Sm ) );
  32807. }
  32808. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  32809. return I.max( vec3( 0.0 ) );
  32810. } ).setLayout( {
  32811. name: 'evalIridescence',
  32812. type: 'vec3',
  32813. inputs: [
  32814. { name: 'outsideIOR', type: 'float' },
  32815. { name: 'eta2', type: 'float' },
  32816. { name: 'cosTheta1', type: 'float' },
  32817. { name: 'thinFilmThickness', type: 'float' },
  32818. { name: 'baseF0', type: 'vec3' }
  32819. ]
  32820. } );
  32821. //
  32822. // Sheen
  32823. //
  32824. // This is a curve-fit approxmation to the "Charlie sheen" BRDF integrated over the hemisphere from
  32825. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  32826. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  32827. const IBLSheenBRDF = tslFn( ( { normal, viewDir, roughness } ) => {
  32828. const dotNV = normal.dot( viewDir ).saturate();
  32829. const r2 = roughness.pow2();
  32830. const a = cond(
  32831. roughness.lessThan( 0.25 ),
  32832. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  32833. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  32834. );
  32835. const b = cond(
  32836. roughness.lessThan( 0.25 ),
  32837. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  32838. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  32839. );
  32840. const DG = cond( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  32841. return DG.mul( 1.0 / Math.PI ).saturate();
  32842. } );
  32843. const clearcoatF0 = vec3( 0.04 );
  32844. const clearcoatF90 = float( 1 );
  32845. //
  32846. class PhysicalLightingModel extends LightingModel {
  32847. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  32848. super();
  32849. this.clearcoat = clearcoat;
  32850. this.sheen = sheen;
  32851. this.iridescence = iridescence;
  32852. this.anisotropy = anisotropy;
  32853. this.transmission = transmission;
  32854. this.dispersion = dispersion;
  32855. this.clearcoatRadiance = null;
  32856. this.clearcoatSpecularDirect = null;
  32857. this.clearcoatSpecularIndirect = null;
  32858. this.sheenSpecularDirect = null;
  32859. this.sheenSpecularIndirect = null;
  32860. this.iridescenceFresnel = null;
  32861. this.iridescenceF0 = null;
  32862. }
  32863. start( context ) {
  32864. if ( this.clearcoat === true ) {
  32865. this.clearcoatRadiance = vec3().temp( 'clearcoatRadiance' );
  32866. this.clearcoatSpecularDirect = vec3().temp( 'clearcoatSpecularDirect' );
  32867. this.clearcoatSpecularIndirect = vec3().temp( 'clearcoatSpecularIndirect' );
  32868. }
  32869. if ( this.sheen === true ) {
  32870. this.sheenSpecularDirect = vec3().temp( 'sheenSpecularDirect' );
  32871. this.sheenSpecularIndirect = vec3().temp( 'sheenSpecularIndirect' );
  32872. }
  32873. if ( this.iridescence === true ) {
  32874. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  32875. this.iridescenceFresnel = evalIridescence( {
  32876. outsideIOR: float( 1.0 ),
  32877. eta2: iridescenceIOR,
  32878. cosTheta1: dotNVi,
  32879. thinFilmThickness: iridescenceThickness,
  32880. baseF0: specularColor
  32881. } );
  32882. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  32883. }
  32884. if ( this.transmission === true ) {
  32885. const position = positionWorld;
  32886. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  32887. const n = transformedNormalWorld;
  32888. context.backdrop = getIBLVolumeRefraction(
  32889. n,
  32890. v,
  32891. roughness,
  32892. diffuseColor,
  32893. specularColor,
  32894. specularF90, // specularF90
  32895. position, // positionWorld
  32896. modelWorldMatrix, // modelMatrix
  32897. cameraViewMatrix, // viewMatrix
  32898. cameraProjectionMatrix, // projMatrix
  32899. ior,
  32900. thickness,
  32901. attenuationColor,
  32902. attenuationDistance,
  32903. this.dispersion ? dispersion : null
  32904. );
  32905. context.backdropAlpha = transmission;
  32906. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  32907. }
  32908. }
  32909. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  32910. // Approximates multiscattering in order to preserve energy.
  32911. // http://www.jcgt.org/published/0008/01/03/
  32912. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  32913. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  32914. const fab = DFGApprox( { roughness, dotNV } );
  32915. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  32916. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  32917. const Ess = fab.x.add( fab.y );
  32918. const Ems = Ess.oneMinus();
  32919. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  32920. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  32921. singleScatter.addAssign( FssEss );
  32922. multiScatter.addAssign( Fms.mul( Ems ) );
  32923. }
  32924. direct( { lightDirection, lightColor, reflectedLight } ) {
  32925. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  32926. const irradiance = dotNL.mul( lightColor );
  32927. if ( this.sheen === true ) {
  32928. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  32929. }
  32930. if ( this.clearcoat === true ) {
  32931. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  32932. const ccIrradiance = dotNLcc.mul( lightColor );
  32933. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  32934. }
  32935. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  32936. 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 } ) ) );
  32937. }
  32938. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  32939. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  32940. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  32941. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  32942. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  32943. const N = transformedNormalView;
  32944. const V = positionViewDirection;
  32945. const P = positionView.toVar();
  32946. const uv = LTC_Uv( { N, V, roughness } );
  32947. const t1 = ltc_1.uv( uv ).toVar();
  32948. const t2 = ltc_2.uv( uv ).toVar();
  32949. const mInv = mat3(
  32950. vec3( t1.x, 0, t1.y ),
  32951. vec3( 0, 1, 0 ),
  32952. vec3( t1.z, 0, t1.w )
  32953. ).toVar();
  32954. // LTC Fresnel Approximation by Stephen Hill
  32955. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  32956. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  32957. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  32958. 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 } ) ) );
  32959. }
  32960. indirectDiffuse( { irradiance, reflectedLight } ) {
  32961. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  32962. }
  32963. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  32964. if ( this.sheen === true ) {
  32965. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  32966. sheen,
  32967. IBLSheenBRDF( {
  32968. normal: transformedNormalView,
  32969. viewDir: positionViewDirection,
  32970. roughness: sheenRoughness
  32971. } )
  32972. ) );
  32973. }
  32974. if ( this.clearcoat === true ) {
  32975. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  32976. const clearcoatEnv = EnvironmentBRDF( {
  32977. dotNV: dotNVcc,
  32978. specularColor: clearcoatF0,
  32979. specularF90: clearcoatF90,
  32980. roughness: clearcoatRoughness
  32981. } );
  32982. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  32983. }
  32984. // Both indirect specular and indirect diffuse light accumulate here
  32985. const singleScattering = vec3().temp( 'singleScattering' );
  32986. const multiScattering = vec3().temp( 'multiScattering' );
  32987. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  32988. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  32989. const totalScattering = singleScattering.add( multiScattering );
  32990. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  32991. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  32992. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  32993. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  32994. }
  32995. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  32996. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  32997. const aoNV = dotNV.add( ambientOcclusion );
  32998. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  32999. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  33000. if ( this.clearcoat === true ) {
  33001. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  33002. }
  33003. if ( this.sheen === true ) {
  33004. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  33005. }
  33006. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  33007. reflectedLight.indirectSpecular.mulAssign( aoNode );
  33008. }
  33009. finish( context ) {
  33010. const { outgoingLight } = context;
  33011. if ( this.clearcoat === true ) {
  33012. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  33013. const Fcc = F_Schlick( {
  33014. dotVH: dotNVcc,
  33015. f0: clearcoatF0,
  33016. f90: clearcoatF90
  33017. } );
  33018. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  33019. outgoingLight.assign( clearcoatLight );
  33020. }
  33021. if ( this.sheen === true ) {
  33022. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  33023. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  33024. outgoingLight.assign( sheenLight );
  33025. }
  33026. }
  33027. }
  33028. const defaultValues$6 = new MeshStandardMaterial();
  33029. class MeshStandardNodeMaterial extends NodeMaterial {
  33030. constructor( parameters ) {
  33031. super();
  33032. this.isMeshStandardNodeMaterial = true;
  33033. this.emissiveNode = null;
  33034. this.metalnessNode = null;
  33035. this.roughnessNode = null;
  33036. this.setDefaultValues( defaultValues$6 );
  33037. this.setValues( parameters );
  33038. }
  33039. setupLightingModel( /*builder*/ ) {
  33040. return new PhysicalLightingModel();
  33041. }
  33042. setupSpecular() {
  33043. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  33044. specularColor.assign( specularColorNode );
  33045. specularF90.assign( 1.0 );
  33046. }
  33047. setupVariants() {
  33048. // METALNESS
  33049. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  33050. metalness.assign( metalnessNode );
  33051. // ROUGHNESS
  33052. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  33053. roughnessNode = getRoughness( { roughness: roughnessNode } );
  33054. roughness.assign( roughnessNode );
  33055. // SPECULAR COLOR
  33056. this.setupSpecular();
  33057. // DIFFUSE COLOR
  33058. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  33059. }
  33060. copy( source ) {
  33061. this.emissiveNode = source.emissiveNode;
  33062. this.metalnessNode = source.metalnessNode;
  33063. this.roughnessNode = source.roughnessNode;
  33064. return super.copy( source );
  33065. }
  33066. }
  33067. addNodeMaterial( 'MeshStandardNodeMaterial', MeshStandardNodeMaterial );
  33068. const defaultValues$5 = new MeshPhysicalMaterial();
  33069. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  33070. constructor( parameters ) {
  33071. super();
  33072. this.isMeshPhysicalNodeMaterial = true;
  33073. this.clearcoatNode = null;
  33074. this.clearcoatRoughnessNode = null;
  33075. this.clearcoatNormalNode = null;
  33076. this.sheenNode = null;
  33077. this.sheenRoughnessNode = null;
  33078. this.iridescenceNode = null;
  33079. this.iridescenceIORNode = null;
  33080. this.iridescenceThicknessNode = null;
  33081. this.specularIntensityNode = null;
  33082. this.specularColorNode = null;
  33083. this.iorNode = null;
  33084. this.transmissionNode = null;
  33085. this.thicknessNode = null;
  33086. this.attenuationDistanceNode = null;
  33087. this.attenuationColorNode = null;
  33088. this.dispersionNode = null;
  33089. this.anisotropyNode = null;
  33090. this.setDefaultValues( defaultValues$5 );
  33091. this.setValues( parameters );
  33092. }
  33093. get useClearcoat() {
  33094. return this.clearcoat > 0 || this.clearcoatNode !== null;
  33095. }
  33096. get useIridescence() {
  33097. return this.iridescence > 0 || this.iridescenceNode !== null;
  33098. }
  33099. get useSheen() {
  33100. return this.sheen > 0 || this.sheenNode !== null;
  33101. }
  33102. get useAnisotropy() {
  33103. return this.anisotropy > 0 || this.anisotropyNode !== null;
  33104. }
  33105. get useTransmission() {
  33106. return this.transmission > 0 || this.transmissionNode !== null;
  33107. }
  33108. get useDispersion() {
  33109. return this.dispersion > 0 || this.dispersionNode !== null;
  33110. }
  33111. setupSpecular() {
  33112. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  33113. ior.assign( iorNode );
  33114. 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 ) );
  33115. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  33116. }
  33117. setupLightingModel( /*builder*/ ) {
  33118. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  33119. }
  33120. setupVariants( builder ) {
  33121. super.setupVariants( builder );
  33122. // CLEARCOAT
  33123. if ( this.useClearcoat ) {
  33124. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  33125. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  33126. clearcoat.assign( clearcoatNode );
  33127. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  33128. }
  33129. // SHEEN
  33130. if ( this.useSheen ) {
  33131. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  33132. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  33133. sheen.assign( sheenNode );
  33134. sheenRoughness.assign( sheenRoughnessNode );
  33135. }
  33136. // IRIDESCENCE
  33137. if ( this.useIridescence ) {
  33138. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  33139. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  33140. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  33141. iridescence.assign( iridescenceNode );
  33142. iridescenceIOR.assign( iridescenceIORNode );
  33143. iridescenceThickness.assign( iridescenceThicknessNode );
  33144. }
  33145. // ANISOTROPY
  33146. if ( this.useAnisotropy ) {
  33147. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  33148. anisotropy.assign( anisotropyV.length() );
  33149. If( anisotropy.equal( 0.0 ), () => {
  33150. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  33151. } ).else( () => {
  33152. anisotropyV.divAssign( vec2( anisotropy ) );
  33153. anisotropy.assign( anisotropy.saturate() );
  33154. } );
  33155. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  33156. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  33157. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  33158. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  33159. }
  33160. // TRANSMISSION
  33161. if ( this.useTransmission ) {
  33162. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  33163. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  33164. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  33165. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  33166. transmission.assign( transmissionNode );
  33167. thickness.assign( thicknessNode );
  33168. attenuationDistance.assign( attenuationDistanceNode );
  33169. attenuationColor.assign( attenuationColorNode );
  33170. if ( this.useDispersion ) {
  33171. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  33172. dispersion.assign( dispersionNode );
  33173. }
  33174. }
  33175. }
  33176. setupNormal( builder ) {
  33177. super.setupNormal( builder );
  33178. // CLEARCOAT NORMAL
  33179. const clearcoatNormalNode = this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  33180. transformedClearcoatNormalView.assign( clearcoatNormalNode );
  33181. }
  33182. copy( source ) {
  33183. this.clearcoatNode = source.clearcoatNode;
  33184. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  33185. this.clearcoatNormalNode = source.clearcoatNormalNode;
  33186. this.sheenNode = source.sheenNode;
  33187. this.sheenRoughnessNode = source.sheenRoughnessNode;
  33188. this.iridescenceNode = source.iridescenceNode;
  33189. this.iridescenceIORNode = source.iridescenceIORNode;
  33190. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  33191. this.specularIntensityNode = source.specularIntensityNode;
  33192. this.specularColorNode = source.specularColorNode;
  33193. this.transmissionNode = source.transmissionNode;
  33194. this.thicknessNode = source.thicknessNode;
  33195. this.attenuationDistanceNode = source.attenuationDistanceNode;
  33196. this.attenuationColorNode = source.attenuationColorNode;
  33197. this.dispersionNode = source.dispersionNode;
  33198. this.anisotropyNode = source.anisotropyNode;
  33199. return super.copy( source );
  33200. }
  33201. }
  33202. addNodeMaterial( 'MeshPhysicalNodeMaterial', MeshPhysicalNodeMaterial );
  33203. class SSSLightingModel extends PhysicalLightingModel {
  33204. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  33205. super( useClearcoat, useSheen, useIridescence );
  33206. this.useSSS = useSSS;
  33207. }
  33208. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  33209. if ( this.useSSS === true ) {
  33210. const material = builder.material;
  33211. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  33212. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  33213. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  33214. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  33215. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  33216. }
  33217. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  33218. }
  33219. }
  33220. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  33221. constructor( parameters ) {
  33222. super( parameters );
  33223. this.thicknessColorNode = null;
  33224. this.thicknessDistortionNode = float( 0.1 );
  33225. this.thicknessAmbientNode = float( 0.0 );
  33226. this.thicknessAttenuationNode = float( .1 );
  33227. this.thicknessPowerNode = float( 2.0 );
  33228. this.thicknessScaleNode = float( 10.0 );
  33229. }
  33230. get useSSS() {
  33231. return this.thicknessColorNode !== null;
  33232. }
  33233. setupLightingModel( /*builder*/ ) {
  33234. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  33235. }
  33236. copy( source ) {
  33237. this.thicknessColorNode = source.thicknessColorNode;
  33238. this.thicknessDistortionNode = source.thicknessDistortionNode;
  33239. this.thicknessAmbientNode = source.thicknessAmbientNode;
  33240. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  33241. this.thicknessPowerNode = source.thicknessPowerNode;
  33242. this.thicknessScaleNode = source.thicknessScaleNode;
  33243. return super.copy( source );
  33244. }
  33245. }
  33246. addNodeMaterial( 'MeshSSSNodeMaterial', MeshSSSNodeMaterial );
  33247. const getGradientIrradiance = tslFn( ( { normal, lightDirection, builder } ) => {
  33248. // dotNL will be from -1.0 to 1.0
  33249. const dotNL = normal.dot( lightDirection );
  33250. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  33251. if ( builder.material.gradientMap ) {
  33252. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  33253. return vec3( gradientMap.r );
  33254. } else {
  33255. const fw = coord.fwidth().mul( 0.5 );
  33256. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  33257. }
  33258. } );
  33259. class ToonLightingModel extends LightingModel {
  33260. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  33261. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  33262. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  33263. }
  33264. indirectDiffuse( { irradiance, reflectedLight } ) {
  33265. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  33266. }
  33267. }
  33268. const defaultValues$4 = new MeshToonMaterial();
  33269. class MeshToonNodeMaterial extends NodeMaterial {
  33270. constructor( parameters ) {
  33271. super();
  33272. this.isMeshToonNodeMaterial = true;
  33273. this.lights = true;
  33274. this.setDefaultValues( defaultValues$4 );
  33275. this.setValues( parameters );
  33276. }
  33277. setupLightingModel( /*builder*/ ) {
  33278. return new ToonLightingModel();
  33279. }
  33280. }
  33281. addNodeMaterial( 'MeshToonNodeMaterial', MeshToonNodeMaterial );
  33282. const defaultValues$3 = new MeshMatcapMaterial();
  33283. class MeshMatcapNodeMaterial extends NodeMaterial {
  33284. constructor( parameters ) {
  33285. super();
  33286. this.lights = false;
  33287. this.isMeshMatcapNodeMaterial = true;
  33288. this.setDefaultValues( defaultValues$3 );
  33289. this.setValues( parameters );
  33290. }
  33291. setupVariants( builder ) {
  33292. const uv = matcapUV;
  33293. let matcapColor;
  33294. if ( builder.material.matcap ) {
  33295. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  33296. } else {
  33297. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  33298. }
  33299. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  33300. }
  33301. }
  33302. addNodeMaterial( 'MeshMatcapNodeMaterial', MeshMatcapNodeMaterial );
  33303. const defaultValues$2 = new PointsMaterial();
  33304. class PointsNodeMaterial extends NodeMaterial {
  33305. constructor( parameters ) {
  33306. super();
  33307. this.isPointsNodeMaterial = true;
  33308. this.lights = false;
  33309. this.normals = false;
  33310. this.transparent = true;
  33311. this.sizeNode = null;
  33312. this.setDefaultValues( defaultValues$2 );
  33313. this.setValues( parameters );
  33314. }
  33315. copy( source ) {
  33316. this.sizeNode = source.sizeNode;
  33317. return super.copy( source );
  33318. }
  33319. }
  33320. addNodeMaterial( 'PointsNodeMaterial', PointsNodeMaterial );
  33321. const defaultValues$1 = new SpriteMaterial();
  33322. class SpriteNodeMaterial extends NodeMaterial {
  33323. constructor( parameters ) {
  33324. super();
  33325. this.isSpriteNodeMaterial = true;
  33326. this.lights = false;
  33327. this.normals = false;
  33328. this.positionNode = null;
  33329. this.rotationNode = null;
  33330. this.scaleNode = null;
  33331. this.setDefaultValues( defaultValues$1 );
  33332. this.setValues( parameters );
  33333. }
  33334. setupPosition( { object, context } ) {
  33335. // < VERTEX STAGE >
  33336. const { positionNode, rotationNode, scaleNode } = this;
  33337. const vertex = positionLocal;
  33338. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  33339. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  33340. if ( scaleNode !== null ) {
  33341. scale = scale.mul( scaleNode );
  33342. }
  33343. let alignedPosition = vertex.xy;
  33344. if ( object.center && object.center.isVector2 === true ) {
  33345. alignedPosition = alignedPosition.sub( uniform( object.center ).sub( 0.5 ) );
  33346. }
  33347. alignedPosition = alignedPosition.mul( scale );
  33348. const rotation = float( rotationNode || materialRotation );
  33349. const rotatedPosition = alignedPosition.rotate( rotation );
  33350. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  33351. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  33352. context.vertex = vertex;
  33353. return modelViewProjection;
  33354. }
  33355. copy( source ) {
  33356. this.positionNode = source.positionNode;
  33357. this.rotationNode = source.rotationNode;
  33358. this.scaleNode = source.scaleNode;
  33359. return super.copy( source );
  33360. }
  33361. }
  33362. addNodeMaterial( 'SpriteNodeMaterial', SpriteNodeMaterial );
  33363. class ShadowMaskModel extends LightingModel {
  33364. constructor() {
  33365. super();
  33366. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  33367. }
  33368. direct( { shadowMask } ) {
  33369. this.shadowNode.mulAssign( shadowMask );
  33370. }
  33371. finish( context ) {
  33372. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  33373. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  33374. }
  33375. }
  33376. const defaultValues = new ShadowMaterial();
  33377. class ShadowNodeMaterial extends NodeMaterial {
  33378. constructor( parameters ) {
  33379. super();
  33380. this.isShadowNodeMaterial = true;
  33381. this.lights = true;
  33382. this.setDefaultValues( defaultValues );
  33383. this.setValues( parameters );
  33384. }
  33385. setupLightingModel( /*builder*/ ) {
  33386. return new ShadowMaskModel();
  33387. }
  33388. }
  33389. addNodeMaterial( 'ShadowNodeMaterial', ShadowNodeMaterial );
  33390. class VolumeNodeMaterial extends NodeMaterial {
  33391. constructor( params = {} ) {
  33392. super();
  33393. this.normals = false;
  33394. this.lights = false;
  33395. this.isVolumeNodeMaterial = true;
  33396. this.testNode = null;
  33397. this.setValues( params );
  33398. }
  33399. setup( builder ) {
  33400. const map = texture3D( this.map, null, 0 );
  33401. const hitBox = tslFn( ( { orig, dir } ) => {
  33402. const box_min = vec3( - 0.5 );
  33403. const box_max = vec3( 0.5 );
  33404. const inv_dir = dir.reciprocal();
  33405. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  33406. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  33407. const tmin = min$1( tmin_tmp, tmax_tmp );
  33408. const tmax = max$1( tmin_tmp, tmax_tmp );
  33409. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  33410. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  33411. return vec2( t0, t1 );
  33412. } );
  33413. this.fragmentNode = tslFn( () => {
  33414. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  33415. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  33416. const rayDir = vDirection.normalize();
  33417. const bounds = property( 'vec2', 'bounds' ).assign( hitBox( { orig: vOrigin, dir: rayDir } ) );
  33418. bounds.x.greaterThan( bounds.y ).discard();
  33419. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  33420. const p = property( 'vec3', 'p' ).assign( vOrigin.add( bounds.x.mul( rayDir ) ) );
  33421. const inc = property( 'vec3', 'inc' ).assign( vec3( rayDir.abs().reciprocal() ) );
  33422. const delta = property( 'float', 'delta' ).assign( min$1( inc.x, min$1( inc.y, inc.z ) ) );
  33423. delta.divAssign( materialReference( 'steps', 'float' ) );
  33424. const ac = property( 'vec4', 'ac' ).assign( vec4( materialReference( 'base', 'color' ), 0.0 ) );
  33425. loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  33426. const d = property( 'float', 'd' ).assign( map.uv( p.add( 0.5 ) ).r );
  33427. if ( this.testNode !== null ) {
  33428. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  33429. } else {
  33430. // default to show surface of mesh
  33431. ac.a.assign( 1 );
  33432. Break();
  33433. }
  33434. p.addAssign( rayDir.mul( delta ) );
  33435. } );
  33436. ac.a.equal( 0 ).discard();
  33437. return vec4( ac );
  33438. } )();
  33439. super.setup( builder );
  33440. }
  33441. }
  33442. addNodeMaterial( 'VolumeNodeMaterial', VolumeNodeMaterial );
  33443. const superFromTypeFunction = MaterialLoader.createMaterialFromType;
  33444. MaterialLoader.createMaterialFromType = function ( type ) {
  33445. const material = createNodeMaterialFromType( type );
  33446. if ( material !== undefined ) {
  33447. return material;
  33448. }
  33449. return superFromTypeFunction.call( this, type );
  33450. };
  33451. class NodeMaterialLoader extends MaterialLoader {
  33452. constructor( manager ) {
  33453. super( manager );
  33454. this.nodes = {};
  33455. }
  33456. parse( json ) {
  33457. const material = super.parse( json );
  33458. const nodes = this.nodes;
  33459. const inputNodes = json.inputNodes;
  33460. for ( const property in inputNodes ) {
  33461. const uuid = inputNodes[ property ];
  33462. material[ property ] = nodes[ uuid ];
  33463. }
  33464. return material;
  33465. }
  33466. setNodes( value ) {
  33467. this.nodes = value;
  33468. return this;
  33469. }
  33470. }
  33471. class NodeObjectLoader extends ObjectLoader {
  33472. constructor( manager ) {
  33473. super( manager );
  33474. this._nodesJSON = null;
  33475. }
  33476. parse( json, onLoad ) {
  33477. this._nodesJSON = json.nodes;
  33478. const data = super.parse( json, onLoad );
  33479. this._nodesJSON = null; // dispose
  33480. return data;
  33481. }
  33482. parseNodes( json, textures ) {
  33483. if ( json !== undefined ) {
  33484. const loader = new NodeLoader();
  33485. loader.setTextures( textures );
  33486. return loader.parseNodes( json );
  33487. }
  33488. return {};
  33489. }
  33490. parseMaterials( json, textures ) {
  33491. const materials = {};
  33492. if ( json !== undefined ) {
  33493. const nodes = this.parseNodes( this._nodesJSON, textures );
  33494. const loader = new NodeMaterialLoader();
  33495. loader.setTextures( textures );
  33496. loader.setNodes( nodes );
  33497. for ( let i = 0, l = json.length; i < l; i ++ ) {
  33498. const data = json[ i ];
  33499. materials[ data.uuid ] = loader.parse( data );
  33500. }
  33501. }
  33502. return materials;
  33503. }
  33504. }
  33505. class NodeParser {
  33506. parseFunction( /*source*/ ) {
  33507. console.warn( 'Abstract function.' );
  33508. }
  33509. }
  33510. class NodeFunction {
  33511. constructor( type, inputs, name = '', precision = '' ) {
  33512. this.type = type;
  33513. this.inputs = inputs;
  33514. this.name = name;
  33515. this.precision = precision;
  33516. }
  33517. getCode( /*name = this.name*/ ) {
  33518. console.warn( 'Abstract function.' );
  33519. }
  33520. }
  33521. NodeFunction.isNodeFunction = true;
  33522. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  33523. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  33524. const pragmaMain = '#pragma main';
  33525. const parse$1 = ( source ) => {
  33526. source = source.trim();
  33527. const pragmaMainIndex = source.indexOf( pragmaMain );
  33528. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  33529. const declaration = mainCode.match( declarationRegexp$1 );
  33530. if ( declaration !== null && declaration.length === 5 ) {
  33531. // tokenizer
  33532. const inputsCode = declaration[ 4 ];
  33533. const propsMatches = [];
  33534. let nameMatch = null;
  33535. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  33536. propsMatches.push( nameMatch );
  33537. }
  33538. // parser
  33539. const inputs = [];
  33540. let i = 0;
  33541. while ( i < propsMatches.length ) {
  33542. const isConst = propsMatches[ i ][ 0 ] === 'const';
  33543. if ( isConst === true ) {
  33544. i ++;
  33545. }
  33546. let qualifier = propsMatches[ i ][ 0 ];
  33547. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  33548. i ++;
  33549. } else {
  33550. qualifier = '';
  33551. }
  33552. const type = propsMatches[ i ++ ][ 0 ];
  33553. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  33554. if ( Number.isNaN( count ) === false ) i ++;
  33555. else count = null;
  33556. const name = propsMatches[ i ++ ][ 0 ];
  33557. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  33558. }
  33559. //
  33560. const blockCode = mainCode.substring( declaration[ 0 ].length );
  33561. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  33562. const type = declaration[ 2 ];
  33563. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  33564. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  33565. return {
  33566. type,
  33567. inputs,
  33568. name,
  33569. precision,
  33570. inputsCode,
  33571. blockCode,
  33572. headerCode
  33573. };
  33574. } else {
  33575. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  33576. }
  33577. };
  33578. class GLSLNodeFunction extends NodeFunction {
  33579. constructor( source ) {
  33580. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  33581. super( type, inputs, name, precision );
  33582. this.inputsCode = inputsCode;
  33583. this.blockCode = blockCode;
  33584. this.headerCode = headerCode;
  33585. }
  33586. getCode( name = this.name ) {
  33587. let code;
  33588. const blockCode = this.blockCode;
  33589. if ( blockCode !== '' ) {
  33590. const { type, inputsCode, headerCode, precision } = this;
  33591. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  33592. if ( precision !== '' ) {
  33593. declarationCode = `${ precision } ${ declarationCode }`;
  33594. }
  33595. code = headerCode + declarationCode + blockCode;
  33596. } else {
  33597. // interface function
  33598. code = '';
  33599. }
  33600. return code;
  33601. }
  33602. }
  33603. class GLSLNodeParser extends NodeParser {
  33604. parseFunction( source ) {
  33605. return new GLSLNodeFunction( source );
  33606. }
  33607. }
  33608. // Three.js Transpiler
  33609. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  33610. const mx_select = /*#__PURE__*/ tslFn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  33611. const f = float( f_immutable ).toVar();
  33612. const t = float( t_immutable ).toVar();
  33613. const b = bool( b_immutable ).toVar();
  33614. return cond( b, t, f );
  33615. } ).setLayout( {
  33616. name: 'mx_select',
  33617. type: 'float',
  33618. inputs: [
  33619. { name: 'b', type: 'bool' },
  33620. { name: 't', type: 'float' },
  33621. { name: 'f', type: 'float' }
  33622. ]
  33623. } );
  33624. const mx_negate_if = /*#__PURE__*/ tslFn( ( [ val_immutable, b_immutable ] ) => {
  33625. const b = bool( b_immutable ).toVar();
  33626. const val = float( val_immutable ).toVar();
  33627. return cond( b, val.negate(), val );
  33628. } ).setLayout( {
  33629. name: 'mx_negate_if',
  33630. type: 'float',
  33631. inputs: [
  33632. { name: 'val', type: 'float' },
  33633. { name: 'b', type: 'bool' }
  33634. ]
  33635. } );
  33636. const mx_floor = /*#__PURE__*/ tslFn( ( [ x_immutable ] ) => {
  33637. const x = float( x_immutable ).toVar();
  33638. return int( floor( x ) );
  33639. } ).setLayout( {
  33640. name: 'mx_floor',
  33641. type: 'int',
  33642. inputs: [
  33643. { name: 'x', type: 'float' }
  33644. ]
  33645. } );
  33646. const mx_floorfrac = /*#__PURE__*/ tslFn( ( [ x_immutable, i ] ) => {
  33647. const x = float( x_immutable ).toVar();
  33648. i.assign( mx_floor( x ) );
  33649. return x.sub( float( i ) );
  33650. } );
  33651. const mx_bilerp_0 = /*#__PURE__*/ tslFn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  33652. const t = float( t_immutable ).toVar();
  33653. const s = float( s_immutable ).toVar();
  33654. const v3 = float( v3_immutable ).toVar();
  33655. const v2 = float( v2_immutable ).toVar();
  33656. const v1 = float( v1_immutable ).toVar();
  33657. const v0 = float( v0_immutable ).toVar();
  33658. const s1 = float( sub( 1.0, s ) ).toVar();
  33659. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  33660. } ).setLayout( {
  33661. name: 'mx_bilerp_0',
  33662. type: 'float',
  33663. inputs: [
  33664. { name: 'v0', type: 'float' },
  33665. { name: 'v1', type: 'float' },
  33666. { name: 'v2', type: 'float' },
  33667. { name: 'v3', type: 'float' },
  33668. { name: 's', type: 'float' },
  33669. { name: 't', type: 'float' }
  33670. ]
  33671. } );
  33672. const mx_bilerp_1 = /*#__PURE__*/ tslFn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  33673. const t = float( t_immutable ).toVar();
  33674. const s = float( s_immutable ).toVar();
  33675. const v3 = vec3( v3_immutable ).toVar();
  33676. const v2 = vec3( v2_immutable ).toVar();
  33677. const v1 = vec3( v1_immutable ).toVar();
  33678. const v0 = vec3( v0_immutable ).toVar();
  33679. const s1 = float( sub( 1.0, s ) ).toVar();
  33680. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  33681. } ).setLayout( {
  33682. name: 'mx_bilerp_1',
  33683. type: 'vec3',
  33684. inputs: [
  33685. { name: 'v0', type: 'vec3' },
  33686. { name: 'v1', type: 'vec3' },
  33687. { name: 'v2', type: 'vec3' },
  33688. { name: 'v3', type: 'vec3' },
  33689. { name: 's', type: 'float' },
  33690. { name: 't', type: 'float' }
  33691. ]
  33692. } );
  33693. const mx_bilerp = /*#__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  33694. 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 ] ) => {
  33695. const r = float( r_immutable ).toVar();
  33696. const t = float( t_immutable ).toVar();
  33697. const s = float( s_immutable ).toVar();
  33698. const v7 = float( v7_immutable ).toVar();
  33699. const v6 = float( v6_immutable ).toVar();
  33700. const v5 = float( v5_immutable ).toVar();
  33701. const v4 = float( v4_immutable ).toVar();
  33702. const v3 = float( v3_immutable ).toVar();
  33703. const v2 = float( v2_immutable ).toVar();
  33704. const v1 = float( v1_immutable ).toVar();
  33705. const v0 = float( v0_immutable ).toVar();
  33706. const s1 = float( sub( 1.0, s ) ).toVar();
  33707. const t1 = float( sub( 1.0, t ) ).toVar();
  33708. const r1 = float( sub( 1.0, r ) ).toVar();
  33709. 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 ) ) ) ) ) );
  33710. } ).setLayout( {
  33711. name: 'mx_trilerp_0',
  33712. type: 'float',
  33713. inputs: [
  33714. { name: 'v0', type: 'float' },
  33715. { name: 'v1', type: 'float' },
  33716. { name: 'v2', type: 'float' },
  33717. { name: 'v3', type: 'float' },
  33718. { name: 'v4', type: 'float' },
  33719. { name: 'v5', type: 'float' },
  33720. { name: 'v6', type: 'float' },
  33721. { name: 'v7', type: 'float' },
  33722. { name: 's', type: 'float' },
  33723. { name: 't', type: 'float' },
  33724. { name: 'r', type: 'float' }
  33725. ]
  33726. } );
  33727. 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 ] ) => {
  33728. const r = float( r_immutable ).toVar();
  33729. const t = float( t_immutable ).toVar();
  33730. const s = float( s_immutable ).toVar();
  33731. const v7 = vec3( v7_immutable ).toVar();
  33732. const v6 = vec3( v6_immutable ).toVar();
  33733. const v5 = vec3( v5_immutable ).toVar();
  33734. const v4 = vec3( v4_immutable ).toVar();
  33735. const v3 = vec3( v3_immutable ).toVar();
  33736. const v2 = vec3( v2_immutable ).toVar();
  33737. const v1 = vec3( v1_immutable ).toVar();
  33738. const v0 = vec3( v0_immutable ).toVar();
  33739. const s1 = float( sub( 1.0, s ) ).toVar();
  33740. const t1 = float( sub( 1.0, t ) ).toVar();
  33741. const r1 = float( sub( 1.0, r ) ).toVar();
  33742. 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 ) ) ) ) ) );
  33743. } ).setLayout( {
  33744. name: 'mx_trilerp_1',
  33745. type: 'vec3',
  33746. inputs: [
  33747. { name: 'v0', type: 'vec3' },
  33748. { name: 'v1', type: 'vec3' },
  33749. { name: 'v2', type: 'vec3' },
  33750. { name: 'v3', type: 'vec3' },
  33751. { name: 'v4', type: 'vec3' },
  33752. { name: 'v5', type: 'vec3' },
  33753. { name: 'v6', type: 'vec3' },
  33754. { name: 'v7', type: 'vec3' },
  33755. { name: 's', type: 'float' },
  33756. { name: 't', type: 'float' },
  33757. { name: 'r', type: 'float' }
  33758. ]
  33759. } );
  33760. const mx_trilerp = /*#__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  33761. const mx_gradient_float_0 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  33762. const y = float( y_immutable ).toVar();
  33763. const x = float( x_immutable ).toVar();
  33764. const hash = uint( hash_immutable ).toVar();
  33765. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  33766. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  33767. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  33768. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  33769. } ).setLayout( {
  33770. name: 'mx_gradient_float_0',
  33771. type: 'float',
  33772. inputs: [
  33773. { name: 'hash', type: 'uint' },
  33774. { name: 'x', type: 'float' },
  33775. { name: 'y', type: 'float' }
  33776. ]
  33777. } );
  33778. const mx_gradient_float_1 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  33779. const z = float( z_immutable ).toVar();
  33780. const y = float( y_immutable ).toVar();
  33781. const x = float( x_immutable ).toVar();
  33782. const hash = uint( hash_immutable ).toVar();
  33783. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  33784. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  33785. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  33786. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  33787. } ).setLayout( {
  33788. name: 'mx_gradient_float_1',
  33789. type: 'float',
  33790. inputs: [
  33791. { name: 'hash', type: 'uint' },
  33792. { name: 'x', type: 'float' },
  33793. { name: 'y', type: 'float' },
  33794. { name: 'z', type: 'float' }
  33795. ]
  33796. } );
  33797. const mx_gradient_float = /*#__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  33798. const mx_gradient_vec3_0 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  33799. const y = float( y_immutable ).toVar();
  33800. const x = float( x_immutable ).toVar();
  33801. const hash = uvec3( hash_immutable ).toVar();
  33802. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  33803. } ).setLayout( {
  33804. name: 'mx_gradient_vec3_0',
  33805. type: 'vec3',
  33806. inputs: [
  33807. { name: 'hash', type: 'uvec3' },
  33808. { name: 'x', type: 'float' },
  33809. { name: 'y', type: 'float' }
  33810. ]
  33811. } );
  33812. const mx_gradient_vec3_1 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  33813. const z = float( z_immutable ).toVar();
  33814. const y = float( y_immutable ).toVar();
  33815. const x = float( x_immutable ).toVar();
  33816. const hash = uvec3( hash_immutable ).toVar();
  33817. 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 ) );
  33818. } ).setLayout( {
  33819. name: 'mx_gradient_vec3_1',
  33820. type: 'vec3',
  33821. inputs: [
  33822. { name: 'hash', type: 'uvec3' },
  33823. { name: 'x', type: 'float' },
  33824. { name: 'y', type: 'float' },
  33825. { name: 'z', type: 'float' }
  33826. ]
  33827. } );
  33828. const mx_gradient_vec3 = /*#__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  33829. const mx_gradient_scale2d_0 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  33830. const v = float( v_immutable ).toVar();
  33831. return mul( 0.6616, v );
  33832. } ).setLayout( {
  33833. name: 'mx_gradient_scale2d_0',
  33834. type: 'float',
  33835. inputs: [
  33836. { name: 'v', type: 'float' }
  33837. ]
  33838. } );
  33839. const mx_gradient_scale3d_0 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  33840. const v = float( v_immutable ).toVar();
  33841. return mul( 0.9820, v );
  33842. } ).setLayout( {
  33843. name: 'mx_gradient_scale3d_0',
  33844. type: 'float',
  33845. inputs: [
  33846. { name: 'v', type: 'float' }
  33847. ]
  33848. } );
  33849. const mx_gradient_scale2d_1 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  33850. const v = vec3( v_immutable ).toVar();
  33851. return mul( 0.6616, v );
  33852. } ).setLayout( {
  33853. name: 'mx_gradient_scale2d_1',
  33854. type: 'vec3',
  33855. inputs: [
  33856. { name: 'v', type: 'vec3' }
  33857. ]
  33858. } );
  33859. const mx_gradient_scale2d = /*#__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  33860. const mx_gradient_scale3d_1 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  33861. const v = vec3( v_immutable ).toVar();
  33862. return mul( 0.9820, v );
  33863. } ).setLayout( {
  33864. name: 'mx_gradient_scale3d_1',
  33865. type: 'vec3',
  33866. inputs: [
  33867. { name: 'v', type: 'vec3' }
  33868. ]
  33869. } );
  33870. const mx_gradient_scale3d = /*#__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  33871. const mx_rotl32 = /*#__PURE__*/ tslFn( ( [ x_immutable, k_immutable ] ) => {
  33872. const k = int( k_immutable ).toVar();
  33873. const x = uint( x_immutable ).toVar();
  33874. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  33875. } ).setLayout( {
  33876. name: 'mx_rotl32',
  33877. type: 'uint',
  33878. inputs: [
  33879. { name: 'x', type: 'uint' },
  33880. { name: 'k', type: 'int' }
  33881. ]
  33882. } );
  33883. const mx_bjmix = /*#__PURE__*/ tslFn( ( [ a, b, c ] ) => {
  33884. a.subAssign( c );
  33885. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  33886. c.addAssign( b );
  33887. b.subAssign( a );
  33888. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  33889. a.addAssign( c );
  33890. c.subAssign( b );
  33891. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  33892. b.addAssign( a );
  33893. a.subAssign( c );
  33894. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  33895. c.addAssign( b );
  33896. b.subAssign( a );
  33897. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  33898. a.addAssign( c );
  33899. c.subAssign( b );
  33900. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  33901. b.addAssign( a );
  33902. } );
  33903. const mx_bjfinal = /*#__PURE__*/ tslFn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  33904. const c = uint( c_immutable ).toVar();
  33905. const b = uint( b_immutable ).toVar();
  33906. const a = uint( a_immutable ).toVar();
  33907. c.bitXorAssign( b );
  33908. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  33909. a.bitXorAssign( c );
  33910. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  33911. b.bitXorAssign( a );
  33912. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  33913. c.bitXorAssign( b );
  33914. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  33915. a.bitXorAssign( c );
  33916. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  33917. b.bitXorAssign( a );
  33918. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  33919. c.bitXorAssign( b );
  33920. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  33921. return c;
  33922. } ).setLayout( {
  33923. name: 'mx_bjfinal',
  33924. type: 'uint',
  33925. inputs: [
  33926. { name: 'a', type: 'uint' },
  33927. { name: 'b', type: 'uint' },
  33928. { name: 'c', type: 'uint' }
  33929. ]
  33930. } );
  33931. const mx_bits_to_01 = /*#__PURE__*/ tslFn( ( [ bits_immutable ] ) => {
  33932. const bits = uint( bits_immutable ).toVar();
  33933. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  33934. } ).setLayout( {
  33935. name: 'mx_bits_to_01',
  33936. type: 'float',
  33937. inputs: [
  33938. { name: 'bits', type: 'uint' }
  33939. ]
  33940. } );
  33941. const mx_fade = /*#__PURE__*/ tslFn( ( [ t_immutable ] ) => {
  33942. const t = float( t_immutable ).toVar();
  33943. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  33944. } ).setLayout( {
  33945. name: 'mx_fade',
  33946. type: 'float',
  33947. inputs: [
  33948. { name: 't', type: 'float' }
  33949. ]
  33950. } );
  33951. const mx_hash_int_0 = /*#__PURE__*/ tslFn( ( [ x_immutable ] ) => {
  33952. const x = int( x_immutable ).toVar();
  33953. const len = uint( uint( 1 ) ).toVar();
  33954. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  33955. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  33956. } ).setLayout( {
  33957. name: 'mx_hash_int_0',
  33958. type: 'uint',
  33959. inputs: [
  33960. { name: 'x', type: 'int' }
  33961. ]
  33962. } );
  33963. const mx_hash_int_1 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable ] ) => {
  33964. const y = int( y_immutable ).toVar();
  33965. const x = int( x_immutable ).toVar();
  33966. const len = uint( uint( 2 ) ).toVar();
  33967. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  33968. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  33969. a.addAssign( uint( x ) );
  33970. b.addAssign( uint( y ) );
  33971. return mx_bjfinal( a, b, c );
  33972. } ).setLayout( {
  33973. name: 'mx_hash_int_1',
  33974. type: 'uint',
  33975. inputs: [
  33976. { name: 'x', type: 'int' },
  33977. { name: 'y', type: 'int' }
  33978. ]
  33979. } );
  33980. const mx_hash_int_2 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  33981. const z = int( z_immutable ).toVar();
  33982. const y = int( y_immutable ).toVar();
  33983. const x = int( x_immutable ).toVar();
  33984. const len = uint( uint( 3 ) ).toVar();
  33985. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  33986. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  33987. a.addAssign( uint( x ) );
  33988. b.addAssign( uint( y ) );
  33989. c.addAssign( uint( z ) );
  33990. return mx_bjfinal( a, b, c );
  33991. } ).setLayout( {
  33992. name: 'mx_hash_int_2',
  33993. type: 'uint',
  33994. inputs: [
  33995. { name: 'x', type: 'int' },
  33996. { name: 'y', type: 'int' },
  33997. { name: 'z', type: 'int' }
  33998. ]
  33999. } );
  34000. const mx_hash_int_3 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  34001. const xx = int( xx_immutable ).toVar();
  34002. const z = int( z_immutable ).toVar();
  34003. const y = int( y_immutable ).toVar();
  34004. const x = int( x_immutable ).toVar();
  34005. const len = uint( uint( 4 ) ).toVar();
  34006. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34007. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34008. a.addAssign( uint( x ) );
  34009. b.addAssign( uint( y ) );
  34010. c.addAssign( uint( z ) );
  34011. mx_bjmix( a, b, c );
  34012. a.addAssign( uint( xx ) );
  34013. return mx_bjfinal( a, b, c );
  34014. } ).setLayout( {
  34015. name: 'mx_hash_int_3',
  34016. type: 'uint',
  34017. inputs: [
  34018. { name: 'x', type: 'int' },
  34019. { name: 'y', type: 'int' },
  34020. { name: 'z', type: 'int' },
  34021. { name: 'xx', type: 'int' }
  34022. ]
  34023. } );
  34024. const mx_hash_int_4 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  34025. const yy = int( yy_immutable ).toVar();
  34026. const xx = int( xx_immutable ).toVar();
  34027. const z = int( z_immutable ).toVar();
  34028. const y = int( y_immutable ).toVar();
  34029. const x = int( x_immutable ).toVar();
  34030. const len = uint( uint( 5 ) ).toVar();
  34031. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34032. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34033. a.addAssign( uint( x ) );
  34034. b.addAssign( uint( y ) );
  34035. c.addAssign( uint( z ) );
  34036. mx_bjmix( a, b, c );
  34037. a.addAssign( uint( xx ) );
  34038. b.addAssign( uint( yy ) );
  34039. return mx_bjfinal( a, b, c );
  34040. } ).setLayout( {
  34041. name: 'mx_hash_int_4',
  34042. type: 'uint',
  34043. inputs: [
  34044. { name: 'x', type: 'int' },
  34045. { name: 'y', type: 'int' },
  34046. { name: 'z', type: 'int' },
  34047. { name: 'xx', type: 'int' },
  34048. { name: 'yy', type: 'int' }
  34049. ]
  34050. } );
  34051. 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 ] );
  34052. const mx_hash_vec3_0 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable ] ) => {
  34053. const y = int( y_immutable ).toVar();
  34054. const x = int( x_immutable ).toVar();
  34055. const h = uint( mx_hash_int( x, y ) ).toVar();
  34056. const result = uvec3().toVar();
  34057. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  34058. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  34059. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  34060. return result;
  34061. } ).setLayout( {
  34062. name: 'mx_hash_vec3_0',
  34063. type: 'uvec3',
  34064. inputs: [
  34065. { name: 'x', type: 'int' },
  34066. { name: 'y', type: 'int' }
  34067. ]
  34068. } );
  34069. const mx_hash_vec3_1 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  34070. const z = int( z_immutable ).toVar();
  34071. const y = int( y_immutable ).toVar();
  34072. const x = int( x_immutable ).toVar();
  34073. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  34074. const result = uvec3().toVar();
  34075. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  34076. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  34077. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  34078. return result;
  34079. } ).setLayout( {
  34080. name: 'mx_hash_vec3_1',
  34081. type: 'uvec3',
  34082. inputs: [
  34083. { name: 'x', type: 'int' },
  34084. { name: 'y', type: 'int' },
  34085. { name: 'z', type: 'int' }
  34086. ]
  34087. } );
  34088. const mx_hash_vec3 = /*#__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  34089. const mx_perlin_noise_float_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34090. const p = vec2( p_immutable ).toVar();
  34091. const X = int().toVar(), Y = int().toVar();
  34092. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34093. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34094. const u = float( mx_fade( fx ) ).toVar();
  34095. const v = float( mx_fade( fy ) ).toVar();
  34096. 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();
  34097. return mx_gradient_scale2d( result );
  34098. } ).setLayout( {
  34099. name: 'mx_perlin_noise_float_0',
  34100. type: 'float',
  34101. inputs: [
  34102. { name: 'p', type: 'vec2' }
  34103. ]
  34104. } );
  34105. const mx_perlin_noise_float_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34106. const p = vec3( p_immutable ).toVar();
  34107. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34108. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34109. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34110. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  34111. const u = float( mx_fade( fx ) ).toVar();
  34112. const v = float( mx_fade( fy ) ).toVar();
  34113. const w = float( mx_fade( fz ) ).toVar();
  34114. 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();
  34115. return mx_gradient_scale3d( result );
  34116. } ).setLayout( {
  34117. name: 'mx_perlin_noise_float_1',
  34118. type: 'float',
  34119. inputs: [
  34120. { name: 'p', type: 'vec3' }
  34121. ]
  34122. } );
  34123. const mx_perlin_noise_float = /*#__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  34124. const mx_perlin_noise_vec3_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34125. const p = vec2( p_immutable ).toVar();
  34126. const X = int().toVar(), Y = int().toVar();
  34127. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34128. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34129. const u = float( mx_fade( fx ) ).toVar();
  34130. const v = float( mx_fade( fy ) ).toVar();
  34131. 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();
  34132. return mx_gradient_scale2d( result );
  34133. } ).setLayout( {
  34134. name: 'mx_perlin_noise_vec3_0',
  34135. type: 'vec3',
  34136. inputs: [
  34137. { name: 'p', type: 'vec2' }
  34138. ]
  34139. } );
  34140. const mx_perlin_noise_vec3_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34141. const p = vec3( p_immutable ).toVar();
  34142. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34143. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34144. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34145. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  34146. const u = float( mx_fade( fx ) ).toVar();
  34147. const v = float( mx_fade( fy ) ).toVar();
  34148. const w = float( mx_fade( fz ) ).toVar();
  34149. 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();
  34150. return mx_gradient_scale3d( result );
  34151. } ).setLayout( {
  34152. name: 'mx_perlin_noise_vec3_1',
  34153. type: 'vec3',
  34154. inputs: [
  34155. { name: 'p', type: 'vec3' }
  34156. ]
  34157. } );
  34158. const mx_perlin_noise_vec3 = /*#__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  34159. const mx_cell_noise_float_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34160. const p = float( p_immutable ).toVar();
  34161. const ix = int( mx_floor( p ) ).toVar();
  34162. return mx_bits_to_01( mx_hash_int( ix ) );
  34163. } ).setLayout( {
  34164. name: 'mx_cell_noise_float_0',
  34165. type: 'float',
  34166. inputs: [
  34167. { name: 'p', type: 'float' }
  34168. ]
  34169. } );
  34170. const mx_cell_noise_float_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34171. const p = vec2( p_immutable ).toVar();
  34172. const ix = int( mx_floor( p.x ) ).toVar();
  34173. const iy = int( mx_floor( p.y ) ).toVar();
  34174. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  34175. } ).setLayout( {
  34176. name: 'mx_cell_noise_float_1',
  34177. type: 'float',
  34178. inputs: [
  34179. { name: 'p', type: 'vec2' }
  34180. ]
  34181. } );
  34182. const mx_cell_noise_float_2 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34183. const p = vec3( p_immutable ).toVar();
  34184. const ix = int( mx_floor( p.x ) ).toVar();
  34185. const iy = int( mx_floor( p.y ) ).toVar();
  34186. const iz = int( mx_floor( p.z ) ).toVar();
  34187. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  34188. } ).setLayout( {
  34189. name: 'mx_cell_noise_float_2',
  34190. type: 'float',
  34191. inputs: [
  34192. { name: 'p', type: 'vec3' }
  34193. ]
  34194. } );
  34195. const mx_cell_noise_float_3 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34196. const p = vec4( p_immutable ).toVar();
  34197. const ix = int( mx_floor( p.x ) ).toVar();
  34198. const iy = int( mx_floor( p.y ) ).toVar();
  34199. const iz = int( mx_floor( p.z ) ).toVar();
  34200. const iw = int( mx_floor( p.w ) ).toVar();
  34201. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  34202. } ).setLayout( {
  34203. name: 'mx_cell_noise_float_3',
  34204. type: 'float',
  34205. inputs: [
  34206. { name: 'p', type: 'vec4' }
  34207. ]
  34208. } );
  34209. 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 ] );
  34210. const mx_cell_noise_vec3_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34211. const p = float( p_immutable ).toVar();
  34212. const ix = int( mx_floor( p ) ).toVar();
  34213. 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 ) ) ) );
  34214. } ).setLayout( {
  34215. name: 'mx_cell_noise_vec3_0',
  34216. type: 'vec3',
  34217. inputs: [
  34218. { name: 'p', type: 'float' }
  34219. ]
  34220. } );
  34221. const mx_cell_noise_vec3_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34222. const p = vec2( p_immutable ).toVar();
  34223. const ix = int( mx_floor( p.x ) ).toVar();
  34224. const iy = int( mx_floor( p.y ) ).toVar();
  34225. 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 ) ) ) );
  34226. } ).setLayout( {
  34227. name: 'mx_cell_noise_vec3_1',
  34228. type: 'vec3',
  34229. inputs: [
  34230. { name: 'p', type: 'vec2' }
  34231. ]
  34232. } );
  34233. const mx_cell_noise_vec3_2 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34234. const p = vec3( p_immutable ).toVar();
  34235. const ix = int( mx_floor( p.x ) ).toVar();
  34236. const iy = int( mx_floor( p.y ) ).toVar();
  34237. const iz = int( mx_floor( p.z ) ).toVar();
  34238. 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 ) ) ) );
  34239. } ).setLayout( {
  34240. name: 'mx_cell_noise_vec3_2',
  34241. type: 'vec3',
  34242. inputs: [
  34243. { name: 'p', type: 'vec3' }
  34244. ]
  34245. } );
  34246. const mx_cell_noise_vec3_3 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34247. const p = vec4( p_immutable ).toVar();
  34248. const ix = int( mx_floor( p.x ) ).toVar();
  34249. const iy = int( mx_floor( p.y ) ).toVar();
  34250. const iz = int( mx_floor( p.z ) ).toVar();
  34251. const iw = int( mx_floor( p.w ) ).toVar();
  34252. 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 ) ) ) );
  34253. } ).setLayout( {
  34254. name: 'mx_cell_noise_vec3_3',
  34255. type: 'vec3',
  34256. inputs: [
  34257. { name: 'p', type: 'vec4' }
  34258. ]
  34259. } );
  34260. 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 ] );
  34261. const mx_fractal_noise_float$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34262. const diminish = float( diminish_immutable ).toVar();
  34263. const lacunarity = float( lacunarity_immutable ).toVar();
  34264. const octaves = int( octaves_immutable ).toVar();
  34265. const p = vec3( p_immutable ).toVar();
  34266. const result = float( 0.0 ).toVar();
  34267. const amplitude = float( 1.0 ).toVar();
  34268. loop( octaves, () => {
  34269. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  34270. amplitude.mulAssign( diminish );
  34271. p.mulAssign( lacunarity );
  34272. } );
  34273. return result;
  34274. } ).setLayout( {
  34275. name: 'mx_fractal_noise_float',
  34276. type: 'float',
  34277. inputs: [
  34278. { name: 'p', type: 'vec3' },
  34279. { name: 'octaves', type: 'int' },
  34280. { name: 'lacunarity', type: 'float' },
  34281. { name: 'diminish', type: 'float' }
  34282. ]
  34283. } );
  34284. const mx_fractal_noise_vec3$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34285. const diminish = float( diminish_immutable ).toVar();
  34286. const lacunarity = float( lacunarity_immutable ).toVar();
  34287. const octaves = int( octaves_immutable ).toVar();
  34288. const p = vec3( p_immutable ).toVar();
  34289. const result = vec3( 0.0 ).toVar();
  34290. const amplitude = float( 1.0 ).toVar();
  34291. loop( octaves, () => {
  34292. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  34293. amplitude.mulAssign( diminish );
  34294. p.mulAssign( lacunarity );
  34295. } );
  34296. return result;
  34297. } ).setLayout( {
  34298. name: 'mx_fractal_noise_vec3',
  34299. type: 'vec3',
  34300. inputs: [
  34301. { name: 'p', type: 'vec3' },
  34302. { name: 'octaves', type: 'int' },
  34303. { name: 'lacunarity', type: 'float' },
  34304. { name: 'diminish', type: 'float' }
  34305. ]
  34306. } );
  34307. const mx_fractal_noise_vec2$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34308. const diminish = float( diminish_immutable ).toVar();
  34309. const lacunarity = float( lacunarity_immutable ).toVar();
  34310. const octaves = int( octaves_immutable ).toVar();
  34311. const p = vec3( p_immutable ).toVar();
  34312. 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 ) );
  34313. } ).setLayout( {
  34314. name: 'mx_fractal_noise_vec2',
  34315. type: 'vec2',
  34316. inputs: [
  34317. { name: 'p', type: 'vec3' },
  34318. { name: 'octaves', type: 'int' },
  34319. { name: 'lacunarity', type: 'float' },
  34320. { name: 'diminish', type: 'float' }
  34321. ]
  34322. } );
  34323. const mx_fractal_noise_vec4$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34324. const diminish = float( diminish_immutable ).toVar();
  34325. const lacunarity = float( lacunarity_immutable ).toVar();
  34326. const octaves = int( octaves_immutable ).toVar();
  34327. const p = vec3( p_immutable ).toVar();
  34328. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  34329. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  34330. return vec4( c, f );
  34331. } ).setLayout( {
  34332. name: 'mx_fractal_noise_vec4',
  34333. type: 'vec4',
  34334. inputs: [
  34335. { name: 'p', type: 'vec3' },
  34336. { name: 'octaves', type: 'int' },
  34337. { name: 'lacunarity', type: 'float' },
  34338. { name: 'diminish', type: 'float' }
  34339. ]
  34340. } );
  34341. const mx_worley_distance_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  34342. const metric = int( metric_immutable ).toVar();
  34343. const jitter = float( jitter_immutable ).toVar();
  34344. const yoff = int( yoff_immutable ).toVar();
  34345. const xoff = int( xoff_immutable ).toVar();
  34346. const y = int( y_immutable ).toVar();
  34347. const x = int( x_immutable ).toVar();
  34348. const p = vec2( p_immutable ).toVar();
  34349. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  34350. const off = vec2( tmp.x, tmp.y ).toVar();
  34351. off.subAssign( 0.5 );
  34352. off.mulAssign( jitter );
  34353. off.addAssign( 0.5 );
  34354. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  34355. const diff = vec2( cellpos.sub( p ) ).toVar();
  34356. If( metric.equal( int( 2 ) ), () => {
  34357. return abs( diff.x ).add( abs( diff.y ) );
  34358. } );
  34359. If( metric.equal( int( 3 ) ), () => {
  34360. return max$1( abs( diff.x ), abs( diff.y ) );
  34361. } );
  34362. return dot( diff, diff );
  34363. } ).setLayout( {
  34364. name: 'mx_worley_distance_0',
  34365. type: 'float',
  34366. inputs: [
  34367. { name: 'p', type: 'vec2' },
  34368. { name: 'x', type: 'int' },
  34369. { name: 'y', type: 'int' },
  34370. { name: 'xoff', type: 'int' },
  34371. { name: 'yoff', type: 'int' },
  34372. { name: 'jitter', type: 'float' },
  34373. { name: 'metric', type: 'int' }
  34374. ]
  34375. } );
  34376. 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 ] ) => {
  34377. const metric = int( metric_immutable ).toVar();
  34378. const jitter = float( jitter_immutable ).toVar();
  34379. const zoff = int( zoff_immutable ).toVar();
  34380. const yoff = int( yoff_immutable ).toVar();
  34381. const xoff = int( xoff_immutable ).toVar();
  34382. const z = int( z_immutable ).toVar();
  34383. const y = int( y_immutable ).toVar();
  34384. const x = int( x_immutable ).toVar();
  34385. const p = vec3( p_immutable ).toVar();
  34386. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  34387. off.subAssign( 0.5 );
  34388. off.mulAssign( jitter );
  34389. off.addAssign( 0.5 );
  34390. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  34391. const diff = vec3( cellpos.sub( p ) ).toVar();
  34392. If( metric.equal( int( 2 ) ), () => {
  34393. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  34394. } );
  34395. If( metric.equal( int( 3 ) ), () => {
  34396. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  34397. } );
  34398. return dot( diff, diff );
  34399. } ).setLayout( {
  34400. name: 'mx_worley_distance_1',
  34401. type: 'float',
  34402. inputs: [
  34403. { name: 'p', type: 'vec3' },
  34404. { name: 'x', type: 'int' },
  34405. { name: 'y', type: 'int' },
  34406. { name: 'z', type: 'int' },
  34407. { name: 'xoff', type: 'int' },
  34408. { name: 'yoff', type: 'int' },
  34409. { name: 'zoff', type: 'int' },
  34410. { name: 'jitter', type: 'float' },
  34411. { name: 'metric', type: 'int' }
  34412. ]
  34413. } );
  34414. const mx_worley_distance = /*#__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  34415. const mx_worley_noise_float_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34416. const metric = int( metric_immutable ).toVar();
  34417. const jitter = float( jitter_immutable ).toVar();
  34418. const p = vec2( p_immutable ).toVar();
  34419. const X = int().toVar(), Y = int().toVar();
  34420. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34421. const sqdist = float( 1e6 ).toVar();
  34422. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34423. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34424. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34425. sqdist.assign( min$1( sqdist, dist ) );
  34426. } );
  34427. } );
  34428. If( metric.equal( int( 0 ) ), () => {
  34429. sqdist.assign( sqrt( sqdist ) );
  34430. } );
  34431. return sqdist;
  34432. } ).setLayout( {
  34433. name: 'mx_worley_noise_float_0',
  34434. type: 'float',
  34435. inputs: [
  34436. { name: 'p', type: 'vec2' },
  34437. { name: 'jitter', type: 'float' },
  34438. { name: 'metric', type: 'int' }
  34439. ]
  34440. } );
  34441. const mx_worley_noise_vec2_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34442. const metric = int( metric_immutable ).toVar();
  34443. const jitter = float( jitter_immutable ).toVar();
  34444. const p = vec2( p_immutable ).toVar();
  34445. const X = int().toVar(), Y = int().toVar();
  34446. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34447. const sqdist = vec2( 1e6, 1e6 ).toVar();
  34448. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34449. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34450. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34451. If( dist.lessThan( sqdist.x ), () => {
  34452. sqdist.y.assign( sqdist.x );
  34453. sqdist.x.assign( dist );
  34454. } ).elseif( dist.lessThan( sqdist.y ), () => {
  34455. sqdist.y.assign( dist );
  34456. } );
  34457. } );
  34458. } );
  34459. If( metric.equal( int( 0 ) ), () => {
  34460. sqdist.assign( sqrt( sqdist ) );
  34461. } );
  34462. return sqdist;
  34463. } ).setLayout( {
  34464. name: 'mx_worley_noise_vec2_0',
  34465. type: 'vec2',
  34466. inputs: [
  34467. { name: 'p', type: 'vec2' },
  34468. { name: 'jitter', type: 'float' },
  34469. { name: 'metric', type: 'int' }
  34470. ]
  34471. } );
  34472. const mx_worley_noise_vec3_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34473. const metric = int( metric_immutable ).toVar();
  34474. const jitter = float( jitter_immutable ).toVar();
  34475. const p = vec2( p_immutable ).toVar();
  34476. const X = int().toVar(), Y = int().toVar();
  34477. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34478. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  34479. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34480. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34481. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34482. If( dist.lessThan( sqdist.x ), () => {
  34483. sqdist.z.assign( sqdist.y );
  34484. sqdist.y.assign( sqdist.x );
  34485. sqdist.x.assign( dist );
  34486. } ).elseif( dist.lessThan( sqdist.y ), () => {
  34487. sqdist.z.assign( sqdist.y );
  34488. sqdist.y.assign( dist );
  34489. } ).elseif( dist.lessThan( sqdist.z ), () => {
  34490. sqdist.z.assign( dist );
  34491. } );
  34492. } );
  34493. } );
  34494. If( metric.equal( int( 0 ) ), () => {
  34495. sqdist.assign( sqrt( sqdist ) );
  34496. } );
  34497. return sqdist;
  34498. } ).setLayout( {
  34499. name: 'mx_worley_noise_vec3_0',
  34500. type: 'vec3',
  34501. inputs: [
  34502. { name: 'p', type: 'vec2' },
  34503. { name: 'jitter', type: 'float' },
  34504. { name: 'metric', type: 'int' }
  34505. ]
  34506. } );
  34507. const mx_worley_noise_float_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34508. const metric = int( metric_immutable ).toVar();
  34509. const jitter = float( jitter_immutable ).toVar();
  34510. const p = vec3( p_immutable ).toVar();
  34511. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34512. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34513. const sqdist = float( 1e6 ).toVar();
  34514. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34515. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34516. loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34517. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34518. sqdist.assign( min$1( sqdist, dist ) );
  34519. } );
  34520. } );
  34521. } );
  34522. If( metric.equal( int( 0 ) ), () => {
  34523. sqdist.assign( sqrt( sqdist ) );
  34524. } );
  34525. return sqdist;
  34526. } ).setLayout( {
  34527. name: 'mx_worley_noise_float_1',
  34528. type: 'float',
  34529. inputs: [
  34530. { name: 'p', type: 'vec3' },
  34531. { name: 'jitter', type: 'float' },
  34532. { name: 'metric', type: 'int' }
  34533. ]
  34534. } );
  34535. const mx_worley_noise_float$1 = /*#__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  34536. const mx_worley_noise_vec2_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34537. const metric = int( metric_immutable ).toVar();
  34538. const jitter = float( jitter_immutable ).toVar();
  34539. const p = vec3( p_immutable ).toVar();
  34540. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34541. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34542. const sqdist = vec2( 1e6, 1e6 ).toVar();
  34543. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34544. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34545. loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34546. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34547. If( dist.lessThan( sqdist.x ), () => {
  34548. sqdist.y.assign( sqdist.x );
  34549. sqdist.x.assign( dist );
  34550. } ).elseif( dist.lessThan( sqdist.y ), () => {
  34551. sqdist.y.assign( dist );
  34552. } );
  34553. } );
  34554. } );
  34555. } );
  34556. If( metric.equal( int( 0 ) ), () => {
  34557. sqdist.assign( sqrt( sqdist ) );
  34558. } );
  34559. return sqdist;
  34560. } ).setLayout( {
  34561. name: 'mx_worley_noise_vec2_1',
  34562. type: 'vec2',
  34563. inputs: [
  34564. { name: 'p', type: 'vec3' },
  34565. { name: 'jitter', type: 'float' },
  34566. { name: 'metric', type: 'int' }
  34567. ]
  34568. } );
  34569. const mx_worley_noise_vec2$1 = /*#__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  34570. const mx_worley_noise_vec3_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34571. const metric = int( metric_immutable ).toVar();
  34572. const jitter = float( jitter_immutable ).toVar();
  34573. const p = vec3( p_immutable ).toVar();
  34574. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34575. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34576. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  34577. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34578. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34579. loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34580. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34581. If( dist.lessThan( sqdist.x ), () => {
  34582. sqdist.z.assign( sqdist.y );
  34583. sqdist.y.assign( sqdist.x );
  34584. sqdist.x.assign( dist );
  34585. } ).elseif( dist.lessThan( sqdist.y ), () => {
  34586. sqdist.z.assign( sqdist.y );
  34587. sqdist.y.assign( dist );
  34588. } ).elseif( dist.lessThan( sqdist.z ), () => {
  34589. sqdist.z.assign( dist );
  34590. } );
  34591. } );
  34592. } );
  34593. } );
  34594. If( metric.equal( int( 0 ) ), () => {
  34595. sqdist.assign( sqrt( sqdist ) );
  34596. } );
  34597. return sqdist;
  34598. } ).setLayout( {
  34599. name: 'mx_worley_noise_vec3_1',
  34600. type: 'vec3',
  34601. inputs: [
  34602. { name: 'p', type: 'vec3' },
  34603. { name: 'jitter', type: 'float' },
  34604. { name: 'metric', type: 'int' }
  34605. ]
  34606. } );
  34607. const mx_worley_noise_vec3$1 = /*#__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  34608. // Three.js Transpiler
  34609. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  34610. const mx_hsvtorgb = /*#__PURE__*/ tslFn( ( [ hsv_immutable ] ) => {
  34611. const hsv = vec3( hsv_immutable ).toVar();
  34612. const h = float( hsv.x ).toVar();
  34613. const s = float( hsv.y ).toVar();
  34614. const v = float( hsv.z ).toVar();
  34615. If( s.lessThan( 0.0001 ), () => {
  34616. return vec3( v, v, v );
  34617. } ).else( () => {
  34618. h.assign( mul( 6.0, h.sub( floor( h ) ) ) );
  34619. const hi = int( trunc( h ) ).toVar();
  34620. const f = float( h.sub( float( hi ) ) ).toVar();
  34621. const p = float( v.mul( sub( 1.0, s ) ) ).toVar();
  34622. const q = float( v.mul( sub( 1.0, s.mul( f ) ) ) ).toVar();
  34623. const t = float( v.mul( sub( 1.0, s.mul( sub( 1.0, f ) ) ) ) ).toVar();
  34624. If( hi.equal( int( 0 ) ), () => {
  34625. return vec3( v, t, p );
  34626. } ).elseif( hi.equal( int( 1 ) ), () => {
  34627. return vec3( q, v, p );
  34628. } ).elseif( hi.equal( int( 2 ) ), () => {
  34629. return vec3( p, v, t );
  34630. } ).elseif( hi.equal( int( 3 ) ), () => {
  34631. return vec3( p, q, v );
  34632. } ).elseif( hi.equal( int( 4 ) ), () => {
  34633. return vec3( t, p, v );
  34634. } );
  34635. return vec3( v, p, q );
  34636. } );
  34637. } ).setLayout( {
  34638. name: 'mx_hsvtorgb',
  34639. type: 'vec3',
  34640. inputs: [
  34641. { name: 'hsv', type: 'vec3' }
  34642. ]
  34643. } );
  34644. const mx_rgbtohsv = /*#__PURE__*/ tslFn( ( [ c_immutable ] ) => {
  34645. const c = vec3( c_immutable ).toVar();
  34646. const r = float( c.x ).toVar();
  34647. const g = float( c.y ).toVar();
  34648. const b = float( c.z ).toVar();
  34649. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  34650. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  34651. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  34652. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  34653. v.assign( maxcomp );
  34654. If( maxcomp.greaterThan( 0.0 ), () => {
  34655. s.assign( delta.div( maxcomp ) );
  34656. } ).else( () => {
  34657. s.assign( 0.0 );
  34658. } );
  34659. If( s.lessThanEqual( 0.0 ), () => {
  34660. h.assign( 0.0 );
  34661. } ).else( () => {
  34662. If( r.greaterThanEqual( maxcomp ), () => {
  34663. h.assign( g.sub( b ).div( delta ) );
  34664. } ).elseif( g.greaterThanEqual( maxcomp ), () => {
  34665. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  34666. } ).else( () => {
  34667. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  34668. } );
  34669. h.mulAssign( 1.0 / 6.0 );
  34670. If( h.lessThan( 0.0 ), () => {
  34671. h.addAssign( 1.0 );
  34672. } );
  34673. } );
  34674. return vec3( h, s, v );
  34675. } ).setLayout( {
  34676. name: 'mx_rgbtohsv',
  34677. type: 'vec3',
  34678. inputs: [
  34679. { name: 'c', type: 'vec3' }
  34680. ]
  34681. } );
  34682. // Three.js Transpiler
  34683. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  34684. const mx_srgb_texture_to_lin_rec709 = /*#__PURE__*/ tslFn( ( [ color_immutable ] ) => {
  34685. const color = vec3( color_immutable ).toVar();
  34686. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  34687. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  34688. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  34689. return mix( linSeg, powSeg, isAbove );
  34690. } ).setLayout( {
  34691. name: 'mx_srgb_texture_to_lin_rec709',
  34692. type: 'vec3',
  34693. inputs: [
  34694. { name: 'color', type: 'vec3' }
  34695. ]
  34696. } );
  34697. const mx_aastep = ( threshold, value ) => {
  34698. threshold = float( threshold );
  34699. value = float( value );
  34700. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  34701. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  34702. };
  34703. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  34704. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  34705. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  34706. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  34707. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  34708. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  34709. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  34710. const mx_safepower = ( in1, in2 = 1 ) => {
  34711. in1 = float( in1 );
  34712. return in1.abs().pow( in2 ).mul( in1.sign() );
  34713. };
  34714. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  34715. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  34716. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  34717. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  34718. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  34719. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  34720. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  34721. return noise_vec4.mul( amplitude ).add( pivot );
  34722. };
  34723. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  34724. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  34725. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  34726. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  34727. 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 );
  34728. 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 );
  34729. 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 );
  34730. 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 );
  34731. function painterSortStable( a, b ) {
  34732. if ( a.groupOrder !== b.groupOrder ) {
  34733. return a.groupOrder - b.groupOrder;
  34734. } else if ( a.renderOrder !== b.renderOrder ) {
  34735. return a.renderOrder - b.renderOrder;
  34736. } else if ( a.material.id !== b.material.id ) {
  34737. return a.material.id - b.material.id;
  34738. } else if ( a.z !== b.z ) {
  34739. return a.z - b.z;
  34740. } else {
  34741. return a.id - b.id;
  34742. }
  34743. }
  34744. function reversePainterSortStable( a, b ) {
  34745. if ( a.groupOrder !== b.groupOrder ) {
  34746. return a.groupOrder - b.groupOrder;
  34747. } else if ( a.renderOrder !== b.renderOrder ) {
  34748. return a.renderOrder - b.renderOrder;
  34749. } else if ( a.z !== b.z ) {
  34750. return b.z - a.z;
  34751. } else {
  34752. return a.id - b.id;
  34753. }
  34754. }
  34755. class RenderList {
  34756. constructor() {
  34757. this.renderItems = [];
  34758. this.renderItemsIndex = 0;
  34759. this.opaque = [];
  34760. this.transparent = [];
  34761. this.bundles = [];
  34762. this.lightsNode = new LightsNode( [] );
  34763. this.lightsArray = [];
  34764. this.occlusionQueryCount = 0;
  34765. }
  34766. begin() {
  34767. this.renderItemsIndex = 0;
  34768. this.opaque.length = 0;
  34769. this.transparent.length = 0;
  34770. this.bundles.length = 0;
  34771. this.lightsArray.length = 0;
  34772. this.occlusionQueryCount = 0;
  34773. return this;
  34774. }
  34775. getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  34776. let renderItem = this.renderItems[ this.renderItemsIndex ];
  34777. if ( renderItem === undefined ) {
  34778. renderItem = {
  34779. id: object.id,
  34780. object: object,
  34781. geometry: geometry,
  34782. material: material,
  34783. groupOrder: groupOrder,
  34784. renderOrder: object.renderOrder,
  34785. z: z,
  34786. group: group
  34787. };
  34788. this.renderItems[ this.renderItemsIndex ] = renderItem;
  34789. } else {
  34790. renderItem.id = object.id;
  34791. renderItem.object = object;
  34792. renderItem.geometry = geometry;
  34793. renderItem.material = material;
  34794. renderItem.groupOrder = groupOrder;
  34795. renderItem.renderOrder = object.renderOrder;
  34796. renderItem.z = z;
  34797. renderItem.group = group;
  34798. }
  34799. this.renderItemsIndex ++;
  34800. return renderItem;
  34801. }
  34802. push( object, geometry, material, groupOrder, z, group ) {
  34803. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  34804. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  34805. ( material.transparent === true || material.transmission > 0 ? this.transparent : this.opaque ).push( renderItem );
  34806. }
  34807. unshift( object, geometry, material, groupOrder, z, group ) {
  34808. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  34809. ( material.transparent === true ? this.transparent : this.opaque ).unshift( renderItem );
  34810. }
  34811. pushBundle( group ) {
  34812. this.bundles.push( group );
  34813. }
  34814. pushLight( light ) {
  34815. this.lightsArray.push( light );
  34816. }
  34817. getLightsNode() {
  34818. return this.lightsNode.fromLights( this.lightsArray );
  34819. }
  34820. sort( customOpaqueSort, customTransparentSort ) {
  34821. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  34822. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  34823. }
  34824. finish() {
  34825. // update lights
  34826. this.lightsNode.fromLights( this.lightsArray );
  34827. // Clear references from inactive renderItems in the list
  34828. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  34829. const renderItem = this.renderItems[ i ];
  34830. if ( renderItem.id === null ) break;
  34831. renderItem.id = null;
  34832. renderItem.object = null;
  34833. renderItem.geometry = null;
  34834. renderItem.material = null;
  34835. renderItem.groupOrder = null;
  34836. renderItem.renderOrder = null;
  34837. renderItem.z = null;
  34838. renderItem.group = null;
  34839. }
  34840. }
  34841. }
  34842. class RenderLists {
  34843. constructor() {
  34844. this.lists = new ChainMap();
  34845. }
  34846. get( scene, camera ) {
  34847. const lists = this.lists;
  34848. const keys = [ scene, camera ];
  34849. let list = lists.get( keys );
  34850. if ( list === undefined ) {
  34851. list = new RenderList();
  34852. lists.set( keys, list );
  34853. }
  34854. return list;
  34855. }
  34856. dispose() {
  34857. this.lists = new ChainMap();
  34858. }
  34859. }
  34860. let id$2 = 0;
  34861. class RenderContext {
  34862. constructor() {
  34863. this.id = id$2 ++;
  34864. this.color = true;
  34865. this.clearColor = true;
  34866. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  34867. this.depth = true;
  34868. this.clearDepth = true;
  34869. this.clearDepthValue = 1;
  34870. this.stencil = false;
  34871. this.clearStencil = true;
  34872. this.clearStencilValue = 1;
  34873. this.viewport = false;
  34874. this.viewportValue = new Vector4();
  34875. this.scissor = false;
  34876. this.scissorValue = new Vector4();
  34877. this.textures = null;
  34878. this.depthTexture = null;
  34879. this.activeCubeFace = 0;
  34880. this.sampleCount = 1;
  34881. this.width = 0;
  34882. this.height = 0;
  34883. this.isRenderContext = true;
  34884. }
  34885. }
  34886. class RenderContexts {
  34887. constructor() {
  34888. this.chainMaps = {};
  34889. }
  34890. get( scene, camera, renderTarget = null ) {
  34891. const chainKey = [ scene, camera ];
  34892. let attachmentState;
  34893. if ( renderTarget === null ) {
  34894. attachmentState = 'default';
  34895. } else {
  34896. const format = renderTarget.texture.format;
  34897. const count = renderTarget.count;
  34898. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  34899. }
  34900. const chainMap = this.getChainMap( attachmentState );
  34901. let renderState = chainMap.get( chainKey );
  34902. if ( renderState === undefined ) {
  34903. renderState = new RenderContext();
  34904. chainMap.set( chainKey, renderState );
  34905. }
  34906. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  34907. return renderState;
  34908. }
  34909. getChainMap( attachmentState ) {
  34910. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  34911. }
  34912. dispose() {
  34913. this.chainMaps = {};
  34914. }
  34915. }
  34916. const _size = new Vector3();
  34917. class Textures extends DataMap {
  34918. constructor( renderer, backend, info ) {
  34919. super();
  34920. this.renderer = renderer;
  34921. this.backend = backend;
  34922. this.info = info;
  34923. }
  34924. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  34925. const renderTargetData = this.get( renderTarget );
  34926. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  34927. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  34928. const texture = renderTarget.texture;
  34929. const textures = renderTarget.textures;
  34930. const size = this.getSize( texture );
  34931. const mipWidth = size.width >> activeMipmapLevel;
  34932. const mipHeight = size.height >> activeMipmapLevel;
  34933. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  34934. let textureNeedsUpdate = false;
  34935. if ( depthTexture === undefined ) {
  34936. depthTexture = new DepthTexture();
  34937. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  34938. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  34939. depthTexture.image.width = mipWidth;
  34940. depthTexture.image.height = mipHeight;
  34941. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  34942. }
  34943. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  34944. textureNeedsUpdate = true;
  34945. depthTexture.needsUpdate = true;
  34946. depthTexture.image.width = mipWidth;
  34947. depthTexture.image.height = mipHeight;
  34948. }
  34949. renderTargetData.width = size.width;
  34950. renderTargetData.height = size.height;
  34951. renderTargetData.textures = textures;
  34952. renderTargetData.depthTexture = depthTexture;
  34953. renderTargetData.depth = renderTarget.depthBuffer;
  34954. renderTargetData.stencil = renderTarget.stencilBuffer;
  34955. renderTargetData.renderTarget = renderTarget;
  34956. if ( renderTargetData.sampleCount !== sampleCount ) {
  34957. textureNeedsUpdate = true;
  34958. depthTexture.needsUpdate = true;
  34959. renderTargetData.sampleCount = sampleCount;
  34960. }
  34961. //
  34962. const options = { sampleCount };
  34963. for ( let i = 0; i < textures.length; i ++ ) {
  34964. const texture = textures[ i ];
  34965. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  34966. this.updateTexture( texture, options );
  34967. }
  34968. this.updateTexture( depthTexture, options );
  34969. // dispose handler
  34970. if ( renderTargetData.initialized !== true ) {
  34971. renderTargetData.initialized = true;
  34972. // dispose
  34973. const onDispose = () => {
  34974. renderTarget.removeEventListener( 'dispose', onDispose );
  34975. if ( textures !== undefined ) {
  34976. for ( let i = 0; i < textures.length; i ++ ) {
  34977. this._destroyTexture( textures[ i ] );
  34978. }
  34979. } else {
  34980. this._destroyTexture( texture );
  34981. }
  34982. this._destroyTexture( depthTexture );
  34983. };
  34984. renderTarget.addEventListener( 'dispose', onDispose );
  34985. }
  34986. }
  34987. updateTexture( texture, options = {} ) {
  34988. const textureData = this.get( texture );
  34989. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  34990. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  34991. const backend = this.backend;
  34992. if ( isRenderTarget && textureData.initialized === true ) {
  34993. // it's an update
  34994. backend.destroySampler( texture );
  34995. backend.destroyTexture( texture );
  34996. }
  34997. //
  34998. if ( texture.isFramebufferTexture ) {
  34999. const renderer = this.renderer;
  35000. const renderTarget = renderer.getRenderTarget();
  35001. if ( renderTarget ) {
  35002. texture.type = renderTarget.texture.type;
  35003. } else {
  35004. texture.type = UnsignedByteType;
  35005. }
  35006. }
  35007. //
  35008. const { width, height, depth } = this.getSize( texture );
  35009. options.width = width;
  35010. options.height = height;
  35011. options.depth = depth;
  35012. options.needsMipmaps = this.needsMipmaps( texture );
  35013. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  35014. //
  35015. if ( isRenderTarget || texture.isStorageTexture === true ) {
  35016. backend.createSampler( texture );
  35017. backend.createTexture( texture, options );
  35018. } else {
  35019. const needsCreate = textureData.initialized !== true;
  35020. if ( needsCreate ) backend.createSampler( texture );
  35021. if ( texture.version > 0 ) {
  35022. const image = texture.image;
  35023. if ( image === undefined ) {
  35024. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  35025. } else if ( image.complete === false ) {
  35026. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  35027. } else {
  35028. if ( texture.images ) {
  35029. const images = [];
  35030. for ( const image of texture.images ) {
  35031. images.push( image );
  35032. }
  35033. options.images = images;
  35034. } else {
  35035. options.image = image;
  35036. }
  35037. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  35038. backend.createTexture( texture, options );
  35039. textureData.isDefaultTexture = false;
  35040. }
  35041. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  35042. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  35043. }
  35044. } else {
  35045. // async update
  35046. backend.createDefaultTexture( texture );
  35047. textureData.isDefaultTexture = true;
  35048. }
  35049. }
  35050. // dispose handler
  35051. if ( textureData.initialized !== true ) {
  35052. textureData.initialized = true;
  35053. //
  35054. this.info.memory.textures ++;
  35055. // dispose
  35056. const onDispose = () => {
  35057. texture.removeEventListener( 'dispose', onDispose );
  35058. this._destroyTexture( texture );
  35059. this.info.memory.textures --;
  35060. };
  35061. texture.addEventListener( 'dispose', onDispose );
  35062. }
  35063. //
  35064. textureData.version = texture.version;
  35065. }
  35066. getSize( texture, target = _size ) {
  35067. let image = texture.images ? texture.images[ 0 ] : texture.image;
  35068. if ( image ) {
  35069. if ( image.image !== undefined ) image = image.image;
  35070. target.width = image.width;
  35071. target.height = image.height;
  35072. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  35073. } else {
  35074. target.width = target.height = target.depth = 1;
  35075. }
  35076. return target;
  35077. }
  35078. getMipLevels( texture, width, height ) {
  35079. let mipLevelCount;
  35080. if ( texture.isCompressedTexture ) {
  35081. mipLevelCount = texture.mipmaps.length;
  35082. } else {
  35083. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  35084. }
  35085. return mipLevelCount;
  35086. }
  35087. needsMipmaps( texture ) {
  35088. if ( this.isEnvironmentTexture( texture ) ) return true;
  35089. return ( texture.isCompressedTexture === true ) || ( ( texture.minFilter !== NearestFilter ) && ( texture.minFilter !== LinearFilter ) );
  35090. }
  35091. isEnvironmentTexture( texture ) {
  35092. const mapping = texture.mapping;
  35093. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  35094. }
  35095. _destroyTexture( texture ) {
  35096. this.backend.destroySampler( texture );
  35097. this.backend.destroyTexture( texture );
  35098. this.delete( texture );
  35099. }
  35100. }
  35101. class Color4 extends Color {
  35102. constructor( r, g, b, a = 1 ) {
  35103. super( r, g, b );
  35104. this.a = a;
  35105. }
  35106. set( r, g, b, a = 1 ) {
  35107. this.a = a;
  35108. return super.set( r, g, b );
  35109. }
  35110. copy( color ) {
  35111. if ( color.a !== undefined ) this.a = color.a;
  35112. return super.copy( color );
  35113. }
  35114. clone() {
  35115. return new this.constructor( this.r, this.g, this.b, this.a );
  35116. }
  35117. }
  35118. const _clearColor = new Color4();
  35119. class Background extends DataMap {
  35120. constructor( renderer, nodes ) {
  35121. super();
  35122. this.renderer = renderer;
  35123. this.nodes = nodes;
  35124. }
  35125. update( scene, renderList, renderContext ) {
  35126. const renderer = this.renderer;
  35127. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  35128. let forceClear = false;
  35129. if ( background === null ) {
  35130. // no background settings, use clear color configuration from the renderer
  35131. renderer._clearColor.getRGB( _clearColor, LinearSRGBColorSpace );
  35132. _clearColor.a = renderer._clearColor.a;
  35133. } else if ( background.isColor === true ) {
  35134. // background is an opaque color
  35135. background.getRGB( _clearColor, LinearSRGBColorSpace );
  35136. _clearColor.a = 1;
  35137. forceClear = true;
  35138. } else if ( background.isNode === true ) {
  35139. const sceneData = this.get( scene );
  35140. const backgroundNode = background;
  35141. _clearColor.copy( renderer._clearColor );
  35142. let backgroundMesh = sceneData.backgroundMesh;
  35143. if ( backgroundMesh === undefined ) {
  35144. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  35145. // @TODO: Add Texture2D support using node context
  35146. getUV: () => normalWorld,
  35147. getTextureLevel: () => backgroundBlurriness
  35148. } );
  35149. let viewProj = modelViewProjection();
  35150. viewProj = viewProj.setZ( viewProj.w );
  35151. const nodeMaterial = new NodeMaterial();
  35152. nodeMaterial.side = BackSide;
  35153. nodeMaterial.depthTest = false;
  35154. nodeMaterial.depthWrite = false;
  35155. nodeMaterial.fog = false;
  35156. nodeMaterial.vertexNode = viewProj;
  35157. nodeMaterial.fragmentNode = backgroundMeshNode;
  35158. sceneData.backgroundMeshNode = backgroundMeshNode;
  35159. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  35160. backgroundMesh.frustumCulled = false;
  35161. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  35162. this.matrixWorld.copyPosition( camera.matrixWorld );
  35163. };
  35164. }
  35165. const backgroundCacheKey = backgroundNode.getCacheKey();
  35166. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  35167. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  35168. backgroundMesh.material.needsUpdate = true;
  35169. sceneData.backgroundCacheKey = backgroundCacheKey;
  35170. }
  35171. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null );
  35172. } else {
  35173. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  35174. }
  35175. //
  35176. if ( renderer.autoClear === true || forceClear === true ) {
  35177. _clearColor.multiplyScalar( _clearColor.a );
  35178. const clearColorValue = renderContext.clearColorValue;
  35179. clearColorValue.r = _clearColor.r;
  35180. clearColorValue.g = _clearColor.g;
  35181. clearColorValue.b = _clearColor.b;
  35182. clearColorValue.a = _clearColor.a;
  35183. renderContext.depthClearValue = renderer._clearDepth;
  35184. renderContext.stencilClearValue = renderer._clearStencil;
  35185. renderContext.clearColor = renderer.autoClearColor === true;
  35186. renderContext.clearDepth = renderer.autoClearDepth === true;
  35187. renderContext.clearStencil = renderer.autoClearStencil === true;
  35188. } else {
  35189. renderContext.clearColor = false;
  35190. renderContext.clearDepth = false;
  35191. renderContext.clearStencil = false;
  35192. }
  35193. }
  35194. }
  35195. class NodeBuilderState {
  35196. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, instanceBindGroups = true, transforms = [] ) {
  35197. this.vertexShader = vertexShader;
  35198. this.fragmentShader = fragmentShader;
  35199. this.computeShader = computeShader;
  35200. this.transforms = transforms;
  35201. this.nodeAttributes = nodeAttributes;
  35202. this.bindings = bindings;
  35203. this.updateNodes = updateNodes;
  35204. this.updateBeforeNodes = updateBeforeNodes;
  35205. this.updateAfterNodes = updateAfterNodes;
  35206. this.instanceBindGroups = instanceBindGroups;
  35207. this.usedTimes = 0;
  35208. }
  35209. createBindings() {
  35210. const bindings = [];
  35211. for ( const instanceGroup of this.bindings ) {
  35212. const shared = this.instanceBindGroups && instanceGroup.bindings[ 0 ].groupNode.shared;
  35213. if ( shared !== true ) {
  35214. const bindingsGroup = new BindGroup( instanceGroup.name );
  35215. bindings.push( bindingsGroup );
  35216. for ( const instanceBinding of instanceGroup.bindings ) {
  35217. bindingsGroup.bindings.push( instanceBinding.clone() );
  35218. }
  35219. } else {
  35220. bindings.push( instanceGroup );
  35221. }
  35222. }
  35223. return bindings;
  35224. }
  35225. }
  35226. class Nodes extends DataMap {
  35227. constructor( renderer, backend ) {
  35228. super();
  35229. this.renderer = renderer;
  35230. this.backend = backend;
  35231. this.nodeFrame = new NodeFrame();
  35232. this.nodeBuilderCache = new Map();
  35233. this.callHashCache = new ChainMap();
  35234. this.groupsData = new ChainMap();
  35235. }
  35236. updateGroup( nodeUniformsGroup ) {
  35237. const groupNode = nodeUniformsGroup.groupNode;
  35238. const name = groupNode.name;
  35239. // objectGroup is every updated
  35240. if ( name === objectGroup.name ) return true;
  35241. // renderGroup is updated once per render/compute call
  35242. if ( name === renderGroup.name ) {
  35243. const uniformsGroupData = this.get( nodeUniformsGroup );
  35244. const renderId = this.nodeFrame.renderId;
  35245. if ( uniformsGroupData.renderId !== renderId ) {
  35246. uniformsGroupData.renderId = renderId;
  35247. return true;
  35248. }
  35249. return false;
  35250. }
  35251. // frameGroup is updated once per frame
  35252. if ( name === frameGroup.name ) {
  35253. const uniformsGroupData = this.get( nodeUniformsGroup );
  35254. const frameId = this.nodeFrame.frameId;
  35255. if ( uniformsGroupData.frameId !== frameId ) {
  35256. uniformsGroupData.frameId = frameId;
  35257. return true;
  35258. }
  35259. return false;
  35260. }
  35261. // other groups are updated just when groupNode.needsUpdate is true
  35262. const groupChain = [ groupNode, nodeUniformsGroup ];
  35263. let groupData = this.groupsData.get( groupChain );
  35264. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  35265. if ( groupData.version !== groupNode.version ) {
  35266. groupData.version = groupNode.version;
  35267. return true;
  35268. }
  35269. return false;
  35270. }
  35271. getForRenderCacheKey( renderObject ) {
  35272. return renderObject.initialCacheKey;
  35273. }
  35274. getForRender( renderObject ) {
  35275. const renderObjectData = this.get( renderObject );
  35276. let nodeBuilderState = renderObjectData.nodeBuilderState;
  35277. if ( nodeBuilderState === undefined ) {
  35278. const { nodeBuilderCache } = this;
  35279. const cacheKey = this.getForRenderCacheKey( renderObject );
  35280. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  35281. if ( nodeBuilderState === undefined ) {
  35282. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  35283. nodeBuilder.scene = renderObject.scene;
  35284. nodeBuilder.material = renderObject.material;
  35285. nodeBuilder.camera = renderObject.camera;
  35286. nodeBuilder.context.material = renderObject.material;
  35287. nodeBuilder.lightsNode = renderObject.lightsNode;
  35288. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  35289. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  35290. nodeBuilder.clippingContext = renderObject.clippingContext;
  35291. nodeBuilder.build();
  35292. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  35293. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  35294. }
  35295. nodeBuilderState.usedTimes ++;
  35296. renderObjectData.nodeBuilderState = nodeBuilderState;
  35297. }
  35298. return nodeBuilderState;
  35299. }
  35300. delete( object ) {
  35301. if ( object.isRenderObject ) {
  35302. const nodeBuilderState = this.get( object ).nodeBuilderState;
  35303. nodeBuilderState.usedTimes --;
  35304. if ( nodeBuilderState.usedTimes === 0 ) {
  35305. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  35306. }
  35307. }
  35308. return super.delete( object );
  35309. }
  35310. getForCompute( computeNode ) {
  35311. const computeData = this.get( computeNode );
  35312. let nodeBuilderState = computeData.nodeBuilderState;
  35313. if ( nodeBuilderState === undefined ) {
  35314. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  35315. nodeBuilder.build();
  35316. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  35317. computeData.nodeBuilderState = nodeBuilderState;
  35318. }
  35319. return nodeBuilderState;
  35320. }
  35321. _createNodeBuilderState( nodeBuilder ) {
  35322. return new NodeBuilderState(
  35323. nodeBuilder.vertexShader,
  35324. nodeBuilder.fragmentShader,
  35325. nodeBuilder.computeShader,
  35326. nodeBuilder.getAttributesArray(),
  35327. nodeBuilder.getBindings(),
  35328. nodeBuilder.updateNodes,
  35329. nodeBuilder.updateBeforeNodes,
  35330. nodeBuilder.updateAfterNodes,
  35331. nodeBuilder.instanceBindGroups,
  35332. nodeBuilder.transforms
  35333. );
  35334. }
  35335. getEnvironmentNode( scene ) {
  35336. return scene.environmentNode || this.get( scene ).environmentNode || null;
  35337. }
  35338. getBackgroundNode( scene ) {
  35339. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  35340. }
  35341. getFogNode( scene ) {
  35342. return scene.fogNode || this.get( scene ).fogNode || null;
  35343. }
  35344. getCacheKey( scene, lightsNode ) {
  35345. const chain = [ scene, lightsNode ];
  35346. const callId = this.renderer.info.calls;
  35347. let cacheKeyData = this.callHashCache.get( chain );
  35348. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  35349. const environmentNode = this.getEnvironmentNode( scene );
  35350. const fogNode = this.getFogNode( scene );
  35351. const cacheKey = [];
  35352. if ( lightsNode ) cacheKey.push( lightsNode.getCacheKey() );
  35353. if ( environmentNode ) cacheKey.push( environmentNode.getCacheKey() );
  35354. if ( fogNode ) cacheKey.push( fogNode.getCacheKey() );
  35355. cacheKeyData = {
  35356. callId,
  35357. cacheKey: cacheKey.join( ',' )
  35358. };
  35359. this.callHashCache.set( chain, cacheKeyData );
  35360. }
  35361. return cacheKeyData.cacheKey;
  35362. }
  35363. updateScene( scene ) {
  35364. this.updateEnvironment( scene );
  35365. this.updateFog( scene );
  35366. this.updateBackground( scene );
  35367. }
  35368. get isToneMappingState() {
  35369. return this.renderer.getRenderTarget() ? false : true;
  35370. }
  35371. updateBackground( scene ) {
  35372. const sceneData = this.get( scene );
  35373. const background = scene.background;
  35374. if ( background ) {
  35375. if ( sceneData.background !== background ) {
  35376. let backgroundNode = null;
  35377. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping ) ) {
  35378. backgroundNode = pmremTexture( background, normalWorld );
  35379. } else if ( background.isTexture === true ) {
  35380. backgroundNode = texture( background, viewportBottomLeft ).setUpdateMatrix( true );
  35381. } else if ( background.isColor !== true ) {
  35382. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  35383. }
  35384. sceneData.backgroundNode = backgroundNode;
  35385. sceneData.background = background;
  35386. }
  35387. } else if ( sceneData.backgroundNode ) {
  35388. delete sceneData.backgroundNode;
  35389. delete sceneData.background;
  35390. }
  35391. }
  35392. updateFog( scene ) {
  35393. const sceneData = this.get( scene );
  35394. const fog = scene.fog;
  35395. if ( fog ) {
  35396. if ( sceneData.fog !== fog ) {
  35397. let fogNode = null;
  35398. if ( fog.isFogExp2 ) {
  35399. fogNode = densityFog( reference( 'color', 'color', fog ), reference( 'density', 'float', fog ) );
  35400. } else if ( fog.isFog ) {
  35401. fogNode = rangeFog( reference( 'color', 'color', fog ), reference( 'near', 'float', fog ), reference( 'far', 'float', fog ) );
  35402. } else {
  35403. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  35404. }
  35405. sceneData.fogNode = fogNode;
  35406. sceneData.fog = fog;
  35407. }
  35408. } else {
  35409. delete sceneData.fogNode;
  35410. delete sceneData.fog;
  35411. }
  35412. }
  35413. updateEnvironment( scene ) {
  35414. const sceneData = this.get( scene );
  35415. const environment = scene.environment;
  35416. if ( environment ) {
  35417. if ( sceneData.environment !== environment ) {
  35418. let environmentNode = null;
  35419. if ( environment.isCubeTexture === true ) {
  35420. environmentNode = cubeTexture( environment );
  35421. } else if ( environment.isTexture === true ) {
  35422. environmentNode = texture( environment );
  35423. } else {
  35424. console.error( 'Nodes: Unsupported environment configuration.', environment );
  35425. }
  35426. sceneData.environmentNode = environmentNode;
  35427. sceneData.environment = environment;
  35428. }
  35429. } else if ( sceneData.environmentNode ) {
  35430. delete sceneData.environmentNode;
  35431. delete sceneData.environment;
  35432. }
  35433. }
  35434. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  35435. const nodeFrame = this.nodeFrame;
  35436. nodeFrame.renderer = renderer;
  35437. nodeFrame.scene = scene;
  35438. nodeFrame.object = object;
  35439. nodeFrame.camera = camera;
  35440. nodeFrame.material = material;
  35441. return nodeFrame;
  35442. }
  35443. getNodeFrameForRender( renderObject ) {
  35444. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  35445. }
  35446. getOutputNode( outputTexture ) {
  35447. let output = texture( outputTexture, viewportTopLeft );
  35448. if ( this.isToneMappingState ) {
  35449. if ( this.renderer.toneMappingNode ) {
  35450. output = vec4( this.renderer.toneMappingNode.context( { color: output.rgb } ), output.a );
  35451. } else if ( this.renderer.toneMapping !== NoToneMapping ) {
  35452. output = output.toneMapping( this.renderer.toneMapping );
  35453. }
  35454. }
  35455. if ( this.renderer.currentColorSpace === SRGBColorSpace ) {
  35456. output = output.linearToColorSpace( this.renderer.currentColorSpace );
  35457. }
  35458. return output;
  35459. }
  35460. updateBefore( renderObject ) {
  35461. const nodeFrame = this.getNodeFrameForRender( renderObject );
  35462. const nodeBuilder = renderObject.getNodeBuilderState();
  35463. for ( const node of nodeBuilder.updateBeforeNodes ) {
  35464. nodeFrame.updateBeforeNode( node );
  35465. }
  35466. }
  35467. updateAfter( renderObject ) {
  35468. const nodeFrame = this.getNodeFrameForRender( renderObject );
  35469. const nodeBuilder = renderObject.getNodeBuilderState();
  35470. for ( const node of nodeBuilder.updateAfterNodes ) {
  35471. nodeFrame.updateAfterNode( node );
  35472. }
  35473. }
  35474. updateForCompute( computeNode ) {
  35475. const nodeFrame = this.getNodeFrame();
  35476. const nodeBuilder = this.getForCompute( computeNode );
  35477. for ( const node of nodeBuilder.updateNodes ) {
  35478. nodeFrame.updateNode( node );
  35479. }
  35480. }
  35481. updateForRender( renderObject ) {
  35482. const nodeFrame = this.getNodeFrameForRender( renderObject );
  35483. const nodeBuilder = renderObject.getNodeBuilderState();
  35484. for ( const node of nodeBuilder.updateNodes ) {
  35485. nodeFrame.updateNode( node );
  35486. }
  35487. }
  35488. dispose() {
  35489. super.dispose();
  35490. this.nodeFrame = new NodeFrame();
  35491. this.nodeBuilderCache = new Map();
  35492. }
  35493. }
  35494. class RenderBundle {
  35495. constructor( scene, camera ) {
  35496. this.scene = scene;
  35497. this.camera = camera;
  35498. }
  35499. clone() {
  35500. return Object.assign( new this.constructor(), this );
  35501. }
  35502. }
  35503. class RenderBundles {
  35504. constructor() {
  35505. this.lists = new ChainMap();
  35506. }
  35507. get( scene, camera ) {
  35508. const lists = this.lists;
  35509. const keys = [ scene, camera ];
  35510. let list = lists.get( keys );
  35511. if ( list === undefined ) {
  35512. list = new RenderBundle( scene, camera );
  35513. lists.set( keys, list );
  35514. }
  35515. return list;
  35516. }
  35517. dispose() {
  35518. this.lists = new ChainMap();
  35519. }
  35520. }
  35521. const _scene = new Scene();
  35522. const _drawingBufferSize = new Vector2();
  35523. const _screen = new Vector4();
  35524. const _frustum = new Frustum();
  35525. const _projScreenMatrix = new Matrix4();
  35526. const _vector3 = new Vector3();
  35527. const _quad = new QuadMesh( new NodeMaterial() );
  35528. class Renderer {
  35529. constructor( backend, parameters = {} ) {
  35530. this.isRenderer = true;
  35531. //
  35532. const {
  35533. logarithmicDepthBuffer = false,
  35534. alpha = true
  35535. } = parameters;
  35536. // public
  35537. this.domElement = backend.getDomElement();
  35538. this.backend = backend;
  35539. this.autoClear = true;
  35540. this.autoClearColor = true;
  35541. this.autoClearDepth = true;
  35542. this.autoClearStencil = true;
  35543. this.alpha = alpha;
  35544. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  35545. this.outputColorSpace = SRGBColorSpace;
  35546. this.toneMapping = NoToneMapping;
  35547. this.toneMappingExposure = 1.0;
  35548. this.sortObjects = true;
  35549. this.depth = true;
  35550. this.stencil = false;
  35551. this.clippingPlanes = [];
  35552. this.info = new Info();
  35553. // nodes
  35554. this.toneMappingNode = null;
  35555. // internals
  35556. this._pixelRatio = 1;
  35557. this._width = this.domElement.width;
  35558. this._height = this.domElement.height;
  35559. this._viewport = new Vector4( 0, 0, this._width, this._height );
  35560. this._scissor = new Vector4( 0, 0, this._width, this._height );
  35561. this._scissorTest = false;
  35562. this._attributes = null;
  35563. this._geometries = null;
  35564. this._nodes = null;
  35565. this._animation = null;
  35566. this._bindings = null;
  35567. this._objects = null;
  35568. this._pipelines = null;
  35569. this._bundles = null;
  35570. this._renderLists = null;
  35571. this._renderContexts = null;
  35572. this._textures = null;
  35573. this._background = null;
  35574. this._currentRenderContext = null;
  35575. this._opaqueSort = null;
  35576. this._transparentSort = null;
  35577. this._frameBufferTarget = null;
  35578. const alphaClear = this.alpha === true ? 0 : 1;
  35579. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  35580. this._clearDepth = 1;
  35581. this._clearStencil = 0;
  35582. this._renderTarget = null;
  35583. this._activeCubeFace = 0;
  35584. this._activeMipmapLevel = 0;
  35585. this._renderObjectFunction = null;
  35586. this._currentRenderObjectFunction = null;
  35587. this._currentRenderBundle = null;
  35588. this._handleObjectFunction = this._renderObjectDirect;
  35589. this._initialized = false;
  35590. this._initPromise = null;
  35591. this._compilationPromises = null;
  35592. // backwards compatibility
  35593. this.shadowMap = {
  35594. enabled: false,
  35595. type: null
  35596. };
  35597. this.xr = {
  35598. enabled: false
  35599. };
  35600. this.debug = {
  35601. checkShaderErrors: true,
  35602. onShaderError: null
  35603. };
  35604. }
  35605. async init() {
  35606. if ( this._initialized ) {
  35607. throw new Error( 'Renderer: Backend has already been initialized.' );
  35608. }
  35609. if ( this._initPromise !== null ) {
  35610. return this._initPromise;
  35611. }
  35612. this._initPromise = new Promise( async ( resolve, reject ) => {
  35613. const backend = this.backend;
  35614. try {
  35615. await backend.init( this );
  35616. } catch ( error ) {
  35617. reject( error );
  35618. return;
  35619. }
  35620. this._nodes = new Nodes( this, backend );
  35621. this._animation = new Animation( this._nodes, this.info );
  35622. this._attributes = new Attributes( backend );
  35623. this._background = new Background( this, this._nodes );
  35624. this._geometries = new Geometries( this._attributes, this.info );
  35625. this._textures = new Textures( this, backend, this.info );
  35626. this._pipelines = new Pipelines( backend, this._nodes );
  35627. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  35628. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  35629. this._renderLists = new RenderLists();
  35630. this._bundles = new RenderBundles();
  35631. this._renderContexts = new RenderContexts();
  35632. //
  35633. this._initialized = true;
  35634. resolve();
  35635. } );
  35636. return this._initPromise;
  35637. }
  35638. get coordinateSystem() {
  35639. return this.backend.coordinateSystem;
  35640. }
  35641. async compileAsync( scene, camera, targetScene = null ) {
  35642. if ( this._initialized === false ) await this.init();
  35643. // preserve render tree
  35644. const nodeFrame = this._nodes.nodeFrame;
  35645. const previousRenderId = nodeFrame.renderId;
  35646. const previousRenderContext = this._currentRenderContext;
  35647. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  35648. const previousCompilationPromises = this._compilationPromises;
  35649. //
  35650. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  35651. if ( targetScene === null ) targetScene = scene;
  35652. const renderTarget = this._renderTarget;
  35653. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  35654. const activeMipmapLevel = this._activeMipmapLevel;
  35655. const compilationPromises = [];
  35656. this._currentRenderContext = renderContext;
  35657. this._currentRenderObjectFunction = this.renderObject;
  35658. this._handleObjectFunction = this._createObjectPipeline;
  35659. this._compilationPromises = compilationPromises;
  35660. nodeFrame.renderId ++;
  35661. //
  35662. nodeFrame.update();
  35663. //
  35664. renderContext.depth = this.depth;
  35665. renderContext.stencil = this.stencil;
  35666. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  35667. renderContext.clippingContext.updateGlobal( this, camera );
  35668. //
  35669. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  35670. //
  35671. const renderList = this._renderLists.get( scene, camera );
  35672. renderList.begin();
  35673. this._projectObject( scene, camera, 0, renderList );
  35674. // include lights from target scene
  35675. if ( targetScene !== scene ) {
  35676. targetScene.traverseVisible( function ( object ) {
  35677. if ( object.isLight && object.layers.test( camera.layers ) ) {
  35678. renderList.pushLight( object );
  35679. }
  35680. } );
  35681. }
  35682. renderList.finish();
  35683. //
  35684. if ( renderTarget !== null ) {
  35685. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  35686. const renderTargetData = this._textures.get( renderTarget );
  35687. renderContext.textures = renderTargetData.textures;
  35688. renderContext.depthTexture = renderTargetData.depthTexture;
  35689. } else {
  35690. renderContext.textures = null;
  35691. renderContext.depthTexture = null;
  35692. }
  35693. //
  35694. this._nodes.updateScene( sceneRef );
  35695. //
  35696. this._background.update( sceneRef, renderList, renderContext );
  35697. // process render lists
  35698. const opaqueObjects = renderList.opaque;
  35699. const transparentObjects = renderList.transparent;
  35700. const lightsNode = renderList.lightsNode;
  35701. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  35702. if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  35703. // restore render tree
  35704. nodeFrame.renderId = previousRenderId;
  35705. this._currentRenderContext = previousRenderContext;
  35706. this._currentRenderObjectFunction = previousRenderObjectFunction;
  35707. this._compilationPromises = previousCompilationPromises;
  35708. this._handleObjectFunction = this._renderObjectDirect;
  35709. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  35710. await Promise.all( compilationPromises );
  35711. }
  35712. async renderAsync( scene, camera ) {
  35713. if ( this._initialized === false ) await this.init();
  35714. const renderContext = this._renderScene( scene, camera );
  35715. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  35716. }
  35717. _renderBundle( bundle, sceneRef, lightsNode ) {
  35718. const { object, camera, renderList } = bundle;
  35719. const renderContext = this._currentRenderContext;
  35720. const renderContextData = this.backend.get( renderContext );
  35721. //
  35722. const renderBundle = this._bundles.get( object, camera );
  35723. const renderBundleData = this.backend.get( renderBundle );
  35724. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  35725. //
  35726. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || object.needsUpdate === true;
  35727. renderBundleData.renderContexts.add( renderContext );
  35728. if ( renderBundleNeedsUpdate ) {
  35729. if ( renderContextData.renderObjects === undefined || object.needsUpdate === true ) {
  35730. const nodeFrame = this._nodes.nodeFrame;
  35731. renderContextData.renderObjects = [];
  35732. renderContextData.renderBundles = [];
  35733. renderContextData.scene = sceneRef;
  35734. renderContextData.camera = camera;
  35735. renderContextData.renderId = nodeFrame.renderId;
  35736. renderContextData.registerBundlesPhase = true;
  35737. }
  35738. this._currentRenderBundle = renderBundle;
  35739. const opaqueObjects = renderList.opaque;
  35740. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  35741. this._currentRenderBundle = null;
  35742. //
  35743. object.needsUpdate = false;
  35744. } else {
  35745. const renderContext = this._currentRenderContext;
  35746. const renderContextData = this.backend.get( renderContext );
  35747. for ( let i = 0, l = renderContextData.renderObjects.length; i < l; i ++ ) {
  35748. const renderObject = renderContextData.renderObjects[ i ];
  35749. this._nodes.updateBefore( renderObject );
  35750. //
  35751. renderObject.object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, renderObject.object.matrixWorld );
  35752. renderObject.object.normalMatrix.getNormalMatrix( renderObject.object.modelViewMatrix );
  35753. this._nodes.updateForRender( renderObject );
  35754. this._bindings.updateForRender( renderObject );
  35755. this.backend.draw( renderObject, this.info );
  35756. this._nodes.updateAfter( renderObject );
  35757. }
  35758. }
  35759. }
  35760. render( scene, camera ) {
  35761. if ( this._initialized === false ) {
  35762. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  35763. return this.renderAsync( scene, camera );
  35764. }
  35765. this._renderScene( scene, camera );
  35766. }
  35767. _getFrameBufferTarget() {
  35768. const { currentColorSpace } = this;
  35769. const useToneMapping = this._renderTarget === null && ( this.toneMapping !== NoToneMapping || this.toneMappingNode !== null );
  35770. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace && currentColorSpace !== NoColorSpace;
  35771. if ( useToneMapping === false && useColorSpace === false ) return null;
  35772. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  35773. const { depth, stencil } = this;
  35774. let frameBufferTarget = this._frameBufferTarget;
  35775. if ( frameBufferTarget === null ) {
  35776. frameBufferTarget = new RenderTarget( width, height, {
  35777. depthBuffer: depth,
  35778. stencilBuffer: stencil,
  35779. type: HalfFloatType, // FloatType
  35780. format: RGBAFormat,
  35781. colorSpace: LinearSRGBColorSpace,
  35782. generateMipmaps: false,
  35783. minFilter: LinearFilter,
  35784. magFilter: LinearFilter,
  35785. samples: this.backend.parameters.antialias ? 4 : 0
  35786. } );
  35787. frameBufferTarget.isPostProcessingRenderTarget = true;
  35788. this._frameBufferTarget = frameBufferTarget;
  35789. }
  35790. frameBufferTarget.depthBuffer = depth;
  35791. frameBufferTarget.stencilBuffer = stencil;
  35792. frameBufferTarget.setSize( width, height );
  35793. frameBufferTarget.viewport.copy( this._viewport );
  35794. frameBufferTarget.scissor.copy( this._scissor );
  35795. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  35796. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  35797. frameBufferTarget.scissorTest = this._scissorTest;
  35798. return frameBufferTarget;
  35799. }
  35800. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  35801. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  35802. // preserve render tree
  35803. const nodeFrame = this._nodes.nodeFrame;
  35804. const previousRenderId = nodeFrame.renderId;
  35805. const previousRenderContext = this._currentRenderContext;
  35806. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  35807. //
  35808. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  35809. const outputRenderTarget = this._renderTarget;
  35810. const activeCubeFace = this._activeCubeFace;
  35811. const activeMipmapLevel = this._activeMipmapLevel;
  35812. //
  35813. let renderTarget;
  35814. if ( frameBufferTarget !== null ) {
  35815. renderTarget = frameBufferTarget;
  35816. this.setRenderTarget( renderTarget );
  35817. } else {
  35818. renderTarget = outputRenderTarget;
  35819. }
  35820. //
  35821. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  35822. this._currentRenderContext = renderContext;
  35823. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  35824. //
  35825. this.info.calls ++;
  35826. this.info.render.calls ++;
  35827. this.info.render.frameCalls ++;
  35828. nodeFrame.renderId = this.info.calls;
  35829. //
  35830. const coordinateSystem = this.coordinateSystem;
  35831. if ( camera.coordinateSystem !== coordinateSystem ) {
  35832. camera.coordinateSystem = coordinateSystem;
  35833. camera.updateProjectionMatrix();
  35834. }
  35835. //
  35836. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  35837. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  35838. //
  35839. let viewport = this._viewport;
  35840. let scissor = this._scissor;
  35841. let pixelRatio = this._pixelRatio;
  35842. if ( renderTarget !== null ) {
  35843. viewport = renderTarget.viewport;
  35844. scissor = renderTarget.scissor;
  35845. pixelRatio = 1;
  35846. }
  35847. this.getDrawingBufferSize( _drawingBufferSize );
  35848. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  35849. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  35850. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  35851. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  35852. renderContext.viewportValue.width >>= activeMipmapLevel;
  35853. renderContext.viewportValue.height >>= activeMipmapLevel;
  35854. renderContext.viewportValue.minDepth = minDepth;
  35855. renderContext.viewportValue.maxDepth = maxDepth;
  35856. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  35857. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  35858. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  35859. renderContext.scissorValue.width >>= activeMipmapLevel;
  35860. renderContext.scissorValue.height >>= activeMipmapLevel;
  35861. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  35862. renderContext.clippingContext.updateGlobal( this, camera );
  35863. //
  35864. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  35865. //
  35866. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  35867. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  35868. const renderList = this._renderLists.get( scene, camera );
  35869. renderList.begin();
  35870. this._projectObject( scene, camera, 0, renderList );
  35871. renderList.finish();
  35872. if ( this.sortObjects === true ) {
  35873. renderList.sort( this._opaqueSort, this._transparentSort );
  35874. }
  35875. //
  35876. if ( renderTarget !== null ) {
  35877. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  35878. const renderTargetData = this._textures.get( renderTarget );
  35879. renderContext.textures = renderTargetData.textures;
  35880. renderContext.depthTexture = renderTargetData.depthTexture;
  35881. renderContext.width = renderTargetData.width;
  35882. renderContext.height = renderTargetData.height;
  35883. renderContext.renderTarget = renderTarget;
  35884. renderContext.depth = renderTarget.depthBuffer;
  35885. renderContext.stencil = renderTarget.stencilBuffer;
  35886. } else {
  35887. renderContext.textures = null;
  35888. renderContext.depthTexture = null;
  35889. renderContext.width = this.domElement.width;
  35890. renderContext.height = this.domElement.height;
  35891. renderContext.depth = this.depth;
  35892. renderContext.stencil = this.stencil;
  35893. }
  35894. renderContext.width >>= activeMipmapLevel;
  35895. renderContext.height >>= activeMipmapLevel;
  35896. renderContext.activeCubeFace = activeCubeFace;
  35897. renderContext.activeMipmapLevel = activeMipmapLevel;
  35898. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  35899. //
  35900. this._nodes.updateScene( sceneRef );
  35901. //
  35902. this._background.update( sceneRef, renderList, renderContext );
  35903. //
  35904. this.backend.beginRender( renderContext );
  35905. // process render lists
  35906. const opaqueObjects = renderList.opaque;
  35907. const transparentObjects = renderList.transparent;
  35908. const bundles = renderList.bundles;
  35909. const lightsNode = renderList.lightsNode;
  35910. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  35911. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  35912. if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  35913. // finish render pass
  35914. this.backend.finishRender( renderContext );
  35915. // restore render tree
  35916. nodeFrame.renderId = previousRenderId;
  35917. this._currentRenderContext = previousRenderContext;
  35918. this._currentRenderObjectFunction = previousRenderObjectFunction;
  35919. //
  35920. if ( frameBufferTarget !== null ) {
  35921. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  35922. _quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  35923. this._renderScene( _quad, _quad.camera, false );
  35924. }
  35925. //
  35926. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  35927. //
  35928. return renderContext;
  35929. }
  35930. getMaxAnisotropy() {
  35931. return this.backend.getMaxAnisotropy();
  35932. }
  35933. getActiveCubeFace() {
  35934. return this._activeCubeFace;
  35935. }
  35936. getActiveMipmapLevel() {
  35937. return this._activeMipmapLevel;
  35938. }
  35939. async setAnimationLoop( callback ) {
  35940. if ( this._initialized === false ) await this.init();
  35941. this._animation.setAnimationLoop( callback );
  35942. }
  35943. async getArrayBufferAsync( attribute ) {
  35944. return await this.backend.getArrayBufferAsync( attribute );
  35945. }
  35946. getContext() {
  35947. return this.backend.getContext();
  35948. }
  35949. getPixelRatio() {
  35950. return this._pixelRatio;
  35951. }
  35952. getDrawingBufferSize( target ) {
  35953. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  35954. }
  35955. getSize( target ) {
  35956. return target.set( this._width, this._height );
  35957. }
  35958. setPixelRatio( value = 1 ) {
  35959. this._pixelRatio = value;
  35960. this.setSize( this._width, this._height, false );
  35961. }
  35962. setDrawingBufferSize( width, height, pixelRatio ) {
  35963. this._width = width;
  35964. this._height = height;
  35965. this._pixelRatio = pixelRatio;
  35966. this.domElement.width = Math.floor( width * pixelRatio );
  35967. this.domElement.height = Math.floor( height * pixelRatio );
  35968. this.setViewport( 0, 0, width, height );
  35969. if ( this._initialized ) this.backend.updateSize();
  35970. }
  35971. setSize( width, height, updateStyle = true ) {
  35972. this._width = width;
  35973. this._height = height;
  35974. this.domElement.width = Math.floor( width * this._pixelRatio );
  35975. this.domElement.height = Math.floor( height * this._pixelRatio );
  35976. if ( updateStyle === true ) {
  35977. this.domElement.style.width = width + 'px';
  35978. this.domElement.style.height = height + 'px';
  35979. }
  35980. this.setViewport( 0, 0, width, height );
  35981. if ( this._initialized ) this.backend.updateSize();
  35982. }
  35983. setOpaqueSort( method ) {
  35984. this._opaqueSort = method;
  35985. }
  35986. setTransparentSort( method ) {
  35987. this._transparentSort = method;
  35988. }
  35989. getScissor( target ) {
  35990. const scissor = this._scissor;
  35991. target.x = scissor.x;
  35992. target.y = scissor.y;
  35993. target.width = scissor.width;
  35994. target.height = scissor.height;
  35995. return target;
  35996. }
  35997. setScissor( x, y, width, height ) {
  35998. const scissor = this._scissor;
  35999. if ( x.isVector4 ) {
  36000. scissor.copy( x );
  36001. } else {
  36002. scissor.set( x, y, width, height );
  36003. }
  36004. }
  36005. getScissorTest() {
  36006. return this._scissorTest;
  36007. }
  36008. setScissorTest( boolean ) {
  36009. this._scissorTest = boolean;
  36010. this.backend.setScissorTest( boolean );
  36011. }
  36012. getViewport( target ) {
  36013. return target.copy( this._viewport );
  36014. }
  36015. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  36016. const viewport = this._viewport;
  36017. if ( x.isVector4 ) {
  36018. viewport.copy( x );
  36019. } else {
  36020. viewport.set( x, y, width, height );
  36021. }
  36022. viewport.minDepth = minDepth;
  36023. viewport.maxDepth = maxDepth;
  36024. }
  36025. getClearColor( target ) {
  36026. return target.copy( this._clearColor );
  36027. }
  36028. setClearColor( color, alpha = 1 ) {
  36029. this._clearColor.set( color );
  36030. this._clearColor.a = alpha;
  36031. }
  36032. getClearAlpha() {
  36033. return this._clearColor.a;
  36034. }
  36035. setClearAlpha( alpha ) {
  36036. this._clearColor.a = alpha;
  36037. }
  36038. getClearDepth() {
  36039. return this._clearDepth;
  36040. }
  36041. setClearDepth( depth ) {
  36042. this._clearDepth = depth;
  36043. }
  36044. getClearStencil() {
  36045. return this._clearStencil;
  36046. }
  36047. setClearStencil( stencil ) {
  36048. this._clearStencil = stencil;
  36049. }
  36050. isOccluded( object ) {
  36051. const renderContext = this._currentRenderContext;
  36052. return renderContext && this.backend.isOccluded( renderContext, object );
  36053. }
  36054. clear( color = true, depth = true, stencil = true ) {
  36055. if ( this._initialized === false ) {
  36056. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  36057. return this.clearAsync( color, depth, stencil );
  36058. }
  36059. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  36060. let renderTargetData = null;
  36061. if ( renderTarget !== null ) {
  36062. this._textures.updateRenderTarget( renderTarget );
  36063. renderTargetData = this._textures.get( renderTarget );
  36064. }
  36065. this.backend.clear( color, depth, stencil, renderTargetData );
  36066. if ( renderTarget !== null && this._renderTarget === null ) {
  36067. // If a color space transform or tone mapping is required,
  36068. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  36069. _quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  36070. this._renderScene( _quad, _quad.camera, false );
  36071. }
  36072. }
  36073. clearColor() {
  36074. return this.clear( true, false, false );
  36075. }
  36076. clearDepth() {
  36077. return this.clear( false, true, false );
  36078. }
  36079. clearStencil() {
  36080. return this.clear( false, false, true );
  36081. }
  36082. async clearAsync( color = true, depth = true, stencil = true ) {
  36083. if ( this._initialized === false ) await this.init();
  36084. this.clear( color, depth, stencil );
  36085. }
  36086. clearColorAsync() {
  36087. return this.clearAsync( true, false, false );
  36088. }
  36089. clearDepthAsync() {
  36090. return this.clearAsync( false, true, false );
  36091. }
  36092. clearStencilAsync() {
  36093. return this.clearAsync( false, false, true );
  36094. }
  36095. get currentColorSpace() {
  36096. const renderTarget = this._renderTarget;
  36097. if ( renderTarget !== null ) {
  36098. const texture = renderTarget.texture;
  36099. return ( Array.isArray( texture ) ? texture[ 0 ] : texture ).colorSpace;
  36100. }
  36101. return this.outputColorSpace;
  36102. }
  36103. dispose() {
  36104. this.info.dispose();
  36105. this._animation.dispose();
  36106. this._objects.dispose();
  36107. this._pipelines.dispose();
  36108. this._nodes.dispose();
  36109. this._bindings.dispose();
  36110. this._renderLists.dispose();
  36111. this._renderContexts.dispose();
  36112. this._textures.dispose();
  36113. this.setRenderTarget( null );
  36114. this.setAnimationLoop( null );
  36115. }
  36116. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  36117. this._renderTarget = renderTarget;
  36118. this._activeCubeFace = activeCubeFace;
  36119. this._activeMipmapLevel = activeMipmapLevel;
  36120. }
  36121. getRenderTarget() {
  36122. return this._renderTarget;
  36123. }
  36124. setRenderObjectFunction( renderObjectFunction ) {
  36125. this._renderObjectFunction = renderObjectFunction;
  36126. }
  36127. getRenderObjectFunction() {
  36128. return this._renderObjectFunction;
  36129. }
  36130. async computeAsync( computeNodes ) {
  36131. if ( this._initialized === false ) await this.init();
  36132. const nodeFrame = this._nodes.nodeFrame;
  36133. const previousRenderId = nodeFrame.renderId;
  36134. //
  36135. this.info.calls ++;
  36136. this.info.compute.calls ++;
  36137. this.info.compute.frameCalls ++;
  36138. nodeFrame.renderId = this.info.calls;
  36139. //
  36140. const backend = this.backend;
  36141. const pipelines = this._pipelines;
  36142. const bindings = this._bindings;
  36143. const nodes = this._nodes;
  36144. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  36145. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  36146. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  36147. }
  36148. backend.beginCompute( computeNodes );
  36149. for ( const computeNode of computeList ) {
  36150. // onInit
  36151. if ( pipelines.has( computeNode ) === false ) {
  36152. const dispose = () => {
  36153. computeNode.removeEventListener( 'dispose', dispose );
  36154. pipelines.delete( computeNode );
  36155. bindings.delete( computeNode );
  36156. nodes.delete( computeNode );
  36157. };
  36158. computeNode.addEventListener( 'dispose', dispose );
  36159. //
  36160. computeNode.onInit( { renderer: this } );
  36161. }
  36162. nodes.updateForCompute( computeNode );
  36163. bindings.updateForCompute( computeNode );
  36164. const computeBindings = bindings.getForCompute( computeNode );
  36165. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  36166. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  36167. }
  36168. backend.finishCompute( computeNodes );
  36169. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  36170. //
  36171. nodeFrame.renderId = previousRenderId;
  36172. }
  36173. async hasFeatureAsync( name ) {
  36174. if ( this._initialized === false ) await this.init();
  36175. return this.backend.hasFeature( name );
  36176. }
  36177. hasFeature( name ) {
  36178. if ( this._initialized === false ) {
  36179. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  36180. return false;
  36181. }
  36182. return this.backend.hasFeature( name );
  36183. }
  36184. copyFramebufferToTexture( framebufferTexture ) {
  36185. const renderContext = this._currentRenderContext;
  36186. this._textures.updateTexture( framebufferTexture );
  36187. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext );
  36188. }
  36189. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  36190. this._textures.updateTexture( srcTexture );
  36191. this._textures.updateTexture( dstTexture );
  36192. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  36193. }
  36194. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0 ) {
  36195. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height );
  36196. }
  36197. _projectObject( object, camera, groupOrder, renderList ) {
  36198. if ( object.visible === false ) return;
  36199. const visible = object.layers.test( camera.layers );
  36200. if ( visible ) {
  36201. if ( object.isGroup ) {
  36202. groupOrder = object.renderOrder;
  36203. } else if ( object.isLOD ) {
  36204. if ( object.autoUpdate === true ) object.update( camera );
  36205. } else if ( object.isLight ) {
  36206. renderList.pushLight( object );
  36207. } else if ( object.isSprite ) {
  36208. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  36209. if ( this.sortObjects === true ) {
  36210. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  36211. }
  36212. const geometry = object.geometry;
  36213. const material = object.material;
  36214. if ( material.visible ) {
  36215. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  36216. }
  36217. }
  36218. } else if ( object.isLineLoop ) {
  36219. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  36220. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  36221. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  36222. const geometry = object.geometry;
  36223. const material = object.material;
  36224. if ( this.sortObjects === true ) {
  36225. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  36226. _vector3
  36227. .copy( geometry.boundingSphere.center )
  36228. .applyMatrix4( object.matrixWorld )
  36229. .applyMatrix4( _projScreenMatrix );
  36230. }
  36231. if ( Array.isArray( material ) ) {
  36232. const groups = geometry.groups;
  36233. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  36234. const group = groups[ i ];
  36235. const groupMaterial = material[ group.materialIndex ];
  36236. if ( groupMaterial && groupMaterial.visible ) {
  36237. renderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  36238. }
  36239. }
  36240. } else if ( material.visible ) {
  36241. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  36242. }
  36243. }
  36244. }
  36245. }
  36246. if ( object.static === true ) {
  36247. const baseRenderList = renderList;
  36248. // replace render list
  36249. renderList = this._renderLists.get( object, camera );
  36250. renderList.begin();
  36251. baseRenderList.pushBundle( {
  36252. object,
  36253. camera,
  36254. renderList,
  36255. } );
  36256. renderList.finish();
  36257. }
  36258. const children = object.children;
  36259. for ( let i = 0, l = children.length; i < l; i ++ ) {
  36260. this._projectObject( children[ i ], camera, groupOrder, renderList );
  36261. }
  36262. }
  36263. _renderBundles( bundles, sceneRef, lightsNode ) {
  36264. for ( const bundle of bundles ) {
  36265. this._renderBundle( bundle, sceneRef, lightsNode );
  36266. }
  36267. }
  36268. _renderObjects( renderList, camera, scene, lightsNode ) {
  36269. // process renderable objects
  36270. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  36271. const renderItem = renderList[ i ];
  36272. // @TODO: Add support for multiple materials per object. This will require to extract
  36273. // the material from the renderItem object and pass it with its group data to renderObject().
  36274. const { object, geometry, material, group } = renderItem;
  36275. if ( camera.isArrayCamera ) {
  36276. const cameras = camera.cameras;
  36277. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  36278. const camera2 = cameras[ j ];
  36279. if ( object.layers.test( camera2.layers ) ) {
  36280. const vp = camera2.viewport;
  36281. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  36282. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  36283. const viewportValue = this._currentRenderContext.viewportValue;
  36284. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  36285. viewportValue.minDepth = minDepth;
  36286. viewportValue.maxDepth = maxDepth;
  36287. this.backend.updateViewport( this._currentRenderContext );
  36288. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode );
  36289. }
  36290. }
  36291. } else {
  36292. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode );
  36293. }
  36294. }
  36295. }
  36296. renderObject( object, scene, camera, geometry, material, group, lightsNode ) {
  36297. let overridePositionNode;
  36298. let overrideFragmentNode;
  36299. let overrideDepthNode;
  36300. //
  36301. object.onBeforeRender( this, scene, camera, geometry, material, group );
  36302. //
  36303. if ( scene.overrideMaterial !== null ) {
  36304. const overrideMaterial = scene.overrideMaterial;
  36305. if ( material.positionNode && material.positionNode.isNode ) {
  36306. overridePositionNode = overrideMaterial.positionNode;
  36307. overrideMaterial.positionNode = material.positionNode;
  36308. }
  36309. if ( overrideMaterial.isShadowNodeMaterial ) {
  36310. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  36311. if ( material.depthNode && material.depthNode.isNode ) {
  36312. overrideDepthNode = overrideMaterial.depthNode;
  36313. overrideMaterial.depthNode = material.depthNode;
  36314. }
  36315. if ( material.shadowNode && material.shadowNode.isNode ) {
  36316. overrideFragmentNode = overrideMaterial.fragmentNode;
  36317. overrideMaterial.fragmentNode = material.shadowNode;
  36318. }
  36319. if ( this.localClippingEnabled ) {
  36320. if ( material.clipShadows ) {
  36321. if ( overrideMaterial.clippingPlanes !== material.clippingPlanes ) {
  36322. overrideMaterial.clippingPlanes = material.clippingPlanes;
  36323. overrideMaterial.needsUpdate = true;
  36324. }
  36325. if ( overrideMaterial.clipIntersection !== material.clipIntersection ) {
  36326. overrideMaterial.clipIntersection = material.clipIntersection;
  36327. }
  36328. } else if ( Array.isArray( overrideMaterial.clippingPlanes ) ) {
  36329. overrideMaterial.clippingPlanes = null;
  36330. overrideMaterial.needsUpdate = true;
  36331. }
  36332. }
  36333. }
  36334. material = overrideMaterial;
  36335. }
  36336. //
  36337. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  36338. material.side = BackSide;
  36339. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, 'backSide' ); // create backSide pass id
  36340. material.side = FrontSide;
  36341. this._handleObjectFunction( object, material, scene, camera, lightsNode, group ); // use default pass id
  36342. material.side = DoubleSide;
  36343. } else {
  36344. this._handleObjectFunction( object, material, scene, camera, lightsNode, group );
  36345. }
  36346. //
  36347. if ( overridePositionNode !== undefined ) {
  36348. scene.overrideMaterial.positionNode = overridePositionNode;
  36349. }
  36350. if ( overrideDepthNode !== undefined ) {
  36351. scene.overrideMaterial.depthNode = overrideDepthNode;
  36352. }
  36353. if ( overrideFragmentNode !== undefined ) {
  36354. scene.overrideMaterial.fragmentNode = overrideFragmentNode;
  36355. }
  36356. //
  36357. object.onAfterRender( this, scene, camera, geometry, material, group );
  36358. }
  36359. _renderObjectDirect( object, material, scene, camera, lightsNode, group, passId ) {
  36360. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  36361. renderObject.drawRange = group || object.geometry.drawRange;
  36362. //
  36363. this._nodes.updateBefore( renderObject );
  36364. //
  36365. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  36366. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  36367. //
  36368. this._nodes.updateForRender( renderObject );
  36369. this._geometries.updateForRender( renderObject );
  36370. this._bindings.updateForRender( renderObject );
  36371. this._pipelines.updateForRender( renderObject );
  36372. //
  36373. if ( this._currentRenderBundle !== null && this._currentRenderBundle.needsUpdate === true ) {
  36374. const renderObjectData = this.backend.get( renderObject );
  36375. renderObjectData.bundleEncoder = undefined;
  36376. renderObjectData.lastPipelineGPU = undefined;
  36377. }
  36378. this.backend.draw( renderObject, this.info );
  36379. if ( this._currentRenderBundle !== null ) {
  36380. const renderContextData = this.backend.get( this._currentRenderContext );
  36381. renderContextData.renderObjects.push( renderObject );
  36382. }
  36383. this._nodes.updateAfter( renderObject );
  36384. }
  36385. _createObjectPipeline( object, material, scene, camera, lightsNode, passId ) {
  36386. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  36387. //
  36388. this._nodes.updateBefore( renderObject );
  36389. //
  36390. this._nodes.updateForRender( renderObject );
  36391. this._geometries.updateForRender( renderObject );
  36392. this._bindings.updateForRender( renderObject );
  36393. this._pipelines.getForRender( renderObject, this._compilationPromises );
  36394. this._nodes.updateAfter( renderObject );
  36395. }
  36396. get compute() {
  36397. return this.computeAsync;
  36398. }
  36399. get compile() {
  36400. return this.compileAsync;
  36401. }
  36402. }
  36403. class Binding {
  36404. constructor( name = '' ) {
  36405. this.name = name;
  36406. this.visibility = 0;
  36407. }
  36408. setVisibility( visibility ) {
  36409. this.visibility |= visibility;
  36410. }
  36411. clone() {
  36412. return Object.assign( new this.constructor(), this );
  36413. }
  36414. }
  36415. function getFloatLength( floatLength ) {
  36416. // ensure chunk size alignment (STD140 layout)
  36417. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  36418. }
  36419. class Buffer extends Binding {
  36420. constructor( name, buffer = null ) {
  36421. super( name );
  36422. this.isBuffer = true;
  36423. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  36424. this._buffer = buffer;
  36425. }
  36426. get byteLength() {
  36427. return getFloatLength( this._buffer.byteLength );
  36428. }
  36429. get buffer() {
  36430. return this._buffer;
  36431. }
  36432. update() {
  36433. return true;
  36434. }
  36435. }
  36436. class UniformBuffer extends Buffer {
  36437. constructor( name, buffer = null ) {
  36438. super( name, buffer );
  36439. this.isUniformBuffer = true;
  36440. }
  36441. }
  36442. let _id$2 = 0;
  36443. class NodeUniformBuffer extends UniformBuffer {
  36444. constructor( nodeUniform, groupNode ) {
  36445. super( 'UniformBuffer_' + _id$2 ++, nodeUniform ? nodeUniform.value : null );
  36446. this.nodeUniform = nodeUniform;
  36447. this.groupNode = groupNode;
  36448. }
  36449. get buffer() {
  36450. return this.nodeUniform.value;
  36451. }
  36452. }
  36453. class UniformsGroup extends UniformBuffer {
  36454. constructor( name ) {
  36455. super( name );
  36456. this.isUniformsGroup = true;
  36457. this._values = null;
  36458. // the order of uniforms in this array must match the order of uniforms in the shader
  36459. this.uniforms = [];
  36460. }
  36461. addUniform( uniform ) {
  36462. this.uniforms.push( uniform );
  36463. return this;
  36464. }
  36465. removeUniform( uniform ) {
  36466. const index = this.uniforms.indexOf( uniform );
  36467. if ( index !== - 1 ) {
  36468. this.uniforms.splice( index, 1 );
  36469. }
  36470. return this;
  36471. }
  36472. get values() {
  36473. if ( this._values === null ) {
  36474. this._values = Array.from( this.buffer );
  36475. }
  36476. return this._values;
  36477. }
  36478. get buffer() {
  36479. let buffer = this._buffer;
  36480. if ( buffer === null ) {
  36481. const byteLength = this.byteLength;
  36482. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  36483. this._buffer = buffer;
  36484. }
  36485. return buffer;
  36486. }
  36487. get byteLength() {
  36488. let offset = 0; // global buffer offset in bytes
  36489. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  36490. const uniform = this.uniforms[ i ];
  36491. const { boundary, itemSize } = uniform;
  36492. // offset within a single chunk in bytes
  36493. const chunkOffset = offset % GPU_CHUNK_BYTES;
  36494. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  36495. // conformance tests
  36496. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  36497. // check for chunk overflow
  36498. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  36499. } else if ( chunkOffset % boundary !== 0 ) {
  36500. // check for correct alignment
  36501. offset += ( chunkOffset % boundary );
  36502. }
  36503. uniform.offset = ( offset / this.bytesPerElement );
  36504. offset += ( itemSize * this.bytesPerElement );
  36505. }
  36506. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  36507. }
  36508. update() {
  36509. let updated = false;
  36510. for ( const uniform of this.uniforms ) {
  36511. if ( this.updateByType( uniform ) === true ) {
  36512. updated = true;
  36513. }
  36514. }
  36515. return updated;
  36516. }
  36517. updateByType( uniform ) {
  36518. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  36519. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  36520. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  36521. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  36522. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  36523. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  36524. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  36525. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  36526. }
  36527. updateNumber( uniform ) {
  36528. let updated = false;
  36529. const a = this.values;
  36530. const v = uniform.getValue();
  36531. const offset = uniform.offset;
  36532. if ( a[ offset ] !== v ) {
  36533. const b = this.buffer;
  36534. b[ offset ] = a[ offset ] = v;
  36535. updated = true;
  36536. }
  36537. return updated;
  36538. }
  36539. updateVector2( uniform ) {
  36540. let updated = false;
  36541. const a = this.values;
  36542. const v = uniform.getValue();
  36543. const offset = uniform.offset;
  36544. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  36545. const b = this.buffer;
  36546. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36547. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36548. updated = true;
  36549. }
  36550. return updated;
  36551. }
  36552. updateVector3( uniform ) {
  36553. let updated = false;
  36554. const a = this.values;
  36555. const v = uniform.getValue();
  36556. const offset = uniform.offset;
  36557. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  36558. const b = this.buffer;
  36559. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36560. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36561. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  36562. updated = true;
  36563. }
  36564. return updated;
  36565. }
  36566. updateVector4( uniform ) {
  36567. let updated = false;
  36568. const a = this.values;
  36569. const v = uniform.getValue();
  36570. const offset = uniform.offset;
  36571. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  36572. const b = this.buffer;
  36573. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36574. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36575. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  36576. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  36577. updated = true;
  36578. }
  36579. return updated;
  36580. }
  36581. updateColor( uniform ) {
  36582. let updated = false;
  36583. const a = this.values;
  36584. const c = uniform.getValue();
  36585. const offset = uniform.offset;
  36586. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  36587. const b = this.buffer;
  36588. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  36589. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  36590. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  36591. updated = true;
  36592. }
  36593. return updated;
  36594. }
  36595. updateMatrix3( uniform ) {
  36596. let updated = false;
  36597. const a = this.values;
  36598. const e = uniform.getValue().elements;
  36599. const offset = uniform.offset;
  36600. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  36601. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  36602. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  36603. const b = this.buffer;
  36604. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  36605. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  36606. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  36607. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  36608. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  36609. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  36610. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  36611. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  36612. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  36613. updated = true;
  36614. }
  36615. return updated;
  36616. }
  36617. updateMatrix4( uniform ) {
  36618. let updated = false;
  36619. const a = this.values;
  36620. const e = uniform.getValue().elements;
  36621. const offset = uniform.offset;
  36622. if ( arraysEqual( a, e, offset ) === false ) {
  36623. const b = this.buffer;
  36624. b.set( e, offset );
  36625. setArray( a, e, offset );
  36626. updated = true;
  36627. }
  36628. return updated;
  36629. }
  36630. }
  36631. function setArray( a, b, offset ) {
  36632. for ( let i = 0, l = b.length; i < l; i ++ ) {
  36633. a[ offset + i ] = b[ i ];
  36634. }
  36635. }
  36636. function arraysEqual( a, b, offset ) {
  36637. for ( let i = 0, l = b.length; i < l; i ++ ) {
  36638. if ( a[ offset + i ] !== b[ i ] ) return false;
  36639. }
  36640. return true;
  36641. }
  36642. let id$1 = 0;
  36643. class NodeUniformsGroup extends UniformsGroup {
  36644. constructor( name, groupNode ) {
  36645. super( name );
  36646. this.id = id$1 ++;
  36647. this.groupNode = groupNode;
  36648. this.isNodeUniformsGroup = true;
  36649. }
  36650. getNodes() {
  36651. const nodes = [];
  36652. for ( const uniform of this.uniforms ) {
  36653. const node = uniform.nodeUniform.node;
  36654. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  36655. nodes.push( node );
  36656. }
  36657. return nodes;
  36658. }
  36659. }
  36660. let id = 0;
  36661. class SampledTexture extends Binding {
  36662. constructor( name, texture ) {
  36663. super( name );
  36664. this.id = id ++;
  36665. this.texture = texture;
  36666. this.version = texture ? texture.version : 0;
  36667. this.store = false;
  36668. this.isSampledTexture = true;
  36669. }
  36670. get needsBindingsUpdate() {
  36671. const { texture, version } = this;
  36672. return texture.isVideoTexture ? true : version !== texture.version; // @TODO: version === 0 && texture.version > 0 ( add it just to External Textures like PNG,JPG )
  36673. }
  36674. update() {
  36675. const { texture, version } = this;
  36676. if ( version !== texture.version ) {
  36677. this.version = texture.version;
  36678. return true;
  36679. }
  36680. return false;
  36681. }
  36682. }
  36683. class NodeSampledTexture extends SampledTexture {
  36684. constructor( name, textureNode, groupNode, access = null ) {
  36685. super( name, textureNode ? textureNode.value : null );
  36686. this.textureNode = textureNode;
  36687. this.groupNode = groupNode;
  36688. this.access = access;
  36689. }
  36690. get needsBindingsUpdate() {
  36691. return this.textureNode.value !== this.texture || super.needsBindingsUpdate;
  36692. }
  36693. update() {
  36694. const { textureNode } = this;
  36695. if ( this.texture !== textureNode.value ) {
  36696. this.texture = textureNode.value;
  36697. return true;
  36698. }
  36699. return super.update();
  36700. }
  36701. }
  36702. class NodeSampledCubeTexture extends NodeSampledTexture {
  36703. constructor( name, textureNode, groupNode, access ) {
  36704. super( name, textureNode, groupNode, access );
  36705. this.isSampledCubeTexture = true;
  36706. }
  36707. }
  36708. class NodeSampledTexture3D extends NodeSampledTexture {
  36709. constructor( name, textureNode, groupNode, access ) {
  36710. super( name, textureNode, groupNode, access );
  36711. this.isSampledTexture3D = true;
  36712. }
  36713. }
  36714. const glslMethods = {
  36715. [ MathNode.ATAN2 ]: 'atan',
  36716. textureDimensions: 'textureSize',
  36717. equals: 'equal'
  36718. };
  36719. const precisionLib = {
  36720. low: 'lowp',
  36721. medium: 'mediump',
  36722. high: 'highp'
  36723. };
  36724. const supports$1 = {
  36725. swizzleAssign: true,
  36726. storageBuffer: false
  36727. };
  36728. const defaultPrecisions = `
  36729. precision highp float;
  36730. precision highp int;
  36731. precision highp sampler2D;
  36732. precision highp sampler3D;
  36733. precision highp samplerCube;
  36734. precision highp sampler2DArray;
  36735. precision highp usampler2D;
  36736. precision highp usampler3D;
  36737. precision highp usamplerCube;
  36738. precision highp usampler2DArray;
  36739. precision highp isampler2D;
  36740. precision highp isampler3D;
  36741. precision highp isamplerCube;
  36742. precision highp isampler2DArray;
  36743. precision lowp sampler2DShadow;
  36744. `;
  36745. class GLSLNodeBuilder extends NodeBuilder {
  36746. constructor( object, renderer ) {
  36747. super( object, renderer, new GLSLNodeParser() );
  36748. this.uniformGroups = {};
  36749. this.transforms = [];
  36750. this.instanceBindGroups = false;
  36751. }
  36752. getMethod( method ) {
  36753. return glslMethods[ method ] || method;
  36754. }
  36755. getOutputStructName() {
  36756. return '';
  36757. }
  36758. buildFunctionCode( shaderNode ) {
  36759. const layout = shaderNode.layout;
  36760. const flowData = this.flowShaderNode( shaderNode );
  36761. const parameters = [];
  36762. for ( const input of layout.inputs ) {
  36763. parameters.push( this.getType( input.type ) + ' ' + input.name );
  36764. }
  36765. //
  36766. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  36767. ${ flowData.vars }
  36768. ${ flowData.code }
  36769. return ${ flowData.result };
  36770. }`;
  36771. //
  36772. return code;
  36773. }
  36774. setupPBO( storageBufferNode ) {
  36775. const attribute = storageBufferNode.value;
  36776. if ( attribute.pbo === undefined ) {
  36777. const originalArray = attribute.array;
  36778. const numElements = attribute.count * attribute.itemSize;
  36779. const { itemSize } = attribute;
  36780. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  36781. let format = isInteger ? RedIntegerFormat : RedFormat;
  36782. if ( itemSize === 2 ) {
  36783. format = isInteger ? RGIntegerFormat : RGFormat;
  36784. } else if ( itemSize === 3 ) {
  36785. format = isInteger ? RGBIntegerFormat : RGBFormat;
  36786. } else if ( itemSize === 4 ) {
  36787. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  36788. }
  36789. const typeMap = {
  36790. Float32Array: FloatType,
  36791. Uint8Array: UnsignedByteType,
  36792. Uint16Array: UnsignedShortType,
  36793. Uint32Array: UnsignedIntType,
  36794. Int8Array: ByteType,
  36795. Int16Array: ShortType,
  36796. Int32Array: IntType,
  36797. Uint8ClampedArray: UnsignedByteType,
  36798. };
  36799. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  36800. let height = Math.ceil( ( numElements / itemSize ) / width );
  36801. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  36802. const newSize = width * height * itemSize;
  36803. const newArray = new originalArray.constructor( newSize );
  36804. newArray.set( originalArray, 0 );
  36805. attribute.array = newArray;
  36806. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  36807. pboTexture.needsUpdate = true;
  36808. pboTexture.isPBOTexture = true;
  36809. const pbo = new TextureNode( pboTexture, null, null );
  36810. pbo.setPrecision( 'high' );
  36811. attribute.pboNode = pbo;
  36812. attribute.pbo = pbo.value;
  36813. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  36814. }
  36815. }
  36816. getPropertyName( node, shaderStage = this.shaderStage ) {
  36817. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  36818. return shaderStage.charAt( 0 ) + '_' + node.name;
  36819. }
  36820. return super.getPropertyName( node, shaderStage );
  36821. }
  36822. generatePBO( storageArrayElementNode ) {
  36823. const { node, indexNode } = storageArrayElementNode;
  36824. const attribute = node.value;
  36825. if ( this.renderer.backend.has( attribute ) ) {
  36826. const attributeData = this.renderer.backend.get( attribute );
  36827. attributeData.pbo = attribute.pbo;
  36828. }
  36829. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  36830. const textureName = this.getPropertyName( nodeUniform );
  36831. indexNode.increaseUsage( this ); // force cache generate to be used as index in x,y
  36832. const indexSnippet = indexNode.build( this, 'uint' );
  36833. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  36834. let propertyName = elementNodeData.propertyName;
  36835. if ( propertyName === undefined ) {
  36836. // property element
  36837. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  36838. propertyName = this.getPropertyName( nodeVar );
  36839. // property size
  36840. const bufferNodeData = this.getDataFromNode( node );
  36841. let propertySizeName = bufferNodeData.propertySizeName;
  36842. if ( propertySizeName === undefined ) {
  36843. propertySizeName = propertyName + 'Size';
  36844. this.getVarFromNode( node, propertySizeName, 'uint' );
  36845. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )` );
  36846. bufferNodeData.propertySizeName = propertySizeName;
  36847. }
  36848. //
  36849. const { itemSize } = attribute;
  36850. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  36851. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  36852. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  36853. //
  36854. let prefix = 'vec4';
  36855. if ( attribute.pbo.type === UnsignedIntType ) {
  36856. prefix = 'uvec4';
  36857. } else if ( attribute.pbo.type === IntType ) {
  36858. prefix = 'ivec4';
  36859. }
  36860. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}` );
  36861. elementNodeData.propertyName = propertyName;
  36862. }
  36863. return propertyName;
  36864. }
  36865. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  36866. if ( depthSnippet ) {
  36867. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  36868. } else {
  36869. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  36870. }
  36871. }
  36872. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  36873. if ( texture.isDepthTexture ) {
  36874. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  36875. } else {
  36876. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  36877. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  36878. }
  36879. }
  36880. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  36881. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  36882. }
  36883. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  36884. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  36885. }
  36886. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  36887. if ( shaderStage === 'fragment' ) {
  36888. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  36889. } else {
  36890. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  36891. }
  36892. }
  36893. getVars( shaderStage ) {
  36894. const snippets = [];
  36895. const vars = this.vars[ shaderStage ];
  36896. if ( vars !== undefined ) {
  36897. for ( const variable of vars ) {
  36898. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  36899. }
  36900. }
  36901. return snippets.join( '\n\t' );
  36902. }
  36903. getUniforms( shaderStage ) {
  36904. const uniforms = this.uniforms[ shaderStage ];
  36905. const bindingSnippets = [];
  36906. const uniformGroups = {};
  36907. for ( const uniform of uniforms ) {
  36908. let snippet = null;
  36909. let group = false;
  36910. if ( uniform.type === 'texture' ) {
  36911. const texture = uniform.node.value;
  36912. let typePrefix = '';
  36913. if ( texture.isDataTexture === true ) {
  36914. if ( texture.type === UnsignedIntType ) {
  36915. typePrefix = 'u';
  36916. } else if ( texture.type === IntType ) {
  36917. typePrefix = 'i';
  36918. }
  36919. }
  36920. if ( texture.compareFunction ) {
  36921. snippet = `sampler2DShadow ${ uniform.name };`;
  36922. } else if ( texture.isDataArrayTexture === true ) {
  36923. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  36924. } else {
  36925. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  36926. }
  36927. } else if ( uniform.type === 'cubeTexture' ) {
  36928. snippet = `samplerCube ${ uniform.name };`;
  36929. } else if ( uniform.type === 'texture3D' ) {
  36930. snippet = `sampler3D ${ uniform.name };`;
  36931. } else if ( uniform.type === 'buffer' ) {
  36932. const bufferNode = uniform.node;
  36933. const bufferType = this.getType( bufferNode.bufferType );
  36934. const bufferCount = bufferNode.bufferCount;
  36935. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  36936. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  36937. } else {
  36938. const vectorType = this.getVectorType( uniform.type );
  36939. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  36940. group = true;
  36941. }
  36942. const precision = uniform.node.precision;
  36943. if ( precision !== null ) {
  36944. snippet = precisionLib[ precision ] + ' ' + snippet;
  36945. }
  36946. if ( group ) {
  36947. snippet = '\t' + snippet;
  36948. const groupName = uniform.groupNode.name;
  36949. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  36950. groupSnippets.push( snippet );
  36951. } else {
  36952. snippet = 'uniform ' + snippet;
  36953. bindingSnippets.push( snippet );
  36954. }
  36955. }
  36956. let output = '';
  36957. for ( const name in uniformGroups ) {
  36958. const groupSnippets = uniformGroups[ name ];
  36959. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  36960. }
  36961. output += bindingSnippets.join( '\n' );
  36962. return output;
  36963. }
  36964. getTypeFromAttribute( attribute ) {
  36965. let nodeType = super.getTypeFromAttribute( attribute );
  36966. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  36967. let dataAttribute = attribute;
  36968. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  36969. const array = dataAttribute.array;
  36970. if ( ( array instanceof Uint32Array || array instanceof Int32Array || array instanceof Uint16Array || array instanceof Int16Array ) === false ) {
  36971. nodeType = nodeType.slice( 1 );
  36972. }
  36973. }
  36974. return nodeType;
  36975. }
  36976. getAttributes( shaderStage ) {
  36977. let snippet = '';
  36978. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  36979. const attributes = this.getAttributesArray();
  36980. let location = 0;
  36981. for ( const attribute of attributes ) {
  36982. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  36983. }
  36984. }
  36985. return snippet;
  36986. }
  36987. getStructMembers( struct ) {
  36988. const snippets = [];
  36989. const members = struct.getMemberTypes();
  36990. for ( let i = 0; i < members.length; i ++ ) {
  36991. const member = members[ i ];
  36992. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  36993. }
  36994. return snippets.join( '\n' );
  36995. }
  36996. getStructs( shaderStage ) {
  36997. const snippets = [];
  36998. const structs = this.structs[ shaderStage ];
  36999. if ( structs.length === 0 ) {
  37000. return 'layout( location = 0 ) out vec4 fragColor;\n';
  37001. }
  37002. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  37003. const struct = structs[ index ];
  37004. let snippet = '\n';
  37005. snippet += this.getStructMembers( struct );
  37006. snippet += '\n';
  37007. snippets.push( snippet );
  37008. }
  37009. return snippets.join( '\n\n' );
  37010. }
  37011. getVaryings( shaderStage ) {
  37012. let snippet = '';
  37013. const varyings = this.varyings;
  37014. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  37015. for ( const varying of varyings ) {
  37016. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  37017. const type = varying.type;
  37018. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  37019. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  37020. }
  37021. } else if ( shaderStage === 'fragment' ) {
  37022. for ( const varying of varyings ) {
  37023. if ( varying.needsInterpolation ) {
  37024. const type = varying.type;
  37025. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  37026. snippet += `${flat}in ${type} ${varying.name};\n`;
  37027. }
  37028. }
  37029. }
  37030. return snippet;
  37031. }
  37032. getVertexIndex() {
  37033. return 'uint( gl_VertexID )';
  37034. }
  37035. getInstanceIndex() {
  37036. return 'uint( gl_InstanceID )';
  37037. }
  37038. getDrawIndex() {
  37039. const extensions = this.renderer.backend.extensions;
  37040. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  37041. return 'uint( gl_DrawID )';
  37042. }
  37043. return null;
  37044. }
  37045. getFrontFacing() {
  37046. return 'gl_FrontFacing';
  37047. }
  37048. getFragCoord() {
  37049. return 'gl_FragCoord';
  37050. }
  37051. getFragDepth() {
  37052. return 'gl_FragDepth';
  37053. }
  37054. getExtensions( shaderStage ) {
  37055. let extensions = '';
  37056. if ( shaderStage === 'vertex' ) {
  37057. const ext = this.renderer.backend.extensions;
  37058. const isBatchedMesh = this.object.isBatchedMesh;
  37059. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  37060. extensions += '#extension GL_ANGLE_multi_draw : require\n';
  37061. }
  37062. }
  37063. return extensions;
  37064. }
  37065. isAvailable( name ) {
  37066. let result = supports$1[ name ];
  37067. if ( result === undefined ) {
  37068. if ( name === 'float32Filterable' ) {
  37069. const extensions = this.renderer.backend.extensions;
  37070. if ( extensions.has( 'OES_texture_float_linear' ) ) {
  37071. extensions.get( 'OES_texture_float_linear' );
  37072. result = true;
  37073. } else {
  37074. result = false;
  37075. }
  37076. }
  37077. supports$1[ name ] = result;
  37078. }
  37079. return result;
  37080. }
  37081. isFlipY() {
  37082. return true;
  37083. }
  37084. registerTransform( varyingName, attributeNode ) {
  37085. this.transforms.push( { varyingName, attributeNode } );
  37086. }
  37087. getTransforms( /* shaderStage */ ) {
  37088. const transforms = this.transforms;
  37089. let snippet = '';
  37090. for ( let i = 0; i < transforms.length; i ++ ) {
  37091. const transform = transforms[ i ];
  37092. const attributeName = this.getPropertyName( transform.attributeNode );
  37093. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  37094. }
  37095. return snippet;
  37096. }
  37097. _getGLSLUniformStruct( name, vars ) {
  37098. return `
  37099. layout( std140 ) uniform ${name} {
  37100. ${vars}
  37101. };`;
  37102. }
  37103. _getGLSLVertexCode( shaderData ) {
  37104. return `#version 300 es
  37105. // extensions
  37106. ${shaderData.extensions}
  37107. // precision
  37108. ${ defaultPrecisions }
  37109. // uniforms
  37110. ${shaderData.uniforms}
  37111. // varyings
  37112. ${shaderData.varyings}
  37113. // attributes
  37114. ${shaderData.attributes}
  37115. // codes
  37116. ${shaderData.codes}
  37117. void main() {
  37118. // vars
  37119. ${shaderData.vars}
  37120. // transforms
  37121. ${shaderData.transforms}
  37122. // flow
  37123. ${shaderData.flow}
  37124. gl_PointSize = 1.0;
  37125. }
  37126. `;
  37127. }
  37128. _getGLSLFragmentCode( shaderData ) {
  37129. return `#version 300 es
  37130. ${ this.getSignature() }
  37131. // precision
  37132. ${ defaultPrecisions }
  37133. // uniforms
  37134. ${shaderData.uniforms}
  37135. // varyings
  37136. ${shaderData.varyings}
  37137. // codes
  37138. ${shaderData.codes}
  37139. ${shaderData.structs}
  37140. void main() {
  37141. // vars
  37142. ${shaderData.vars}
  37143. // flow
  37144. ${shaderData.flow}
  37145. }
  37146. `;
  37147. }
  37148. buildCode() {
  37149. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  37150. for ( const shaderStage in shadersData ) {
  37151. let flow = '// code\n\n';
  37152. flow += this.flowCode[ shaderStage ];
  37153. const flowNodes = this.flowNodes[ shaderStage ];
  37154. const mainNode = flowNodes[ flowNodes.length - 1 ];
  37155. for ( const node of flowNodes ) {
  37156. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  37157. const slotName = node.name;
  37158. if ( slotName ) {
  37159. if ( flow.length > 0 ) flow += '\n';
  37160. flow += `\t// flow -> ${ slotName }\n\t`;
  37161. }
  37162. flow += `${ flowSlotData.code }\n\t`;
  37163. if ( node === mainNode && shaderStage !== 'compute' ) {
  37164. flow += '// result\n\t';
  37165. if ( shaderStage === 'vertex' ) {
  37166. flow += 'gl_Position = ';
  37167. flow += `${ flowSlotData.result };`;
  37168. } else if ( shaderStage === 'fragment' ) {
  37169. if ( ! node.outputNode.isOutputStructNode ) {
  37170. flow += 'fragColor = ';
  37171. flow += `${ flowSlotData.result };`;
  37172. }
  37173. }
  37174. }
  37175. }
  37176. const stageData = shadersData[ shaderStage ];
  37177. stageData.extensions = this.getExtensions( shaderStage );
  37178. stageData.uniforms = this.getUniforms( shaderStage );
  37179. stageData.attributes = this.getAttributes( shaderStage );
  37180. stageData.varyings = this.getVaryings( shaderStage );
  37181. stageData.vars = this.getVars( shaderStage );
  37182. stageData.structs = this.getStructs( shaderStage );
  37183. stageData.codes = this.getCodes( shaderStage );
  37184. stageData.transforms = this.getTransforms( shaderStage );
  37185. stageData.flow = flow;
  37186. }
  37187. if ( this.material !== null ) {
  37188. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  37189. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  37190. } else {
  37191. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  37192. }
  37193. }
  37194. getUniformFromNode( node, type, shaderStage, name = null ) {
  37195. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  37196. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  37197. let uniformGPU = nodeData.uniformGPU;
  37198. if ( uniformGPU === undefined ) {
  37199. const group = node.groupNode;
  37200. const groupName = group.name;
  37201. const bindings = this.getBindGroupArray( groupName, shaderStage );
  37202. if ( type === 'texture' ) {
  37203. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  37204. bindings.push( uniformGPU );
  37205. } else if ( type === 'cubeTexture' ) {
  37206. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  37207. bindings.push( uniformGPU );
  37208. } else if ( type === 'texture3D' ) {
  37209. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  37210. bindings.push( uniformGPU );
  37211. } else if ( type === 'buffer' ) {
  37212. node.name = `NodeBuffer_${ node.id }`;
  37213. uniformNode.name = `buffer${ node.id }`;
  37214. const buffer = new NodeUniformBuffer( node, group );
  37215. buffer.name = node.name;
  37216. bindings.push( buffer );
  37217. uniformGPU = buffer;
  37218. } else {
  37219. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  37220. let uniformsGroup = uniformsStage[ groupName ];
  37221. if ( uniformsGroup === undefined ) {
  37222. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  37223. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  37224. uniformsStage[ groupName ] = uniformsGroup;
  37225. bindings.push( uniformsGroup );
  37226. }
  37227. uniformGPU = this.getNodeUniform( uniformNode, type );
  37228. uniformsGroup.addUniform( uniformGPU );
  37229. }
  37230. nodeData.uniformGPU = uniformGPU;
  37231. }
  37232. return uniformNode;
  37233. }
  37234. }
  37235. let vector2 = null;
  37236. let vector4 = null;
  37237. let color4 = null;
  37238. class Backend {
  37239. constructor( parameters = {} ) {
  37240. this.parameters = Object.assign( {}, parameters );
  37241. this.data = new WeakMap();
  37242. this.renderer = null;
  37243. this.domElement = null;
  37244. }
  37245. async init( renderer ) {
  37246. this.renderer = renderer;
  37247. }
  37248. // render context
  37249. begin( /*renderContext*/ ) { }
  37250. finish( /*renderContext*/ ) { }
  37251. // render object
  37252. draw( /*renderObject, info*/ ) { }
  37253. // program
  37254. createProgram( /*program*/ ) { }
  37255. destroyProgram( /*program*/ ) { }
  37256. // bindings
  37257. createBindings( /*renderObject*/ ) { }
  37258. updateBindings( /*renderObject*/ ) { }
  37259. // pipeline
  37260. createRenderPipeline( /*renderObject*/ ) { }
  37261. createComputePipeline( /*computeNode, pipeline*/ ) { }
  37262. destroyPipeline( /*pipeline*/ ) { }
  37263. // cache key
  37264. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  37265. getRenderCacheKey( /*renderObject*/ ) { } // return String
  37266. // node builder
  37267. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  37268. // textures
  37269. createSampler( /*texture*/ ) { }
  37270. createDefaultTexture( /*texture*/ ) { }
  37271. createTexture( /*texture*/ ) { }
  37272. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  37273. // attributes
  37274. createAttribute( /*attribute*/ ) { }
  37275. createIndexAttribute( /*attribute*/ ) { }
  37276. updateAttribute( /*attribute*/ ) { }
  37277. destroyAttribute( /*attribute*/ ) { }
  37278. // canvas
  37279. getContext() { }
  37280. updateSize() { }
  37281. // utils
  37282. resolveTimestampAsync( /*renderContext, type*/ ) { }
  37283. hasFeatureAsync( /*name*/ ) { } // return Boolean
  37284. hasFeature( /*name*/ ) { } // return Boolean
  37285. getInstanceCount( renderObject ) {
  37286. const { object, geometry } = renderObject;
  37287. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  37288. }
  37289. getDrawingBufferSize() {
  37290. vector2 = vector2 || new Vector2();
  37291. return this.renderer.getDrawingBufferSize( vector2 );
  37292. }
  37293. getScissor() {
  37294. vector4 = vector4 || new Vector4();
  37295. return this.renderer.getScissor( vector4 );
  37296. }
  37297. setScissorTest( /*boolean*/ ) { }
  37298. getClearColor() {
  37299. const renderer = this.renderer;
  37300. color4 = color4 || new Color4();
  37301. renderer.getClearColor( color4 );
  37302. color4.getRGB( color4, this.renderer.currentColorSpace );
  37303. return color4;
  37304. }
  37305. getDomElement() {
  37306. let domElement = this.domElement;
  37307. if ( domElement === null ) {
  37308. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  37309. // OffscreenCanvas does not have setAttribute, see #22811
  37310. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  37311. this.domElement = domElement;
  37312. }
  37313. return domElement;
  37314. }
  37315. // resource properties
  37316. set( object, value ) {
  37317. this.data.set( object, value );
  37318. }
  37319. get( object ) {
  37320. let map = this.data.get( object );
  37321. if ( map === undefined ) {
  37322. map = {};
  37323. this.data.set( object, map );
  37324. }
  37325. return map;
  37326. }
  37327. has( object ) {
  37328. return this.data.has( object );
  37329. }
  37330. delete( object ) {
  37331. this.data.delete( object );
  37332. }
  37333. }
  37334. let _id$1 = 0;
  37335. class DualAttributeData {
  37336. constructor( attributeData, dualBuffer ) {
  37337. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  37338. this.type = attributeData.type;
  37339. this.bufferType = attributeData.bufferType;
  37340. this.pbo = attributeData.pbo;
  37341. this.byteLength = attributeData.byteLength;
  37342. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  37343. this.version = attributeData.version;
  37344. this.isInteger = attributeData.isInteger;
  37345. this.activeBufferIndex = 0;
  37346. this.baseId = attributeData.id;
  37347. }
  37348. get id() {
  37349. return `${ this.baseId }|${ this.activeBufferIndex }`;
  37350. }
  37351. get bufferGPU() {
  37352. return this.buffers[ this.activeBufferIndex ];
  37353. }
  37354. get transformBuffer() {
  37355. return this.buffers[ this.activeBufferIndex ^ 1 ];
  37356. }
  37357. switchBuffers() {
  37358. this.activeBufferIndex ^= 1;
  37359. }
  37360. }
  37361. class WebGLAttributeUtils {
  37362. constructor( backend ) {
  37363. this.backend = backend;
  37364. }
  37365. createAttribute( attribute, bufferType ) {
  37366. const backend = this.backend;
  37367. const { gl } = backend;
  37368. const array = attribute.array;
  37369. const usage = attribute.usage || gl.STATIC_DRAW;
  37370. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  37371. const bufferData = backend.get( bufferAttribute );
  37372. let bufferGPU = bufferData.bufferGPU;
  37373. if ( bufferGPU === undefined ) {
  37374. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  37375. bufferData.bufferGPU = bufferGPU;
  37376. bufferData.bufferType = bufferType;
  37377. bufferData.version = bufferAttribute.version;
  37378. }
  37379. //attribute.onUploadCallback();
  37380. let type;
  37381. if ( array instanceof Float32Array ) {
  37382. type = gl.FLOAT;
  37383. } else if ( array instanceof Uint16Array ) {
  37384. if ( attribute.isFloat16BufferAttribute ) {
  37385. type = gl.HALF_FLOAT;
  37386. } else {
  37387. type = gl.UNSIGNED_SHORT;
  37388. }
  37389. } else if ( array instanceof Int16Array ) {
  37390. type = gl.SHORT;
  37391. } else if ( array instanceof Uint32Array ) {
  37392. type = gl.UNSIGNED_INT;
  37393. } else if ( array instanceof Int32Array ) {
  37394. type = gl.INT;
  37395. } else if ( array instanceof Int8Array ) {
  37396. type = gl.BYTE;
  37397. } else if ( array instanceof Uint8Array ) {
  37398. type = gl.UNSIGNED_BYTE;
  37399. } else if ( array instanceof Uint8ClampedArray ) {
  37400. type = gl.UNSIGNED_BYTE;
  37401. } else {
  37402. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  37403. }
  37404. let attributeData = {
  37405. bufferGPU,
  37406. bufferType,
  37407. type,
  37408. byteLength: array.byteLength,
  37409. bytesPerElement: array.BYTES_PER_ELEMENT,
  37410. version: attribute.version,
  37411. pbo: attribute.pbo,
  37412. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || type === gl.UNSIGNED_SHORT || attribute.gpuType === IntType,
  37413. id: _id$1 ++
  37414. };
  37415. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  37416. // create buffer for tranform feedback use
  37417. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  37418. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  37419. }
  37420. backend.set( attribute, attributeData );
  37421. }
  37422. updateAttribute( attribute ) {
  37423. const backend = this.backend;
  37424. const { gl } = backend;
  37425. const array = attribute.array;
  37426. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  37427. const bufferData = backend.get( bufferAttribute );
  37428. const bufferType = bufferData.bufferType;
  37429. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  37430. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  37431. if ( updateRanges.length === 0 ) {
  37432. // Not using update ranges
  37433. gl.bufferSubData( bufferType, 0, array );
  37434. } else {
  37435. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  37436. const range = updateRanges[ i ];
  37437. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  37438. array, range.start, range.count );
  37439. }
  37440. bufferAttribute.clearUpdateRanges();
  37441. }
  37442. gl.bindBuffer( bufferType, null );
  37443. bufferData.version = bufferAttribute.version;
  37444. }
  37445. destroyAttribute( attribute ) {
  37446. const backend = this.backend;
  37447. const { gl } = backend;
  37448. if ( attribute.isInterleavedBufferAttribute ) {
  37449. backend.delete( attribute.data );
  37450. }
  37451. const attributeData = backend.get( attribute );
  37452. gl.deleteBuffer( attributeData.bufferGPU );
  37453. backend.delete( attribute );
  37454. }
  37455. async getArrayBufferAsync( attribute ) {
  37456. const backend = this.backend;
  37457. const { gl } = backend;
  37458. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  37459. const { bufferGPU } = backend.get( bufferAttribute );
  37460. const array = attribute.array;
  37461. const byteLength = array.byteLength;
  37462. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  37463. const writeBuffer = gl.createBuffer();
  37464. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  37465. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  37466. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  37467. await backend.utils._clientWaitAsync();
  37468. const dstBuffer = new attribute.array.constructor( array.length );
  37469. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  37470. gl.deleteBuffer( writeBuffer );
  37471. return dstBuffer.buffer;
  37472. }
  37473. _createBuffer( gl, bufferType, array, usage ) {
  37474. const bufferGPU = gl.createBuffer();
  37475. gl.bindBuffer( bufferType, bufferGPU );
  37476. gl.bufferData( bufferType, array, usage );
  37477. gl.bindBuffer( bufferType, null );
  37478. return bufferGPU;
  37479. }
  37480. }
  37481. let initialized$1 = false, equationToGL, factorToGL;
  37482. class WebGLState {
  37483. constructor( backend ) {
  37484. this.backend = backend;
  37485. this.gl = this.backend.gl;
  37486. this.enabled = {};
  37487. this.currentFlipSided = null;
  37488. this.currentCullFace = null;
  37489. this.currentProgram = null;
  37490. this.currentBlendingEnabled = false;
  37491. this.currentBlending = null;
  37492. this.currentBlendSrc = null;
  37493. this.currentBlendDst = null;
  37494. this.currentBlendSrcAlpha = null;
  37495. this.currentBlendDstAlpha = null;
  37496. this.currentPremultipledAlpha = null;
  37497. this.currentPolygonOffsetFactor = null;
  37498. this.currentPolygonOffsetUnits = null;
  37499. this.currentColorMask = null;
  37500. this.currentDepthFunc = null;
  37501. this.currentDepthMask = null;
  37502. this.currentStencilFunc = null;
  37503. this.currentStencilRef = null;
  37504. this.currentStencilFuncMask = null;
  37505. this.currentStencilFail = null;
  37506. this.currentStencilZFail = null;
  37507. this.currentStencilZPass = null;
  37508. this.currentStencilMask = null;
  37509. this.currentLineWidth = null;
  37510. this.currentBoundFramebuffers = {};
  37511. this.currentDrawbuffers = new WeakMap();
  37512. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  37513. this.currentTextureSlot = null;
  37514. this.currentBoundTextures = {};
  37515. if ( initialized$1 === false ) {
  37516. this._init( this.gl );
  37517. initialized$1 = true;
  37518. }
  37519. }
  37520. _init( gl ) {
  37521. // Store only WebGL constants here.
  37522. equationToGL = {
  37523. [ AddEquation ]: gl.FUNC_ADD,
  37524. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  37525. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  37526. };
  37527. factorToGL = {
  37528. [ ZeroFactor ]: gl.ZERO,
  37529. [ OneFactor ]: gl.ONE,
  37530. [ SrcColorFactor ]: gl.SRC_COLOR,
  37531. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  37532. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  37533. [ DstColorFactor ]: gl.DST_COLOR,
  37534. [ DstAlphaFactor ]: gl.DST_ALPHA,
  37535. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  37536. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  37537. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  37538. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  37539. };
  37540. }
  37541. enable( id ) {
  37542. const { enabled } = this;
  37543. if ( enabled[ id ] !== true ) {
  37544. this.gl.enable( id );
  37545. enabled[ id ] = true;
  37546. }
  37547. }
  37548. disable( id ) {
  37549. const { enabled } = this;
  37550. if ( enabled[ id ] !== false ) {
  37551. this.gl.disable( id );
  37552. enabled[ id ] = false;
  37553. }
  37554. }
  37555. setFlipSided( flipSided ) {
  37556. if ( this.currentFlipSided !== flipSided ) {
  37557. const { gl } = this;
  37558. if ( flipSided ) {
  37559. gl.frontFace( gl.CW );
  37560. } else {
  37561. gl.frontFace( gl.CCW );
  37562. }
  37563. this.currentFlipSided = flipSided;
  37564. }
  37565. }
  37566. setCullFace( cullFace ) {
  37567. const { gl } = this;
  37568. if ( cullFace !== CullFaceNone ) {
  37569. this.enable( gl.CULL_FACE );
  37570. if ( cullFace !== this.currentCullFace ) {
  37571. if ( cullFace === CullFaceBack ) {
  37572. gl.cullFace( gl.BACK );
  37573. } else if ( cullFace === CullFaceFront ) {
  37574. gl.cullFace( gl.FRONT );
  37575. } else {
  37576. gl.cullFace( gl.FRONT_AND_BACK );
  37577. }
  37578. }
  37579. } else {
  37580. this.disable( gl.CULL_FACE );
  37581. }
  37582. this.currentCullFace = cullFace;
  37583. }
  37584. setLineWidth( width ) {
  37585. const { currentLineWidth, gl } = this;
  37586. if ( width !== currentLineWidth ) {
  37587. gl.lineWidth( width );
  37588. this.currentLineWidth = width;
  37589. }
  37590. }
  37591. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  37592. const { gl } = this;
  37593. if ( blending === NoBlending ) {
  37594. if ( this.currentBlendingEnabled === true ) {
  37595. this.disable( gl.BLEND );
  37596. this.currentBlendingEnabled = false;
  37597. }
  37598. return;
  37599. }
  37600. if ( this.currentBlendingEnabled === false ) {
  37601. this.enable( gl.BLEND );
  37602. this.currentBlendingEnabled = true;
  37603. }
  37604. if ( blending !== CustomBlending ) {
  37605. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  37606. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  37607. gl.blendEquation( gl.FUNC_ADD );
  37608. this.currentBlendEquation = AddEquation;
  37609. this.currentBlendEquationAlpha = AddEquation;
  37610. }
  37611. if ( premultipliedAlpha ) {
  37612. switch ( blending ) {
  37613. case NormalBlending:
  37614. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  37615. break;
  37616. case AdditiveBlending:
  37617. gl.blendFunc( gl.ONE, gl.ONE );
  37618. break;
  37619. case SubtractiveBlending:
  37620. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  37621. break;
  37622. case MultiplyBlending:
  37623. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  37624. break;
  37625. default:
  37626. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  37627. break;
  37628. }
  37629. } else {
  37630. switch ( blending ) {
  37631. case NormalBlending:
  37632. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  37633. break;
  37634. case AdditiveBlending:
  37635. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  37636. break;
  37637. case SubtractiveBlending:
  37638. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  37639. break;
  37640. case MultiplyBlending:
  37641. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  37642. break;
  37643. default:
  37644. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  37645. break;
  37646. }
  37647. }
  37648. this.currentBlendSrc = null;
  37649. this.currentBlendDst = null;
  37650. this.currentBlendSrcAlpha = null;
  37651. this.currentBlendDstAlpha = null;
  37652. this.currentBlending = blending;
  37653. this.currentPremultipledAlpha = premultipliedAlpha;
  37654. }
  37655. return;
  37656. }
  37657. // custom blending
  37658. blendEquationAlpha = blendEquationAlpha || blendEquation;
  37659. blendSrcAlpha = blendSrcAlpha || blendSrc;
  37660. blendDstAlpha = blendDstAlpha || blendDst;
  37661. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  37662. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  37663. this.currentBlendEquation = blendEquation;
  37664. this.currentBlendEquationAlpha = blendEquationAlpha;
  37665. }
  37666. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  37667. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  37668. this.currentBlendSrc = blendSrc;
  37669. this.currentBlendDst = blendDst;
  37670. this.currentBlendSrcAlpha = blendSrcAlpha;
  37671. this.currentBlendDstAlpha = blendDstAlpha;
  37672. }
  37673. this.currentBlending = blending;
  37674. this.currentPremultipledAlpha = false;
  37675. }
  37676. setColorMask( colorMask ) {
  37677. if ( this.currentColorMask !== colorMask ) {
  37678. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  37679. this.currentColorMask = colorMask;
  37680. }
  37681. }
  37682. setDepthTest( depthTest ) {
  37683. const { gl } = this;
  37684. if ( depthTest ) {
  37685. this.enable( gl.DEPTH_TEST );
  37686. } else {
  37687. this.disable( gl.DEPTH_TEST );
  37688. }
  37689. }
  37690. setDepthMask( depthMask ) {
  37691. if ( this.currentDepthMask !== depthMask ) {
  37692. this.gl.depthMask( depthMask );
  37693. this.currentDepthMask = depthMask;
  37694. }
  37695. }
  37696. setDepthFunc( depthFunc ) {
  37697. if ( this.currentDepthFunc !== depthFunc ) {
  37698. const { gl } = this;
  37699. switch ( depthFunc ) {
  37700. case NeverDepth:
  37701. gl.depthFunc( gl.NEVER );
  37702. break;
  37703. case AlwaysDepth:
  37704. gl.depthFunc( gl.ALWAYS );
  37705. break;
  37706. case LessDepth:
  37707. gl.depthFunc( gl.LESS );
  37708. break;
  37709. case LessEqualDepth:
  37710. gl.depthFunc( gl.LEQUAL );
  37711. break;
  37712. case EqualDepth:
  37713. gl.depthFunc( gl.EQUAL );
  37714. break;
  37715. case GreaterEqualDepth:
  37716. gl.depthFunc( gl.GEQUAL );
  37717. break;
  37718. case GreaterDepth:
  37719. gl.depthFunc( gl.GREATER );
  37720. break;
  37721. case NotEqualDepth:
  37722. gl.depthFunc( gl.NOTEQUAL );
  37723. break;
  37724. default:
  37725. gl.depthFunc( gl.LEQUAL );
  37726. }
  37727. this.currentDepthFunc = depthFunc;
  37728. }
  37729. }
  37730. setStencilTest( stencilTest ) {
  37731. const { gl } = this;
  37732. if ( stencilTest ) {
  37733. this.enable( gl.STENCIL_TEST );
  37734. } else {
  37735. this.disable( gl.STENCIL_TEST );
  37736. }
  37737. }
  37738. setStencilMask( stencilMask ) {
  37739. if ( this.currentStencilMask !== stencilMask ) {
  37740. this.gl.stencilMask( stencilMask );
  37741. this.currentStencilMask = stencilMask;
  37742. }
  37743. }
  37744. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  37745. if ( this.currentStencilFunc !== stencilFunc ||
  37746. this.currentStencilRef !== stencilRef ||
  37747. this.currentStencilFuncMask !== stencilMask ) {
  37748. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  37749. this.currentStencilFunc = stencilFunc;
  37750. this.currentStencilRef = stencilRef;
  37751. this.currentStencilFuncMask = stencilMask;
  37752. }
  37753. }
  37754. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  37755. if ( this.currentStencilFail !== stencilFail ||
  37756. this.currentStencilZFail !== stencilZFail ||
  37757. this.currentStencilZPass !== stencilZPass ) {
  37758. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  37759. this.currentStencilFail = stencilFail;
  37760. this.currentStencilZFail = stencilZFail;
  37761. this.currentStencilZPass = stencilZPass;
  37762. }
  37763. }
  37764. setMaterial( material, frontFaceCW ) {
  37765. const { gl } = this;
  37766. material.side === DoubleSide
  37767. ? this.disable( gl.CULL_FACE )
  37768. : this.enable( gl.CULL_FACE );
  37769. let flipSided = ( material.side === BackSide );
  37770. if ( frontFaceCW ) flipSided = ! flipSided;
  37771. this.setFlipSided( flipSided );
  37772. ( material.blending === NormalBlending && material.transparent === false )
  37773. ? this.setBlending( NoBlending )
  37774. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  37775. this.setDepthFunc( material.depthFunc );
  37776. this.setDepthTest( material.depthTest );
  37777. this.setDepthMask( material.depthWrite );
  37778. this.setColorMask( material.colorWrite );
  37779. const stencilWrite = material.stencilWrite;
  37780. this.setStencilTest( stencilWrite );
  37781. if ( stencilWrite ) {
  37782. this.setStencilMask( material.stencilWriteMask );
  37783. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  37784. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  37785. }
  37786. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  37787. material.alphaToCoverage === true
  37788. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  37789. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  37790. }
  37791. setPolygonOffset( polygonOffset, factor, units ) {
  37792. const { gl } = this;
  37793. if ( polygonOffset ) {
  37794. this.enable( gl.POLYGON_OFFSET_FILL );
  37795. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  37796. gl.polygonOffset( factor, units );
  37797. this.currentPolygonOffsetFactor = factor;
  37798. this.currentPolygonOffsetUnits = units;
  37799. }
  37800. } else {
  37801. this.disable( gl.POLYGON_OFFSET_FILL );
  37802. }
  37803. }
  37804. useProgram( program ) {
  37805. if ( this.currentProgram !== program ) {
  37806. this.gl.useProgram( program );
  37807. this.currentProgram = program;
  37808. return true;
  37809. }
  37810. return false;
  37811. }
  37812. // framebuffer
  37813. bindFramebuffer( target, framebuffer ) {
  37814. const { gl, currentBoundFramebuffers } = this;
  37815. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  37816. gl.bindFramebuffer( target, framebuffer );
  37817. currentBoundFramebuffers[ target ] = framebuffer;
  37818. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  37819. if ( target === gl.DRAW_FRAMEBUFFER ) {
  37820. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  37821. }
  37822. if ( target === gl.FRAMEBUFFER ) {
  37823. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  37824. }
  37825. return true;
  37826. }
  37827. return false;
  37828. }
  37829. drawBuffers( renderContext, framebuffer ) {
  37830. const { gl } = this;
  37831. let drawBuffers = [];
  37832. let needsUpdate = false;
  37833. if ( renderContext.textures !== null ) {
  37834. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  37835. if ( drawBuffers === undefined ) {
  37836. drawBuffers = [];
  37837. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  37838. }
  37839. const textures = renderContext.textures;
  37840. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  37841. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  37842. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  37843. }
  37844. drawBuffers.length = textures.length;
  37845. needsUpdate = true;
  37846. }
  37847. } else {
  37848. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  37849. drawBuffers[ 0 ] = gl.BACK;
  37850. needsUpdate = true;
  37851. }
  37852. }
  37853. if ( needsUpdate ) {
  37854. gl.drawBuffers( drawBuffers );
  37855. }
  37856. }
  37857. // texture
  37858. activeTexture( webglSlot ) {
  37859. const { gl, currentTextureSlot, maxTextures } = this;
  37860. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  37861. if ( currentTextureSlot !== webglSlot ) {
  37862. gl.activeTexture( webglSlot );
  37863. this.currentTextureSlot = webglSlot;
  37864. }
  37865. }
  37866. bindTexture( webglType, webglTexture, webglSlot ) {
  37867. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  37868. if ( webglSlot === undefined ) {
  37869. if ( currentTextureSlot === null ) {
  37870. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  37871. } else {
  37872. webglSlot = currentTextureSlot;
  37873. }
  37874. }
  37875. let boundTexture = currentBoundTextures[ webglSlot ];
  37876. if ( boundTexture === undefined ) {
  37877. boundTexture = { type: undefined, texture: undefined };
  37878. currentBoundTextures[ webglSlot ] = boundTexture;
  37879. }
  37880. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  37881. if ( currentTextureSlot !== webglSlot ) {
  37882. gl.activeTexture( webglSlot );
  37883. this.currentTextureSlot = webglSlot;
  37884. }
  37885. gl.bindTexture( webglType, webglTexture );
  37886. boundTexture.type = webglType;
  37887. boundTexture.texture = webglTexture;
  37888. }
  37889. }
  37890. unbindTexture() {
  37891. const { gl, currentTextureSlot, currentBoundTextures } = this;
  37892. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  37893. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  37894. gl.bindTexture( boundTexture.type, null );
  37895. boundTexture.type = undefined;
  37896. boundTexture.texture = undefined;
  37897. }
  37898. }
  37899. }
  37900. class WebGLUtils {
  37901. constructor( backend ) {
  37902. this.backend = backend;
  37903. this.gl = this.backend.gl;
  37904. this.extensions = backend.extensions;
  37905. }
  37906. convert( p, colorSpace = NoColorSpace ) {
  37907. const { gl, extensions } = this;
  37908. let extension;
  37909. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  37910. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  37911. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  37912. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  37913. if ( p === ByteType ) return gl.BYTE;
  37914. if ( p === ShortType ) return gl.SHORT;
  37915. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  37916. if ( p === IntType ) return gl.INT;
  37917. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  37918. if ( p === FloatType ) return gl.FLOAT;
  37919. if ( p === HalfFloatType ) {
  37920. return gl.HALF_FLOAT;
  37921. }
  37922. if ( p === AlphaFormat ) return gl.ALPHA;
  37923. if ( p === RGBFormat ) return gl.RGB;
  37924. if ( p === RGBAFormat ) return gl.RGBA;
  37925. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  37926. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  37927. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  37928. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  37929. // WebGL2 formats.
  37930. if ( p === RedFormat ) return gl.RED;
  37931. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  37932. if ( p === RGFormat ) return gl.RG;
  37933. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  37934. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  37935. // S3TC
  37936. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  37937. if ( colorSpace === SRGBColorSpace ) {
  37938. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  37939. if ( extension !== null ) {
  37940. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  37941. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  37942. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  37943. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  37944. } else {
  37945. return null;
  37946. }
  37947. } else {
  37948. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  37949. if ( extension !== null ) {
  37950. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  37951. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  37952. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  37953. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  37954. } else {
  37955. return null;
  37956. }
  37957. }
  37958. }
  37959. // PVRTC
  37960. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  37961. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  37962. if ( extension !== null ) {
  37963. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  37964. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  37965. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  37966. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  37967. } else {
  37968. return null;
  37969. }
  37970. }
  37971. // ETC
  37972. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  37973. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  37974. if ( extension !== null ) {
  37975. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  37976. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  37977. } else {
  37978. return null;
  37979. }
  37980. }
  37981. // ASTC
  37982. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  37983. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  37984. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  37985. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  37986. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  37987. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  37988. if ( extension !== null ) {
  37989. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  37990. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  37991. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  37992. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  37993. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  37994. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  37995. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  37996. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  37997. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  37998. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  37999. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  38000. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  38001. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  38002. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  38003. } else {
  38004. return null;
  38005. }
  38006. }
  38007. // BPTC
  38008. if ( p === RGBA_BPTC_Format ) {
  38009. extension = extensions.get( 'EXT_texture_compression_bptc' );
  38010. if ( extension !== null ) {
  38011. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  38012. } else {
  38013. return null;
  38014. }
  38015. }
  38016. // RGTC
  38017. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  38018. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  38019. if ( extension !== null ) {
  38020. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  38021. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  38022. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  38023. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  38024. } else {
  38025. return null;
  38026. }
  38027. }
  38028. //
  38029. if ( p === UnsignedInt248Type ) {
  38030. return gl.UNSIGNED_INT_24_8;
  38031. }
  38032. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  38033. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  38034. }
  38035. _clientWaitAsync() {
  38036. const { gl } = this;
  38037. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  38038. gl.flush();
  38039. return new Promise( ( resolve, reject ) => {
  38040. function test() {
  38041. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  38042. if ( res === gl.WAIT_FAILED ) {
  38043. gl.deleteSync( sync );
  38044. reject();
  38045. return;
  38046. }
  38047. if ( res === gl.TIMEOUT_EXPIRED ) {
  38048. requestAnimationFrame( test );
  38049. return;
  38050. }
  38051. gl.deleteSync( sync );
  38052. resolve();
  38053. }
  38054. test();
  38055. } );
  38056. }
  38057. }
  38058. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  38059. class WebGLTextureUtils {
  38060. constructor( backend ) {
  38061. this.backend = backend;
  38062. this.gl = backend.gl;
  38063. this.extensions = backend.extensions;
  38064. this.defaultTextures = {};
  38065. if ( initialized === false ) {
  38066. this._init( this.gl );
  38067. initialized = true;
  38068. }
  38069. }
  38070. _init( gl ) {
  38071. // Store only WebGL constants here.
  38072. wrappingToGL = {
  38073. [ RepeatWrapping ]: gl.REPEAT,
  38074. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  38075. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  38076. };
  38077. filterToGL = {
  38078. [ NearestFilter ]: gl.NEAREST,
  38079. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  38080. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  38081. [ LinearFilter ]: gl.LINEAR,
  38082. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  38083. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  38084. };
  38085. compareToGL = {
  38086. [ NeverCompare ]: gl.NEVER,
  38087. [ AlwaysCompare ]: gl.ALWAYS,
  38088. [ LessCompare ]: gl.LESS,
  38089. [ LessEqualCompare ]: gl.LEQUAL,
  38090. [ EqualCompare ]: gl.EQUAL,
  38091. [ GreaterEqualCompare ]: gl.GEQUAL,
  38092. [ GreaterCompare ]: gl.GREATER,
  38093. [ NotEqualCompare ]: gl.NOTEQUAL
  38094. };
  38095. }
  38096. filterFallback( f ) {
  38097. const { gl } = this;
  38098. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  38099. return gl.NEAREST;
  38100. }
  38101. return gl.LINEAR;
  38102. }
  38103. getGLTextureType( texture ) {
  38104. const { gl } = this;
  38105. let glTextureType;
  38106. if ( texture.isCubeTexture === true ) {
  38107. glTextureType = gl.TEXTURE_CUBE_MAP;
  38108. } else if ( texture.isDataArrayTexture === true ) {
  38109. glTextureType = gl.TEXTURE_2D_ARRAY;
  38110. } else if ( texture.isData3DTexture === true ) {
  38111. glTextureType = gl.TEXTURE_3D;
  38112. } else {
  38113. glTextureType = gl.TEXTURE_2D;
  38114. }
  38115. return glTextureType;
  38116. }
  38117. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  38118. const { gl, extensions } = this;
  38119. if ( internalFormatName !== null ) {
  38120. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  38121. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  38122. }
  38123. let internalFormat = glFormat;
  38124. if ( glFormat === gl.RED ) {
  38125. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  38126. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  38127. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  38128. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  38129. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  38130. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  38131. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  38132. if ( glType === gl.INT ) internalFormat = gl.R32I;
  38133. }
  38134. if ( glFormat === gl.RED_INTEGER ) {
  38135. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  38136. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  38137. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  38138. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  38139. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  38140. if ( glType === gl.INT ) internalFormat = gl.R32I;
  38141. }
  38142. if ( glFormat === gl.RG ) {
  38143. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  38144. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  38145. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  38146. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  38147. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  38148. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  38149. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  38150. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  38151. }
  38152. if ( glFormat === gl.RG_INTEGER ) {
  38153. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  38154. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  38155. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  38156. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  38157. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  38158. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  38159. }
  38160. if ( glFormat === gl.RGB ) {
  38161. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  38162. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  38163. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  38164. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  38165. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  38166. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  38167. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  38168. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  38169. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  38170. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  38171. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  38172. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  38173. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  38174. }
  38175. if ( glFormat === gl.RGB_INTEGER ) {
  38176. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  38177. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  38178. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  38179. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  38180. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  38181. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  38182. }
  38183. if ( glFormat === gl.RGBA ) {
  38184. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  38185. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  38186. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  38187. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  38188. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  38189. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  38190. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  38191. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  38192. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  38193. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  38194. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  38195. }
  38196. if ( glFormat === gl.RGBA_INTEGER ) {
  38197. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  38198. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  38199. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  38200. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  38201. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  38202. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  38203. }
  38204. if ( glFormat === gl.DEPTH_COMPONENT ) {
  38205. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  38206. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  38207. }
  38208. if ( glFormat === gl.DEPTH_STENCIL ) {
  38209. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  38210. }
  38211. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  38212. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  38213. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  38214. extensions.get( 'EXT_color_buffer_float' );
  38215. }
  38216. return internalFormat;
  38217. }
  38218. setTextureParameters( textureType, texture ) {
  38219. const { gl, extensions, backend } = this;
  38220. const { currentAnisotropy } = backend.get( texture );
  38221. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  38222. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  38223. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  38224. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  38225. }
  38226. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  38227. // follow WebGPU backend mapping for texture filtering
  38228. const minFilter = ! texture.isVideoTexture && texture.minFilter === LinearFilter ? LinearMipmapLinearFilter : texture.minFilter;
  38229. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  38230. if ( texture.compareFunction ) {
  38231. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  38232. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  38233. }
  38234. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  38235. if ( texture.magFilter === NearestFilter ) return;
  38236. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  38237. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  38238. if ( texture.anisotropy > 1 || currentAnisotropy !== texture.anisotropy ) {
  38239. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  38240. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  38241. backend.get( texture ).currentAnisotropy = texture.anisotropy;
  38242. }
  38243. }
  38244. }
  38245. createDefaultTexture( texture ) {
  38246. const { gl, backend, defaultTextures } = this;
  38247. const glTextureType = this.getGLTextureType( texture );
  38248. let textureGPU = defaultTextures[ glTextureType ];
  38249. if ( textureGPU === undefined ) {
  38250. textureGPU = gl.createTexture();
  38251. backend.state.bindTexture( glTextureType, textureGPU );
  38252. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  38253. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  38254. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  38255. defaultTextures[ glTextureType ] = textureGPU;
  38256. }
  38257. backend.set( texture, {
  38258. textureGPU,
  38259. glTextureType,
  38260. isDefault: true
  38261. } );
  38262. }
  38263. createTexture( texture, options ) {
  38264. const { gl, backend } = this;
  38265. const { levels, width, height, depth } = options;
  38266. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  38267. const glType = backend.utils.convert( texture.type );
  38268. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  38269. const textureGPU = gl.createTexture();
  38270. const glTextureType = this.getGLTextureType( texture );
  38271. backend.state.bindTexture( glTextureType, textureGPU );
  38272. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  38273. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  38274. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  38275. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  38276. this.setTextureParameters( glTextureType, texture );
  38277. if ( texture.isDataArrayTexture ) {
  38278. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  38279. } else if ( texture.isData3DTexture ) {
  38280. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  38281. } else if ( ! texture.isVideoTexture ) {
  38282. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  38283. }
  38284. backend.set( texture, {
  38285. textureGPU,
  38286. glTextureType,
  38287. glFormat,
  38288. glType,
  38289. glInternalFormat
  38290. } );
  38291. }
  38292. copyBufferToTexture( buffer, texture ) {
  38293. const { gl, backend } = this;
  38294. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  38295. const { width, height } = texture.source.data;
  38296. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  38297. backend.state.bindTexture( glTextureType, textureGPU );
  38298. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  38299. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  38300. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  38301. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  38302. backend.state.unbindTexture();
  38303. // debug
  38304. // const framebuffer = gl.createFramebuffer();
  38305. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  38306. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  38307. // const readout = new Float32Array( width * height * 4 );
  38308. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  38309. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  38310. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  38311. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  38312. // console.log( readout );
  38313. }
  38314. updateTexture( texture, options ) {
  38315. const { gl } = this;
  38316. const { width, height } = options;
  38317. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  38318. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  38319. return;
  38320. const getImage = ( source ) => {
  38321. if ( source.isDataTexture ) {
  38322. return source.image.data;
  38323. } else if ( source instanceof ImageBitmap || source instanceof OffscreenCanvas || source instanceof HTMLImageElement || source instanceof HTMLCanvasElement ) {
  38324. return source;
  38325. }
  38326. return source.data;
  38327. };
  38328. this.backend.state.bindTexture( glTextureType, textureGPU );
  38329. if ( texture.isCompressedTexture ) {
  38330. const mipmaps = texture.mipmaps;
  38331. for ( let i = 0; i < mipmaps.length; i ++ ) {
  38332. const mipmap = mipmaps[ i ];
  38333. if ( texture.isCompressedArrayTexture ) {
  38334. const image = options.image;
  38335. if ( texture.format !== gl.RGBA ) {
  38336. if ( glFormat !== null ) {
  38337. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  38338. } else {
  38339. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  38340. }
  38341. } else {
  38342. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  38343. }
  38344. } else {
  38345. if ( glFormat !== null ) {
  38346. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  38347. } else {
  38348. console.warn( 'Unsupported compressed texture format' );
  38349. }
  38350. }
  38351. }
  38352. } else if ( texture.isCubeTexture ) {
  38353. const images = options.images;
  38354. for ( let i = 0; i < 6; i ++ ) {
  38355. const image = getImage( images[ i ] );
  38356. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  38357. }
  38358. } else if ( texture.isDataArrayTexture ) {
  38359. const image = options.image;
  38360. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  38361. } else if ( texture.isData3DTexture ) {
  38362. const image = options.image;
  38363. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  38364. } else if ( texture.isVideoTexture ) {
  38365. texture.update();
  38366. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  38367. } else {
  38368. const image = getImage( options.image );
  38369. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  38370. }
  38371. }
  38372. generateMipmaps( texture ) {
  38373. const { gl, backend } = this;
  38374. const { textureGPU, glTextureType } = backend.get( texture );
  38375. backend.state.bindTexture( glTextureType, textureGPU );
  38376. gl.generateMipmap( glTextureType );
  38377. }
  38378. deallocateRenderBuffers( renderTarget ) {
  38379. const { gl, backend } = this;
  38380. // remove framebuffer reference
  38381. if ( renderTarget ) {
  38382. const renderContextData = backend.get( renderTarget );
  38383. renderContextData.renderBufferStorageSetup = undefined;
  38384. if ( renderContextData.framebuffer ) {
  38385. gl.deleteFramebuffer( renderContextData.framebuffer );
  38386. renderContextData.framebuffer = undefined;
  38387. }
  38388. if ( renderContextData.depthRenderbuffer ) {
  38389. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  38390. renderContextData.depthRenderbuffer = undefined;
  38391. }
  38392. if ( renderContextData.stencilRenderbuffer ) {
  38393. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  38394. renderContextData.stencilRenderbuffer = undefined;
  38395. }
  38396. if ( renderContextData.msaaFrameBuffer ) {
  38397. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  38398. renderContextData.msaaFrameBuffer = undefined;
  38399. }
  38400. if ( renderContextData.msaaRenderbuffers ) {
  38401. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  38402. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  38403. }
  38404. renderContextData.msaaRenderbuffers = undefined;
  38405. }
  38406. }
  38407. }
  38408. destroyTexture( texture ) {
  38409. const { gl, backend } = this;
  38410. const { textureGPU, renderTarget } = backend.get( texture );
  38411. this.deallocateRenderBuffers( renderTarget );
  38412. gl.deleteTexture( textureGPU );
  38413. backend.delete( texture );
  38414. }
  38415. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  38416. const { gl, backend } = this;
  38417. const { state } = this.backend;
  38418. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  38419. let width, height, minX, minY;
  38420. let dstX, dstY;
  38421. if ( srcRegion !== null ) {
  38422. width = srcRegion.max.x - srcRegion.min.x;
  38423. height = srcRegion.max.y - srcRegion.min.y;
  38424. minX = srcRegion.min.x;
  38425. minY = srcRegion.min.y;
  38426. } else {
  38427. width = srcTexture.image.width;
  38428. height = srcTexture.image.height;
  38429. minX = 0;
  38430. minY = 0;
  38431. }
  38432. if ( dstPosition !== null ) {
  38433. dstX = dstPosition.x;
  38434. dstY = dstPosition.y;
  38435. } else {
  38436. dstX = 0;
  38437. dstY = 0;
  38438. }
  38439. state.bindTexture( glTextureType, dstTextureGPU );
  38440. // As another texture upload may have changed pixelStorei
  38441. // parameters, make sure they are correct for the dstTexture
  38442. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  38443. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  38444. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  38445. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  38446. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  38447. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  38448. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  38449. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  38450. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  38451. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  38452. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  38453. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  38454. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  38455. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  38456. if ( srcTexture.isDataTexture ) {
  38457. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  38458. } else {
  38459. if ( srcTexture.isCompressedTexture ) {
  38460. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  38461. } else {
  38462. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  38463. }
  38464. }
  38465. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  38466. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  38467. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  38468. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  38469. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  38470. // Generate mipmaps only when copying level 0
  38471. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  38472. state.unbindTexture();
  38473. }
  38474. copyFramebufferToTexture( texture, renderContext ) {
  38475. const { gl } = this;
  38476. const { state } = this.backend;
  38477. const { textureGPU } = this.backend.get( texture );
  38478. const width = texture.image.width;
  38479. const height = texture.image.height;
  38480. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  38481. if ( requireDrawFrameBuffer ) {
  38482. let mask;
  38483. let attachment;
  38484. if ( texture.isDepthTexture === true ) {
  38485. mask = gl.DEPTH_BUFFER_BIT;
  38486. attachment = gl.DEPTH_ATTACHMENT;
  38487. if ( renderContext.stencil ) {
  38488. mask |= gl.STENCIL_BUFFER_BIT;
  38489. }
  38490. } else {
  38491. mask = gl.COLOR_BUFFER_BIT;
  38492. attachment = gl.COLOR_ATTACHMENT0;
  38493. }
  38494. const fb = gl.createFramebuffer();
  38495. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  38496. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  38497. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  38498. gl.deleteFramebuffer( fb );
  38499. } else {
  38500. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  38501. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, 0, 0, width, height );
  38502. state.unbindTexture();
  38503. }
  38504. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  38505. this.backend._setFramebuffer( renderContext );
  38506. }
  38507. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  38508. setupRenderBufferStorage( renderbuffer, renderContext ) {
  38509. const { gl } = this;
  38510. const renderTarget = renderContext.renderTarget;
  38511. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  38512. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  38513. if ( depthBuffer && ! stencilBuffer ) {
  38514. let glInternalFormat = gl.DEPTH_COMPONENT24;
  38515. if ( samples > 0 ) {
  38516. if ( depthTexture && depthTexture.isDepthTexture ) {
  38517. if ( depthTexture.type === gl.FLOAT ) {
  38518. glInternalFormat = gl.DEPTH_COMPONENT32F;
  38519. }
  38520. }
  38521. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  38522. } else {
  38523. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  38524. }
  38525. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  38526. } else if ( depthBuffer && stencilBuffer ) {
  38527. if ( samples > 0 ) {
  38528. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  38529. } else {
  38530. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  38531. }
  38532. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  38533. }
  38534. }
  38535. async copyTextureToBuffer( texture, x, y, width, height ) {
  38536. const { backend, gl } = this;
  38537. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  38538. const fb = gl.createFramebuffer();
  38539. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  38540. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  38541. const typedArrayType = this._getTypedArrayType( glType );
  38542. const bytesPerTexel = this._getBytesPerTexel( glFormat );
  38543. const elementCount = width * height;
  38544. const byteLength = elementCount * bytesPerTexel;
  38545. const buffer = gl.createBuffer();
  38546. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  38547. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  38548. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  38549. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  38550. await backend.utils._clientWaitAsync();
  38551. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  38552. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  38553. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  38554. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  38555. gl.deleteFramebuffer( fb );
  38556. return dstBuffer;
  38557. }
  38558. _getTypedArrayType( glType ) {
  38559. const { gl } = this;
  38560. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  38561. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  38562. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  38563. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  38564. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  38565. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  38566. if ( glType === gl.FLOAT ) return Float32Array;
  38567. throw new Error( `Unsupported WebGL type: ${glType}` );
  38568. }
  38569. _getBytesPerTexel( glFormat ) {
  38570. const { gl } = this;
  38571. if ( glFormat === gl.RGBA ) return 4;
  38572. if ( glFormat === gl.RGB ) return 3;
  38573. if ( glFormat === gl.ALPHA ) return 1;
  38574. }
  38575. }
  38576. class WebGLExtensions {
  38577. constructor( backend ) {
  38578. this.backend = backend;
  38579. this.gl = this.backend.gl;
  38580. this.availableExtensions = this.gl.getSupportedExtensions();
  38581. this.extensions = {};
  38582. }
  38583. get( name ) {
  38584. let extension = this.extensions[ name ];
  38585. if ( extension === undefined ) {
  38586. extension = this.gl.getExtension( name );
  38587. this.extensions[ name ] = extension;
  38588. }
  38589. return extension;
  38590. }
  38591. has( name ) {
  38592. return this.availableExtensions.includes( name );
  38593. }
  38594. }
  38595. class WebGLCapabilities {
  38596. constructor( backend ) {
  38597. this.backend = backend;
  38598. this.maxAnisotropy = null;
  38599. }
  38600. getMaxAnisotropy() {
  38601. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  38602. const gl = this.backend.gl;
  38603. const extensions = this.backend.extensions;
  38604. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  38605. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  38606. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  38607. } else {
  38608. this.maxAnisotropy = 0;
  38609. }
  38610. return this.maxAnisotropy;
  38611. }
  38612. }
  38613. const GLFeatureName = {
  38614. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  38615. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  38616. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  38617. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  38618. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  38619. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  38620. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  38621. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  38622. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  38623. };
  38624. class WebGLBufferRenderer {
  38625. constructor( backend ) {
  38626. this.gl = backend.gl;
  38627. this.extensions = backend.extensions;
  38628. this.info = backend.renderer.info;
  38629. this.mode = null;
  38630. this.index = 0;
  38631. this.type = null;
  38632. this.object = null;
  38633. }
  38634. render( start, count ) {
  38635. const { gl, mode, object, type, info, index } = this;
  38636. if ( index !== 0 ) {
  38637. gl.drawElements( mode, count, type, start );
  38638. } else {
  38639. gl.drawArrays( mode, start, count );
  38640. }
  38641. info.update( object, count, mode, 1 );
  38642. }
  38643. renderInstances( start, count, primcount ) {
  38644. const { gl, mode, type, index, object, info } = this;
  38645. if ( primcount === 0 ) return;
  38646. if ( index !== 0 ) {
  38647. gl.drawElementsInstanced( mode, count, type, start, primcount );
  38648. } else {
  38649. gl.drawArraysInstanced( mode, start, count, primcount );
  38650. }
  38651. info.update( object, count, mode, primcount );
  38652. }
  38653. renderMultiDraw( starts, counts, drawCount ) {
  38654. const { extensions, mode, object, info } = this;
  38655. if ( drawCount === 0 ) return;
  38656. const extension = extensions.get( 'WEBGL_multi_draw' );
  38657. if ( extension === null ) {
  38658. for ( let i = 0; i < drawCount; i ++ ) {
  38659. this.render( starts[ i ], counts[ i ] );
  38660. }
  38661. } else {
  38662. if ( this.index !== 0 ) {
  38663. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  38664. } else {
  38665. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  38666. }
  38667. let elementCount = 0;
  38668. for ( let i = 0; i < drawCount; i ++ ) {
  38669. elementCount += counts[ i ];
  38670. }
  38671. info.update( object, elementCount, mode, 1 );
  38672. }
  38673. }
  38674. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  38675. const { extensions, mode, object, info } = this;
  38676. if ( drawCount === 0 ) return;
  38677. const extension = extensions.get( 'WEBGL_multi_draw' );
  38678. if ( extension === null ) {
  38679. for ( let i = 0; i < drawCount; i ++ ) {
  38680. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  38681. }
  38682. } else {
  38683. if ( this.index !== 0 ) {
  38684. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  38685. } else {
  38686. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  38687. }
  38688. let elementCount = 0;
  38689. for ( let i = 0; i < drawCount; i ++ ) {
  38690. elementCount += counts[ i ];
  38691. }
  38692. for ( let i = 0; i < primcount.length; i ++ ) {
  38693. info.update( object, elementCount, mode, primcount[ i ] );
  38694. }
  38695. }
  38696. }
  38697. //
  38698. }
  38699. //
  38700. class WebGLBackend extends Backend {
  38701. constructor( parameters = {} ) {
  38702. super( parameters );
  38703. this.isWebGLBackend = true;
  38704. }
  38705. init( renderer ) {
  38706. super.init( renderer );
  38707. //
  38708. const parameters = this.parameters;
  38709. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  38710. this.gl = glContext;
  38711. this.extensions = new WebGLExtensions( this );
  38712. this.capabilities = new WebGLCapabilities( this );
  38713. this.attributeUtils = new WebGLAttributeUtils( this );
  38714. this.textureUtils = new WebGLTextureUtils( this );
  38715. this.bufferRenderer = new WebGLBufferRenderer( this );
  38716. this.state = new WebGLState( this );
  38717. this.utils = new WebGLUtils( this );
  38718. this.vaoCache = {};
  38719. this.transformFeedbackCache = {};
  38720. this.discard = false;
  38721. this.trackTimestamp = ( parameters.trackTimestamp === true );
  38722. this.extensions.get( 'EXT_color_buffer_float' );
  38723. this.extensions.get( 'WEBGL_multi_draw' );
  38724. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  38725. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  38726. this._currentContext = null;
  38727. }
  38728. get coordinateSystem() {
  38729. return WebGLCoordinateSystem;
  38730. }
  38731. async getArrayBufferAsync( attribute ) {
  38732. return await this.attributeUtils.getArrayBufferAsync( attribute );
  38733. }
  38734. initTimestampQuery( renderContext ) {
  38735. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  38736. const renderContextData = this.get( renderContext );
  38737. if ( this.queryRunning ) {
  38738. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  38739. renderContextData.queryQueue.push( renderContext );
  38740. return;
  38741. }
  38742. if ( renderContextData.activeQuery ) {
  38743. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  38744. renderContextData.activeQuery = null;
  38745. }
  38746. renderContextData.activeQuery = this.gl.createQuery();
  38747. if ( renderContextData.activeQuery !== null ) {
  38748. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  38749. this.queryRunning = true;
  38750. }
  38751. }
  38752. // timestamp utils
  38753. prepareTimestampBuffer( renderContext ) {
  38754. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  38755. const renderContextData = this.get( renderContext );
  38756. if ( renderContextData.activeQuery ) {
  38757. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  38758. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  38759. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  38760. renderContextData.activeQuery = null;
  38761. this.queryRunning = false;
  38762. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  38763. const nextRenderContext = renderContextData.queryQueue.shift();
  38764. this.initTimestampQuery( nextRenderContext );
  38765. }
  38766. }
  38767. }
  38768. async resolveTimestampAsync( renderContext, type = 'render' ) {
  38769. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  38770. const renderContextData = this.get( renderContext );
  38771. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  38772. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  38773. const queryInfo = renderContextData.gpuQueries[ i ];
  38774. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  38775. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  38776. if ( available && ! disjoint ) {
  38777. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  38778. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  38779. this.gl.deleteQuery( queryInfo.query );
  38780. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  38781. i --;
  38782. this.renderer.info.updateTimestamp( type, duration );
  38783. }
  38784. }
  38785. }
  38786. getContext() {
  38787. return this.gl;
  38788. }
  38789. beginRender( renderContext ) {
  38790. const { gl } = this;
  38791. const renderContextData = this.get( renderContext );
  38792. //
  38793. //
  38794. this.initTimestampQuery( renderContext );
  38795. renderContextData.previousContext = this._currentContext;
  38796. this._currentContext = renderContext;
  38797. this._setFramebuffer( renderContext );
  38798. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  38799. //
  38800. if ( renderContext.viewport ) {
  38801. this.updateViewport( renderContext );
  38802. } else {
  38803. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  38804. }
  38805. if ( renderContext.scissor ) {
  38806. const { x, y, width, height } = renderContext.scissorValue;
  38807. gl.scissor( x, y, width, height );
  38808. }
  38809. const occlusionQueryCount = renderContext.occlusionQueryCount;
  38810. if ( occlusionQueryCount > 0 ) {
  38811. // Get a reference to the array of objects with queries. The renderContextData property
  38812. // can be changed by another render pass before the async reading of all previous queries complete
  38813. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  38814. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  38815. renderContextData.lastOcclusionObject = null;
  38816. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  38817. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  38818. renderContextData.occlusionQueryIndex = 0;
  38819. }
  38820. }
  38821. finishRender( renderContext ) {
  38822. const { gl, state } = this;
  38823. const renderContextData = this.get( renderContext );
  38824. const previousContext = renderContextData.previousContext;
  38825. const textures = renderContext.textures;
  38826. if ( textures !== null ) {
  38827. for ( let i = 0; i < textures.length; i ++ ) {
  38828. const texture = textures[ i ];
  38829. if ( texture.generateMipmaps ) {
  38830. this.generateMipmaps( texture );
  38831. }
  38832. }
  38833. }
  38834. this._currentContext = previousContext;
  38835. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  38836. const renderTargetContextData = this.get( renderContext.renderTarget );
  38837. const { samples } = renderContext.renderTarget;
  38838. const fb = renderTargetContextData.framebuffer;
  38839. const mask = gl.COLOR_BUFFER_BIT;
  38840. if ( samples > 0 ) {
  38841. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  38842. const textures = renderContext.textures;
  38843. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  38844. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  38845. for ( let i = 0; i < textures.length; i ++ ) {
  38846. // TODO Add support for MRT
  38847. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  38848. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  38849. }
  38850. }
  38851. }
  38852. if ( previousContext !== null ) {
  38853. this._setFramebuffer( previousContext );
  38854. if ( previousContext.viewport ) {
  38855. this.updateViewport( previousContext );
  38856. } else {
  38857. const gl = this.gl;
  38858. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  38859. }
  38860. }
  38861. const occlusionQueryCount = renderContext.occlusionQueryCount;
  38862. if ( occlusionQueryCount > 0 ) {
  38863. const renderContextData = this.get( renderContext );
  38864. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  38865. const { gl } = this;
  38866. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  38867. }
  38868. this.resolveOccludedAsync( renderContext );
  38869. }
  38870. this.prepareTimestampBuffer( renderContext );
  38871. }
  38872. resolveOccludedAsync( renderContext ) {
  38873. const renderContextData = this.get( renderContext );
  38874. // handle occlusion query results
  38875. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  38876. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  38877. const occluded = new WeakSet();
  38878. const { gl } = this;
  38879. renderContextData.currentOcclusionQueryObjects = null;
  38880. renderContextData.currentOcclusionQueries = null;
  38881. const check = () => {
  38882. let completed = 0;
  38883. // check all queries and requeue as appropriate
  38884. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  38885. const query = currentOcclusionQueries[ i ];
  38886. if ( query === null ) continue;
  38887. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  38888. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  38889. currentOcclusionQueries[ i ] = null;
  38890. gl.deleteQuery( query );
  38891. completed ++;
  38892. }
  38893. }
  38894. if ( completed < currentOcclusionQueries.length ) {
  38895. requestAnimationFrame( check );
  38896. } else {
  38897. renderContextData.occluded = occluded;
  38898. }
  38899. };
  38900. check();
  38901. }
  38902. }
  38903. isOccluded( renderContext, object ) {
  38904. const renderContextData = this.get( renderContext );
  38905. return renderContextData.occluded && renderContextData.occluded.has( object );
  38906. }
  38907. updateViewport( renderContext ) {
  38908. const gl = this.gl;
  38909. const { x, y, width, height } = renderContext.viewportValue;
  38910. gl.viewport( x, y, width, height );
  38911. }
  38912. setScissorTest( boolean ) {
  38913. const gl = this.gl;
  38914. if ( boolean ) {
  38915. gl.enable( gl.SCISSOR_TEST );
  38916. } else {
  38917. gl.disable( gl.SCISSOR_TEST );
  38918. }
  38919. }
  38920. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  38921. const { gl } = this;
  38922. if ( descriptor === null ) {
  38923. descriptor = {
  38924. textures: null,
  38925. clearColorValue: this.getClearColor()
  38926. };
  38927. }
  38928. //
  38929. let clear = 0;
  38930. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  38931. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  38932. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  38933. if ( clear !== 0 ) {
  38934. const clearColor = descriptor.clearColorValue || this.getClearColor();
  38935. if ( depth ) this.state.setDepthMask( true );
  38936. if ( descriptor.textures === null ) {
  38937. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  38938. gl.clear( clear );
  38939. } else {
  38940. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  38941. if ( color ) {
  38942. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  38943. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  38944. }
  38945. }
  38946. if ( depth && stencil ) {
  38947. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  38948. } else if ( depth ) {
  38949. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  38950. } else if ( stencil ) {
  38951. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  38952. }
  38953. }
  38954. }
  38955. }
  38956. beginCompute( computeGroup ) {
  38957. const gl = this.gl;
  38958. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  38959. this.initTimestampQuery( computeGroup );
  38960. }
  38961. compute( computeGroup, computeNode, bindings, pipeline ) {
  38962. const gl = this.gl;
  38963. if ( ! this.discard ) {
  38964. // required here to handle async behaviour of render.compute()
  38965. gl.enable( gl.RASTERIZER_DISCARD );
  38966. this.discard = true;
  38967. }
  38968. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  38969. const vaoKey = this._getVaoKey( null, attributes );
  38970. const vaoGPU = this.vaoCache[ vaoKey ];
  38971. if ( vaoGPU === undefined ) {
  38972. this._createVao( null, attributes );
  38973. } else {
  38974. gl.bindVertexArray( vaoGPU );
  38975. }
  38976. gl.useProgram( programGPU );
  38977. this._bindUniforms( bindings );
  38978. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  38979. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  38980. gl.beginTransformFeedback( gl.POINTS );
  38981. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  38982. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  38983. } else {
  38984. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  38985. }
  38986. gl.endTransformFeedback();
  38987. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  38988. // switch active buffers
  38989. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  38990. const dualAttributeData = transformBuffers[ i ];
  38991. if ( dualAttributeData.pbo ) {
  38992. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  38993. }
  38994. dualAttributeData.switchBuffers();
  38995. }
  38996. }
  38997. finishCompute( computeGroup ) {
  38998. const gl = this.gl;
  38999. this.discard = false;
  39000. gl.disable( gl.RASTERIZER_DISCARD );
  39001. this.prepareTimestampBuffer( computeGroup );
  39002. }
  39003. draw( renderObject/*, info*/ ) {
  39004. const { object, pipeline, material, context } = renderObject;
  39005. const { programGPU } = this.get( pipeline );
  39006. const { gl, state } = this;
  39007. const contextData = this.get( context );
  39008. //
  39009. this._bindUniforms( renderObject.getBindings() );
  39010. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  39011. state.setMaterial( material, frontFaceCW );
  39012. gl.useProgram( programGPU );
  39013. //
  39014. let vaoGPU = renderObject.staticVao;
  39015. if ( vaoGPU === undefined ) {
  39016. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  39017. vaoGPU = this.vaoCache[ vaoKey ];
  39018. if ( vaoGPU === undefined ) {
  39019. let staticVao;
  39020. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  39021. if ( staticVao ) renderObject.staticVao = vaoGPU;
  39022. }
  39023. }
  39024. gl.bindVertexArray( vaoGPU );
  39025. //
  39026. const index = renderObject.getIndex();
  39027. const geometry = renderObject.geometry;
  39028. const drawRange = renderObject.drawRange;
  39029. const firstVertex = drawRange.start;
  39030. //
  39031. const lastObject = contextData.lastOcclusionObject;
  39032. if ( lastObject !== object && lastObject !== undefined ) {
  39033. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  39034. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  39035. contextData.occlusionQueryIndex ++;
  39036. }
  39037. if ( object.occlusionTest === true ) {
  39038. const query = gl.createQuery();
  39039. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  39040. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  39041. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  39042. }
  39043. contextData.lastOcclusionObject = object;
  39044. }
  39045. //
  39046. const renderer = this.bufferRenderer;
  39047. if ( object.isPoints ) renderer.mode = gl.POINTS;
  39048. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  39049. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  39050. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  39051. else {
  39052. if ( material.wireframe === true ) {
  39053. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  39054. renderer.mode = gl.LINES;
  39055. } else {
  39056. renderer.mode = gl.TRIANGLES;
  39057. }
  39058. }
  39059. //
  39060. let count;
  39061. renderer.object = object;
  39062. if ( index !== null ) {
  39063. const indexData = this.get( index );
  39064. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  39065. renderer.index = index.count;
  39066. renderer.type = indexData.type;
  39067. count = indexCount;
  39068. } else {
  39069. renderer.index = 0;
  39070. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : geometry.attributes.position.count;
  39071. count = vertexCount;
  39072. }
  39073. const instanceCount = this.getInstanceCount( renderObject );
  39074. if ( object.isBatchedMesh ) {
  39075. if ( object._multiDrawInstances !== null ) {
  39076. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  39077. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  39078. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  39079. } else {
  39080. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  39081. }
  39082. } else if ( instanceCount > 1 ) {
  39083. renderer.renderInstances( firstVertex, count, instanceCount );
  39084. } else {
  39085. renderer.render( firstVertex, count );
  39086. }
  39087. //
  39088. gl.bindVertexArray( null );
  39089. }
  39090. needsRenderUpdate( /*renderObject*/ ) {
  39091. return false;
  39092. }
  39093. getRenderCacheKey( renderObject ) {
  39094. return renderObject.id;
  39095. }
  39096. // textures
  39097. createDefaultTexture( texture ) {
  39098. this.textureUtils.createDefaultTexture( texture );
  39099. }
  39100. createTexture( texture, options ) {
  39101. this.textureUtils.createTexture( texture, options );
  39102. }
  39103. updateTexture( texture, options ) {
  39104. this.textureUtils.updateTexture( texture, options );
  39105. }
  39106. generateMipmaps( texture ) {
  39107. this.textureUtils.generateMipmaps( texture );
  39108. }
  39109. destroyTexture( texture ) {
  39110. this.textureUtils.destroyTexture( texture );
  39111. }
  39112. copyTextureToBuffer( texture, x, y, width, height ) {
  39113. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  39114. }
  39115. createSampler( /*texture*/ ) {
  39116. //console.warn( 'Abstract class.' );
  39117. }
  39118. destroySampler() {}
  39119. // node builder
  39120. createNodeBuilder( object, renderer ) {
  39121. return new GLSLNodeBuilder( object, renderer );
  39122. }
  39123. // program
  39124. createProgram( program ) {
  39125. const gl = this.gl;
  39126. const { stage, code } = program;
  39127. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  39128. gl.shaderSource( shader, code );
  39129. gl.compileShader( shader );
  39130. this.set( program, {
  39131. shaderGPU: shader
  39132. } );
  39133. }
  39134. destroyProgram( /*program*/ ) {
  39135. console.warn( 'Abstract class.' );
  39136. }
  39137. createRenderPipeline( renderObject, promises ) {
  39138. const gl = this.gl;
  39139. const pipeline = renderObject.pipeline;
  39140. // Program
  39141. const { fragmentProgram, vertexProgram } = pipeline;
  39142. const programGPU = gl.createProgram();
  39143. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  39144. const vertexShader = this.get( vertexProgram ).shaderGPU;
  39145. gl.attachShader( programGPU, fragmentShader );
  39146. gl.attachShader( programGPU, vertexShader );
  39147. gl.linkProgram( programGPU );
  39148. this.set( pipeline, {
  39149. programGPU,
  39150. fragmentShader,
  39151. vertexShader
  39152. } );
  39153. if ( promises !== null && this.parallel ) {
  39154. const p = new Promise( ( resolve /*, reject*/ ) => {
  39155. const parallel = this.parallel;
  39156. const checkStatus = () => {
  39157. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  39158. this._completeCompile( renderObject, pipeline );
  39159. resolve();
  39160. } else {
  39161. requestAnimationFrame( checkStatus );
  39162. }
  39163. };
  39164. checkStatus();
  39165. } );
  39166. promises.push( p );
  39167. return;
  39168. }
  39169. this._completeCompile( renderObject, pipeline );
  39170. }
  39171. _handleSource( string, errorLine ) {
  39172. const lines = string.split( '\n' );
  39173. const lines2 = [];
  39174. const from = Math.max( errorLine - 6, 0 );
  39175. const to = Math.min( errorLine + 6, lines.length );
  39176. for ( let i = from; i < to; i ++ ) {
  39177. const line = i + 1;
  39178. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  39179. }
  39180. return lines2.join( '\n' );
  39181. }
  39182. _getShaderErrors( gl, shader, type ) {
  39183. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  39184. const errors = gl.getShaderInfoLog( shader ).trim();
  39185. if ( status && errors === '' ) return '';
  39186. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  39187. if ( errorMatches ) {
  39188. const errorLine = parseInt( errorMatches[ 1 ] );
  39189. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  39190. } else {
  39191. return errors;
  39192. }
  39193. }
  39194. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  39195. if ( this.renderer.debug.checkShaderErrors ) {
  39196. const gl = this.gl;
  39197. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  39198. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  39199. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  39200. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  39201. } else {
  39202. // default error reporting
  39203. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  39204. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  39205. console.error(
  39206. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  39207. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  39208. 'Program Info Log: ' + programLog + '\n' +
  39209. vertexErrors + '\n' +
  39210. fragmentErrors
  39211. );
  39212. }
  39213. } else if ( programLog !== '' ) {
  39214. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  39215. }
  39216. }
  39217. }
  39218. _completeCompile( renderObject, pipeline ) {
  39219. const gl = this.gl;
  39220. const pipelineData = this.get( pipeline );
  39221. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  39222. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  39223. this._logProgramError( programGPU, fragmentShader, vertexShader );
  39224. }
  39225. gl.useProgram( programGPU );
  39226. // Bindings
  39227. const bindings = renderObject.getBindings();
  39228. this._setupBindings( bindings, programGPU );
  39229. //
  39230. this.set( pipeline, {
  39231. programGPU
  39232. } );
  39233. }
  39234. createComputePipeline( computePipeline, bindings ) {
  39235. const gl = this.gl;
  39236. // Program
  39237. const fragmentProgram = {
  39238. stage: 'fragment',
  39239. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  39240. };
  39241. this.createProgram( fragmentProgram );
  39242. const { computeProgram } = computePipeline;
  39243. const programGPU = gl.createProgram();
  39244. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  39245. const vertexShader = this.get( computeProgram ).shaderGPU;
  39246. const transforms = computeProgram.transforms;
  39247. const transformVaryingNames = [];
  39248. const transformAttributeNodes = [];
  39249. for ( let i = 0; i < transforms.length; i ++ ) {
  39250. const transform = transforms[ i ];
  39251. transformVaryingNames.push( transform.varyingName );
  39252. transformAttributeNodes.push( transform.attributeNode );
  39253. }
  39254. gl.attachShader( programGPU, fragmentShader );
  39255. gl.attachShader( programGPU, vertexShader );
  39256. gl.transformFeedbackVaryings(
  39257. programGPU,
  39258. transformVaryingNames,
  39259. gl.SEPARATE_ATTRIBS
  39260. );
  39261. gl.linkProgram( programGPU );
  39262. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  39263. this._logProgramError( programGPU, fragmentShader, vertexShader );
  39264. }
  39265. gl.useProgram( programGPU );
  39266. // Bindings
  39267. this.createBindings( null, bindings );
  39268. this._setupBindings( bindings, programGPU );
  39269. const attributeNodes = computeProgram.attributes;
  39270. const attributes = [];
  39271. const transformBuffers = [];
  39272. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  39273. const attribute = attributeNodes[ i ].node.attribute;
  39274. attributes.push( attribute );
  39275. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  39276. }
  39277. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  39278. const attribute = transformAttributeNodes[ i ].attribute;
  39279. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  39280. const attributeData = this.get( attribute );
  39281. transformBuffers.push( attributeData );
  39282. }
  39283. //
  39284. this.set( computePipeline, {
  39285. programGPU,
  39286. transformBuffers,
  39287. attributes
  39288. } );
  39289. }
  39290. createBindings( bindGroup, bindings ) {
  39291. this.updateBindings( bindGroup, bindings );
  39292. }
  39293. updateBindings( bindGroup, bindings ) {
  39294. const { gl } = this;
  39295. let groupIndex = 0;
  39296. let textureIndex = 0;
  39297. for ( const bindGroup of bindings ) {
  39298. for ( const binding of bindGroup.bindings ) {
  39299. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39300. const bufferGPU = gl.createBuffer();
  39301. const data = binding.buffer;
  39302. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  39303. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  39304. gl.bindBufferBase( gl.UNIFORM_BUFFER, groupIndex, bufferGPU );
  39305. this.set( binding, {
  39306. index: groupIndex ++,
  39307. bufferGPU
  39308. } );
  39309. } else if ( binding.isSampledTexture ) {
  39310. const { textureGPU, glTextureType } = this.get( binding.texture );
  39311. this.set( binding, {
  39312. index: textureIndex ++,
  39313. textureGPU,
  39314. glTextureType
  39315. } );
  39316. }
  39317. }
  39318. }
  39319. }
  39320. updateBinding( binding ) {
  39321. const gl = this.gl;
  39322. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39323. const bindingData = this.get( binding );
  39324. const bufferGPU = bindingData.bufferGPU;
  39325. const data = binding.buffer;
  39326. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  39327. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  39328. }
  39329. }
  39330. // attributes
  39331. createIndexAttribute( attribute ) {
  39332. const gl = this.gl;
  39333. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  39334. }
  39335. createAttribute( attribute ) {
  39336. if ( this.has( attribute ) ) return;
  39337. const gl = this.gl;
  39338. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  39339. }
  39340. createStorageAttribute( attribute ) {
  39341. if ( this.has( attribute ) ) return;
  39342. const gl = this.gl;
  39343. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  39344. }
  39345. updateAttribute( attribute ) {
  39346. this.attributeUtils.updateAttribute( attribute );
  39347. }
  39348. destroyAttribute( attribute ) {
  39349. this.attributeUtils.destroyAttribute( attribute );
  39350. }
  39351. updateSize() {
  39352. //console.warn( 'Abstract class.' );
  39353. }
  39354. hasFeature( name ) {
  39355. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  39356. const extensions = this.extensions;
  39357. for ( let i = 0; i < keysMatching.length; i ++ ) {
  39358. if ( extensions.has( keysMatching[ i ] ) ) return true;
  39359. }
  39360. return false;
  39361. }
  39362. getMaxAnisotropy() {
  39363. return this.capabilities.getMaxAnisotropy();
  39364. }
  39365. copyTextureToTexture( position, srcTexture, dstTexture, level ) {
  39366. this.textureUtils.copyTextureToTexture( position, srcTexture, dstTexture, level );
  39367. }
  39368. copyFramebufferToTexture( texture, renderContext ) {
  39369. this.textureUtils.copyFramebufferToTexture( texture, renderContext );
  39370. }
  39371. _setFramebuffer( renderContext ) {
  39372. const { gl, state } = this;
  39373. let currentFrameBuffer = null;
  39374. if ( renderContext.textures !== null ) {
  39375. const renderTarget = renderContext.renderTarget;
  39376. const renderTargetContextData = this.get( renderTarget );
  39377. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  39378. const cubeFace = this.renderer._activeCubeFace;
  39379. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  39380. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  39381. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  39382. let fb;
  39383. if ( isCube ) {
  39384. if ( renderTargetContextData.cubeFramebuffers === undefined ) {
  39385. renderTargetContextData.cubeFramebuffers = [];
  39386. }
  39387. fb = renderTargetContextData.cubeFramebuffers[ cubeFace ];
  39388. } else {
  39389. fb = renderTargetContextData.framebuffer;
  39390. }
  39391. if ( fb === undefined ) {
  39392. fb = gl.createFramebuffer();
  39393. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  39394. const textures = renderContext.textures;
  39395. if ( isCube ) {
  39396. renderTargetContextData.cubeFramebuffers[ cubeFace ] = fb;
  39397. const { textureGPU } = this.get( textures[ 0 ] );
  39398. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  39399. } else {
  39400. for ( let i = 0; i < textures.length; i ++ ) {
  39401. const texture = textures[ i ];
  39402. const textureData = this.get( texture );
  39403. textureData.renderTarget = renderContext.renderTarget;
  39404. const attachment = gl.COLOR_ATTACHMENT0 + i;
  39405. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  39406. }
  39407. renderTargetContextData.framebuffer = fb;
  39408. state.drawBuffers( renderContext, fb );
  39409. }
  39410. if ( renderContext.depthTexture !== null ) {
  39411. const textureData = this.get( renderContext.depthTexture );
  39412. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  39413. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  39414. }
  39415. }
  39416. if ( samples > 0 ) {
  39417. if ( msaaFb === undefined ) {
  39418. const invalidationArray = [];
  39419. msaaFb = gl.createFramebuffer();
  39420. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  39421. const msaaRenderbuffers = [];
  39422. const textures = renderContext.textures;
  39423. for ( let i = 0; i < textures.length; i ++ ) {
  39424. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  39425. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  39426. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  39427. if ( depthBuffer ) {
  39428. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  39429. invalidationArray.push( depthStyle );
  39430. }
  39431. const texture = renderContext.textures[ i ];
  39432. const textureData = this.get( texture );
  39433. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, renderContext.width, renderContext.height );
  39434. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  39435. }
  39436. renderTargetContextData.msaaFrameBuffer = msaaFb;
  39437. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  39438. if ( depthRenderbuffer === undefined ) {
  39439. depthRenderbuffer = gl.createRenderbuffer();
  39440. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, renderContext );
  39441. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  39442. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  39443. invalidationArray.push( depthStyle );
  39444. }
  39445. renderTargetContextData.invalidationArray = invalidationArray;
  39446. }
  39447. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  39448. } else {
  39449. currentFrameBuffer = fb;
  39450. }
  39451. }
  39452. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  39453. }
  39454. _getVaoKey( index, attributes ) {
  39455. let key = [];
  39456. if ( index !== null ) {
  39457. const indexData = this.get( index );
  39458. key += ':' + indexData.id;
  39459. }
  39460. for ( let i = 0; i < attributes.length; i ++ ) {
  39461. const attributeData = this.get( attributes[ i ] );
  39462. key += ':' + attributeData.id;
  39463. }
  39464. return key;
  39465. }
  39466. _createVao( index, attributes ) {
  39467. const { gl } = this;
  39468. const vaoGPU = gl.createVertexArray();
  39469. let key = '';
  39470. let staticVao = true;
  39471. gl.bindVertexArray( vaoGPU );
  39472. if ( index !== null ) {
  39473. const indexData = this.get( index );
  39474. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  39475. key += ':' + indexData.id;
  39476. }
  39477. for ( let i = 0; i < attributes.length; i ++ ) {
  39478. const attribute = attributes[ i ];
  39479. const attributeData = this.get( attribute );
  39480. key += ':' + attributeData.id;
  39481. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  39482. gl.enableVertexAttribArray( i );
  39483. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  39484. let stride, offset;
  39485. if ( attribute.isInterleavedBufferAttribute === true ) {
  39486. stride = attribute.data.stride * attributeData.bytesPerElement;
  39487. offset = attribute.offset * attributeData.bytesPerElement;
  39488. } else {
  39489. stride = 0;
  39490. offset = 0;
  39491. }
  39492. if ( attributeData.isInteger ) {
  39493. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  39494. } else {
  39495. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  39496. }
  39497. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  39498. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  39499. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  39500. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  39501. }
  39502. }
  39503. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  39504. this.vaoCache[ key ] = vaoGPU;
  39505. return { vaoGPU, staticVao };
  39506. }
  39507. _getTransformFeedback( transformBuffers ) {
  39508. let key = '';
  39509. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  39510. key += ':' + transformBuffers[ i ].id;
  39511. }
  39512. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  39513. if ( transformFeedbackGPU !== undefined ) {
  39514. return transformFeedbackGPU;
  39515. }
  39516. const gl = this.gl;
  39517. transformFeedbackGPU = gl.createTransformFeedback();
  39518. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  39519. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  39520. const attributeData = transformBuffers[ i ];
  39521. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  39522. }
  39523. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  39524. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  39525. return transformFeedbackGPU;
  39526. }
  39527. _setupBindings( bindings, programGPU ) {
  39528. const gl = this.gl;
  39529. for ( const bindGroup of bindings ) {
  39530. for ( const binding of bindGroup.bindings ) {
  39531. const bindingData = this.get( binding );
  39532. const index = bindingData.index;
  39533. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39534. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  39535. gl.uniformBlockBinding( programGPU, location, index );
  39536. } else if ( binding.isSampledTexture ) {
  39537. const location = gl.getUniformLocation( programGPU, binding.name );
  39538. gl.uniform1i( location, index );
  39539. }
  39540. }
  39541. }
  39542. }
  39543. _bindUniforms( bindings ) {
  39544. const { gl, state } = this;
  39545. for ( const bindGroup of bindings ) {
  39546. for ( const binding of bindGroup.bindings ) {
  39547. const bindingData = this.get( binding );
  39548. const index = bindingData.index;
  39549. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39550. gl.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  39551. } else if ( binding.isSampledTexture ) {
  39552. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  39553. }
  39554. }
  39555. }
  39556. }
  39557. }
  39558. class Sampler extends Binding {
  39559. constructor( name, texture ) {
  39560. super( name );
  39561. this.texture = texture;
  39562. this.version = texture ? texture.version : 0;
  39563. this.isSampler = true;
  39564. }
  39565. }
  39566. class NodeSampler extends Sampler {
  39567. constructor( name, textureNode, groupNode ) {
  39568. super( name, textureNode ? textureNode.value : null );
  39569. this.textureNode = textureNode;
  39570. this.groupNode = groupNode;
  39571. }
  39572. update() {
  39573. this.texture = this.textureNode.value;
  39574. }
  39575. }
  39576. class StorageBuffer extends Buffer {
  39577. constructor( name, attribute ) {
  39578. super( name, attribute ? attribute.array : null );
  39579. this.attribute = attribute;
  39580. this.isStorageBuffer = true;
  39581. }
  39582. }
  39583. let _id = 0;
  39584. class NodeStorageBuffer extends StorageBuffer {
  39585. constructor( nodeUniform, groupNode ) {
  39586. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  39587. this.nodeUniform = nodeUniform;
  39588. this.access = nodeUniform ? nodeUniform.access : GPUBufferBindingType.Storage;
  39589. this.groupNode = groupNode;
  39590. }
  39591. get buffer() {
  39592. return this.nodeUniform.value;
  39593. }
  39594. }
  39595. class WebGPUTexturePassUtils {
  39596. constructor( device ) {
  39597. this.device = device;
  39598. const mipmapVertexSource = `
  39599. struct VarysStruct {
  39600. @builtin( position ) Position: vec4<f32>,
  39601. @location( 0 ) vTex : vec2<f32>
  39602. };
  39603. @vertex
  39604. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  39605. var Varys : VarysStruct;
  39606. var pos = array< vec2<f32>, 4 >(
  39607. vec2<f32>( -1.0, 1.0 ),
  39608. vec2<f32>( 1.0, 1.0 ),
  39609. vec2<f32>( -1.0, -1.0 ),
  39610. vec2<f32>( 1.0, -1.0 )
  39611. );
  39612. var tex = array< vec2<f32>, 4 >(
  39613. vec2<f32>( 0.0, 0.0 ),
  39614. vec2<f32>( 1.0, 0.0 ),
  39615. vec2<f32>( 0.0, 1.0 ),
  39616. vec2<f32>( 1.0, 1.0 )
  39617. );
  39618. Varys.vTex = tex[ vertexIndex ];
  39619. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  39620. return Varys;
  39621. }
  39622. `;
  39623. const mipmapFragmentSource = `
  39624. @group( 0 ) @binding( 0 )
  39625. var imgSampler : sampler;
  39626. @group( 0 ) @binding( 1 )
  39627. var img : texture_2d<f32>;
  39628. @fragment
  39629. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  39630. return textureSample( img, imgSampler, vTex );
  39631. }
  39632. `;
  39633. const flipYFragmentSource = `
  39634. @group( 0 ) @binding( 0 )
  39635. var imgSampler : sampler;
  39636. @group( 0 ) @binding( 1 )
  39637. var img : texture_2d<f32>;
  39638. @fragment
  39639. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  39640. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  39641. }
  39642. `;
  39643. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  39644. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  39645. // We'll need a new pipeline for every texture format used.
  39646. this.transferPipelines = {};
  39647. this.flipYPipelines = {};
  39648. this.mipmapVertexShaderModule = device.createShaderModule( {
  39649. label: 'mipmapVertex',
  39650. code: mipmapVertexSource
  39651. } );
  39652. this.mipmapFragmentShaderModule = device.createShaderModule( {
  39653. label: 'mipmapFragment',
  39654. code: mipmapFragmentSource
  39655. } );
  39656. this.flipYFragmentShaderModule = device.createShaderModule( {
  39657. label: 'flipYFragment',
  39658. code: flipYFragmentSource
  39659. } );
  39660. }
  39661. getTransferPipeline( format ) {
  39662. let pipeline = this.transferPipelines[ format ];
  39663. if ( pipeline === undefined ) {
  39664. pipeline = this.device.createRenderPipeline( {
  39665. vertex: {
  39666. module: this.mipmapVertexShaderModule,
  39667. entryPoint: 'main'
  39668. },
  39669. fragment: {
  39670. module: this.mipmapFragmentShaderModule,
  39671. entryPoint: 'main',
  39672. targets: [ { format } ]
  39673. },
  39674. primitive: {
  39675. topology: GPUPrimitiveTopology.TriangleStrip,
  39676. stripIndexFormat: GPUIndexFormat.Uint32
  39677. },
  39678. layout: 'auto'
  39679. } );
  39680. this.transferPipelines[ format ] = pipeline;
  39681. }
  39682. return pipeline;
  39683. }
  39684. getFlipYPipeline( format ) {
  39685. let pipeline = this.flipYPipelines[ format ];
  39686. if ( pipeline === undefined ) {
  39687. pipeline = this.device.createRenderPipeline( {
  39688. vertex: {
  39689. module: this.mipmapVertexShaderModule,
  39690. entryPoint: 'main'
  39691. },
  39692. fragment: {
  39693. module: this.flipYFragmentShaderModule,
  39694. entryPoint: 'main',
  39695. targets: [ { format } ]
  39696. },
  39697. primitive: {
  39698. topology: GPUPrimitiveTopology.TriangleStrip,
  39699. stripIndexFormat: GPUIndexFormat.Uint32
  39700. },
  39701. layout: 'auto'
  39702. } );
  39703. this.flipYPipelines[ format ] = pipeline;
  39704. }
  39705. return pipeline;
  39706. }
  39707. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  39708. const format = textureGPUDescriptor.format;
  39709. const { width, height } = textureGPUDescriptor.size;
  39710. const transferPipeline = this.getTransferPipeline( format );
  39711. const flipYPipeline = this.getFlipYPipeline( format );
  39712. const tempTexture = this.device.createTexture( {
  39713. size: { width, height, depthOrArrayLayers: 1 },
  39714. format,
  39715. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  39716. } );
  39717. const srcView = textureGPU.createView( {
  39718. baseMipLevel: 0,
  39719. mipLevelCount: 1,
  39720. dimension: GPUTextureViewDimension.TwoD,
  39721. baseArrayLayer
  39722. } );
  39723. const dstView = tempTexture.createView( {
  39724. baseMipLevel: 0,
  39725. mipLevelCount: 1,
  39726. dimension: GPUTextureViewDimension.TwoD,
  39727. baseArrayLayer: 0
  39728. } );
  39729. const commandEncoder = this.device.createCommandEncoder( {} );
  39730. const pass = ( pipeline, sourceView, destinationView ) => {
  39731. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  39732. const bindGroup = this.device.createBindGroup( {
  39733. layout: bindGroupLayout,
  39734. entries: [ {
  39735. binding: 0,
  39736. resource: this.flipYSampler
  39737. }, {
  39738. binding: 1,
  39739. resource: sourceView
  39740. } ]
  39741. } );
  39742. const passEncoder = commandEncoder.beginRenderPass( {
  39743. colorAttachments: [ {
  39744. view: destinationView,
  39745. loadOp: GPULoadOp.Clear,
  39746. storeOp: GPUStoreOp.Store,
  39747. clearValue: [ 0, 0, 0, 0 ]
  39748. } ]
  39749. } );
  39750. passEncoder.setPipeline( pipeline );
  39751. passEncoder.setBindGroup( 0, bindGroup );
  39752. passEncoder.draw( 4, 1, 0, 0 );
  39753. passEncoder.end();
  39754. };
  39755. pass( transferPipeline, srcView, dstView );
  39756. pass( flipYPipeline, dstView, srcView );
  39757. this.device.queue.submit( [ commandEncoder.finish() ] );
  39758. tempTexture.destroy();
  39759. }
  39760. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  39761. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  39762. const commandEncoder = this.device.createCommandEncoder( {} );
  39763. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  39764. let srcView = textureGPU.createView( {
  39765. baseMipLevel: 0,
  39766. mipLevelCount: 1,
  39767. dimension: GPUTextureViewDimension.TwoD,
  39768. baseArrayLayer
  39769. } );
  39770. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  39771. const bindGroup = this.device.createBindGroup( {
  39772. layout: bindGroupLayout,
  39773. entries: [ {
  39774. binding: 0,
  39775. resource: this.mipmapSampler
  39776. }, {
  39777. binding: 1,
  39778. resource: srcView
  39779. } ]
  39780. } );
  39781. const dstView = textureGPU.createView( {
  39782. baseMipLevel: i,
  39783. mipLevelCount: 1,
  39784. dimension: GPUTextureViewDimension.TwoD,
  39785. baseArrayLayer
  39786. } );
  39787. const passEncoder = commandEncoder.beginRenderPass( {
  39788. colorAttachments: [ {
  39789. view: dstView,
  39790. loadOp: GPULoadOp.Clear,
  39791. storeOp: GPUStoreOp.Store,
  39792. clearValue: [ 0, 0, 0, 0 ]
  39793. } ]
  39794. } );
  39795. passEncoder.setPipeline( pipeline );
  39796. passEncoder.setBindGroup( 0, bindGroup );
  39797. passEncoder.draw( 4, 1, 0, 0 );
  39798. passEncoder.end();
  39799. srcView = dstView;
  39800. }
  39801. this.device.queue.submit( [ commandEncoder.finish() ] );
  39802. }
  39803. }
  39804. const _compareToWebGPU = {
  39805. [ NeverCompare ]: 'never',
  39806. [ LessCompare ]: 'less',
  39807. [ EqualCompare ]: 'equal',
  39808. [ LessEqualCompare ]: 'less-equal',
  39809. [ GreaterCompare ]: 'greater',
  39810. [ GreaterEqualCompare ]: 'greater-equal',
  39811. [ AlwaysCompare ]: 'always',
  39812. [ NotEqualCompare ]: 'not-equal'
  39813. };
  39814. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  39815. class WebGPUTextureUtils {
  39816. constructor( backend ) {
  39817. this.backend = backend;
  39818. this._passUtils = null;
  39819. this.defaultTexture = {};
  39820. this.defaultCubeTexture = {};
  39821. this.colorBuffer = null;
  39822. this.depthTexture = new DepthTexture();
  39823. this.depthTexture.name = 'depthBuffer';
  39824. }
  39825. createSampler( texture ) {
  39826. const backend = this.backend;
  39827. const device = backend.device;
  39828. const textureGPU = backend.get( texture );
  39829. const samplerDescriptorGPU = {
  39830. addressModeU: this._convertAddressMode( texture.wrapS ),
  39831. addressModeV: this._convertAddressMode( texture.wrapT ),
  39832. addressModeW: this._convertAddressMode( texture.wrapR ),
  39833. magFilter: this._convertFilterMode( texture.magFilter ),
  39834. minFilter: this._convertFilterMode( texture.minFilter ),
  39835. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  39836. maxAnisotropy: texture.anisotropy
  39837. };
  39838. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  39839. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  39840. }
  39841. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  39842. }
  39843. createDefaultTexture( texture ) {
  39844. let textureGPU;
  39845. const format = getFormat( texture );
  39846. if ( texture.isCubeTexture ) {
  39847. textureGPU = this._getDefaultCubeTextureGPU( format );
  39848. } else {
  39849. textureGPU = this._getDefaultTextureGPU( format );
  39850. }
  39851. this.backend.get( texture ).texture = textureGPU;
  39852. }
  39853. createTexture( texture, options = {} ) {
  39854. const backend = this.backend;
  39855. const textureData = backend.get( texture );
  39856. if ( textureData.initialized ) {
  39857. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  39858. }
  39859. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  39860. if ( options.levels === undefined ) options.levels = 1;
  39861. if ( options.depth === undefined ) options.depth = 1;
  39862. const { width, height, depth, levels } = options;
  39863. const dimension = this._getDimension( texture );
  39864. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  39865. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  39866. if ( sampleCount > 1 ) {
  39867. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  39868. sampleCount = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  39869. if ( sampleCount === 2 ) {
  39870. sampleCount = 4;
  39871. }
  39872. }
  39873. const primarySampleCount = texture.isRenderTargetTexture ? 1 : sampleCount;
  39874. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  39875. if ( texture.isStorageTexture === true ) {
  39876. usage |= GPUTextureUsage.STORAGE_BINDING;
  39877. }
  39878. if ( texture.isCompressedTexture !== true ) {
  39879. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  39880. }
  39881. const textureDescriptorGPU = {
  39882. label: texture.name,
  39883. size: {
  39884. width: width,
  39885. height: height,
  39886. depthOrArrayLayers: depth,
  39887. },
  39888. mipLevelCount: levels,
  39889. sampleCount: primarySampleCount,
  39890. dimension: dimension,
  39891. format: format,
  39892. usage: usage
  39893. };
  39894. // texture creation
  39895. if ( texture.isVideoTexture ) {
  39896. const video = texture.source.data;
  39897. const videoFrame = new VideoFrame( video );
  39898. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  39899. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  39900. videoFrame.close();
  39901. textureData.externalTexture = video;
  39902. } else {
  39903. if ( format === undefined ) {
  39904. console.warn( 'WebGPURenderer: Texture format not supported.' );
  39905. return this.createDefaultTexture( texture );
  39906. }
  39907. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  39908. }
  39909. if ( texture.isRenderTargetTexture && sampleCount > 1 ) {
  39910. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  39911. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  39912. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  39913. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  39914. }
  39915. textureData.initialized = true;
  39916. textureData.textureDescriptorGPU = textureDescriptorGPU;
  39917. }
  39918. destroyTexture( texture ) {
  39919. const backend = this.backend;
  39920. const textureData = backend.get( texture );
  39921. textureData.texture.destroy();
  39922. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  39923. backend.delete( texture );
  39924. }
  39925. destroySampler( texture ) {
  39926. const backend = this.backend;
  39927. const textureData = backend.get( texture );
  39928. delete textureData.sampler;
  39929. }
  39930. generateMipmaps( texture ) {
  39931. const textureData = this.backend.get( texture );
  39932. if ( texture.isCubeTexture ) {
  39933. for ( let i = 0; i < 6; i ++ ) {
  39934. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  39935. }
  39936. } else {
  39937. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU );
  39938. }
  39939. }
  39940. getColorBuffer() {
  39941. if ( this.colorBuffer ) this.colorBuffer.destroy();
  39942. const backend = this.backend;
  39943. const { width, height } = backend.getDrawingBufferSize();
  39944. this.colorBuffer = backend.device.createTexture( {
  39945. label: 'colorBuffer',
  39946. size: {
  39947. width: width,
  39948. height: height,
  39949. depthOrArrayLayers: 1
  39950. },
  39951. sampleCount: backend.parameters.sampleCount,
  39952. format: GPUTextureFormat.BGRA8Unorm,
  39953. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  39954. } );
  39955. return this.colorBuffer;
  39956. }
  39957. getDepthBuffer( depth = true, stencil = false ) {
  39958. const backend = this.backend;
  39959. const { width, height } = backend.getDrawingBufferSize();
  39960. const depthTexture = this.depthTexture;
  39961. const depthTextureGPU = backend.get( depthTexture ).texture;
  39962. let format, type;
  39963. if ( stencil ) {
  39964. format = DepthStencilFormat;
  39965. type = UnsignedInt248Type;
  39966. } else if ( depth ) {
  39967. format = DepthFormat;
  39968. type = UnsignedIntType;
  39969. }
  39970. if ( depthTextureGPU !== undefined ) {
  39971. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  39972. return depthTextureGPU;
  39973. }
  39974. this.destroyTexture( depthTexture );
  39975. }
  39976. depthTexture.name = 'depthBuffer';
  39977. depthTexture.format = format;
  39978. depthTexture.type = type;
  39979. depthTexture.image.width = width;
  39980. depthTexture.image.height = height;
  39981. this.createTexture( depthTexture, { sampleCount: backend.parameters.sampleCount, width, height } );
  39982. return backend.get( depthTexture ).texture;
  39983. }
  39984. updateTexture( texture, options ) {
  39985. const textureData = this.backend.get( texture );
  39986. const { textureDescriptorGPU } = textureData;
  39987. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  39988. return;
  39989. // transfer texture data
  39990. if ( texture.isDataTexture ) {
  39991. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  39992. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  39993. for ( let i = 0; i < options.image.depth; i ++ ) {
  39994. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  39995. }
  39996. } else if ( texture.isCompressedTexture ) {
  39997. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  39998. } else if ( texture.isCubeTexture ) {
  39999. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  40000. } else if ( texture.isVideoTexture ) {
  40001. const video = texture.source.data;
  40002. textureData.externalTexture = video;
  40003. } else {
  40004. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  40005. }
  40006. //
  40007. textureData.version = texture.version;
  40008. if ( texture.onUpdate ) texture.onUpdate( texture );
  40009. }
  40010. async copyTextureToBuffer( texture, x, y, width, height ) {
  40011. const device = this.backend.device;
  40012. const textureData = this.backend.get( texture );
  40013. const textureGPU = textureData.texture;
  40014. const format = textureData.textureDescriptorGPU.format;
  40015. const bytesPerTexel = this._getBytesPerTexel( format );
  40016. let bytesPerRow = width * bytesPerTexel;
  40017. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  40018. const readBuffer = device.createBuffer(
  40019. {
  40020. size: width * height * bytesPerTexel,
  40021. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  40022. }
  40023. );
  40024. const encoder = device.createCommandEncoder();
  40025. encoder.copyTextureToBuffer(
  40026. {
  40027. texture: textureGPU,
  40028. origin: { x, y },
  40029. },
  40030. {
  40031. buffer: readBuffer,
  40032. bytesPerRow: bytesPerRow
  40033. },
  40034. {
  40035. width: width,
  40036. height: height
  40037. }
  40038. );
  40039. const typedArrayType = this._getTypedArrayType( format );
  40040. device.queue.submit( [ encoder.finish() ] );
  40041. await readBuffer.mapAsync( GPUMapMode.READ );
  40042. const buffer = readBuffer.getMappedRange();
  40043. return new typedArrayType( buffer );
  40044. }
  40045. _isEnvironmentTexture( texture ) {
  40046. const mapping = texture.mapping;
  40047. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  40048. }
  40049. _getDefaultTextureGPU( format ) {
  40050. let defaultTexture = this.defaultTexture[ format ];
  40051. if ( defaultTexture === undefined ) {
  40052. const texture = new Texture();
  40053. texture.minFilter = NearestFilter;
  40054. texture.magFilter = NearestFilter;
  40055. this.createTexture( texture, { width: 1, height: 1, format } );
  40056. this.defaultTexture[ format ] = defaultTexture = texture;
  40057. }
  40058. return this.backend.get( defaultTexture ).texture;
  40059. }
  40060. _getDefaultCubeTextureGPU( format ) {
  40061. let defaultCubeTexture = this.defaultTexture[ format ];
  40062. if ( defaultCubeTexture === undefined ) {
  40063. const texture = new CubeTexture();
  40064. texture.minFilter = NearestFilter;
  40065. texture.magFilter = NearestFilter;
  40066. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  40067. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  40068. }
  40069. return this.backend.get( defaultCubeTexture ).texture;
  40070. }
  40071. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  40072. for ( let i = 0; i < 6; i ++ ) {
  40073. const image = images[ i ];
  40074. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  40075. if ( image.isDataTexture ) {
  40076. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  40077. } else {
  40078. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  40079. }
  40080. }
  40081. }
  40082. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  40083. const device = this.backend.device;
  40084. device.queue.copyExternalImageToTexture(
  40085. {
  40086. source: image
  40087. }, {
  40088. texture: textureGPU,
  40089. mipLevel: 0,
  40090. origin: { x: 0, y: 0, z: originDepth }
  40091. }, {
  40092. width: image.width,
  40093. height: image.height,
  40094. depthOrArrayLayers: 1
  40095. }
  40096. );
  40097. if ( flipY === true ) {
  40098. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  40099. }
  40100. }
  40101. _getPassUtils() {
  40102. let passUtils = this._passUtils;
  40103. if ( passUtils === null ) {
  40104. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  40105. }
  40106. return passUtils;
  40107. }
  40108. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  40109. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  40110. }
  40111. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  40112. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  40113. }
  40114. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  40115. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  40116. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  40117. const device = this.backend.device;
  40118. const data = image.data;
  40119. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  40120. const bytesPerRow = image.width * bytesPerTexel;
  40121. device.queue.writeTexture(
  40122. {
  40123. texture: textureGPU,
  40124. mipLevel: 0,
  40125. origin: { x: 0, y: 0, z: originDepth }
  40126. },
  40127. data,
  40128. {
  40129. offset: image.width * image.height * bytesPerTexel * depth,
  40130. bytesPerRow
  40131. },
  40132. {
  40133. width: image.width,
  40134. height: image.height,
  40135. depthOrArrayLayers: 1
  40136. } );
  40137. if ( flipY === true ) {
  40138. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  40139. }
  40140. }
  40141. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  40142. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  40143. const device = this.backend.device;
  40144. const blockData = this._getBlockData( textureDescriptorGPU.format );
  40145. for ( let i = 0; i < mipmaps.length; i ++ ) {
  40146. const mipmap = mipmaps[ i ];
  40147. const width = mipmap.width;
  40148. const height = mipmap.height;
  40149. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  40150. device.queue.writeTexture(
  40151. {
  40152. texture: textureGPU,
  40153. mipLevel: i
  40154. },
  40155. mipmap.data,
  40156. {
  40157. offset: 0,
  40158. bytesPerRow
  40159. },
  40160. {
  40161. width: Math.ceil( width / blockData.width ) * blockData.width,
  40162. height: Math.ceil( height / blockData.width ) * blockData.width,
  40163. depthOrArrayLayers: 1
  40164. }
  40165. );
  40166. }
  40167. }
  40168. _getBlockData( format ) {
  40169. // this method is only relevant for compressed texture formats
  40170. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  40171. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  40172. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  40173. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  40174. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  40175. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  40176. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  40177. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  40178. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  40179. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  40180. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  40181. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  40182. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  40183. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  40184. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  40185. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  40186. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  40187. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  40188. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  40189. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  40190. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  40191. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  40192. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  40193. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  40194. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  40195. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  40196. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  40197. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  40198. }
  40199. _convertAddressMode( value ) {
  40200. let addressMode = GPUAddressMode.ClampToEdge;
  40201. if ( value === RepeatWrapping ) {
  40202. addressMode = GPUAddressMode.Repeat;
  40203. } else if ( value === MirroredRepeatWrapping ) {
  40204. addressMode = GPUAddressMode.MirrorRepeat;
  40205. }
  40206. return addressMode;
  40207. }
  40208. _convertFilterMode( value ) {
  40209. let filterMode = GPUFilterMode.Linear;
  40210. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  40211. filterMode = GPUFilterMode.Nearest;
  40212. }
  40213. return filterMode;
  40214. }
  40215. _getBytesPerTexel( format ) {
  40216. // 8-bit formats
  40217. if ( format === GPUTextureFormat.R8Unorm ||
  40218. format === GPUTextureFormat.R8Snorm ||
  40219. format === GPUTextureFormat.R8Uint ||
  40220. format === GPUTextureFormat.R8Sint ) return 1;
  40221. // 16-bit formats
  40222. if ( format === GPUTextureFormat.R16Uint ||
  40223. format === GPUTextureFormat.R16Sint ||
  40224. format === GPUTextureFormat.R16Float ||
  40225. format === GPUTextureFormat.RG8Unorm ||
  40226. format === GPUTextureFormat.RG8Snorm ||
  40227. format === GPUTextureFormat.RG8Uint ||
  40228. format === GPUTextureFormat.RG8Sint ) return 2;
  40229. // 32-bit formats
  40230. if ( format === GPUTextureFormat.R32Uint ||
  40231. format === GPUTextureFormat.R32Sint ||
  40232. format === GPUTextureFormat.R32Float ||
  40233. format === GPUTextureFormat.RG16Uint ||
  40234. format === GPUTextureFormat.RG16Sint ||
  40235. format === GPUTextureFormat.RG16Float ||
  40236. format === GPUTextureFormat.RGBA8Unorm ||
  40237. format === GPUTextureFormat.RGBA8UnormSRGB ||
  40238. format === GPUTextureFormat.RGBA8Snorm ||
  40239. format === GPUTextureFormat.RGBA8Uint ||
  40240. format === GPUTextureFormat.RGBA8Sint ||
  40241. format === GPUTextureFormat.BGRA8Unorm ||
  40242. format === GPUTextureFormat.BGRA8UnormSRGB ||
  40243. // Packed 32-bit formats
  40244. format === GPUTextureFormat.RGB9E5UFloat ||
  40245. format === GPUTextureFormat.RGB10A2Unorm ||
  40246. format === GPUTextureFormat.RG11B10UFloat ||
  40247. format === GPUTextureFormat.Depth32Float ||
  40248. format === GPUTextureFormat.Depth24Plus ||
  40249. format === GPUTextureFormat.Depth24PlusStencil8 ||
  40250. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  40251. // 64-bit formats
  40252. if ( format === GPUTextureFormat.RG32Uint ||
  40253. format === GPUTextureFormat.RG32Sint ||
  40254. format === GPUTextureFormat.RG32Float ||
  40255. format === GPUTextureFormat.RGBA16Uint ||
  40256. format === GPUTextureFormat.RGBA16Sint ||
  40257. format === GPUTextureFormat.RGBA16Float ) return 8;
  40258. // 128-bit formats
  40259. if ( format === GPUTextureFormat.RGBA32Uint ||
  40260. format === GPUTextureFormat.RGBA32Sint ||
  40261. format === GPUTextureFormat.RGBA32Float ) return 16;
  40262. }
  40263. _getTypedArrayType( format ) {
  40264. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  40265. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  40266. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  40267. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  40268. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  40269. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  40270. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  40271. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  40272. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  40273. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  40274. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  40275. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  40276. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  40277. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  40278. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  40279. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  40280. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  40281. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  40282. if ( format === GPUTextureFormat.R16Float ) return Float32Array;
  40283. if ( format === GPUTextureFormat.RG16Float ) return Float32Array;
  40284. if ( format === GPUTextureFormat.RGBA16Float ) return Float32Array;
  40285. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  40286. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  40287. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  40288. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  40289. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  40290. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  40291. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  40292. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  40293. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  40294. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  40295. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  40296. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  40297. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  40298. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  40299. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  40300. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  40301. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  40302. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  40303. }
  40304. _getDimension( texture ) {
  40305. let dimension;
  40306. if ( texture.isData3DTexture ) {
  40307. dimension = GPUTextureDimension.ThreeD;
  40308. } else {
  40309. dimension = GPUTextureDimension.TwoD;
  40310. }
  40311. return dimension;
  40312. }
  40313. }
  40314. function getFormat( texture, device = null ) {
  40315. const format = texture.format;
  40316. const type = texture.type;
  40317. const colorSpace = texture.colorSpace;
  40318. let formatGPU;
  40319. if ( texture.isFramebufferTexture === true && texture.type === UnsignedByteType ) {
  40320. formatGPU = GPUTextureFormat.BGRA8Unorm;
  40321. } else if ( texture.isCompressedTexture === true ) {
  40322. switch ( format ) {
  40323. case RGBA_S3TC_DXT1_Format:
  40324. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  40325. break;
  40326. case RGBA_S3TC_DXT3_Format:
  40327. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  40328. break;
  40329. case RGBA_S3TC_DXT5_Format:
  40330. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  40331. break;
  40332. case RGB_ETC2_Format:
  40333. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  40334. break;
  40335. case RGBA_ETC2_EAC_Format:
  40336. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  40337. break;
  40338. case RGBA_ASTC_4x4_Format:
  40339. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  40340. break;
  40341. case RGBA_ASTC_5x4_Format:
  40342. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  40343. break;
  40344. case RGBA_ASTC_5x5_Format:
  40345. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  40346. break;
  40347. case RGBA_ASTC_6x5_Format:
  40348. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  40349. break;
  40350. case RGBA_ASTC_6x6_Format:
  40351. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  40352. break;
  40353. case RGBA_ASTC_8x5_Format:
  40354. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  40355. break;
  40356. case RGBA_ASTC_8x6_Format:
  40357. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  40358. break;
  40359. case RGBA_ASTC_8x8_Format:
  40360. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  40361. break;
  40362. case RGBA_ASTC_10x5_Format:
  40363. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  40364. break;
  40365. case RGBA_ASTC_10x6_Format:
  40366. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  40367. break;
  40368. case RGBA_ASTC_10x8_Format:
  40369. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  40370. break;
  40371. case RGBA_ASTC_10x10_Format:
  40372. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  40373. break;
  40374. case RGBA_ASTC_12x10_Format:
  40375. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  40376. break;
  40377. case RGBA_ASTC_12x12_Format:
  40378. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  40379. break;
  40380. default:
  40381. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  40382. }
  40383. } else {
  40384. switch ( format ) {
  40385. case RGBAFormat:
  40386. switch ( type ) {
  40387. case ByteType:
  40388. formatGPU = GPUTextureFormat.RGBA8Snorm;
  40389. break;
  40390. case ShortType:
  40391. formatGPU = GPUTextureFormat.RGBA16Sint;
  40392. break;
  40393. case UnsignedShortType:
  40394. formatGPU = GPUTextureFormat.RGBA16Uint;
  40395. break;
  40396. case UnsignedIntType:
  40397. formatGPU = GPUTextureFormat.RGBA32Uint;
  40398. break;
  40399. case IntType:
  40400. formatGPU = GPUTextureFormat.RGBA32Sint;
  40401. break;
  40402. case UnsignedByteType:
  40403. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  40404. break;
  40405. case HalfFloatType:
  40406. formatGPU = GPUTextureFormat.RGBA16Float;
  40407. break;
  40408. case FloatType:
  40409. formatGPU = GPUTextureFormat.RGBA32Float;
  40410. break;
  40411. default:
  40412. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  40413. }
  40414. break;
  40415. case RGBFormat:
  40416. switch ( type ) {
  40417. case UnsignedInt5999Type:
  40418. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  40419. break;
  40420. default:
  40421. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  40422. }
  40423. break;
  40424. case RedFormat:
  40425. switch ( type ) {
  40426. case ByteType:
  40427. formatGPU = GPUTextureFormat.R8Snorm;
  40428. break;
  40429. case ShortType:
  40430. formatGPU = GPUTextureFormat.R16Sint;
  40431. break;
  40432. case UnsignedShortType:
  40433. formatGPU = GPUTextureFormat.R16Uint;
  40434. break;
  40435. case UnsignedIntType:
  40436. formatGPU = GPUTextureFormat.R32Uint;
  40437. break;
  40438. case IntType:
  40439. formatGPU = GPUTextureFormat.R32Sint;
  40440. break;
  40441. case UnsignedByteType:
  40442. formatGPU = GPUTextureFormat.R8Unorm;
  40443. break;
  40444. case HalfFloatType:
  40445. formatGPU = GPUTextureFormat.R16Float;
  40446. break;
  40447. case FloatType:
  40448. formatGPU = GPUTextureFormat.R32Float;
  40449. break;
  40450. default:
  40451. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  40452. }
  40453. break;
  40454. case RGFormat:
  40455. switch ( type ) {
  40456. case ByteType:
  40457. formatGPU = GPUTextureFormat.RG8Snorm;
  40458. break;
  40459. case ShortType:
  40460. formatGPU = GPUTextureFormat.RG16Sint;
  40461. break;
  40462. case UnsignedShortType:
  40463. formatGPU = GPUTextureFormat.RG16Uint;
  40464. break;
  40465. case UnsignedIntType:
  40466. formatGPU = GPUTextureFormat.RG32Uint;
  40467. break;
  40468. case IntType:
  40469. formatGPU = GPUTextureFormat.RG32Sint;
  40470. break;
  40471. case UnsignedByteType:
  40472. formatGPU = GPUTextureFormat.RG8Unorm;
  40473. break;
  40474. case HalfFloatType:
  40475. formatGPU = GPUTextureFormat.RG16Float;
  40476. break;
  40477. case FloatType:
  40478. formatGPU = GPUTextureFormat.RG32Float;
  40479. break;
  40480. default:
  40481. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  40482. }
  40483. break;
  40484. case DepthFormat:
  40485. switch ( type ) {
  40486. case UnsignedShortType:
  40487. formatGPU = GPUTextureFormat.Depth16Unorm;
  40488. break;
  40489. case UnsignedIntType:
  40490. formatGPU = GPUTextureFormat.Depth24Plus;
  40491. break;
  40492. case FloatType:
  40493. formatGPU = GPUTextureFormat.Depth32Float;
  40494. break;
  40495. default:
  40496. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  40497. }
  40498. break;
  40499. case DepthStencilFormat:
  40500. switch ( type ) {
  40501. case UnsignedInt248Type:
  40502. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  40503. break;
  40504. case FloatType:
  40505. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  40506. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  40507. }
  40508. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  40509. break;
  40510. default:
  40511. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  40512. }
  40513. break;
  40514. case RedIntegerFormat:
  40515. switch ( type ) {
  40516. case IntType:
  40517. formatGPU = GPUTextureFormat.R32Sint;
  40518. break;
  40519. case UnsignedIntType:
  40520. formatGPU = GPUTextureFormat.R32Uint;
  40521. break;
  40522. default:
  40523. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  40524. }
  40525. break;
  40526. case RGIntegerFormat:
  40527. switch ( type ) {
  40528. case IntType:
  40529. formatGPU = GPUTextureFormat.RG32Sint;
  40530. break;
  40531. case UnsignedIntType:
  40532. formatGPU = GPUTextureFormat.RG32Uint;
  40533. break;
  40534. default:
  40535. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  40536. }
  40537. break;
  40538. case RGBAIntegerFormat:
  40539. switch ( type ) {
  40540. case IntType:
  40541. formatGPU = GPUTextureFormat.RGBA32Sint;
  40542. break;
  40543. case UnsignedIntType:
  40544. formatGPU = GPUTextureFormat.RGBA32Uint;
  40545. break;
  40546. default:
  40547. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  40548. }
  40549. break;
  40550. default:
  40551. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  40552. }
  40553. }
  40554. return formatGPU;
  40555. }
  40556. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  40557. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  40558. const wgslTypeLib$1 = {
  40559. 'f32': 'float',
  40560. 'i32': 'int',
  40561. 'u32': 'uint',
  40562. 'bool': 'bool',
  40563. 'vec2<f32>': 'vec2',
  40564. 'vec2<i32>': 'ivec2',
  40565. 'vec2<u32>': 'uvec2',
  40566. 'vec2<bool>': 'bvec2',
  40567. 'vec2f': 'vec2',
  40568. 'vec2i': 'ivec2',
  40569. 'vec2u': 'uvec2',
  40570. 'vec2b': 'bvec2',
  40571. 'vec3<f32>': 'vec3',
  40572. 'vec3<i32>': 'ivec3',
  40573. 'vec3<u32>': 'uvec3',
  40574. 'vec3<bool>': 'bvec3',
  40575. 'vec3f': 'vec3',
  40576. 'vec3i': 'ivec3',
  40577. 'vec3u': 'uvec3',
  40578. 'vec3b': 'bvec3',
  40579. 'vec4<f32>': 'vec4',
  40580. 'vec4<i32>': 'ivec4',
  40581. 'vec4<u32>': 'uvec4',
  40582. 'vec4<bool>': 'bvec4',
  40583. 'vec4f': 'vec4',
  40584. 'vec4i': 'ivec4',
  40585. 'vec4u': 'uvec4',
  40586. 'vec4b': 'bvec4',
  40587. 'mat2x2<f32>': 'mat2',
  40588. 'mat2x2f': 'mat2',
  40589. 'mat3x3<f32>': 'mat3',
  40590. 'mat3x3f': 'mat3',
  40591. 'mat4x4<f32>': 'mat4',
  40592. 'mat4x4f': 'mat4',
  40593. 'sampler': 'sampler',
  40594. 'texture_2d': 'texture',
  40595. 'texture_cube': 'cubeTexture',
  40596. 'texture_depth_2d': 'depthTexture',
  40597. 'texture_storage_2d': 'storageTexture',
  40598. 'texture_3d': 'texture3D'
  40599. };
  40600. const parse = ( source ) => {
  40601. source = source.trim();
  40602. const declaration = source.match( declarationRegexp );
  40603. if ( declaration !== null && declaration.length === 4 ) {
  40604. const inputsCode = declaration[ 2 ];
  40605. const propsMatches = [];
  40606. let match = null;
  40607. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  40608. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  40609. }
  40610. // Process matches to correctly pair names and types
  40611. const inputs = [];
  40612. for ( let i = 0; i < propsMatches.length; i ++ ) {
  40613. const { name, type } = propsMatches[ i ];
  40614. let resolvedType = type;
  40615. if ( resolvedType.startsWith( 'texture' ) ) {
  40616. resolvedType = type.split( '<' )[ 0 ];
  40617. }
  40618. resolvedType = wgslTypeLib$1[ resolvedType ] || resolvedType;
  40619. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  40620. }
  40621. const blockCode = source.substring( declaration[ 0 ].length );
  40622. const outputType = declaration[ 3 ] || 'void';
  40623. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  40624. const type = wgslTypeLib$1[ outputType ] || outputType;
  40625. return {
  40626. type,
  40627. inputs,
  40628. name,
  40629. inputsCode,
  40630. blockCode,
  40631. outputType
  40632. };
  40633. } else {
  40634. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  40635. }
  40636. };
  40637. class WGSLNodeFunction extends NodeFunction {
  40638. constructor( source ) {
  40639. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  40640. super( type, inputs, name );
  40641. this.inputsCode = inputsCode;
  40642. this.blockCode = blockCode;
  40643. this.outputType = outputType;
  40644. }
  40645. getCode( name = this.name ) {
  40646. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  40647. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  40648. }
  40649. }
  40650. class WGSLNodeParser extends NodeParser {
  40651. parseFunction( source ) {
  40652. return new WGSLNodeFunction( source );
  40653. }
  40654. }
  40655. // GPUShaderStage is not defined in browsers not supporting WebGPU
  40656. const GPUShaderStage = self.GPUShaderStage;
  40657. const gpuShaderStageLib = {
  40658. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  40659. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  40660. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  40661. };
  40662. const supports = {
  40663. instance: true,
  40664. swizzleAssign: false,
  40665. storageBuffer: true
  40666. };
  40667. const wgslFnOpLib = {
  40668. '^^': 'threejs_xor'
  40669. };
  40670. const wgslTypeLib = {
  40671. float: 'f32',
  40672. int: 'i32',
  40673. uint: 'u32',
  40674. bool: 'bool',
  40675. color: 'vec3<f32>',
  40676. vec2: 'vec2<f32>',
  40677. ivec2: 'vec2<i32>',
  40678. uvec2: 'vec2<u32>',
  40679. bvec2: 'vec2<bool>',
  40680. vec3: 'vec3<f32>',
  40681. ivec3: 'vec3<i32>',
  40682. uvec3: 'vec3<u32>',
  40683. bvec3: 'vec3<bool>',
  40684. vec4: 'vec4<f32>',
  40685. ivec4: 'vec4<i32>',
  40686. uvec4: 'vec4<u32>',
  40687. bvec4: 'vec4<bool>',
  40688. mat2: 'mat2x2<f32>',
  40689. imat2: 'mat2x2<i32>',
  40690. umat2: 'mat2x2<u32>',
  40691. bmat2: 'mat2x2<bool>',
  40692. mat3: 'mat3x3<f32>',
  40693. imat3: 'mat3x3<i32>',
  40694. umat3: 'mat3x3<u32>',
  40695. bmat3: 'mat3x3<bool>',
  40696. mat4: 'mat4x4<f32>',
  40697. imat4: 'mat4x4<i32>',
  40698. umat4: 'mat4x4<u32>',
  40699. bmat4: 'mat4x4<bool>'
  40700. };
  40701. const wgslMethods = {
  40702. dFdx: 'dpdx',
  40703. dFdy: '- dpdy',
  40704. mod_float: 'threejs_mod_float',
  40705. mod_vec2: 'threejs_mod_vec2',
  40706. mod_vec3: 'threejs_mod_vec3',
  40707. mod_vec4: 'threejs_mod_vec4',
  40708. equals_bool: 'threejs_equals_bool',
  40709. equals_bvec2: 'threejs_equals_bvec2',
  40710. equals_bvec3: 'threejs_equals_bvec3',
  40711. equals_bvec4: 'threejs_equals_bvec4',
  40712. lessThanEqual: 'threejs_lessThanEqual',
  40713. greaterThan: 'threejs_greaterThan',
  40714. inversesqrt: 'inverseSqrt',
  40715. bitcast: 'bitcast<f32>'
  40716. };
  40717. const wgslPolyfill = {
  40718. threejs_xor: new CodeNode( `
  40719. fn threejs_xor( a : bool, b : bool ) -> bool {
  40720. return ( a || b ) && !( a && b );
  40721. }
  40722. ` ),
  40723. lessThanEqual: new CodeNode( `
  40724. fn threejs_lessThanEqual( a : vec3<f32>, b : vec3<f32> ) -> vec3<bool> {
  40725. return vec3<bool>( a.x <= b.x, a.y <= b.y, a.z <= b.z );
  40726. }
  40727. ` ),
  40728. greaterThan: new CodeNode( `
  40729. fn threejs_greaterThan( a : vec3<f32>, b : vec3<f32> ) -> vec3<bool> {
  40730. return vec3<bool>( a.x > b.x, a.y > b.y, a.z > b.z );
  40731. }
  40732. ` ),
  40733. mod_float: new CodeNode( 'fn threejs_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  40734. mod_vec2: new CodeNode( 'fn threejs_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  40735. mod_vec3: new CodeNode( 'fn threejs_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  40736. mod_vec4: new CodeNode( 'fn threejs_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  40737. equals_bool: new CodeNode( 'fn threejs_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  40738. 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 ); }' ),
  40739. 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 ); }' ),
  40740. 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 ); }' ),
  40741. repeatWrapping: new CodeNode( `
  40742. fn threejs_repeatWrapping( uv : vec2<f32>, dimension : vec2<u32> ) -> vec2<u32> {
  40743. let uvScaled = vec2<u32>( uv * vec2<f32>( dimension ) );
  40744. return ( ( uvScaled % dimension ) + dimension ) % dimension;
  40745. }
  40746. ` ),
  40747. biquadraticTexture: new CodeNode( `
  40748. fn threejs_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, level : i32 ) -> vec4f {
  40749. let res = vec2f( textureDimensions( map, level ) );
  40750. let uvScaled = coord * res;
  40751. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  40752. // https://www.shadertoy.com/view/WtyXRy
  40753. let uv = uvWrapping - 0.5;
  40754. let iuv = floor( uv );
  40755. let f = fract( uv );
  40756. let rg1 = textureLoad( map, vec2i( iuv + vec2( 0.5, 0.5 ) ), level );
  40757. let rg2 = textureLoad( map, vec2i( iuv + vec2( 1.5, 0.5 ) ), level );
  40758. let rg3 = textureLoad( map, vec2i( iuv + vec2( 0.5, 1.5 ) ), level );
  40759. let rg4 = textureLoad( map, vec2i( iuv + vec2( 1.5, 1.5 ) ), level );
  40760. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  40761. }
  40762. ` )
  40763. };
  40764. class WGSLNodeBuilder extends NodeBuilder {
  40765. constructor( object, renderer ) {
  40766. super( object, renderer, new WGSLNodeParser() );
  40767. this.uniformGroups = {};
  40768. this.builtins = {};
  40769. }
  40770. needsColorSpaceToLinear( texture ) {
  40771. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  40772. }
  40773. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40774. if ( shaderStage === 'fragment' ) {
  40775. if ( depthSnippet ) {
  40776. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  40777. } else {
  40778. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  40779. }
  40780. } else if ( this.isFilteredTexture( texture ) ) {
  40781. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  40782. } else {
  40783. return this.generateTextureLod( texture, textureProperty, uvSnippet, '0' );
  40784. }
  40785. }
  40786. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  40787. if ( shaderStage === 'fragment' ) {
  40788. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  40789. } else {
  40790. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  40791. }
  40792. }
  40793. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40794. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  40795. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  40796. } else if ( this.isFilteredTexture( texture ) ) {
  40797. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  40798. } else {
  40799. return this.generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet );
  40800. }
  40801. }
  40802. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  40803. this._include( 'biquadraticTexture' );
  40804. return `threejs_biquadraticTexture( ${ textureProperty }, ${ uvSnippet }, i32( ${ levelSnippet } ) )`;
  40805. }
  40806. generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  40807. this._include( 'repeatWrapping' );
  40808. const dimension = `textureDimensions( ${ textureProperty }, 0 )`;
  40809. return `textureLoad( ${ textureProperty }, threejs_repeatWrapping( ${ uvSnippet }, ${ dimension } ), i32( ${ levelSnippet } ) )`;
  40810. }
  40811. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  40812. if ( depthSnippet ) {
  40813. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  40814. } else {
  40815. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  40816. }
  40817. }
  40818. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  40819. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  40820. }
  40821. isUnfilterable( texture ) {
  40822. return this.getComponentTypeFromTexture( texture ) !== 'float' || ( texture.isDataTexture === true && texture.type === FloatType );
  40823. }
  40824. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40825. let snippet = null;
  40826. if ( texture.isVideoTexture === true ) {
  40827. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  40828. } else if ( this.isUnfilterable( texture ) ) {
  40829. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, '0', depthSnippet, shaderStage );
  40830. } else {
  40831. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  40832. }
  40833. return snippet;
  40834. }
  40835. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40836. if ( shaderStage === 'fragment' ) {
  40837. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  40838. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  40839. } else {
  40840. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  40841. }
  40842. }
  40843. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40844. if ( shaderStage === 'fragment' ) {
  40845. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  40846. } else {
  40847. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  40848. }
  40849. }
  40850. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40851. let snippet = null;
  40852. if ( texture.isVideoTexture === true ) {
  40853. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  40854. } else {
  40855. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  40856. }
  40857. return snippet;
  40858. }
  40859. getPropertyName( node, shaderStage = this.shaderStage ) {
  40860. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  40861. if ( shaderStage === 'vertex' ) {
  40862. return `varyings.${ node.name }`;
  40863. }
  40864. } else if ( node.isNodeUniform === true ) {
  40865. const name = node.name;
  40866. const type = node.type;
  40867. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  40868. return name;
  40869. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  40870. return `NodeBuffer_${ node.id }.${name}`;
  40871. } else {
  40872. return node.groupNode.name + '.' + name;
  40873. }
  40874. }
  40875. return super.getPropertyName( node );
  40876. }
  40877. getOutputStructName() {
  40878. return 'output';
  40879. }
  40880. _getUniformGroupCount( shaderStage ) {
  40881. return Object.keys( this.uniforms[ shaderStage ] ).length;
  40882. }
  40883. getFunctionOperator( op ) {
  40884. const fnOp = wgslFnOpLib[ op ];
  40885. if ( fnOp !== undefined ) {
  40886. this._include( fnOp );
  40887. return fnOp;
  40888. }
  40889. return null;
  40890. }
  40891. getStorageAccess( node ) {
  40892. if ( node.isStorageTextureNode ) {
  40893. switch ( node.access ) {
  40894. case GPUStorageTextureAccess.ReadOnly:
  40895. return 'read';
  40896. case GPUStorageTextureAccess.WriteOnly:
  40897. return 'write';
  40898. default:
  40899. return 'read_write';
  40900. }
  40901. } else {
  40902. switch ( node.access ) {
  40903. case GPUBufferBindingType.Storage:
  40904. return 'read_write';
  40905. case GPUBufferBindingType.ReadOnlyStorage:
  40906. return 'read';
  40907. default:
  40908. return 'write';
  40909. }
  40910. }
  40911. }
  40912. getUniformFromNode( node, type, shaderStage, name = null ) {
  40913. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  40914. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  40915. if ( nodeData.uniformGPU === undefined ) {
  40916. let uniformGPU;
  40917. const group = node.groupNode;
  40918. const groupName = group.name;
  40919. const bindings = this.getBindGroupArray( groupName, shaderStage );
  40920. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  40921. let texture = null;
  40922. if ( type === 'texture' || type === 'storageTexture' ) {
  40923. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  40924. } else if ( type === 'cubeTexture' ) {
  40925. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  40926. } else if ( type === 'texture3D' ) {
  40927. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  40928. }
  40929. texture.store = node.isStorageTextureNode === true;
  40930. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  40931. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  40932. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  40933. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  40934. bindings.push( sampler, texture );
  40935. uniformGPU = [ sampler, texture ];
  40936. } else {
  40937. bindings.push( texture );
  40938. uniformGPU = [ texture ];
  40939. }
  40940. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  40941. const bufferClass = type === 'storageBuffer' ? NodeStorageBuffer : NodeUniformBuffer;
  40942. const buffer = new bufferClass( node, group );
  40943. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  40944. bindings.push( buffer );
  40945. uniformGPU = buffer;
  40946. } else {
  40947. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  40948. let uniformsGroup = uniformsStage[ groupName ];
  40949. if ( uniformsGroup === undefined ) {
  40950. uniformsGroup = new NodeUniformsGroup( groupName, group );
  40951. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  40952. uniformsStage[ groupName ] = uniformsGroup;
  40953. bindings.push( uniformsGroup );
  40954. }
  40955. uniformGPU = this.getNodeUniform( uniformNode, type );
  40956. uniformsGroup.addUniform( uniformGPU );
  40957. }
  40958. nodeData.uniformGPU = uniformGPU;
  40959. }
  40960. return uniformNode;
  40961. }
  40962. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  40963. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  40964. if ( map.has( name ) === false ) {
  40965. map.set( name, {
  40966. name,
  40967. property,
  40968. type
  40969. } );
  40970. }
  40971. return property;
  40972. }
  40973. getVertexIndex() {
  40974. if ( this.shaderStage === 'vertex' ) {
  40975. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  40976. }
  40977. return 'vertexIndex';
  40978. }
  40979. buildFunctionCode( shaderNode ) {
  40980. const layout = shaderNode.layout;
  40981. const flowData = this.flowShaderNode( shaderNode );
  40982. const parameters = [];
  40983. for ( const input of layout.inputs ) {
  40984. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  40985. }
  40986. //
  40987. const code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  40988. ${ flowData.vars }
  40989. ${ flowData.code }
  40990. return ${ flowData.result };
  40991. }`;
  40992. //
  40993. return code;
  40994. }
  40995. getInstanceIndex() {
  40996. if ( this.shaderStage === 'vertex' ) {
  40997. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  40998. }
  40999. return 'instanceIndex';
  41000. }
  41001. getDrawIndex() {
  41002. return null;
  41003. }
  41004. getFrontFacing() {
  41005. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  41006. }
  41007. getFragCoord() {
  41008. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xyz';
  41009. }
  41010. getFragDepth() {
  41011. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  41012. }
  41013. isFlipY() {
  41014. return false;
  41015. }
  41016. getBuiltins( shaderStage ) {
  41017. const snippets = [];
  41018. const builtins = this.builtins[ shaderStage ];
  41019. if ( builtins !== undefined ) {
  41020. for ( const { name, property, type } of builtins.values() ) {
  41021. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  41022. }
  41023. }
  41024. return snippets.join( ',\n\t' );
  41025. }
  41026. getAttributes( shaderStage ) {
  41027. const snippets = [];
  41028. if ( shaderStage === 'compute' ) {
  41029. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  41030. }
  41031. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  41032. const builtins = this.getBuiltins( 'attribute' );
  41033. if ( builtins ) snippets.push( builtins );
  41034. const attributes = this.getAttributesArray();
  41035. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  41036. const attribute = attributes[ index ];
  41037. const name = attribute.name;
  41038. const type = this.getType( attribute.type );
  41039. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  41040. }
  41041. }
  41042. return snippets.join( ',\n\t' );
  41043. }
  41044. getStructMembers( struct ) {
  41045. const snippets = [];
  41046. const members = struct.getMemberTypes();
  41047. for ( let i = 0; i < members.length; i ++ ) {
  41048. const member = members[ i ];
  41049. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  41050. }
  41051. const builtins = this.getBuiltins( 'output' );
  41052. if ( builtins ) snippets.push( builtins );
  41053. return snippets.join( ',\n' );
  41054. }
  41055. getStructs( shaderStage ) {
  41056. const snippets = [];
  41057. const structs = this.structs[ shaderStage ];
  41058. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  41059. const struct = structs[ index ];
  41060. const name = struct.name;
  41061. let snippet = `\struct ${ name } {\n`;
  41062. snippet += this.getStructMembers( struct );
  41063. snippet += '\n}';
  41064. snippets.push( snippet );
  41065. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  41066. }
  41067. return snippets.join( '\n\n' );
  41068. }
  41069. getVar( type, name ) {
  41070. return `var ${ name } : ${ this.getType( type ) }`;
  41071. }
  41072. getVars( shaderStage ) {
  41073. const snippets = [];
  41074. const vars = this.vars[ shaderStage ];
  41075. if ( vars !== undefined ) {
  41076. for ( const variable of vars ) {
  41077. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  41078. }
  41079. }
  41080. return `\n${ snippets.join( '\n' ) }\n`;
  41081. }
  41082. getVaryings( shaderStage ) {
  41083. const snippets = [];
  41084. if ( shaderStage === 'vertex' ) {
  41085. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  41086. }
  41087. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  41088. const varyings = this.varyings;
  41089. const vars = this.vars[ shaderStage ];
  41090. for ( let index = 0; index < varyings.length; index ++ ) {
  41091. const varying = varyings[ index ];
  41092. if ( varying.needsInterpolation ) {
  41093. let attributesSnippet = `@location( ${index} )`;
  41094. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  41095. attributesSnippet += ' @interpolate( flat )';
  41096. }
  41097. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  41098. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  41099. vars.push( varying );
  41100. }
  41101. }
  41102. }
  41103. const builtins = this.getBuiltins( shaderStage );
  41104. if ( builtins ) snippets.push( builtins );
  41105. const code = snippets.join( ',\n\t' );
  41106. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  41107. }
  41108. getUniforms( shaderStage ) {
  41109. const uniforms = this.uniforms[ shaderStage ];
  41110. const bindingSnippets = [];
  41111. const bufferSnippets = [];
  41112. const structSnippets = [];
  41113. const uniformGroups = {};
  41114. for ( const uniform of uniforms ) {
  41115. const groundName = uniform.groupNode.name;
  41116. const uniformIndexes = this.bindingsIndexes[ groundName ];
  41117. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  41118. const texture = uniform.node.value;
  41119. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  41120. if ( texture.isDepthTexture === true && texture.compareFunction !== null ) {
  41121. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  41122. } else {
  41123. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  41124. }
  41125. }
  41126. let textureType;
  41127. if ( texture.isCubeTexture === true ) {
  41128. textureType = 'texture_cube<f32>';
  41129. } else if ( texture.isDataArrayTexture === true ) {
  41130. textureType = 'texture_2d_array<f32>';
  41131. } else if ( texture.isDepthTexture === true ) {
  41132. textureType = 'texture_depth_2d';
  41133. } else if ( texture.isVideoTexture === true ) {
  41134. textureType = 'texture_external';
  41135. } else if ( texture.isData3DTexture === true ) {
  41136. textureType = 'texture_3d<f32>';
  41137. } else if ( uniform.node.isStorageTextureNode === true ) {
  41138. const format = getFormat( texture );
  41139. const access = this.getStorageAccess( uniform.node );
  41140. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  41141. } else {
  41142. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  41143. textureType = `texture_2d<${ componentPrefix }32>`;
  41144. }
  41145. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  41146. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' ) {
  41147. const bufferNode = uniform.node;
  41148. const bufferType = this.getType( bufferNode.bufferType );
  41149. const bufferCount = bufferNode.bufferCount;
  41150. const bufferCountSnippet = bufferCount > 0 ? ', ' + bufferCount : '';
  41151. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferType }${ bufferCountSnippet } >\n`;
  41152. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode ) }` : 'uniform';
  41153. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  41154. } else {
  41155. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  41156. const groupName = uniform.groupNode.name;
  41157. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  41158. index: uniformIndexes.binding ++,
  41159. id: uniformIndexes.group,
  41160. snippets: []
  41161. } );
  41162. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  41163. }
  41164. }
  41165. for ( const name in uniformGroups ) {
  41166. const group = uniformGroups[ name ];
  41167. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  41168. }
  41169. let code = bindingSnippets.join( '\n' );
  41170. code += bufferSnippets.join( '\n' );
  41171. code += structSnippets.join( '\n' );
  41172. return code;
  41173. }
  41174. buildCode() {
  41175. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  41176. for ( const shaderStage in shadersData ) {
  41177. const stageData = shadersData[ shaderStage ];
  41178. stageData.uniforms = this.getUniforms( shaderStage );
  41179. stageData.attributes = this.getAttributes( shaderStage );
  41180. stageData.varyings = this.getVaryings( shaderStage );
  41181. stageData.structs = this.getStructs( shaderStage );
  41182. stageData.vars = this.getVars( shaderStage );
  41183. stageData.codes = this.getCodes( shaderStage );
  41184. //
  41185. let flow = '// code\n\n';
  41186. flow += this.flowCode[ shaderStage ];
  41187. const flowNodes = this.flowNodes[ shaderStage ];
  41188. const mainNode = flowNodes[ flowNodes.length - 1 ];
  41189. const outputNode = mainNode.outputNode;
  41190. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  41191. for ( const node of flowNodes ) {
  41192. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  41193. const slotName = node.name;
  41194. if ( slotName ) {
  41195. if ( flow.length > 0 ) flow += '\n';
  41196. flow += `\t// flow -> ${ slotName }\n\t`;
  41197. }
  41198. flow += `${ flowSlotData.code }\n\t`;
  41199. if ( node === mainNode && shaderStage !== 'compute' ) {
  41200. flow += '// result\n\n\t';
  41201. if ( shaderStage === 'vertex' ) {
  41202. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  41203. } else if ( shaderStage === 'fragment' ) {
  41204. if ( isOutputStruct ) {
  41205. stageData.returnType = outputNode.nodeType;
  41206. flow += `return ${ flowSlotData.result };`;
  41207. } else {
  41208. let structSnippet = '\t@location(0) color: vec4<f32>';
  41209. const builtins = this.getBuiltins( 'output' );
  41210. if ( builtins ) structSnippet += ',\n\t' + builtins;
  41211. stageData.returnType = 'OutputStruct';
  41212. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  41213. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  41214. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  41215. }
  41216. }
  41217. }
  41218. }
  41219. stageData.flow = flow;
  41220. }
  41221. if ( this.material !== null ) {
  41222. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  41223. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  41224. } else {
  41225. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  41226. }
  41227. }
  41228. getMethod( method, output = null ) {
  41229. let wgslMethod;
  41230. if ( output !== null ) {
  41231. wgslMethod = this._getWGSLMethod( method + '_' + output );
  41232. }
  41233. if ( wgslMethod === undefined ) {
  41234. wgslMethod = this._getWGSLMethod( method );
  41235. }
  41236. return wgslMethod || method;
  41237. }
  41238. getType( type ) {
  41239. return wgslTypeLib[ type ] || type;
  41240. }
  41241. isAvailable( name ) {
  41242. let result = supports[ name ];
  41243. if ( result === undefined ) {
  41244. if ( name === 'float32Filterable' ) {
  41245. result = this.renderer.hasFeature( 'float32-filterable' );
  41246. }
  41247. supports[ name ] = result;
  41248. }
  41249. return result;
  41250. }
  41251. _getWGSLMethod( method ) {
  41252. if ( wgslPolyfill[ method ] !== undefined ) {
  41253. this._include( method );
  41254. }
  41255. return wgslMethods[ method ];
  41256. }
  41257. _include( name ) {
  41258. const codeNode = wgslPolyfill[ name ];
  41259. codeNode.build( this );
  41260. if ( this.currentFunctionNode !== null ) {
  41261. this.currentFunctionNode.includes.push( codeNode );
  41262. }
  41263. return codeNode;
  41264. }
  41265. _getWGSLVertexCode( shaderData ) {
  41266. return `${ this.getSignature() }
  41267. // uniforms
  41268. ${shaderData.uniforms}
  41269. // varyings
  41270. ${shaderData.varyings}
  41271. var<private> varyings : VaryingsStruct;
  41272. // codes
  41273. ${shaderData.codes}
  41274. @vertex
  41275. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  41276. // vars
  41277. ${shaderData.vars}
  41278. // flow
  41279. ${shaderData.flow}
  41280. return varyings;
  41281. }
  41282. `;
  41283. }
  41284. _getWGSLFragmentCode( shaderData ) {
  41285. return `${ this.getSignature() }
  41286. // uniforms
  41287. ${shaderData.uniforms}
  41288. // structs
  41289. ${shaderData.structs}
  41290. // codes
  41291. ${shaderData.codes}
  41292. @fragment
  41293. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  41294. // vars
  41295. ${shaderData.vars}
  41296. // flow
  41297. ${shaderData.flow}
  41298. }
  41299. `;
  41300. }
  41301. _getWGSLComputeCode( shaderData, workgroupSize ) {
  41302. return `${ this.getSignature() }
  41303. // system
  41304. var<private> instanceIndex : u32;
  41305. // uniforms
  41306. ${shaderData.uniforms}
  41307. // codes
  41308. ${shaderData.codes}
  41309. @compute @workgroup_size( ${workgroupSize} )
  41310. fn main( ${shaderData.attributes} ) {
  41311. // system
  41312. instanceIndex = id.x;
  41313. // vars
  41314. ${shaderData.vars}
  41315. // flow
  41316. ${shaderData.flow}
  41317. }
  41318. `;
  41319. }
  41320. _getWGSLStruct( name, vars ) {
  41321. return `
  41322. struct ${name} {
  41323. ${vars}
  41324. };`;
  41325. }
  41326. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  41327. const structName = name + 'Struct';
  41328. const structSnippet = this._getWGSLStruct( structName, vars );
  41329. return `${structSnippet}
  41330. @binding( ${binding} ) @group( ${group} )
  41331. var<${access}> ${name} : ${structName};`;
  41332. }
  41333. }
  41334. class WebGPUUtils {
  41335. constructor( backend ) {
  41336. this.backend = backend;
  41337. }
  41338. getCurrentDepthStencilFormat( renderContext ) {
  41339. let format;
  41340. if ( renderContext.depthTexture !== null ) {
  41341. format = this.getTextureFormatGPU( renderContext.depthTexture );
  41342. } else if ( renderContext.depth && renderContext.stencil ) {
  41343. format = GPUTextureFormat.Depth24PlusStencil8;
  41344. } else if ( renderContext.depth ) {
  41345. format = GPUTextureFormat.Depth24Plus;
  41346. }
  41347. return format;
  41348. }
  41349. getTextureFormatGPU( texture ) {
  41350. return this.backend.get( texture ).texture.format;
  41351. }
  41352. getCurrentColorFormat( renderContext ) {
  41353. let format;
  41354. if ( renderContext.textures !== null ) {
  41355. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  41356. } else {
  41357. format = GPUTextureFormat.BGRA8Unorm; // default context format
  41358. }
  41359. return format;
  41360. }
  41361. getCurrentColorSpace( renderContext ) {
  41362. if ( renderContext.textures !== null ) {
  41363. return renderContext.textures[ 0 ].colorSpace;
  41364. }
  41365. return this.backend.renderer.outputColorSpace;
  41366. }
  41367. getPrimitiveTopology( object, material ) {
  41368. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  41369. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  41370. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  41371. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  41372. }
  41373. getSampleCount( renderContext ) {
  41374. if ( renderContext.textures !== null ) {
  41375. return renderContext.sampleCount;
  41376. }
  41377. return this.backend.parameters.sampleCount;
  41378. }
  41379. }
  41380. const typedArraysToVertexFormatPrefix = new Map( [
  41381. [ Int8Array, [ 'sint8', 'snorm8' ]],
  41382. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  41383. [ Int16Array, [ 'sint16', 'snorm16' ]],
  41384. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  41385. [ Int32Array, [ 'sint32', 'snorm32' ]],
  41386. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  41387. [ Float32Array, [ 'float32', ]],
  41388. ] );
  41389. const typedAttributeToVertexFormatPrefix = new Map( [
  41390. [ Float16BufferAttribute, [ 'float16', ]],
  41391. ] );
  41392. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  41393. [ Int32Array, 'sint32' ],
  41394. [ Int16Array, 'sint32' ], // patch for INT16
  41395. [ Uint32Array, 'uint32' ],
  41396. [ Uint16Array, 'uint32' ], // patch for UINT16
  41397. [ Float32Array, 'float32' ]
  41398. ] );
  41399. class WebGPUAttributeUtils {
  41400. constructor( backend ) {
  41401. this.backend = backend;
  41402. }
  41403. createAttribute( attribute, usage ) {
  41404. const bufferAttribute = this._getBufferAttribute( attribute );
  41405. const backend = this.backend;
  41406. const bufferData = backend.get( bufferAttribute );
  41407. let buffer = bufferData.buffer;
  41408. if ( buffer === undefined ) {
  41409. const device = backend.device;
  41410. let array = bufferAttribute.array;
  41411. // patch for INT16 and UINT16
  41412. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  41413. const tempArray = new Uint32Array( array.length );
  41414. for ( let i = 0; i < array.length; i ++ ) {
  41415. tempArray[ i ] = array[ i ];
  41416. }
  41417. array = tempArray;
  41418. }
  41419. bufferAttribute.array = array;
  41420. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  41421. array = new array.constructor( bufferAttribute.count * 4 );
  41422. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  41423. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  41424. }
  41425. // Update BufferAttribute
  41426. bufferAttribute.itemSize = 4;
  41427. bufferAttribute.array = array;
  41428. }
  41429. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  41430. buffer = device.createBuffer( {
  41431. label: bufferAttribute.name,
  41432. size: size,
  41433. usage: usage,
  41434. mappedAtCreation: true
  41435. } );
  41436. new array.constructor( buffer.getMappedRange() ).set( array );
  41437. buffer.unmap();
  41438. bufferData.buffer = buffer;
  41439. }
  41440. }
  41441. updateAttribute( attribute ) {
  41442. const bufferAttribute = this._getBufferAttribute( attribute );
  41443. const backend = this.backend;
  41444. const device = backend.device;
  41445. const buffer = backend.get( bufferAttribute ).buffer;
  41446. const array = bufferAttribute.array;
  41447. const updateRanges = bufferAttribute.updateRanges;
  41448. if ( updateRanges.length === 0 ) {
  41449. // Not using update ranges
  41450. device.queue.writeBuffer(
  41451. buffer,
  41452. 0,
  41453. array,
  41454. 0
  41455. );
  41456. } else {
  41457. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  41458. const range = updateRanges[ i ];
  41459. device.queue.writeBuffer(
  41460. buffer,
  41461. 0,
  41462. array,
  41463. range.start * array.BYTES_PER_ELEMENT,
  41464. range.count * array.BYTES_PER_ELEMENT
  41465. );
  41466. }
  41467. bufferAttribute.clearUpdateRanges();
  41468. }
  41469. }
  41470. createShaderVertexBuffers( renderObject ) {
  41471. const attributes = renderObject.getAttributes();
  41472. const vertexBuffers = new Map();
  41473. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  41474. const geometryAttribute = attributes[ slot ];
  41475. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  41476. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  41477. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  41478. if ( vertexBufferLayout === undefined ) {
  41479. let arrayStride, stepMode;
  41480. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  41481. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  41482. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  41483. } else {
  41484. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  41485. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  41486. }
  41487. // patch for INT16 and UINT16
  41488. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  41489. arrayStride = 4;
  41490. }
  41491. vertexBufferLayout = {
  41492. arrayStride,
  41493. attributes: [],
  41494. stepMode
  41495. };
  41496. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  41497. }
  41498. const format = this._getVertexFormat( geometryAttribute );
  41499. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  41500. vertexBufferLayout.attributes.push( {
  41501. shaderLocation: slot,
  41502. offset,
  41503. format
  41504. } );
  41505. }
  41506. return Array.from( vertexBuffers.values() );
  41507. }
  41508. destroyAttribute( attribute ) {
  41509. const backend = this.backend;
  41510. const data = backend.get( this._getBufferAttribute( attribute ) );
  41511. data.buffer.destroy();
  41512. backend.delete( attribute );
  41513. }
  41514. async getArrayBufferAsync( attribute ) {
  41515. const backend = this.backend;
  41516. const device = backend.device;
  41517. const data = backend.get( this._getBufferAttribute( attribute ) );
  41518. const bufferGPU = data.buffer;
  41519. const size = bufferGPU.size;
  41520. let readBufferGPU = data.readBuffer;
  41521. let needsUnmap = true;
  41522. if ( readBufferGPU === undefined ) {
  41523. readBufferGPU = device.createBuffer( {
  41524. label: attribute.name,
  41525. size,
  41526. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  41527. } );
  41528. needsUnmap = false;
  41529. data.readBuffer = readBufferGPU;
  41530. }
  41531. const cmdEncoder = device.createCommandEncoder( {} );
  41532. cmdEncoder.copyBufferToBuffer(
  41533. bufferGPU,
  41534. 0,
  41535. readBufferGPU,
  41536. 0,
  41537. size
  41538. );
  41539. if ( needsUnmap ) readBufferGPU.unmap();
  41540. const gpuCommands = cmdEncoder.finish();
  41541. device.queue.submit( [ gpuCommands ] );
  41542. await readBufferGPU.mapAsync( GPUMapMode.READ );
  41543. const arrayBuffer = readBufferGPU.getMappedRange();
  41544. return arrayBuffer;
  41545. }
  41546. _getVertexFormat( geometryAttribute ) {
  41547. const { itemSize, normalized } = geometryAttribute;
  41548. const ArrayType = geometryAttribute.array.constructor;
  41549. const AttributeType = geometryAttribute.constructor;
  41550. let format;
  41551. if ( itemSize == 1 ) {
  41552. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  41553. } else {
  41554. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  41555. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  41556. if ( prefix ) {
  41557. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  41558. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  41559. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  41560. if ( paddedItemSize % 1 ) {
  41561. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  41562. }
  41563. format = `${prefix}x${paddedItemSize}`;
  41564. }
  41565. }
  41566. if ( ! format ) {
  41567. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  41568. }
  41569. return format;
  41570. }
  41571. _getBufferAttribute( attribute ) {
  41572. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  41573. return attribute;
  41574. }
  41575. }
  41576. class WebGPUBindingUtils {
  41577. constructor( backend ) {
  41578. this.backend = backend;
  41579. }
  41580. createBindingsLayout( bindGroup ) {
  41581. const backend = this.backend;
  41582. const device = backend.device;
  41583. const entries = [];
  41584. let index = 0;
  41585. for ( const binding of bindGroup.bindings ) {
  41586. const bindingGPU = {
  41587. binding: index ++,
  41588. visibility: binding.visibility
  41589. };
  41590. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  41591. const buffer = {}; // GPUBufferBindingLayout
  41592. if ( binding.isStorageBuffer ) {
  41593. buffer.type = binding.access;
  41594. }
  41595. bindingGPU.buffer = buffer;
  41596. } else if ( binding.isSampler ) {
  41597. const sampler = {}; // GPUSamplerBindingLayout
  41598. if ( binding.texture.isDepthTexture ) {
  41599. if ( binding.texture.compareFunction !== null ) {
  41600. sampler.type = 'comparison';
  41601. }
  41602. }
  41603. bindingGPU.sampler = sampler;
  41604. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  41605. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  41606. } else if ( binding.isSampledTexture && binding.store ) {
  41607. const format = this.backend.get( binding.texture ).texture.format;
  41608. const access = binding.access;
  41609. bindingGPU.storageTexture = { format, access }; // GPUStorageTextureBindingLayout
  41610. } else if ( binding.isSampledTexture ) {
  41611. const texture = {}; // GPUTextureBindingLayout
  41612. if ( binding.texture.isDepthTexture ) {
  41613. texture.sampleType = GPUTextureSampleType.Depth;
  41614. } else if ( binding.texture.isDataTexture ) {
  41615. const type = binding.texture.type;
  41616. if ( type === IntType ) {
  41617. texture.sampleType = GPUTextureSampleType.SInt;
  41618. } else if ( type === UnsignedIntType ) {
  41619. texture.sampleType = GPUTextureSampleType.UInt;
  41620. } else if ( type === FloatType ) {
  41621. // @TODO: Add support for this soon: backend.hasFeature( 'float32-filterable' )
  41622. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  41623. }
  41624. }
  41625. if ( binding.isSampledCubeTexture ) {
  41626. texture.viewDimension = GPUTextureViewDimension.Cube;
  41627. } else if ( binding.texture.isDataArrayTexture ) {
  41628. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  41629. } else if ( binding.isSampledTexture3D ) {
  41630. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  41631. }
  41632. bindingGPU.texture = texture;
  41633. } else {
  41634. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  41635. }
  41636. entries.push( bindingGPU );
  41637. }
  41638. return device.createBindGroupLayout( { entries } );
  41639. }
  41640. createBindings( bindGroup ) {
  41641. const backend = this.backend;
  41642. const bindingsData = backend.get( bindGroup );
  41643. // setup (static) binding layout and (dynamic) binding group
  41644. const bindLayoutGPU = this.createBindingsLayout( bindGroup );
  41645. const bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  41646. bindingsData.layout = bindLayoutGPU;
  41647. bindingsData.group = bindGroupGPU;
  41648. }
  41649. updateBinding( binding ) {
  41650. const backend = this.backend;
  41651. const device = backend.device;
  41652. const buffer = binding.buffer;
  41653. const bufferGPU = backend.get( binding ).buffer;
  41654. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  41655. }
  41656. createBindGroup( bindGroup, layoutGPU ) {
  41657. const backend = this.backend;
  41658. const device = backend.device;
  41659. let bindingPoint = 0;
  41660. const entriesGPU = [];
  41661. for ( const binding of bindGroup.bindings ) {
  41662. if ( binding.isUniformBuffer ) {
  41663. const bindingData = backend.get( binding );
  41664. if ( bindingData.buffer === undefined ) {
  41665. const byteLength = binding.byteLength;
  41666. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  41667. const bufferGPU = device.createBuffer( {
  41668. label: 'bindingBuffer_' + binding.name,
  41669. size: byteLength,
  41670. usage: usage
  41671. } );
  41672. bindingData.buffer = bufferGPU;
  41673. }
  41674. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  41675. } else if ( binding.isStorageBuffer ) {
  41676. const bindingData = backend.get( binding );
  41677. if ( bindingData.buffer === undefined ) {
  41678. const attribute = binding.attribute;
  41679. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  41680. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  41681. bindingData.buffer = backend.get( attribute ).buffer;
  41682. }
  41683. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  41684. } else if ( binding.isSampler ) {
  41685. const textureGPU = backend.get( binding.texture );
  41686. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  41687. } else if ( binding.isSampledTexture ) {
  41688. const textureData = backend.get( binding.texture );
  41689. let dimensionViewGPU;
  41690. if ( binding.isSampledCubeTexture ) {
  41691. dimensionViewGPU = GPUTextureViewDimension.Cube;
  41692. } else if ( binding.isSampledTexture3D ) {
  41693. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  41694. } else if ( binding.texture.isDataArrayTexture ) {
  41695. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  41696. } else {
  41697. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  41698. }
  41699. let resourceGPU;
  41700. if ( textureData.externalTexture !== undefined ) {
  41701. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  41702. } else {
  41703. const aspectGPU = GPUTextureAspect.All;
  41704. resourceGPU = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount: binding.store ? 1 : textureData.mipLevelCount } );
  41705. }
  41706. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  41707. }
  41708. bindingPoint ++;
  41709. }
  41710. return device.createBindGroup( {
  41711. label: 'bindGroup_' + bindGroup.name,
  41712. layout: layoutGPU,
  41713. entries: entriesGPU
  41714. } );
  41715. }
  41716. }
  41717. class WebGPUPipelineUtils {
  41718. constructor( backend ) {
  41719. this.backend = backend;
  41720. }
  41721. _getSampleCount( renderObjectContext ) {
  41722. let sampleCount = this.backend.utils.getSampleCount( renderObjectContext );
  41723. if ( sampleCount > 1 ) {
  41724. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  41725. sampleCount = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  41726. if ( sampleCount === 2 ) {
  41727. sampleCount = 4;
  41728. }
  41729. }
  41730. return sampleCount;
  41731. }
  41732. createRenderPipeline( renderObject, promises ) {
  41733. const { object, material, geometry, pipeline } = renderObject;
  41734. const { vertexProgram, fragmentProgram } = pipeline;
  41735. const backend = this.backend;
  41736. const device = backend.device;
  41737. const utils = backend.utils;
  41738. const pipelineData = backend.get( pipeline );
  41739. // bind group layouts
  41740. const bindGroupLayouts = [];
  41741. for ( const bindGroup of renderObject.getBindings() ) {
  41742. const bindingsData = backend.get( bindGroup );
  41743. bindGroupLayouts.push( bindingsData.layout );
  41744. }
  41745. // vertex buffers
  41746. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  41747. // blending
  41748. let blending;
  41749. if ( material.transparent === true && material.blending !== NoBlending ) {
  41750. blending = this._getBlending( material );
  41751. }
  41752. // stencil
  41753. let stencilFront = {};
  41754. if ( material.stencilWrite === true ) {
  41755. stencilFront = {
  41756. compare: this._getStencilCompare( material ),
  41757. failOp: this._getStencilOperation( material.stencilFail ),
  41758. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  41759. passOp: this._getStencilOperation( material.stencilZPass )
  41760. };
  41761. }
  41762. const colorWriteMask = this._getColorWriteMask( material );
  41763. const targets = [];
  41764. if ( renderObject.context.textures !== null ) {
  41765. const textures = renderObject.context.textures;
  41766. for ( let i = 0; i < textures.length; i ++ ) {
  41767. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  41768. targets.push( {
  41769. format: colorFormat,
  41770. blend: blending,
  41771. writeMask: colorWriteMask
  41772. } );
  41773. }
  41774. } else {
  41775. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  41776. targets.push( {
  41777. format: colorFormat,
  41778. blend: blending,
  41779. writeMask: colorWriteMask
  41780. } );
  41781. }
  41782. const vertexModule = backend.get( vertexProgram ).module;
  41783. const fragmentModule = backend.get( fragmentProgram ).module;
  41784. const primitiveState = this._getPrimitiveState( object, geometry, material );
  41785. const depthCompare = this._getDepthCompare( material );
  41786. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  41787. const sampleCount = this._getSampleCount( renderObject.context );
  41788. const pipelineDescriptor = {
  41789. label: 'renderPipeline',
  41790. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  41791. fragment: Object.assign( {}, fragmentModule, { targets } ),
  41792. primitive: primitiveState,
  41793. depthStencil: {
  41794. format: depthStencilFormat,
  41795. depthWriteEnabled: material.depthWrite,
  41796. depthCompare: depthCompare,
  41797. stencilFront: stencilFront,
  41798. stencilBack: {}, // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  41799. stencilReadMask: material.stencilFuncMask,
  41800. stencilWriteMask: material.stencilWriteMask
  41801. },
  41802. multisample: {
  41803. count: sampleCount,
  41804. alphaToCoverageEnabled: material.alphaToCoverage
  41805. },
  41806. layout: device.createPipelineLayout( {
  41807. bindGroupLayouts
  41808. } )
  41809. };
  41810. if ( promises === null ) {
  41811. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  41812. } else {
  41813. const p = new Promise( ( resolve /*, reject*/ ) => {
  41814. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  41815. pipelineData.pipeline = pipeline;
  41816. resolve();
  41817. } );
  41818. } );
  41819. promises.push( p );
  41820. }
  41821. }
  41822. createBundleEncoder( renderContext, renderObject ) {
  41823. const backend = this.backend;
  41824. const { utils, device } = backend;
  41825. const renderContextData = backend.get( renderContext );
  41826. const renderObjectData = backend.get( renderObject );
  41827. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  41828. const colorFormat = utils.getCurrentColorFormat( renderContext );
  41829. const sampleCount = this._getSampleCount( renderObject.context );
  41830. const descriptor = {
  41831. label: 'renderBundleEncoder',
  41832. colorFormats: [ colorFormat ],
  41833. depthStencilFormat,
  41834. sampleCount
  41835. };
  41836. const bundleEncoder = device.createRenderBundleEncoder( descriptor );
  41837. renderObjectData.bundleEncoder = bundleEncoder;
  41838. renderContextData.currentSets = { attributes: {} };
  41839. renderContextData._renderBundleViewport = renderContext.width + '_' + renderContext.height;
  41840. return bundleEncoder;
  41841. }
  41842. createComputePipeline( pipeline, bindings ) {
  41843. const backend = this.backend;
  41844. const device = backend.device;
  41845. const computeProgram = backend.get( pipeline.computeProgram ).module;
  41846. const pipelineGPU = backend.get( pipeline );
  41847. // bind group layouts
  41848. const bindGroupLayouts = [];
  41849. for ( const bindingsGroup of bindings ) {
  41850. const bindingsData = backend.get( bindingsGroup );
  41851. bindGroupLayouts.push( bindingsData.layout );
  41852. }
  41853. pipelineGPU.pipeline = device.createComputePipeline( {
  41854. compute: computeProgram,
  41855. layout: device.createPipelineLayout( {
  41856. bindGroupLayouts
  41857. } )
  41858. } );
  41859. }
  41860. _getBlending( material ) {
  41861. let color, alpha;
  41862. const blending = material.blending;
  41863. const blendSrc = material.blendSrc;
  41864. const blendDst = material.blendDst;
  41865. const blendEquation = material.blendEquation;
  41866. if ( blending === CustomBlending ) {
  41867. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  41868. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  41869. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  41870. color = {
  41871. srcFactor: this._getBlendFactor( blendSrc ),
  41872. dstFactor: this._getBlendFactor( blendDst ),
  41873. operation: this._getBlendOperation( blendEquation )
  41874. };
  41875. alpha = {
  41876. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  41877. dstFactor: this._getBlendFactor( blendDstAlpha ),
  41878. operation: this._getBlendOperation( blendEquationAlpha )
  41879. };
  41880. } else {
  41881. const premultipliedAlpha = material.premultipliedAlpha;
  41882. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  41883. color = {
  41884. srcFactor: srcRGB,
  41885. dstFactor: dstRGB,
  41886. operation: GPUBlendOperation.Add
  41887. };
  41888. alpha = {
  41889. srcFactor: srcAlpha,
  41890. dstFactor: dstAlpha,
  41891. operation: GPUBlendOperation.Add
  41892. };
  41893. };
  41894. if ( premultipliedAlpha ) {
  41895. switch ( blending ) {
  41896. case NormalBlending:
  41897. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  41898. break;
  41899. case AdditiveBlending:
  41900. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  41901. break;
  41902. case SubtractiveBlending:
  41903. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  41904. break;
  41905. case MultiplyBlending:
  41906. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  41907. break;
  41908. }
  41909. } else {
  41910. switch ( blending ) {
  41911. case NormalBlending:
  41912. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  41913. break;
  41914. case AdditiveBlending:
  41915. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  41916. break;
  41917. case SubtractiveBlending:
  41918. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  41919. break;
  41920. case MultiplyBlending:
  41921. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  41922. break;
  41923. }
  41924. }
  41925. }
  41926. if ( color !== undefined && alpha !== undefined ) {
  41927. return { color, alpha };
  41928. } else {
  41929. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  41930. }
  41931. }
  41932. _getBlendFactor( blend ) {
  41933. let blendFactor;
  41934. switch ( blend ) {
  41935. case ZeroFactor:
  41936. blendFactor = GPUBlendFactor.Zero;
  41937. break;
  41938. case OneFactor:
  41939. blendFactor = GPUBlendFactor.One;
  41940. break;
  41941. case SrcColorFactor:
  41942. blendFactor = GPUBlendFactor.Src;
  41943. break;
  41944. case OneMinusSrcColorFactor:
  41945. blendFactor = GPUBlendFactor.OneMinusSrc;
  41946. break;
  41947. case SrcAlphaFactor:
  41948. blendFactor = GPUBlendFactor.SrcAlpha;
  41949. break;
  41950. case OneMinusSrcAlphaFactor:
  41951. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  41952. break;
  41953. case DstColorFactor:
  41954. blendFactor = GPUBlendFactor.Dst;
  41955. break;
  41956. case OneMinusDstColorFactor:
  41957. blendFactor = GPUBlendFactor.OneMinusDstColor;
  41958. break;
  41959. case DstAlphaFactor:
  41960. blendFactor = GPUBlendFactor.DstAlpha;
  41961. break;
  41962. case OneMinusDstAlphaFactor:
  41963. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  41964. break;
  41965. case SrcAlphaSaturateFactor:
  41966. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  41967. break;
  41968. case BlendColorFactor:
  41969. blendFactor = GPUBlendFactor.Constant;
  41970. break;
  41971. case OneMinusBlendColorFactor:
  41972. blendFactor = GPUBlendFactor.OneMinusConstant;
  41973. break;
  41974. default:
  41975. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  41976. }
  41977. return blendFactor;
  41978. }
  41979. _getStencilCompare( material ) {
  41980. let stencilCompare;
  41981. const stencilFunc = material.stencilFunc;
  41982. switch ( stencilFunc ) {
  41983. case NeverStencilFunc:
  41984. stencilCompare = GPUCompareFunction.Never;
  41985. break;
  41986. case AlwaysStencilFunc:
  41987. stencilCompare = GPUCompareFunction.Always;
  41988. break;
  41989. case LessStencilFunc:
  41990. stencilCompare = GPUCompareFunction.Less;
  41991. break;
  41992. case LessEqualStencilFunc:
  41993. stencilCompare = GPUCompareFunction.LessEqual;
  41994. break;
  41995. case EqualStencilFunc:
  41996. stencilCompare = GPUCompareFunction.Equal;
  41997. break;
  41998. case GreaterEqualStencilFunc:
  41999. stencilCompare = GPUCompareFunction.GreaterEqual;
  42000. break;
  42001. case GreaterStencilFunc:
  42002. stencilCompare = GPUCompareFunction.Greater;
  42003. break;
  42004. case NotEqualStencilFunc:
  42005. stencilCompare = GPUCompareFunction.NotEqual;
  42006. break;
  42007. default:
  42008. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  42009. }
  42010. return stencilCompare;
  42011. }
  42012. _getStencilOperation( op ) {
  42013. let stencilOperation;
  42014. switch ( op ) {
  42015. case KeepStencilOp:
  42016. stencilOperation = GPUStencilOperation.Keep;
  42017. break;
  42018. case ZeroStencilOp:
  42019. stencilOperation = GPUStencilOperation.Zero;
  42020. break;
  42021. case ReplaceStencilOp:
  42022. stencilOperation = GPUStencilOperation.Replace;
  42023. break;
  42024. case InvertStencilOp:
  42025. stencilOperation = GPUStencilOperation.Invert;
  42026. break;
  42027. case IncrementStencilOp:
  42028. stencilOperation = GPUStencilOperation.IncrementClamp;
  42029. break;
  42030. case DecrementStencilOp:
  42031. stencilOperation = GPUStencilOperation.DecrementClamp;
  42032. break;
  42033. case IncrementWrapStencilOp:
  42034. stencilOperation = GPUStencilOperation.IncrementWrap;
  42035. break;
  42036. case DecrementWrapStencilOp:
  42037. stencilOperation = GPUStencilOperation.DecrementWrap;
  42038. break;
  42039. default:
  42040. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  42041. }
  42042. return stencilOperation;
  42043. }
  42044. _getBlendOperation( blendEquation ) {
  42045. let blendOperation;
  42046. switch ( blendEquation ) {
  42047. case AddEquation:
  42048. blendOperation = GPUBlendOperation.Add;
  42049. break;
  42050. case SubtractEquation:
  42051. blendOperation = GPUBlendOperation.Subtract;
  42052. break;
  42053. case ReverseSubtractEquation:
  42054. blendOperation = GPUBlendOperation.ReverseSubtract;
  42055. break;
  42056. case MinEquation:
  42057. blendOperation = GPUBlendOperation.Min;
  42058. break;
  42059. case MaxEquation:
  42060. blendOperation = GPUBlendOperation.Max;
  42061. break;
  42062. default:
  42063. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  42064. }
  42065. return blendOperation;
  42066. }
  42067. _getPrimitiveState( object, geometry, material ) {
  42068. const descriptor = {};
  42069. const utils = this.backend.utils;
  42070. descriptor.topology = utils.getPrimitiveTopology( object, material );
  42071. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  42072. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  42073. }
  42074. switch ( material.side ) {
  42075. case FrontSide:
  42076. descriptor.frontFace = GPUFrontFace.CCW;
  42077. descriptor.cullMode = GPUCullMode.Back;
  42078. break;
  42079. case BackSide:
  42080. descriptor.frontFace = GPUFrontFace.CCW;
  42081. descriptor.cullMode = GPUCullMode.Front;
  42082. break;
  42083. case DoubleSide:
  42084. descriptor.frontFace = GPUFrontFace.CCW;
  42085. descriptor.cullMode = GPUCullMode.None;
  42086. break;
  42087. default:
  42088. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  42089. break;
  42090. }
  42091. return descriptor;
  42092. }
  42093. _getColorWriteMask( material ) {
  42094. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  42095. }
  42096. _getDepthCompare( material ) {
  42097. let depthCompare;
  42098. if ( material.depthTest === false ) {
  42099. depthCompare = GPUCompareFunction.Always;
  42100. } else {
  42101. const depthFunc = material.depthFunc;
  42102. switch ( depthFunc ) {
  42103. case NeverDepth:
  42104. depthCompare = GPUCompareFunction.Never;
  42105. break;
  42106. case AlwaysDepth:
  42107. depthCompare = GPUCompareFunction.Always;
  42108. break;
  42109. case LessDepth:
  42110. depthCompare = GPUCompareFunction.Less;
  42111. break;
  42112. case LessEqualDepth:
  42113. depthCompare = GPUCompareFunction.LessEqual;
  42114. break;
  42115. case EqualDepth:
  42116. depthCompare = GPUCompareFunction.Equal;
  42117. break;
  42118. case GreaterEqualDepth:
  42119. depthCompare = GPUCompareFunction.GreaterEqual;
  42120. break;
  42121. case GreaterDepth:
  42122. depthCompare = GPUCompareFunction.Greater;
  42123. break;
  42124. case NotEqualDepth:
  42125. depthCompare = GPUCompareFunction.NotEqual;
  42126. break;
  42127. default:
  42128. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  42129. }
  42130. }
  42131. return depthCompare;
  42132. }
  42133. }
  42134. /*// debugger tools
  42135. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  42136. //*/
  42137. //
  42138. class WebGPUBackend extends Backend {
  42139. constructor( parameters = {} ) {
  42140. super( parameters );
  42141. this.isWebGPUBackend = true;
  42142. // some parameters require default values other than "undefined"
  42143. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  42144. this.parameters.antialias = ( parameters.antialias === true );
  42145. if ( this.parameters.antialias === true ) {
  42146. this.parameters.sampleCount = ( parameters.sampleCount === undefined ) ? 4 : parameters.sampleCount;
  42147. } else {
  42148. this.parameters.sampleCount = 1;
  42149. }
  42150. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  42151. this.trackTimestamp = ( parameters.trackTimestamp === true );
  42152. this.device = null;
  42153. this.context = null;
  42154. this.colorBuffer = null;
  42155. this.defaultRenderPassdescriptor = null;
  42156. this.utils = new WebGPUUtils( this );
  42157. this.attributeUtils = new WebGPUAttributeUtils( this );
  42158. this.bindingUtils = new WebGPUBindingUtils( this );
  42159. this.pipelineUtils = new WebGPUPipelineUtils( this );
  42160. this.textureUtils = new WebGPUTextureUtils( this );
  42161. this.occludedResolveCache = new Map();
  42162. }
  42163. async init( renderer ) {
  42164. await super.init( renderer );
  42165. //
  42166. const parameters = this.parameters;
  42167. // create the device if it is not passed with parameters
  42168. let device;
  42169. if ( parameters.device === undefined ) {
  42170. const adapterOptions = {
  42171. powerPreference: parameters.powerPreference
  42172. };
  42173. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  42174. if ( adapter === null ) {
  42175. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  42176. }
  42177. // feature support
  42178. const features = Object.values( GPUFeatureName );
  42179. const supportedFeatures = [];
  42180. for ( const name of features ) {
  42181. if ( adapter.features.has( name ) ) {
  42182. supportedFeatures.push( name );
  42183. }
  42184. }
  42185. const deviceDescriptor = {
  42186. requiredFeatures: supportedFeatures,
  42187. requiredLimits: parameters.requiredLimits
  42188. };
  42189. device = await adapter.requestDevice( deviceDescriptor );
  42190. } else {
  42191. device = parameters.device;
  42192. }
  42193. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  42194. this.device = device;
  42195. this.context = context;
  42196. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  42197. this.context.configure( {
  42198. device: this.device,
  42199. format: GPUTextureFormat.BGRA8Unorm,
  42200. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  42201. alphaMode: alphaMode
  42202. } );
  42203. this.updateSize();
  42204. }
  42205. get coordinateSystem() {
  42206. return WebGPUCoordinateSystem;
  42207. }
  42208. async getArrayBufferAsync( attribute ) {
  42209. return await this.attributeUtils.getArrayBufferAsync( attribute );
  42210. }
  42211. getContext() {
  42212. return this.context;
  42213. }
  42214. _getDefaultRenderPassDescriptor() {
  42215. let descriptor = this.defaultRenderPassdescriptor;
  42216. const antialias = this.parameters.antialias;
  42217. if ( descriptor === null ) {
  42218. const renderer = this.renderer;
  42219. descriptor = {
  42220. colorAttachments: [ {
  42221. view: null
  42222. } ],
  42223. depthStencilAttachment: {
  42224. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  42225. }
  42226. };
  42227. const colorAttachment = descriptor.colorAttachments[ 0 ];
  42228. if ( antialias === true ) {
  42229. colorAttachment.view = this.colorBuffer.createView();
  42230. } else {
  42231. colorAttachment.resolveTarget = undefined;
  42232. }
  42233. this.defaultRenderPassdescriptor = descriptor;
  42234. }
  42235. const colorAttachment = descriptor.colorAttachments[ 0 ];
  42236. if ( antialias === true ) {
  42237. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  42238. } else {
  42239. colorAttachment.view = this.context.getCurrentTexture().createView();
  42240. }
  42241. return descriptor;
  42242. }
  42243. _getRenderPassDescriptor( renderContext ) {
  42244. const renderTarget = renderContext.renderTarget;
  42245. const renderTargetData = this.get( renderTarget );
  42246. let descriptors = renderTargetData.descriptors;
  42247. if ( descriptors === undefined ) {
  42248. descriptors = [];
  42249. renderTargetData.descriptors = descriptors;
  42250. }
  42251. if ( renderTargetData.width !== renderTarget.width ||
  42252. renderTargetData.height !== renderTarget.height ||
  42253. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  42254. renderTargetData.samples !== renderTarget.samples
  42255. ) {
  42256. descriptors.length = 0;
  42257. }
  42258. let descriptor = descriptors[ renderContext.activeCubeFace ];
  42259. if ( descriptor === undefined ) {
  42260. const textures = renderContext.textures;
  42261. const colorAttachments = [];
  42262. for ( let i = 0; i < textures.length; i ++ ) {
  42263. const textureData = this.get( textures[ i ] );
  42264. const textureView = textureData.texture.createView( {
  42265. baseMipLevel: renderContext.activeMipmapLevel,
  42266. mipLevelCount: 1,
  42267. baseArrayLayer: renderContext.activeCubeFace,
  42268. dimension: GPUTextureViewDimension.TwoD
  42269. } );
  42270. let view, resolveTarget;
  42271. if ( textureData.msaaTexture !== undefined ) {
  42272. view = textureData.msaaTexture.createView();
  42273. resolveTarget = textureView;
  42274. } else {
  42275. view = textureView;
  42276. resolveTarget = undefined;
  42277. }
  42278. colorAttachments.push( {
  42279. view,
  42280. resolveTarget,
  42281. loadOp: GPULoadOp.Load,
  42282. storeOp: GPUStoreOp.Store
  42283. } );
  42284. }
  42285. const depthTextureData = this.get( renderContext.depthTexture );
  42286. const depthStencilAttachment = {
  42287. view: depthTextureData.texture.createView(),
  42288. };
  42289. descriptor = {
  42290. colorAttachments,
  42291. depthStencilAttachment
  42292. };
  42293. descriptors[ renderContext.activeCubeFace ] = descriptor;
  42294. renderTargetData.width = renderTarget.width;
  42295. renderTargetData.height = renderTarget.height;
  42296. renderTargetData.samples = renderTarget.samples;
  42297. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  42298. }
  42299. return descriptor;
  42300. }
  42301. beginRender( renderContext ) {
  42302. const renderContextData = this.get( renderContext );
  42303. const device = this.device;
  42304. const occlusionQueryCount = renderContext.occlusionQueryCount;
  42305. let occlusionQuerySet;
  42306. if ( occlusionQueryCount > 0 ) {
  42307. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  42308. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  42309. // Get a reference to the array of objects with queries. The renderContextData property
  42310. // can be changed by another render pass before the buffer.mapAsyc() completes.
  42311. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  42312. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  42313. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  42314. //
  42315. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } );
  42316. renderContextData.occlusionQuerySet = occlusionQuerySet;
  42317. renderContextData.occlusionQueryIndex = 0;
  42318. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  42319. renderContextData.lastOcclusionObject = null;
  42320. }
  42321. let descriptor;
  42322. if ( renderContext.textures === null ) {
  42323. descriptor = this._getDefaultRenderPassDescriptor();
  42324. } else {
  42325. descriptor = this._getRenderPassDescriptor( renderContext );
  42326. }
  42327. this.initTimestampQuery( renderContext, descriptor );
  42328. descriptor.occlusionQuerySet = occlusionQuerySet;
  42329. const depthStencilAttachment = descriptor.depthStencilAttachment;
  42330. if ( renderContext.textures !== null ) {
  42331. const colorAttachments = descriptor.colorAttachments;
  42332. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  42333. const colorAttachment = colorAttachments[ i ];
  42334. if ( renderContext.clearColor ) {
  42335. colorAttachment.clearValue = renderContext.clearColorValue;
  42336. colorAttachment.loadOp = GPULoadOp.Clear;
  42337. colorAttachment.storeOp = GPUStoreOp.Store;
  42338. } else {
  42339. colorAttachment.loadOp = GPULoadOp.Load;
  42340. colorAttachment.storeOp = GPUStoreOp.Store;
  42341. }
  42342. }
  42343. } else {
  42344. const colorAttachment = descriptor.colorAttachments[ 0 ];
  42345. if ( renderContext.clearColor ) {
  42346. colorAttachment.clearValue = renderContext.clearColorValue;
  42347. colorAttachment.loadOp = GPULoadOp.Clear;
  42348. colorAttachment.storeOp = GPUStoreOp.Store;
  42349. } else {
  42350. colorAttachment.loadOp = GPULoadOp.Load;
  42351. colorAttachment.storeOp = GPUStoreOp.Store;
  42352. }
  42353. }
  42354. //
  42355. if ( renderContext.depth ) {
  42356. if ( renderContext.clearDepth ) {
  42357. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  42358. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  42359. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  42360. } else {
  42361. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  42362. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  42363. }
  42364. }
  42365. if ( renderContext.stencil ) {
  42366. if ( renderContext.clearStencil ) {
  42367. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  42368. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  42369. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  42370. } else {
  42371. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  42372. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  42373. }
  42374. }
  42375. //
  42376. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  42377. const currentPass = encoder.beginRenderPass( descriptor );
  42378. //
  42379. renderContextData.descriptor = descriptor;
  42380. renderContextData.encoder = encoder;
  42381. renderContextData.currentPass = currentPass;
  42382. renderContextData.currentSets = { attributes: {} };
  42383. //
  42384. if ( renderContext.viewport ) {
  42385. this.updateViewport( renderContext );
  42386. }
  42387. if ( renderContext.scissor ) {
  42388. const { x, y, width, height } = renderContext.scissorValue;
  42389. currentPass.setScissorRect( x, renderContext.height - height - y, width, height );
  42390. }
  42391. }
  42392. finishRender( renderContext ) {
  42393. const renderContextData = this.get( renderContext );
  42394. const occlusionQueryCount = renderContext.occlusionQueryCount;
  42395. if ( renderContextData.renderBundles !== undefined && renderContextData.renderBundles.length > 0 ) {
  42396. renderContextData.registerBundlesPhase = false;
  42397. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  42398. }
  42399. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  42400. renderContextData.currentPass.endOcclusionQuery();
  42401. }
  42402. renderContextData.currentPass.end();
  42403. if ( occlusionQueryCount > 0 ) {
  42404. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  42405. //
  42406. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  42407. if ( queryResolveBuffer === undefined ) {
  42408. queryResolveBuffer = this.device.createBuffer(
  42409. {
  42410. size: bufferSize,
  42411. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  42412. }
  42413. );
  42414. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  42415. }
  42416. //
  42417. const readBuffer = this.device.createBuffer(
  42418. {
  42419. size: bufferSize,
  42420. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  42421. }
  42422. );
  42423. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  42424. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  42425. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  42426. renderContextData.occlusionQueryBuffer = readBuffer;
  42427. //
  42428. this.resolveOccludedAsync( renderContext );
  42429. }
  42430. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  42431. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  42432. //
  42433. if ( renderContext.textures !== null ) {
  42434. const textures = renderContext.textures;
  42435. for ( let i = 0; i < textures.length; i ++ ) {
  42436. const texture = textures[ i ];
  42437. if ( texture.generateMipmaps === true ) {
  42438. this.textureUtils.generateMipmaps( texture );
  42439. }
  42440. }
  42441. }
  42442. }
  42443. isOccluded( renderContext, object ) {
  42444. const renderContextData = this.get( renderContext );
  42445. return renderContextData.occluded && renderContextData.occluded.has( object );
  42446. }
  42447. async resolveOccludedAsync( renderContext ) {
  42448. const renderContextData = this.get( renderContext );
  42449. // handle occlusion query results
  42450. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  42451. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  42452. const occluded = new WeakSet();
  42453. renderContextData.currentOcclusionQueryObjects = null;
  42454. renderContextData.currentOcclusionQueryBuffer = null;
  42455. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  42456. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  42457. const results = new BigUint64Array( buffer );
  42458. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  42459. if ( results[ i ] !== BigInt( 0 ) ) {
  42460. occluded.add( currentOcclusionQueryObjects[ i ] );
  42461. }
  42462. }
  42463. currentOcclusionQueryBuffer.destroy();
  42464. renderContextData.occluded = occluded;
  42465. }
  42466. }
  42467. updateViewport( renderContext ) {
  42468. const { currentPass } = this.get( renderContext );
  42469. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  42470. currentPass.setViewport( x, renderContext.height - height - y, width, height, minDepth, maxDepth );
  42471. }
  42472. clear( color, depth, stencil, renderTargetData = null ) {
  42473. const device = this.device;
  42474. const renderer = this.renderer;
  42475. let colorAttachments = [];
  42476. let depthStencilAttachment;
  42477. let clearValue;
  42478. let supportsDepth;
  42479. let supportsStencil;
  42480. if ( color ) {
  42481. const clearColor = this.getClearColor();
  42482. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  42483. }
  42484. if ( renderTargetData === null ) {
  42485. supportsDepth = renderer.depth;
  42486. supportsStencil = renderer.stencil;
  42487. const descriptor = this._getDefaultRenderPassDescriptor();
  42488. if ( color ) {
  42489. colorAttachments = descriptor.colorAttachments;
  42490. const colorAttachment = colorAttachments[ 0 ];
  42491. colorAttachment.clearValue = clearValue;
  42492. colorAttachment.loadOp = GPULoadOp.Clear;
  42493. colorAttachment.storeOp = GPUStoreOp.Store;
  42494. }
  42495. if ( supportsDepth || supportsStencil ) {
  42496. depthStencilAttachment = descriptor.depthStencilAttachment;
  42497. }
  42498. } else {
  42499. supportsDepth = renderTargetData.depth;
  42500. supportsStencil = renderTargetData.stencil;
  42501. if ( color ) {
  42502. for ( const texture of renderTargetData.textures ) {
  42503. const textureData = this.get( texture );
  42504. const textureView = textureData.texture.createView();
  42505. let view, resolveTarget;
  42506. if ( textureData.msaaTexture !== undefined ) {
  42507. view = textureData.msaaTexture.createView();
  42508. resolveTarget = textureView;
  42509. } else {
  42510. view = textureView;
  42511. resolveTarget = undefined;
  42512. }
  42513. colorAttachments.push( {
  42514. view,
  42515. resolveTarget,
  42516. clearValue,
  42517. loadOp: GPULoadOp.Clear,
  42518. storeOp: GPUStoreOp.Store
  42519. } );
  42520. }
  42521. }
  42522. if ( supportsDepth || supportsStencil ) {
  42523. const depthTextureData = this.get( renderTargetData.depthTexture );
  42524. depthStencilAttachment = {
  42525. view: depthTextureData.texture.createView()
  42526. };
  42527. }
  42528. }
  42529. //
  42530. if ( supportsDepth ) {
  42531. if ( depth ) {
  42532. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  42533. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  42534. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  42535. } else {
  42536. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  42537. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  42538. }
  42539. }
  42540. //
  42541. if ( supportsStencil ) {
  42542. if ( stencil ) {
  42543. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  42544. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  42545. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  42546. } else {
  42547. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  42548. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  42549. }
  42550. }
  42551. //
  42552. const encoder = device.createCommandEncoder( {} );
  42553. const currentPass = encoder.beginRenderPass( {
  42554. colorAttachments,
  42555. depthStencilAttachment
  42556. } );
  42557. currentPass.end();
  42558. device.queue.submit( [ encoder.finish() ] );
  42559. }
  42560. // compute
  42561. beginCompute( computeGroup ) {
  42562. const groupGPU = this.get( computeGroup );
  42563. const descriptor = {};
  42564. this.initTimestampQuery( computeGroup, descriptor );
  42565. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  42566. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  42567. }
  42568. compute( computeGroup, computeNode, bindings, pipeline ) {
  42569. const { passEncoderGPU } = this.get( computeGroup );
  42570. // pipeline
  42571. const pipelineGPU = this.get( pipeline ).pipeline;
  42572. passEncoderGPU.setPipeline( pipelineGPU );
  42573. // bind groups
  42574. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  42575. const bindGroup = bindings[ i ];
  42576. const bindingsData = this.get( bindGroup );
  42577. passEncoderGPU.setBindGroup( i, bindingsData.group );
  42578. }
  42579. passEncoderGPU.dispatchWorkgroups( computeNode.dispatchCount );
  42580. }
  42581. finishCompute( computeGroup ) {
  42582. const groupData = this.get( computeGroup );
  42583. groupData.passEncoderGPU.end();
  42584. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  42585. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  42586. }
  42587. // render object
  42588. draw( renderObject, info ) {
  42589. const { object, geometry, context, pipeline } = renderObject;
  42590. const bindings = renderObject.getBindings();
  42591. const contextData = this.get( context );
  42592. const pipelineGPU = this.get( pipeline ).pipeline;
  42593. const currentSets = contextData.currentSets;
  42594. const renderObjectData = this.get( renderObject );
  42595. const { bundleEncoder, renderBundle, lastPipelineGPU } = renderObjectData;
  42596. const renderContextData = this.get( context );
  42597. if ( renderContextData.registerBundlesPhase === true && bundleEncoder !== undefined && lastPipelineGPU === pipelineGPU ) {
  42598. renderContextData.renderBundles.push( renderBundle );
  42599. return;
  42600. }
  42601. const passEncoderGPU = this.renderer._currentRenderBundle ? this.createBundleEncoder( context, renderObject ) : contextData.currentPass;
  42602. // pipeline
  42603. if ( currentSets.pipeline !== pipelineGPU ) {
  42604. passEncoderGPU.setPipeline( pipelineGPU );
  42605. currentSets.pipeline = pipelineGPU;
  42606. }
  42607. // bind groups
  42608. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  42609. const bindGroup = bindings[ i ];
  42610. const bindingsData = this.get( bindGroup );
  42611. passEncoderGPU.setBindGroup( i, bindingsData.group );
  42612. }
  42613. // attributes
  42614. const index = renderObject.getIndex();
  42615. const hasIndex = ( index !== null );
  42616. // index
  42617. if ( hasIndex === true ) {
  42618. if ( currentSets.index !== index ) {
  42619. const buffer = this.get( index ).buffer;
  42620. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  42621. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  42622. currentSets.index = index;
  42623. }
  42624. }
  42625. // vertex buffers
  42626. const vertexBuffers = renderObject.getVertexBuffers();
  42627. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  42628. const vertexBuffer = vertexBuffers[ i ];
  42629. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  42630. const buffer = this.get( vertexBuffer ).buffer;
  42631. passEncoderGPU.setVertexBuffer( i, buffer );
  42632. currentSets.attributes[ i ] = vertexBuffer;
  42633. }
  42634. }
  42635. // occlusion queries - handle multiple consecutive draw calls for an object
  42636. if ( contextData.occlusionQuerySet !== undefined ) {
  42637. const lastObject = contextData.lastOcclusionObject;
  42638. if ( lastObject !== object ) {
  42639. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  42640. passEncoderGPU.endOcclusionQuery();
  42641. contextData.occlusionQueryIndex ++;
  42642. }
  42643. if ( object.occlusionTest === true ) {
  42644. passEncoderGPU.beginOcclusionQuery( contextData.occlusionQueryIndex );
  42645. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  42646. }
  42647. contextData.lastOcclusionObject = object;
  42648. }
  42649. }
  42650. // draw
  42651. const drawRange = renderObject.drawRange;
  42652. const firstVertex = drawRange.start;
  42653. const instanceCount = this.getInstanceCount( renderObject );
  42654. if ( instanceCount === 0 ) return;
  42655. if ( object.isBatchedMesh === true ) {
  42656. const starts = object._multiDrawStarts;
  42657. const counts = object._multiDrawCounts;
  42658. const drawCount = object._multiDrawCount;
  42659. const drawInstances = object._multiDrawInstances;
  42660. const bytesPerElement = index.bytesPerElement || 1;
  42661. for ( let i = 0; i < drawCount; i ++ ) {
  42662. const count = drawInstances ? drawInstances[ i ] : 1;
  42663. const firstInstance = count > 1 ? 0 : i;
  42664. passEncoderGPU.drawIndexed( counts[ i ] / bytesPerElement, count, starts[ i ] / 4, 0, firstInstance );
  42665. }
  42666. } else if ( hasIndex === true ) {
  42667. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  42668. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstVertex, 0, 0 );
  42669. info.update( object, indexCount, instanceCount );
  42670. } else {
  42671. const positionAttribute = geometry.attributes.position;
  42672. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : positionAttribute.count;
  42673. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  42674. info.update( object, vertexCount, instanceCount );
  42675. }
  42676. if ( this.renderer._currentRenderBundle ) {
  42677. const renderBundle = passEncoderGPU.finish();
  42678. renderObjectData.lastPipelineGPU = pipelineGPU;
  42679. renderObjectData.renderBundle = renderBundle;
  42680. renderObjectData.bundleEncoder = passEncoderGPU;
  42681. }
  42682. }
  42683. // cache key
  42684. needsRenderUpdate( renderObject ) {
  42685. const data = this.get( renderObject );
  42686. const { object, material } = renderObject;
  42687. const utils = this.utils;
  42688. const sampleCount = utils.getSampleCount( renderObject.context );
  42689. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  42690. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  42691. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  42692. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  42693. let needsUpdate = false;
  42694. if ( data.material !== material || data.materialVersion !== material.version ||
  42695. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  42696. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  42697. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  42698. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  42699. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  42700. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  42701. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  42702. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  42703. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  42704. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  42705. data.primitiveTopology !== primitiveTopology ||
  42706. data.clippingContextVersion !== renderObject.clippingContextVersion
  42707. ) {
  42708. data.material = material; data.materialVersion = material.version;
  42709. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  42710. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  42711. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  42712. data.colorWrite = material.colorWrite;
  42713. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  42714. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  42715. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  42716. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  42717. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  42718. data.sampleCount = sampleCount;
  42719. data.colorSpace = colorSpace;
  42720. data.colorFormat = colorFormat;
  42721. data.depthStencilFormat = depthStencilFormat;
  42722. data.primitiveTopology = primitiveTopology;
  42723. data.clippingContextVersion = renderObject.clippingContextVersion;
  42724. needsUpdate = true;
  42725. }
  42726. return needsUpdate;
  42727. }
  42728. getRenderCacheKey( renderObject ) {
  42729. const { object, material } = renderObject;
  42730. const utils = this.utils;
  42731. const renderContext = renderObject.context;
  42732. return [
  42733. material.transparent, material.blending, material.premultipliedAlpha,
  42734. material.blendSrc, material.blendDst, material.blendEquation,
  42735. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  42736. material.colorWrite,
  42737. material.depthWrite, material.depthTest, material.depthFunc,
  42738. material.stencilWrite, material.stencilFunc,
  42739. material.stencilFail, material.stencilZFail, material.stencilZPass,
  42740. material.stencilFuncMask, material.stencilWriteMask,
  42741. material.side,
  42742. utils.getSampleCount( renderContext ),
  42743. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  42744. utils.getPrimitiveTopology( object, material ),
  42745. renderObject.clippingContextVersion
  42746. ].join();
  42747. }
  42748. // textures
  42749. createSampler( texture ) {
  42750. this.textureUtils.createSampler( texture );
  42751. }
  42752. destroySampler( texture ) {
  42753. this.textureUtils.destroySampler( texture );
  42754. }
  42755. createDefaultTexture( texture ) {
  42756. this.textureUtils.createDefaultTexture( texture );
  42757. }
  42758. createTexture( texture, options ) {
  42759. this.textureUtils.createTexture( texture, options );
  42760. }
  42761. updateTexture( texture, options ) {
  42762. this.textureUtils.updateTexture( texture, options );
  42763. }
  42764. generateMipmaps( texture ) {
  42765. this.textureUtils.generateMipmaps( texture );
  42766. }
  42767. destroyTexture( texture ) {
  42768. this.textureUtils.destroyTexture( texture );
  42769. }
  42770. copyTextureToBuffer( texture, x, y, width, height ) {
  42771. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  42772. }
  42773. initTimestampQuery( renderContext, descriptor ) {
  42774. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  42775. const renderContextData = this.get( renderContext );
  42776. if ( ! renderContextData.timeStampQuerySet ) {
  42777. // Create a GPUQuerySet which holds 2 timestamp query results: one for the
  42778. // beginning and one for the end of compute pass execution.
  42779. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } );
  42780. const timestampWrites = {
  42781. querySet: timeStampQuerySet,
  42782. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  42783. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  42784. };
  42785. Object.assign( descriptor, {
  42786. timestampWrites,
  42787. } );
  42788. renderContextData.timeStampQuerySet = timeStampQuerySet;
  42789. }
  42790. }
  42791. // timestamp utils
  42792. prepareTimestampBuffer( renderContext, encoder ) {
  42793. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  42794. const renderContextData = this.get( renderContext );
  42795. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  42796. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  42797. renderContextData.currentTimestampQueryBuffers = {
  42798. resolveBuffer: this.device.createBuffer( {
  42799. label: 'timestamp resolve buffer',
  42800. size: size,
  42801. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  42802. } ),
  42803. resultBuffer: this.device.createBuffer( {
  42804. label: 'timestamp result buffer',
  42805. size: size,
  42806. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  42807. } ),
  42808. isMappingPending: false,
  42809. };
  42810. }
  42811. const { resolveBuffer, resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  42812. if ( isMappingPending === true ) return;
  42813. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  42814. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  42815. }
  42816. async resolveTimestampAsync( renderContext, type = 'render' ) {
  42817. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  42818. const renderContextData = this.get( renderContext );
  42819. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  42820. const { resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  42821. if ( isMappingPending === true ) return;
  42822. renderContextData.currentTimestampQueryBuffers.isMappingPending = true;
  42823. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  42824. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  42825. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  42826. this.renderer.info.updateTimestamp( type, duration );
  42827. resultBuffer.unmap();
  42828. renderContextData.currentTimestampQueryBuffers.isMappingPending = false;
  42829. } );
  42830. }
  42831. // node builder
  42832. createNodeBuilder( object, renderer ) {
  42833. return new WGSLNodeBuilder( object, renderer );
  42834. }
  42835. // program
  42836. createProgram( program ) {
  42837. const programGPU = this.get( program );
  42838. programGPU.module = {
  42839. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  42840. entryPoint: 'main'
  42841. };
  42842. }
  42843. destroyProgram( program ) {
  42844. this.delete( program );
  42845. }
  42846. // pipelines
  42847. createRenderPipeline( renderObject, promises ) {
  42848. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  42849. }
  42850. createComputePipeline( computePipeline, bindings ) {
  42851. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  42852. }
  42853. createBundleEncoder( renderContext, renderObject ) {
  42854. return this.pipelineUtils.createBundleEncoder( renderContext, renderObject );
  42855. }
  42856. // bindings
  42857. createBindings( bindGroup ) {
  42858. this.bindingUtils.createBindings( bindGroup );
  42859. }
  42860. updateBindings( bindGroup ) {
  42861. this.bindingUtils.createBindings( bindGroup );
  42862. }
  42863. updateBinding( binding ) {
  42864. this.bindingUtils.updateBinding( binding );
  42865. }
  42866. // attributes
  42867. createIndexAttribute( attribute ) {
  42868. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  42869. }
  42870. createAttribute( attribute ) {
  42871. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  42872. }
  42873. createStorageAttribute( attribute ) {
  42874. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  42875. }
  42876. updateAttribute( attribute ) {
  42877. this.attributeUtils.updateAttribute( attribute );
  42878. }
  42879. destroyAttribute( attribute ) {
  42880. this.attributeUtils.destroyAttribute( attribute );
  42881. }
  42882. // canvas
  42883. updateSize() {
  42884. this.colorBuffer = this.textureUtils.getColorBuffer();
  42885. this.defaultRenderPassdescriptor = null;
  42886. }
  42887. // utils public
  42888. getMaxAnisotropy() {
  42889. return 16;
  42890. }
  42891. hasFeature( name ) {
  42892. return this.device.features.has( name );
  42893. }
  42894. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  42895. let dstX = 0;
  42896. let dstY = 0;
  42897. let srcX = 0;
  42898. let srcY = 0;
  42899. let srcWidth = srcTexture.image.width;
  42900. let srcHeight = srcTexture.image.height;
  42901. if ( srcRegion !== null ) {
  42902. srcX = srcRegion.x;
  42903. srcY = srcRegion.y;
  42904. srcWidth = srcRegion.width;
  42905. srcHeight = srcRegion.height;
  42906. }
  42907. if ( dstPosition !== null ) {
  42908. dstX = dstPosition.x;
  42909. dstY = dstPosition.y;
  42910. }
  42911. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  42912. const sourceGPU = this.get( srcTexture ).texture;
  42913. const destinationGPU = this.get( dstTexture ).texture;
  42914. encoder.copyTextureToTexture(
  42915. {
  42916. texture: sourceGPU,
  42917. mipLevel: level,
  42918. origin: { x: srcX, y: srcY, z: 0 }
  42919. },
  42920. {
  42921. texture: destinationGPU,
  42922. mipLevel: level,
  42923. origin: { x: dstX, y: dstY, z: 0 }
  42924. },
  42925. [
  42926. srcWidth,
  42927. srcHeight
  42928. ]
  42929. );
  42930. this.device.queue.submit( [ encoder.finish() ] );
  42931. }
  42932. copyFramebufferToTexture( texture, renderContext ) {
  42933. const renderContextData = this.get( renderContext );
  42934. const { encoder, descriptor } = renderContextData;
  42935. let sourceGPU = null;
  42936. if ( renderContext.renderTarget ) {
  42937. if ( texture.isDepthTexture ) {
  42938. sourceGPU = this.get( renderContext.depthTexture ).texture;
  42939. } else {
  42940. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  42941. }
  42942. } else {
  42943. if ( texture.isDepthTexture ) {
  42944. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  42945. } else {
  42946. sourceGPU = this.context.getCurrentTexture();
  42947. }
  42948. }
  42949. const destinationGPU = this.get( texture ).texture;
  42950. if ( sourceGPU.format !== destinationGPU.format ) {
  42951. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  42952. return;
  42953. }
  42954. renderContextData.currentPass.end();
  42955. encoder.copyTextureToTexture(
  42956. {
  42957. texture: sourceGPU,
  42958. origin: { x: 0, y: 0, z: 0 }
  42959. },
  42960. {
  42961. texture: destinationGPU
  42962. },
  42963. [
  42964. texture.image.width,
  42965. texture.image.height
  42966. ]
  42967. );
  42968. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  42969. descriptor.colorAttachments[ 0 ].loadOp = GPULoadOp.Load;
  42970. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  42971. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  42972. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  42973. renderContextData.currentSets = { attributes: {} };
  42974. }
  42975. }
  42976. /*
  42977. const debugHandler = {
  42978. get: function ( target, name ) {
  42979. // Add |update
  42980. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  42981. return target[ name ];
  42982. }
  42983. };
  42984. */
  42985. class WebGPURenderer extends Renderer {
  42986. constructor( parameters = {} ) {
  42987. let BackendClass;
  42988. if ( parameters.forceWebGL ) {
  42989. BackendClass = WebGLBackend;
  42990. } else if ( WebGPU.isAvailable() ) {
  42991. BackendClass = WebGPUBackend;
  42992. } else {
  42993. BackendClass = WebGLBackend;
  42994. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  42995. }
  42996. const backend = new BackendClass( parameters );
  42997. //super( new Proxy( backend, debugHandler ) );
  42998. super( backend, parameters );
  42999. this.isWebGPURenderer = true;
  43000. }
  43001. }
  43002. const quadMesh = new QuadMesh( new NodeMaterial() );
  43003. class PostProcessing {
  43004. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  43005. this.renderer = renderer;
  43006. this.outputNode = outputNode;
  43007. }
  43008. render() {
  43009. quadMesh.material.fragmentNode = this.outputNode;
  43010. quadMesh.render( this.renderer );
  43011. }
  43012. renderAsync() {
  43013. quadMesh.material.fragmentNode = this.outputNode;
  43014. return quadMesh.renderAsync( this.renderer );
  43015. }
  43016. set needsUpdate( value ) {
  43017. quadMesh.material.needsUpdate = value;
  43018. }
  43019. }
  43020. class StorageTexture extends Texture {
  43021. constructor( width = 1, height = 1 ) {
  43022. super();
  43023. this.image = { width, height };
  43024. this.magFilter = LinearFilter;
  43025. this.minFilter = LinearFilter;
  43026. this.isStorageTexture = true;
  43027. }
  43028. }
  43029. class StorageBufferAttribute extends BufferAttribute {
  43030. constructor( array, itemSize, typeClass = Float32Array ) {
  43031. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  43032. super( array, itemSize );
  43033. this.isStorageBufferAttribute = true;
  43034. }
  43035. }
  43036. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  43037. constructor( array, itemSize, typeClass = Float32Array ) {
  43038. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  43039. super( array, itemSize );
  43040. this.isStorageInstancedBufferAttribute = true;
  43041. }
  43042. }
  43043. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  43044. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  43045. revision: REVISION,
  43046. } } ) );
  43047. }
  43048. if ( typeof window !== 'undefined' ) {
  43049. if ( window.__THREE__ ) {
  43050. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  43051. } else {
  43052. window.__THREE__ = REVISION;
  43053. }
  43054. }
  43055. 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, 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, 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, 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, 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, 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, range, rangeFog, reciprocal, reference, referenceBuffer, reflect, reflectVector, reflectView, reflector, refract, remainder, remap, remapClamp, renderGroup, rendererReference, rgbShift, rotate, rotateUV, roughness, round, 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 };