three.js 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523
  1. /**
  2. * @license
  3. * Copyright 2010-2021 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. (function (global, factory) {
  7. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  8. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  9. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.THREE = {}));
  10. }(this, (function (exports) { 'use strict';
  11. const REVISION = '133dev';
  12. const MOUSE = {
  13. LEFT: 0,
  14. MIDDLE: 1,
  15. RIGHT: 2,
  16. ROTATE: 0,
  17. DOLLY: 1,
  18. PAN: 2
  19. };
  20. const TOUCH = {
  21. ROTATE: 0,
  22. PAN: 1,
  23. DOLLY_PAN: 2,
  24. DOLLY_ROTATE: 3
  25. };
  26. const CullFaceNone = 0;
  27. const CullFaceBack = 1;
  28. const CullFaceFront = 2;
  29. const CullFaceFrontBack = 3;
  30. const BasicShadowMap = 0;
  31. const PCFShadowMap = 1;
  32. const PCFSoftShadowMap = 2;
  33. const VSMShadowMap = 3;
  34. const FrontSide = 0;
  35. const BackSide = 1;
  36. const DoubleSide = 2;
  37. const FlatShading = 1;
  38. const SmoothShading = 2;
  39. const NoBlending = 0;
  40. const NormalBlending = 1;
  41. const AdditiveBlending = 2;
  42. const SubtractiveBlending = 3;
  43. const MultiplyBlending = 4;
  44. const CustomBlending = 5;
  45. const AddEquation = 100;
  46. const SubtractEquation = 101;
  47. const ReverseSubtractEquation = 102;
  48. const MinEquation = 103;
  49. const MaxEquation = 104;
  50. const ZeroFactor = 200;
  51. const OneFactor = 201;
  52. const SrcColorFactor = 202;
  53. const OneMinusSrcColorFactor = 203;
  54. const SrcAlphaFactor = 204;
  55. const OneMinusSrcAlphaFactor = 205;
  56. const DstAlphaFactor = 206;
  57. const OneMinusDstAlphaFactor = 207;
  58. const DstColorFactor = 208;
  59. const OneMinusDstColorFactor = 209;
  60. const SrcAlphaSaturateFactor = 210;
  61. const NeverDepth = 0;
  62. const AlwaysDepth = 1;
  63. const LessDepth = 2;
  64. const LessEqualDepth = 3;
  65. const EqualDepth = 4;
  66. const GreaterEqualDepth = 5;
  67. const GreaterDepth = 6;
  68. const NotEqualDepth = 7;
  69. const MultiplyOperation = 0;
  70. const MixOperation = 1;
  71. const AddOperation = 2;
  72. const NoToneMapping = 0;
  73. const LinearToneMapping = 1;
  74. const ReinhardToneMapping = 2;
  75. const CineonToneMapping = 3;
  76. const ACESFilmicToneMapping = 4;
  77. const CustomToneMapping = 5;
  78. const UVMapping = 300;
  79. const CubeReflectionMapping = 301;
  80. const CubeRefractionMapping = 302;
  81. const EquirectangularReflectionMapping = 303;
  82. const EquirectangularRefractionMapping = 304;
  83. const CubeUVReflectionMapping = 306;
  84. const CubeUVRefractionMapping = 307;
  85. const RepeatWrapping = 1000;
  86. const ClampToEdgeWrapping = 1001;
  87. const MirroredRepeatWrapping = 1002;
  88. const NearestFilter = 1003;
  89. const NearestMipmapNearestFilter = 1004;
  90. const NearestMipMapNearestFilter = 1004;
  91. const NearestMipmapLinearFilter = 1005;
  92. const NearestMipMapLinearFilter = 1005;
  93. const LinearFilter = 1006;
  94. const LinearMipmapNearestFilter = 1007;
  95. const LinearMipMapNearestFilter = 1007;
  96. const LinearMipmapLinearFilter = 1008;
  97. const LinearMipMapLinearFilter = 1008;
  98. const UnsignedByteType = 1009;
  99. const ByteType = 1010;
  100. const ShortType = 1011;
  101. const UnsignedShortType = 1012;
  102. const IntType = 1013;
  103. const UnsignedIntType = 1014;
  104. const FloatType = 1015;
  105. const HalfFloatType = 1016;
  106. const UnsignedShort4444Type = 1017;
  107. const UnsignedShort5551Type = 1018;
  108. const UnsignedShort565Type = 1019;
  109. const UnsignedInt248Type = 1020;
  110. const AlphaFormat = 1021;
  111. const RGBFormat = 1022;
  112. const RGBAFormat = 1023;
  113. const LuminanceFormat = 1024;
  114. const LuminanceAlphaFormat = 1025;
  115. const RGBEFormat = RGBAFormat;
  116. const DepthFormat = 1026;
  117. const DepthStencilFormat = 1027;
  118. const RedFormat = 1028;
  119. const RedIntegerFormat = 1029;
  120. const RGFormat = 1030;
  121. const RGIntegerFormat = 1031;
  122. const RGBIntegerFormat = 1032;
  123. const RGBAIntegerFormat = 1033;
  124. const RGB_S3TC_DXT1_Format = 33776;
  125. const RGBA_S3TC_DXT1_Format = 33777;
  126. const RGBA_S3TC_DXT3_Format = 33778;
  127. const RGBA_S3TC_DXT5_Format = 33779;
  128. const RGB_PVRTC_4BPPV1_Format = 35840;
  129. const RGB_PVRTC_2BPPV1_Format = 35841;
  130. const RGBA_PVRTC_4BPPV1_Format = 35842;
  131. const RGBA_PVRTC_2BPPV1_Format = 35843;
  132. const RGB_ETC1_Format = 36196;
  133. const RGB_ETC2_Format = 37492;
  134. const RGBA_ETC2_EAC_Format = 37496;
  135. const RGBA_ASTC_4x4_Format = 37808;
  136. const RGBA_ASTC_5x4_Format = 37809;
  137. const RGBA_ASTC_5x5_Format = 37810;
  138. const RGBA_ASTC_6x5_Format = 37811;
  139. const RGBA_ASTC_6x6_Format = 37812;
  140. const RGBA_ASTC_8x5_Format = 37813;
  141. const RGBA_ASTC_8x6_Format = 37814;
  142. const RGBA_ASTC_8x8_Format = 37815;
  143. const RGBA_ASTC_10x5_Format = 37816;
  144. const RGBA_ASTC_10x6_Format = 37817;
  145. const RGBA_ASTC_10x8_Format = 37818;
  146. const RGBA_ASTC_10x10_Format = 37819;
  147. const RGBA_ASTC_12x10_Format = 37820;
  148. const RGBA_ASTC_12x12_Format = 37821;
  149. const RGBA_BPTC_Format = 36492;
  150. const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  151. const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  152. const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  153. const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  154. const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  155. const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  156. const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  157. const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  158. const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  159. const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  160. const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  161. const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  162. const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  163. const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  164. const LoopOnce = 2200;
  165. const LoopRepeat = 2201;
  166. const LoopPingPong = 2202;
  167. const InterpolateDiscrete = 2300;
  168. const InterpolateLinear = 2301;
  169. const InterpolateSmooth = 2302;
  170. const ZeroCurvatureEnding = 2400;
  171. const ZeroSlopeEnding = 2401;
  172. const WrapAroundEnding = 2402;
  173. const NormalAnimationBlendMode = 2500;
  174. const AdditiveAnimationBlendMode = 2501;
  175. const TrianglesDrawMode = 0;
  176. const TriangleStripDrawMode = 1;
  177. const TriangleFanDrawMode = 2;
  178. const LinearEncoding = 3000;
  179. const sRGBEncoding = 3001;
  180. const GammaEncoding = 3007;
  181. const RGBEEncoding = 3002;
  182. const LogLuvEncoding = 3003;
  183. const RGBM7Encoding = 3004;
  184. const RGBM16Encoding = 3005;
  185. const RGBDEncoding = 3006;
  186. const BasicDepthPacking = 3200;
  187. const RGBADepthPacking = 3201;
  188. const TangentSpaceNormalMap = 0;
  189. const ObjectSpaceNormalMap = 1;
  190. const ZeroStencilOp = 0;
  191. const KeepStencilOp = 7680;
  192. const ReplaceStencilOp = 7681;
  193. const IncrementStencilOp = 7682;
  194. const DecrementStencilOp = 7683;
  195. const IncrementWrapStencilOp = 34055;
  196. const DecrementWrapStencilOp = 34056;
  197. const InvertStencilOp = 5386;
  198. const NeverStencilFunc = 512;
  199. const LessStencilFunc = 513;
  200. const EqualStencilFunc = 514;
  201. const LessEqualStencilFunc = 515;
  202. const GreaterStencilFunc = 516;
  203. const NotEqualStencilFunc = 517;
  204. const GreaterEqualStencilFunc = 518;
  205. const AlwaysStencilFunc = 519;
  206. const StaticDrawUsage = 35044;
  207. const DynamicDrawUsage = 35048;
  208. const StreamDrawUsage = 35040;
  209. const StaticReadUsage = 35045;
  210. const DynamicReadUsage = 35049;
  211. const StreamReadUsage = 35041;
  212. const StaticCopyUsage = 35046;
  213. const DynamicCopyUsage = 35050;
  214. const StreamCopyUsage = 35042;
  215. const GLSL1 = '100';
  216. const GLSL3 = '300 es';
  217. /**
  218. * https://github.com/mrdoob/eventdispatcher.js/
  219. */
  220. class EventDispatcher {
  221. addEventListener(type, listener) {
  222. if (this._listeners === undefined) this._listeners = {};
  223. const listeners = this._listeners;
  224. if (listeners[type] === undefined) {
  225. listeners[type] = [];
  226. }
  227. if (listeners[type].indexOf(listener) === -1) {
  228. listeners[type].push(listener);
  229. }
  230. }
  231. hasEventListener(type, listener) {
  232. if (this._listeners === undefined) return false;
  233. const listeners = this._listeners;
  234. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  235. }
  236. removeEventListener(type, listener) {
  237. if (this._listeners === undefined) return;
  238. const listeners = this._listeners;
  239. const listenerArray = listeners[type];
  240. if (listenerArray !== undefined) {
  241. const index = listenerArray.indexOf(listener);
  242. if (index !== -1) {
  243. listenerArray.splice(index, 1);
  244. }
  245. }
  246. }
  247. dispatchEvent(event) {
  248. if (this._listeners === undefined) return;
  249. const listeners = this._listeners;
  250. const listenerArray = listeners[event.type];
  251. if (listenerArray !== undefined) {
  252. event.target = this; // Make a copy, in case listeners are removed while iterating.
  253. const array = listenerArray.slice(0);
  254. for (let i = 0, l = array.length; i < l; i++) {
  255. array[i].call(this, event);
  256. }
  257. event.target = null;
  258. }
  259. }
  260. }
  261. const _lut = [];
  262. for (let i = 0; i < 256; i++) {
  263. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  264. }
  265. let _seed = 1234567;
  266. const DEG2RAD = Math.PI / 180;
  267. const RAD2DEG = 180 / Math.PI; // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  268. function generateUUID() {
  269. const d0 = Math.random() * 0xffffffff | 0;
  270. const d1 = Math.random() * 0xffffffff | 0;
  271. const d2 = Math.random() * 0xffffffff | 0;
  272. const d3 = Math.random() * 0xffffffff | 0;
  273. const uuid = _lut[d0 & 0xff] + _lut[d0 >> 8 & 0xff] + _lut[d0 >> 16 & 0xff] + _lut[d0 >> 24 & 0xff] + '-' + _lut[d1 & 0xff] + _lut[d1 >> 8 & 0xff] + '-' + _lut[d1 >> 16 & 0x0f | 0x40] + _lut[d1 >> 24 & 0xff] + '-' + _lut[d2 & 0x3f | 0x80] + _lut[d2 >> 8 & 0xff] + '-' + _lut[d2 >> 16 & 0xff] + _lut[d2 >> 24 & 0xff] + _lut[d3 & 0xff] + _lut[d3 >> 8 & 0xff] + _lut[d3 >> 16 & 0xff] + _lut[d3 >> 24 & 0xff]; // .toUpperCase() here flattens concatenated strings to save heap memory space.
  274. return uuid.toUpperCase();
  275. }
  276. function clamp(value, min, max) {
  277. return Math.max(min, Math.min(max, value));
  278. } // compute euclidian modulo of m % n
  279. // https://en.wikipedia.org/wiki/Modulo_operation
  280. function euclideanModulo(n, m) {
  281. return (n % m + m) % m;
  282. } // Linear mapping from range <a1, a2> to range <b1, b2>
  283. function mapLinear(x, a1, a2, b1, b2) {
  284. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  285. } // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  286. function inverseLerp(x, y, value) {
  287. if (x !== y) {
  288. return (value - x) / (y - x);
  289. } else {
  290. return 0;
  291. }
  292. } // https://en.wikipedia.org/wiki/Linear_interpolation
  293. function lerp(x, y, t) {
  294. return (1 - t) * x + t * y;
  295. } // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  296. function damp(x, y, lambda, dt) {
  297. return lerp(x, y, 1 - Math.exp(-lambda * dt));
  298. } // https://www.desmos.com/calculator/vcsjnyz7x4
  299. function pingpong(x, length = 1) {
  300. return length - Math.abs(euclideanModulo(x, length * 2) - length);
  301. } // http://en.wikipedia.org/wiki/Smoothstep
  302. function smoothstep(x, min, max) {
  303. if (x <= min) return 0;
  304. if (x >= max) return 1;
  305. x = (x - min) / (max - min);
  306. return x * x * (3 - 2 * x);
  307. }
  308. function smootherstep(x, min, max) {
  309. if (x <= min) return 0;
  310. if (x >= max) return 1;
  311. x = (x - min) / (max - min);
  312. return x * x * x * (x * (x * 6 - 15) + 10);
  313. } // Random integer from <low, high> interval
  314. function randInt(low, high) {
  315. return low + Math.floor(Math.random() * (high - low + 1));
  316. } // Random float from <low, high> interval
  317. function randFloat(low, high) {
  318. return low + Math.random() * (high - low);
  319. } // Random float from <-range/2, range/2> interval
  320. function randFloatSpread(range) {
  321. return range * (0.5 - Math.random());
  322. } // Deterministic pseudo-random float in the interval [ 0, 1 ]
  323. function seededRandom(s) {
  324. if (s !== undefined) _seed = s % 2147483647; // Park-Miller algorithm
  325. _seed = _seed * 16807 % 2147483647;
  326. return (_seed - 1) / 2147483646;
  327. }
  328. function degToRad(degrees) {
  329. return degrees * DEG2RAD;
  330. }
  331. function radToDeg(radians) {
  332. return radians * RAD2DEG;
  333. }
  334. function isPowerOfTwo(value) {
  335. return (value & value - 1) === 0 && value !== 0;
  336. }
  337. function ceilPowerOfTwo(value) {
  338. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  339. }
  340. function floorPowerOfTwo(value) {
  341. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  342. }
  343. function setQuaternionFromProperEuler(q, a, b, c, order) {
  344. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  345. // rotations are applied to the axes in the order specified by 'order'
  346. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  347. // angles are in radians
  348. const cos = Math.cos;
  349. const sin = Math.sin;
  350. const c2 = cos(b / 2);
  351. const s2 = sin(b / 2);
  352. const c13 = cos((a + c) / 2);
  353. const s13 = sin((a + c) / 2);
  354. const c1_3 = cos((a - c) / 2);
  355. const s1_3 = sin((a - c) / 2);
  356. const c3_1 = cos((c - a) / 2);
  357. const s3_1 = sin((c - a) / 2);
  358. switch (order) {
  359. case 'XYX':
  360. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  361. break;
  362. case 'YZY':
  363. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  364. break;
  365. case 'ZXZ':
  366. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  367. break;
  368. case 'XZX':
  369. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  370. break;
  371. case 'YXY':
  372. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  373. break;
  374. case 'ZYZ':
  375. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  376. break;
  377. default:
  378. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
  379. }
  380. }
  381. var MathUtils = /*#__PURE__*/Object.freeze({
  382. __proto__: null,
  383. DEG2RAD: DEG2RAD,
  384. RAD2DEG: RAD2DEG,
  385. generateUUID: generateUUID,
  386. clamp: clamp,
  387. euclideanModulo: euclideanModulo,
  388. mapLinear: mapLinear,
  389. inverseLerp: inverseLerp,
  390. lerp: lerp,
  391. damp: damp,
  392. pingpong: pingpong,
  393. smoothstep: smoothstep,
  394. smootherstep: smootherstep,
  395. randInt: randInt,
  396. randFloat: randFloat,
  397. randFloatSpread: randFloatSpread,
  398. seededRandom: seededRandom,
  399. degToRad: degToRad,
  400. radToDeg: radToDeg,
  401. isPowerOfTwo: isPowerOfTwo,
  402. ceilPowerOfTwo: ceilPowerOfTwo,
  403. floorPowerOfTwo: floorPowerOfTwo,
  404. setQuaternionFromProperEuler: setQuaternionFromProperEuler
  405. });
  406. class Vector2 {
  407. constructor(x = 0, y = 0) {
  408. this.x = x;
  409. this.y = y;
  410. }
  411. get width() {
  412. return this.x;
  413. }
  414. set width(value) {
  415. this.x = value;
  416. }
  417. get height() {
  418. return this.y;
  419. }
  420. set height(value) {
  421. this.y = value;
  422. }
  423. set(x, y) {
  424. this.x = x;
  425. this.y = y;
  426. return this;
  427. }
  428. setScalar(scalar) {
  429. this.x = scalar;
  430. this.y = scalar;
  431. return this;
  432. }
  433. setX(x) {
  434. this.x = x;
  435. return this;
  436. }
  437. setY(y) {
  438. this.y = y;
  439. return this;
  440. }
  441. setComponent(index, value) {
  442. switch (index) {
  443. case 0:
  444. this.x = value;
  445. break;
  446. case 1:
  447. this.y = value;
  448. break;
  449. default:
  450. throw new Error('index is out of range: ' + index);
  451. }
  452. return this;
  453. }
  454. getComponent(index) {
  455. switch (index) {
  456. case 0:
  457. return this.x;
  458. case 1:
  459. return this.y;
  460. default:
  461. throw new Error('index is out of range: ' + index);
  462. }
  463. }
  464. clone() {
  465. return new this.constructor(this.x, this.y);
  466. }
  467. copy(v) {
  468. this.x = v.x;
  469. this.y = v.y;
  470. return this;
  471. }
  472. add(v, w) {
  473. if (w !== undefined) {
  474. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  475. return this.addVectors(v, w);
  476. }
  477. this.x += v.x;
  478. this.y += v.y;
  479. return this;
  480. }
  481. addScalar(s) {
  482. this.x += s;
  483. this.y += s;
  484. return this;
  485. }
  486. addVectors(a, b) {
  487. this.x = a.x + b.x;
  488. this.y = a.y + b.y;
  489. return this;
  490. }
  491. addScaledVector(v, s) {
  492. this.x += v.x * s;
  493. this.y += v.y * s;
  494. return this;
  495. }
  496. sub(v, w) {
  497. if (w !== undefined) {
  498. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  499. return this.subVectors(v, w);
  500. }
  501. this.x -= v.x;
  502. this.y -= v.y;
  503. return this;
  504. }
  505. subScalar(s) {
  506. this.x -= s;
  507. this.y -= s;
  508. return this;
  509. }
  510. subVectors(a, b) {
  511. this.x = a.x - b.x;
  512. this.y = a.y - b.y;
  513. return this;
  514. }
  515. multiply(v) {
  516. this.x *= v.x;
  517. this.y *= v.y;
  518. return this;
  519. }
  520. multiplyScalar(scalar) {
  521. this.x *= scalar;
  522. this.y *= scalar;
  523. return this;
  524. }
  525. divide(v) {
  526. this.x /= v.x;
  527. this.y /= v.y;
  528. return this;
  529. }
  530. divideScalar(scalar) {
  531. return this.multiplyScalar(1 / scalar);
  532. }
  533. applyMatrix3(m) {
  534. const x = this.x,
  535. y = this.y;
  536. const e = m.elements;
  537. this.x = e[0] * x + e[3] * y + e[6];
  538. this.y = e[1] * x + e[4] * y + e[7];
  539. return this;
  540. }
  541. min(v) {
  542. this.x = Math.min(this.x, v.x);
  543. this.y = Math.min(this.y, v.y);
  544. return this;
  545. }
  546. max(v) {
  547. this.x = Math.max(this.x, v.x);
  548. this.y = Math.max(this.y, v.y);
  549. return this;
  550. }
  551. clamp(min, max) {
  552. // assumes min < max, componentwise
  553. this.x = Math.max(min.x, Math.min(max.x, this.x));
  554. this.y = Math.max(min.y, Math.min(max.y, this.y));
  555. return this;
  556. }
  557. clampScalar(minVal, maxVal) {
  558. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  559. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  560. return this;
  561. }
  562. clampLength(min, max) {
  563. const length = this.length();
  564. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  565. }
  566. floor() {
  567. this.x = Math.floor(this.x);
  568. this.y = Math.floor(this.y);
  569. return this;
  570. }
  571. ceil() {
  572. this.x = Math.ceil(this.x);
  573. this.y = Math.ceil(this.y);
  574. return this;
  575. }
  576. round() {
  577. this.x = Math.round(this.x);
  578. this.y = Math.round(this.y);
  579. return this;
  580. }
  581. roundToZero() {
  582. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  583. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  584. return this;
  585. }
  586. negate() {
  587. this.x = -this.x;
  588. this.y = -this.y;
  589. return this;
  590. }
  591. dot(v) {
  592. return this.x * v.x + this.y * v.y;
  593. }
  594. cross(v) {
  595. return this.x * v.y - this.y * v.x;
  596. }
  597. lengthSq() {
  598. return this.x * this.x + this.y * this.y;
  599. }
  600. length() {
  601. return Math.sqrt(this.x * this.x + this.y * this.y);
  602. }
  603. manhattanLength() {
  604. return Math.abs(this.x) + Math.abs(this.y);
  605. }
  606. normalize() {
  607. return this.divideScalar(this.length() || 1);
  608. }
  609. angle() {
  610. // computes the angle in radians with respect to the positive x-axis
  611. const angle = Math.atan2(-this.y, -this.x) + Math.PI;
  612. return angle;
  613. }
  614. distanceTo(v) {
  615. return Math.sqrt(this.distanceToSquared(v));
  616. }
  617. distanceToSquared(v) {
  618. const dx = this.x - v.x,
  619. dy = this.y - v.y;
  620. return dx * dx + dy * dy;
  621. }
  622. manhattanDistanceTo(v) {
  623. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  624. }
  625. setLength(length) {
  626. return this.normalize().multiplyScalar(length);
  627. }
  628. lerp(v, alpha) {
  629. this.x += (v.x - this.x) * alpha;
  630. this.y += (v.y - this.y) * alpha;
  631. return this;
  632. }
  633. lerpVectors(v1, v2, alpha) {
  634. this.x = v1.x + (v2.x - v1.x) * alpha;
  635. this.y = v1.y + (v2.y - v1.y) * alpha;
  636. return this;
  637. }
  638. equals(v) {
  639. return v.x === this.x && v.y === this.y;
  640. }
  641. fromArray(array, offset = 0) {
  642. this.x = array[offset];
  643. this.y = array[offset + 1];
  644. return this;
  645. }
  646. toArray(array = [], offset = 0) {
  647. array[offset] = this.x;
  648. array[offset + 1] = this.y;
  649. return array;
  650. }
  651. fromBufferAttribute(attribute, index, offset) {
  652. if (offset !== undefined) {
  653. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  654. }
  655. this.x = attribute.getX(index);
  656. this.y = attribute.getY(index);
  657. return this;
  658. }
  659. rotateAround(center, angle) {
  660. const c = Math.cos(angle),
  661. s = Math.sin(angle);
  662. const x = this.x - center.x;
  663. const y = this.y - center.y;
  664. this.x = x * c - y * s + center.x;
  665. this.y = x * s + y * c + center.y;
  666. return this;
  667. }
  668. random() {
  669. this.x = Math.random();
  670. this.y = Math.random();
  671. return this;
  672. }
  673. }
  674. Vector2.prototype.isVector2 = true;
  675. class Matrix3 {
  676. constructor() {
  677. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  678. if (arguments.length > 0) {
  679. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  680. }
  681. }
  682. set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  683. const te = this.elements;
  684. te[0] = n11;
  685. te[1] = n21;
  686. te[2] = n31;
  687. te[3] = n12;
  688. te[4] = n22;
  689. te[5] = n32;
  690. te[6] = n13;
  691. te[7] = n23;
  692. te[8] = n33;
  693. return this;
  694. }
  695. identity() {
  696. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  697. return this;
  698. }
  699. copy(m) {
  700. const te = this.elements;
  701. const me = m.elements;
  702. te[0] = me[0];
  703. te[1] = me[1];
  704. te[2] = me[2];
  705. te[3] = me[3];
  706. te[4] = me[4];
  707. te[5] = me[5];
  708. te[6] = me[6];
  709. te[7] = me[7];
  710. te[8] = me[8];
  711. return this;
  712. }
  713. extractBasis(xAxis, yAxis, zAxis) {
  714. xAxis.setFromMatrix3Column(this, 0);
  715. yAxis.setFromMatrix3Column(this, 1);
  716. zAxis.setFromMatrix3Column(this, 2);
  717. return this;
  718. }
  719. setFromMatrix4(m) {
  720. const me = m.elements;
  721. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  722. return this;
  723. }
  724. multiply(m) {
  725. return this.multiplyMatrices(this, m);
  726. }
  727. premultiply(m) {
  728. return this.multiplyMatrices(m, this);
  729. }
  730. multiplyMatrices(a, b) {
  731. const ae = a.elements;
  732. const be = b.elements;
  733. const te = this.elements;
  734. const a11 = ae[0],
  735. a12 = ae[3],
  736. a13 = ae[6];
  737. const a21 = ae[1],
  738. a22 = ae[4],
  739. a23 = ae[7];
  740. const a31 = ae[2],
  741. a32 = ae[5],
  742. a33 = ae[8];
  743. const b11 = be[0],
  744. b12 = be[3],
  745. b13 = be[6];
  746. const b21 = be[1],
  747. b22 = be[4],
  748. b23 = be[7];
  749. const b31 = be[2],
  750. b32 = be[5],
  751. b33 = be[8];
  752. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  753. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  754. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  755. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  756. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  757. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  758. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  759. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  760. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  761. return this;
  762. }
  763. multiplyScalar(s) {
  764. const te = this.elements;
  765. te[0] *= s;
  766. te[3] *= s;
  767. te[6] *= s;
  768. te[1] *= s;
  769. te[4] *= s;
  770. te[7] *= s;
  771. te[2] *= s;
  772. te[5] *= s;
  773. te[8] *= s;
  774. return this;
  775. }
  776. determinant() {
  777. const te = this.elements;
  778. const a = te[0],
  779. b = te[1],
  780. c = te[2],
  781. d = te[3],
  782. e = te[4],
  783. f = te[5],
  784. g = te[6],
  785. h = te[7],
  786. i = te[8];
  787. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  788. }
  789. invert() {
  790. const te = this.elements,
  791. n11 = te[0],
  792. n21 = te[1],
  793. n31 = te[2],
  794. n12 = te[3],
  795. n22 = te[4],
  796. n32 = te[5],
  797. n13 = te[6],
  798. n23 = te[7],
  799. n33 = te[8],
  800. t11 = n33 * n22 - n32 * n23,
  801. t12 = n32 * n13 - n33 * n12,
  802. t13 = n23 * n12 - n22 * n13,
  803. det = n11 * t11 + n21 * t12 + n31 * t13;
  804. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  805. const detInv = 1 / det;
  806. te[0] = t11 * detInv;
  807. te[1] = (n31 * n23 - n33 * n21) * detInv;
  808. te[2] = (n32 * n21 - n31 * n22) * detInv;
  809. te[3] = t12 * detInv;
  810. te[4] = (n33 * n11 - n31 * n13) * detInv;
  811. te[5] = (n31 * n12 - n32 * n11) * detInv;
  812. te[6] = t13 * detInv;
  813. te[7] = (n21 * n13 - n23 * n11) * detInv;
  814. te[8] = (n22 * n11 - n21 * n12) * detInv;
  815. return this;
  816. }
  817. transpose() {
  818. let tmp;
  819. const m = this.elements;
  820. tmp = m[1];
  821. m[1] = m[3];
  822. m[3] = tmp;
  823. tmp = m[2];
  824. m[2] = m[6];
  825. m[6] = tmp;
  826. tmp = m[5];
  827. m[5] = m[7];
  828. m[7] = tmp;
  829. return this;
  830. }
  831. getNormalMatrix(matrix4) {
  832. return this.setFromMatrix4(matrix4).invert().transpose();
  833. }
  834. transposeIntoArray(r) {
  835. const m = this.elements;
  836. r[0] = m[0];
  837. r[1] = m[3];
  838. r[2] = m[6];
  839. r[3] = m[1];
  840. r[4] = m[4];
  841. r[5] = m[7];
  842. r[6] = m[2];
  843. r[7] = m[5];
  844. r[8] = m[8];
  845. return this;
  846. }
  847. setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
  848. const c = Math.cos(rotation);
  849. const s = Math.sin(rotation);
  850. this.set(sx * c, sx * s, -sx * (c * cx + s * cy) + cx + tx, -sy * s, sy * c, -sy * (-s * cx + c * cy) + cy + ty, 0, 0, 1);
  851. return this;
  852. }
  853. scale(sx, sy) {
  854. const te = this.elements;
  855. te[0] *= sx;
  856. te[3] *= sx;
  857. te[6] *= sx;
  858. te[1] *= sy;
  859. te[4] *= sy;
  860. te[7] *= sy;
  861. return this;
  862. }
  863. rotate(theta) {
  864. const c = Math.cos(theta);
  865. const s = Math.sin(theta);
  866. const te = this.elements;
  867. const a11 = te[0],
  868. a12 = te[3],
  869. a13 = te[6];
  870. const a21 = te[1],
  871. a22 = te[4],
  872. a23 = te[7];
  873. te[0] = c * a11 + s * a21;
  874. te[3] = c * a12 + s * a22;
  875. te[6] = c * a13 + s * a23;
  876. te[1] = -s * a11 + c * a21;
  877. te[4] = -s * a12 + c * a22;
  878. te[7] = -s * a13 + c * a23;
  879. return this;
  880. }
  881. translate(tx, ty) {
  882. const te = this.elements;
  883. te[0] += tx * te[2];
  884. te[3] += tx * te[5];
  885. te[6] += tx * te[8];
  886. te[1] += ty * te[2];
  887. te[4] += ty * te[5];
  888. te[7] += ty * te[8];
  889. return this;
  890. }
  891. equals(matrix) {
  892. const te = this.elements;
  893. const me = matrix.elements;
  894. for (let i = 0; i < 9; i++) {
  895. if (te[i] !== me[i]) return false;
  896. }
  897. return true;
  898. }
  899. fromArray(array, offset = 0) {
  900. for (let i = 0; i < 9; i++) {
  901. this.elements[i] = array[i + offset];
  902. }
  903. return this;
  904. }
  905. toArray(array = [], offset = 0) {
  906. const te = this.elements;
  907. array[offset] = te[0];
  908. array[offset + 1] = te[1];
  909. array[offset + 2] = te[2];
  910. array[offset + 3] = te[3];
  911. array[offset + 4] = te[4];
  912. array[offset + 5] = te[5];
  913. array[offset + 6] = te[6];
  914. array[offset + 7] = te[7];
  915. array[offset + 8] = te[8];
  916. return array;
  917. }
  918. clone() {
  919. return new this.constructor().fromArray(this.elements);
  920. }
  921. }
  922. Matrix3.prototype.isMatrix3 = true;
  923. let _canvas;
  924. class ImageUtils {
  925. static getDataURL(image) {
  926. if (/^data:/i.test(image.src)) {
  927. return image.src;
  928. }
  929. if (typeof HTMLCanvasElement == 'undefined') {
  930. return image.src;
  931. }
  932. let canvas;
  933. if (image instanceof HTMLCanvasElement) {
  934. canvas = image;
  935. } else {
  936. if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  937. _canvas.width = image.width;
  938. _canvas.height = image.height;
  939. const context = _canvas.getContext('2d');
  940. if (image instanceof ImageData) {
  941. context.putImageData(image, 0, 0);
  942. } else {
  943. context.drawImage(image, 0, 0, image.width, image.height);
  944. }
  945. canvas = _canvas;
  946. }
  947. if (canvas.width > 2048 || canvas.height > 2048) {
  948. console.warn('THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image);
  949. return canvas.toDataURL('image/jpeg', 0.6);
  950. } else {
  951. return canvas.toDataURL('image/png');
  952. }
  953. }
  954. }
  955. let textureId = 0;
  956. class Texture extends EventDispatcher {
  957. constructor(image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding) {
  958. super();
  959. Object.defineProperty(this, 'id', {
  960. value: textureId++
  961. });
  962. this.uuid = generateUUID();
  963. this.name = '';
  964. this.image = image;
  965. this.mipmaps = [];
  966. this.mapping = mapping;
  967. this.wrapS = wrapS;
  968. this.wrapT = wrapT;
  969. this.magFilter = magFilter;
  970. this.minFilter = minFilter;
  971. this.anisotropy = anisotropy;
  972. this.format = format;
  973. this.internalFormat = null;
  974. this.type = type;
  975. this.offset = new Vector2(0, 0);
  976. this.repeat = new Vector2(1, 1);
  977. this.center = new Vector2(0, 0);
  978. this.rotation = 0;
  979. this.matrixAutoUpdate = true;
  980. this.matrix = new Matrix3();
  981. this.generateMipmaps = true;
  982. this.premultiplyAlpha = false;
  983. this.flipY = true;
  984. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  985. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  986. //
  987. // Also changing the encoding after already used by a Material will not automatically make the Material
  988. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  989. this.encoding = encoding;
  990. this.version = 0;
  991. this.onUpdate = null;
  992. this.isRenderTargetTexture = false;
  993. }
  994. updateMatrix() {
  995. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  996. }
  997. clone() {
  998. return new this.constructor().copy(this);
  999. }
  1000. copy(source) {
  1001. this.name = source.name;
  1002. this.image = source.image;
  1003. this.mipmaps = source.mipmaps.slice(0);
  1004. this.mapping = source.mapping;
  1005. this.wrapS = source.wrapS;
  1006. this.wrapT = source.wrapT;
  1007. this.magFilter = source.magFilter;
  1008. this.minFilter = source.minFilter;
  1009. this.anisotropy = source.anisotropy;
  1010. this.format = source.format;
  1011. this.internalFormat = source.internalFormat;
  1012. this.type = source.type;
  1013. this.offset.copy(source.offset);
  1014. this.repeat.copy(source.repeat);
  1015. this.center.copy(source.center);
  1016. this.rotation = source.rotation;
  1017. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1018. this.matrix.copy(source.matrix);
  1019. this.generateMipmaps = source.generateMipmaps;
  1020. this.premultiplyAlpha = source.premultiplyAlpha;
  1021. this.flipY = source.flipY;
  1022. this.unpackAlignment = source.unpackAlignment;
  1023. this.encoding = source.encoding;
  1024. return this;
  1025. }
  1026. toJSON(meta) {
  1027. const isRootObject = meta === undefined || typeof meta === 'string';
  1028. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1029. return meta.textures[this.uuid];
  1030. }
  1031. const output = {
  1032. metadata: {
  1033. version: 4.5,
  1034. type: 'Texture',
  1035. generator: 'Texture.toJSON'
  1036. },
  1037. uuid: this.uuid,
  1038. name: this.name,
  1039. mapping: this.mapping,
  1040. repeat: [this.repeat.x, this.repeat.y],
  1041. offset: [this.offset.x, this.offset.y],
  1042. center: [this.center.x, this.center.y],
  1043. rotation: this.rotation,
  1044. wrap: [this.wrapS, this.wrapT],
  1045. format: this.format,
  1046. type: this.type,
  1047. encoding: this.encoding,
  1048. minFilter: this.minFilter,
  1049. magFilter: this.magFilter,
  1050. anisotropy: this.anisotropy,
  1051. flipY: this.flipY,
  1052. premultiplyAlpha: this.premultiplyAlpha,
  1053. unpackAlignment: this.unpackAlignment
  1054. };
  1055. if (this.image !== undefined) {
  1056. // TODO: Move to THREE.Image
  1057. const image = this.image;
  1058. if (image.uuid === undefined) {
  1059. image.uuid = generateUUID(); // UGH
  1060. }
  1061. if (!isRootObject && meta.images[image.uuid] === undefined) {
  1062. let url;
  1063. if (Array.isArray(image)) {
  1064. // process array of images e.g. CubeTexture
  1065. url = [];
  1066. for (let i = 0, l = image.length; i < l; i++) {
  1067. // check cube texture with data textures
  1068. if (image[i].isDataTexture) {
  1069. url.push(serializeImage(image[i].image));
  1070. } else {
  1071. url.push(serializeImage(image[i]));
  1072. }
  1073. }
  1074. } else {
  1075. // process single image
  1076. url = serializeImage(image);
  1077. }
  1078. meta.images[image.uuid] = {
  1079. uuid: image.uuid,
  1080. url: url
  1081. };
  1082. }
  1083. output.image = image.uuid;
  1084. }
  1085. if (!isRootObject) {
  1086. meta.textures[this.uuid] = output;
  1087. }
  1088. return output;
  1089. }
  1090. dispose() {
  1091. this.dispatchEvent({
  1092. type: 'dispose'
  1093. });
  1094. }
  1095. transformUv(uv) {
  1096. if (this.mapping !== UVMapping) return uv;
  1097. uv.applyMatrix3(this.matrix);
  1098. if (uv.x < 0 || uv.x > 1) {
  1099. switch (this.wrapS) {
  1100. case RepeatWrapping:
  1101. uv.x = uv.x - Math.floor(uv.x);
  1102. break;
  1103. case ClampToEdgeWrapping:
  1104. uv.x = uv.x < 0 ? 0 : 1;
  1105. break;
  1106. case MirroredRepeatWrapping:
  1107. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1108. uv.x = Math.ceil(uv.x) - uv.x;
  1109. } else {
  1110. uv.x = uv.x - Math.floor(uv.x);
  1111. }
  1112. break;
  1113. }
  1114. }
  1115. if (uv.y < 0 || uv.y > 1) {
  1116. switch (this.wrapT) {
  1117. case RepeatWrapping:
  1118. uv.y = uv.y - Math.floor(uv.y);
  1119. break;
  1120. case ClampToEdgeWrapping:
  1121. uv.y = uv.y < 0 ? 0 : 1;
  1122. break;
  1123. case MirroredRepeatWrapping:
  1124. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1125. uv.y = Math.ceil(uv.y) - uv.y;
  1126. } else {
  1127. uv.y = uv.y - Math.floor(uv.y);
  1128. }
  1129. break;
  1130. }
  1131. }
  1132. if (this.flipY) {
  1133. uv.y = 1 - uv.y;
  1134. }
  1135. return uv;
  1136. }
  1137. set needsUpdate(value) {
  1138. if (value === true) this.version++;
  1139. }
  1140. }
  1141. Texture.DEFAULT_IMAGE = undefined;
  1142. Texture.DEFAULT_MAPPING = UVMapping;
  1143. Texture.prototype.isTexture = true;
  1144. function serializeImage(image) {
  1145. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1146. // default images
  1147. return ImageUtils.getDataURL(image);
  1148. } else {
  1149. if (image.data) {
  1150. // images of DataTexture
  1151. return {
  1152. data: Array.prototype.slice.call(image.data),
  1153. width: image.width,
  1154. height: image.height,
  1155. type: image.data.constructor.name
  1156. };
  1157. } else {
  1158. console.warn('THREE.Texture: Unable to serialize Texture.');
  1159. return {};
  1160. }
  1161. }
  1162. }
  1163. class Vector4 {
  1164. constructor(x = 0, y = 0, z = 0, w = 1) {
  1165. this.x = x;
  1166. this.y = y;
  1167. this.z = z;
  1168. this.w = w;
  1169. }
  1170. get width() {
  1171. return this.z;
  1172. }
  1173. set width(value) {
  1174. this.z = value;
  1175. }
  1176. get height() {
  1177. return this.w;
  1178. }
  1179. set height(value) {
  1180. this.w = value;
  1181. }
  1182. set(x, y, z, w) {
  1183. this.x = x;
  1184. this.y = y;
  1185. this.z = z;
  1186. this.w = w;
  1187. return this;
  1188. }
  1189. setScalar(scalar) {
  1190. this.x = scalar;
  1191. this.y = scalar;
  1192. this.z = scalar;
  1193. this.w = scalar;
  1194. return this;
  1195. }
  1196. setX(x) {
  1197. this.x = x;
  1198. return this;
  1199. }
  1200. setY(y) {
  1201. this.y = y;
  1202. return this;
  1203. }
  1204. setZ(z) {
  1205. this.z = z;
  1206. return this;
  1207. }
  1208. setW(w) {
  1209. this.w = w;
  1210. return this;
  1211. }
  1212. setComponent(index, value) {
  1213. switch (index) {
  1214. case 0:
  1215. this.x = value;
  1216. break;
  1217. case 1:
  1218. this.y = value;
  1219. break;
  1220. case 2:
  1221. this.z = value;
  1222. break;
  1223. case 3:
  1224. this.w = value;
  1225. break;
  1226. default:
  1227. throw new Error('index is out of range: ' + index);
  1228. }
  1229. return this;
  1230. }
  1231. getComponent(index) {
  1232. switch (index) {
  1233. case 0:
  1234. return this.x;
  1235. case 1:
  1236. return this.y;
  1237. case 2:
  1238. return this.z;
  1239. case 3:
  1240. return this.w;
  1241. default:
  1242. throw new Error('index is out of range: ' + index);
  1243. }
  1244. }
  1245. clone() {
  1246. return new this.constructor(this.x, this.y, this.z, this.w);
  1247. }
  1248. copy(v) {
  1249. this.x = v.x;
  1250. this.y = v.y;
  1251. this.z = v.z;
  1252. this.w = v.w !== undefined ? v.w : 1;
  1253. return this;
  1254. }
  1255. add(v, w) {
  1256. if (w !== undefined) {
  1257. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  1258. return this.addVectors(v, w);
  1259. }
  1260. this.x += v.x;
  1261. this.y += v.y;
  1262. this.z += v.z;
  1263. this.w += v.w;
  1264. return this;
  1265. }
  1266. addScalar(s) {
  1267. this.x += s;
  1268. this.y += s;
  1269. this.z += s;
  1270. this.w += s;
  1271. return this;
  1272. }
  1273. addVectors(a, b) {
  1274. this.x = a.x + b.x;
  1275. this.y = a.y + b.y;
  1276. this.z = a.z + b.z;
  1277. this.w = a.w + b.w;
  1278. return this;
  1279. }
  1280. addScaledVector(v, s) {
  1281. this.x += v.x * s;
  1282. this.y += v.y * s;
  1283. this.z += v.z * s;
  1284. this.w += v.w * s;
  1285. return this;
  1286. }
  1287. sub(v, w) {
  1288. if (w !== undefined) {
  1289. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  1290. return this.subVectors(v, w);
  1291. }
  1292. this.x -= v.x;
  1293. this.y -= v.y;
  1294. this.z -= v.z;
  1295. this.w -= v.w;
  1296. return this;
  1297. }
  1298. subScalar(s) {
  1299. this.x -= s;
  1300. this.y -= s;
  1301. this.z -= s;
  1302. this.w -= s;
  1303. return this;
  1304. }
  1305. subVectors(a, b) {
  1306. this.x = a.x - b.x;
  1307. this.y = a.y - b.y;
  1308. this.z = a.z - b.z;
  1309. this.w = a.w - b.w;
  1310. return this;
  1311. }
  1312. multiply(v) {
  1313. this.x *= v.x;
  1314. this.y *= v.y;
  1315. this.z *= v.z;
  1316. this.w *= v.w;
  1317. return this;
  1318. }
  1319. multiplyScalar(scalar) {
  1320. this.x *= scalar;
  1321. this.y *= scalar;
  1322. this.z *= scalar;
  1323. this.w *= scalar;
  1324. return this;
  1325. }
  1326. applyMatrix4(m) {
  1327. const x = this.x,
  1328. y = this.y,
  1329. z = this.z,
  1330. w = this.w;
  1331. const e = m.elements;
  1332. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1333. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1334. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1335. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1336. return this;
  1337. }
  1338. divideScalar(scalar) {
  1339. return this.multiplyScalar(1 / scalar);
  1340. }
  1341. setAxisAngleFromQuaternion(q) {
  1342. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1343. // q is assumed to be normalized
  1344. this.w = 2 * Math.acos(q.w);
  1345. const s = Math.sqrt(1 - q.w * q.w);
  1346. if (s < 0.0001) {
  1347. this.x = 1;
  1348. this.y = 0;
  1349. this.z = 0;
  1350. } else {
  1351. this.x = q.x / s;
  1352. this.y = q.y / s;
  1353. this.z = q.z / s;
  1354. }
  1355. return this;
  1356. }
  1357. setAxisAngleFromRotationMatrix(m) {
  1358. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1359. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1360. let angle, x, y, z; // variables for result
  1361. const epsilon = 0.01,
  1362. // margin to allow for rounding errors
  1363. epsilon2 = 0.1,
  1364. // margin to distinguish between 0 and 180 degrees
  1365. te = m.elements,
  1366. m11 = te[0],
  1367. m12 = te[4],
  1368. m13 = te[8],
  1369. m21 = te[1],
  1370. m22 = te[5],
  1371. m23 = te[9],
  1372. m31 = te[2],
  1373. m32 = te[6],
  1374. m33 = te[10];
  1375. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  1376. // singularity found
  1377. // first check for identity matrix which must have +1 for all terms
  1378. // in leading diagonal and zero in other terms
  1379. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  1380. // this singularity is identity matrix so angle = 0
  1381. this.set(1, 0, 0, 0);
  1382. return this; // zero angle, arbitrary axis
  1383. } // otherwise this singularity is angle = 180
  1384. angle = Math.PI;
  1385. const xx = (m11 + 1) / 2;
  1386. const yy = (m22 + 1) / 2;
  1387. const zz = (m33 + 1) / 2;
  1388. const xy = (m12 + m21) / 4;
  1389. const xz = (m13 + m31) / 4;
  1390. const yz = (m23 + m32) / 4;
  1391. if (xx > yy && xx > zz) {
  1392. // m11 is the largest diagonal term
  1393. if (xx < epsilon) {
  1394. x = 0;
  1395. y = 0.707106781;
  1396. z = 0.707106781;
  1397. } else {
  1398. x = Math.sqrt(xx);
  1399. y = xy / x;
  1400. z = xz / x;
  1401. }
  1402. } else if (yy > zz) {
  1403. // m22 is the largest diagonal term
  1404. if (yy < epsilon) {
  1405. x = 0.707106781;
  1406. y = 0;
  1407. z = 0.707106781;
  1408. } else {
  1409. y = Math.sqrt(yy);
  1410. x = xy / y;
  1411. z = yz / y;
  1412. }
  1413. } else {
  1414. // m33 is the largest diagonal term so base result on this
  1415. if (zz < epsilon) {
  1416. x = 0.707106781;
  1417. y = 0.707106781;
  1418. z = 0;
  1419. } else {
  1420. z = Math.sqrt(zz);
  1421. x = xz / z;
  1422. y = yz / z;
  1423. }
  1424. }
  1425. this.set(x, y, z, angle);
  1426. return this; // return 180 deg rotation
  1427. } // as we have reached here there are no singularities so we can handle normally
  1428. let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  1429. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1430. // caught by singularity test above, but I've left it in just in case
  1431. this.x = (m32 - m23) / s;
  1432. this.y = (m13 - m31) / s;
  1433. this.z = (m21 - m12) / s;
  1434. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  1435. return this;
  1436. }
  1437. min(v) {
  1438. this.x = Math.min(this.x, v.x);
  1439. this.y = Math.min(this.y, v.y);
  1440. this.z = Math.min(this.z, v.z);
  1441. this.w = Math.min(this.w, v.w);
  1442. return this;
  1443. }
  1444. max(v) {
  1445. this.x = Math.max(this.x, v.x);
  1446. this.y = Math.max(this.y, v.y);
  1447. this.z = Math.max(this.z, v.z);
  1448. this.w = Math.max(this.w, v.w);
  1449. return this;
  1450. }
  1451. clamp(min, max) {
  1452. // assumes min < max, componentwise
  1453. this.x = Math.max(min.x, Math.min(max.x, this.x));
  1454. this.y = Math.max(min.y, Math.min(max.y, this.y));
  1455. this.z = Math.max(min.z, Math.min(max.z, this.z));
  1456. this.w = Math.max(min.w, Math.min(max.w, this.w));
  1457. return this;
  1458. }
  1459. clampScalar(minVal, maxVal) {
  1460. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  1461. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  1462. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  1463. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  1464. return this;
  1465. }
  1466. clampLength(min, max) {
  1467. const length = this.length();
  1468. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1469. }
  1470. floor() {
  1471. this.x = Math.floor(this.x);
  1472. this.y = Math.floor(this.y);
  1473. this.z = Math.floor(this.z);
  1474. this.w = Math.floor(this.w);
  1475. return this;
  1476. }
  1477. ceil() {
  1478. this.x = Math.ceil(this.x);
  1479. this.y = Math.ceil(this.y);
  1480. this.z = Math.ceil(this.z);
  1481. this.w = Math.ceil(this.w);
  1482. return this;
  1483. }
  1484. round() {
  1485. this.x = Math.round(this.x);
  1486. this.y = Math.round(this.y);
  1487. this.z = Math.round(this.z);
  1488. this.w = Math.round(this.w);
  1489. return this;
  1490. }
  1491. roundToZero() {
  1492. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1493. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1494. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  1495. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  1496. return this;
  1497. }
  1498. negate() {
  1499. this.x = -this.x;
  1500. this.y = -this.y;
  1501. this.z = -this.z;
  1502. this.w = -this.w;
  1503. return this;
  1504. }
  1505. dot(v) {
  1506. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1507. }
  1508. lengthSq() {
  1509. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1510. }
  1511. length() {
  1512. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1513. }
  1514. manhattanLength() {
  1515. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  1516. }
  1517. normalize() {
  1518. return this.divideScalar(this.length() || 1);
  1519. }
  1520. setLength(length) {
  1521. return this.normalize().multiplyScalar(length);
  1522. }
  1523. lerp(v, alpha) {
  1524. this.x += (v.x - this.x) * alpha;
  1525. this.y += (v.y - this.y) * alpha;
  1526. this.z += (v.z - this.z) * alpha;
  1527. this.w += (v.w - this.w) * alpha;
  1528. return this;
  1529. }
  1530. lerpVectors(v1, v2, alpha) {
  1531. this.x = v1.x + (v2.x - v1.x) * alpha;
  1532. this.y = v1.y + (v2.y - v1.y) * alpha;
  1533. this.z = v1.z + (v2.z - v1.z) * alpha;
  1534. this.w = v1.w + (v2.w - v1.w) * alpha;
  1535. return this;
  1536. }
  1537. equals(v) {
  1538. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  1539. }
  1540. fromArray(array, offset = 0) {
  1541. this.x = array[offset];
  1542. this.y = array[offset + 1];
  1543. this.z = array[offset + 2];
  1544. this.w = array[offset + 3];
  1545. return this;
  1546. }
  1547. toArray(array = [], offset = 0) {
  1548. array[offset] = this.x;
  1549. array[offset + 1] = this.y;
  1550. array[offset + 2] = this.z;
  1551. array[offset + 3] = this.w;
  1552. return array;
  1553. }
  1554. fromBufferAttribute(attribute, index, offset) {
  1555. if (offset !== undefined) {
  1556. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  1557. }
  1558. this.x = attribute.getX(index);
  1559. this.y = attribute.getY(index);
  1560. this.z = attribute.getZ(index);
  1561. this.w = attribute.getW(index);
  1562. return this;
  1563. }
  1564. random() {
  1565. this.x = Math.random();
  1566. this.y = Math.random();
  1567. this.z = Math.random();
  1568. this.w = Math.random();
  1569. return this;
  1570. }
  1571. }
  1572. Vector4.prototype.isVector4 = true;
  1573. /*
  1574. In options, we can specify:
  1575. * Texture parameters for an auto-generated target texture
  1576. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1577. */
  1578. class WebGLRenderTarget extends EventDispatcher {
  1579. constructor(width, height, options = {}) {
  1580. super();
  1581. this.width = width;
  1582. this.height = height;
  1583. this.depth = 1;
  1584. this.scissor = new Vector4(0, 0, width, height);
  1585. this.scissorTest = false;
  1586. this.viewport = new Vector4(0, 0, width, height);
  1587. this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  1588. this.texture.isRenderTargetTexture = true;
  1589. this.texture.image = {
  1590. width: width,
  1591. height: height,
  1592. depth: 1
  1593. };
  1594. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1595. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  1596. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1597. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1598. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1599. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1600. }
  1601. setTexture(texture) {
  1602. texture.image = {
  1603. width: this.width,
  1604. height: this.height,
  1605. depth: this.depth
  1606. };
  1607. this.texture = texture;
  1608. }
  1609. setSize(width, height, depth = 1) {
  1610. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1611. this.width = width;
  1612. this.height = height;
  1613. this.depth = depth;
  1614. this.texture.image.width = width;
  1615. this.texture.image.height = height;
  1616. this.texture.image.depth = depth;
  1617. this.dispose();
  1618. }
  1619. this.viewport.set(0, 0, width, height);
  1620. this.scissor.set(0, 0, width, height);
  1621. }
  1622. clone() {
  1623. return new this.constructor().copy(this);
  1624. }
  1625. copy(source) {
  1626. this.width = source.width;
  1627. this.height = source.height;
  1628. this.depth = source.depth;
  1629. this.viewport.copy(source.viewport);
  1630. this.texture = source.texture.clone();
  1631. this.texture.image = { ...this.texture.image
  1632. }; // See #20328.
  1633. this.depthBuffer = source.depthBuffer;
  1634. this.stencilBuffer = source.stencilBuffer;
  1635. this.depthTexture = source.depthTexture;
  1636. return this;
  1637. }
  1638. dispose() {
  1639. this.dispatchEvent({
  1640. type: 'dispose'
  1641. });
  1642. }
  1643. }
  1644. WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
  1645. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1646. constructor(width, height, count) {
  1647. super(width, height);
  1648. const texture = this.texture;
  1649. this.texture = [];
  1650. for (let i = 0; i < count; i++) {
  1651. this.texture[i] = texture.clone();
  1652. }
  1653. }
  1654. setSize(width, height, depth = 1) {
  1655. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1656. this.width = width;
  1657. this.height = height;
  1658. this.depth = depth;
  1659. for (let i = 0, il = this.texture.length; i < il; i++) {
  1660. this.texture[i].image.width = width;
  1661. this.texture[i].image.height = height;
  1662. this.texture[i].image.depth = depth;
  1663. }
  1664. this.dispose();
  1665. }
  1666. this.viewport.set(0, 0, width, height);
  1667. this.scissor.set(0, 0, width, height);
  1668. return this;
  1669. }
  1670. copy(source) {
  1671. this.dispose();
  1672. this.width = source.width;
  1673. this.height = source.height;
  1674. this.depth = source.depth;
  1675. this.viewport.set(0, 0, this.width, this.height);
  1676. this.scissor.set(0, 0, this.width, this.height);
  1677. this.depthBuffer = source.depthBuffer;
  1678. this.stencilBuffer = source.stencilBuffer;
  1679. this.depthTexture = source.depthTexture;
  1680. this.texture.length = 0;
  1681. for (let i = 0, il = source.texture.length; i < il; i++) {
  1682. this.texture[i] = source.texture[i].clone();
  1683. }
  1684. return this;
  1685. }
  1686. }
  1687. WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true;
  1688. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  1689. constructor(width, height, options) {
  1690. super(width, height, options);
  1691. this.samples = 4;
  1692. }
  1693. copy(source) {
  1694. super.copy.call(this, source);
  1695. this.samples = source.samples;
  1696. return this;
  1697. }
  1698. }
  1699. WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true;
  1700. class Quaternion {
  1701. constructor(x = 0, y = 0, z = 0, w = 1) {
  1702. this._x = x;
  1703. this._y = y;
  1704. this._z = z;
  1705. this._w = w;
  1706. }
  1707. static slerp(qa, qb, qm, t) {
  1708. console.warn('THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.');
  1709. return qm.slerpQuaternions(qa, qb, t);
  1710. }
  1711. static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  1712. // fuzz-free, array-based Quaternion SLERP operation
  1713. let x0 = src0[srcOffset0 + 0],
  1714. y0 = src0[srcOffset0 + 1],
  1715. z0 = src0[srcOffset0 + 2],
  1716. w0 = src0[srcOffset0 + 3];
  1717. const x1 = src1[srcOffset1 + 0],
  1718. y1 = src1[srcOffset1 + 1],
  1719. z1 = src1[srcOffset1 + 2],
  1720. w1 = src1[srcOffset1 + 3];
  1721. if (t === 0) {
  1722. dst[dstOffset + 0] = x0;
  1723. dst[dstOffset + 1] = y0;
  1724. dst[dstOffset + 2] = z0;
  1725. dst[dstOffset + 3] = w0;
  1726. return;
  1727. }
  1728. if (t === 1) {
  1729. dst[dstOffset + 0] = x1;
  1730. dst[dstOffset + 1] = y1;
  1731. dst[dstOffset + 2] = z1;
  1732. dst[dstOffset + 3] = w1;
  1733. return;
  1734. }
  1735. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  1736. let s = 1 - t;
  1737. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1738. dir = cos >= 0 ? 1 : -1,
  1739. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  1740. if (sqrSin > Number.EPSILON) {
  1741. const sin = Math.sqrt(sqrSin),
  1742. len = Math.atan2(sin, cos * dir);
  1743. s = Math.sin(s * len) / sin;
  1744. t = Math.sin(t * len) / sin;
  1745. }
  1746. const tDir = t * dir;
  1747. x0 = x0 * s + x1 * tDir;
  1748. y0 = y0 * s + y1 * tDir;
  1749. z0 = z0 * s + z1 * tDir;
  1750. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  1751. if (s === 1 - t) {
  1752. const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  1753. x0 *= f;
  1754. y0 *= f;
  1755. z0 *= f;
  1756. w0 *= f;
  1757. }
  1758. }
  1759. dst[dstOffset] = x0;
  1760. dst[dstOffset + 1] = y0;
  1761. dst[dstOffset + 2] = z0;
  1762. dst[dstOffset + 3] = w0;
  1763. }
  1764. static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  1765. const x0 = src0[srcOffset0];
  1766. const y0 = src0[srcOffset0 + 1];
  1767. const z0 = src0[srcOffset0 + 2];
  1768. const w0 = src0[srcOffset0 + 3];
  1769. const x1 = src1[srcOffset1];
  1770. const y1 = src1[srcOffset1 + 1];
  1771. const z1 = src1[srcOffset1 + 2];
  1772. const w1 = src1[srcOffset1 + 3];
  1773. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1774. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1775. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1776. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1777. return dst;
  1778. }
  1779. get x() {
  1780. return this._x;
  1781. }
  1782. set x(value) {
  1783. this._x = value;
  1784. this._onChangeCallback();
  1785. }
  1786. get y() {
  1787. return this._y;
  1788. }
  1789. set y(value) {
  1790. this._y = value;
  1791. this._onChangeCallback();
  1792. }
  1793. get z() {
  1794. return this._z;
  1795. }
  1796. set z(value) {
  1797. this._z = value;
  1798. this._onChangeCallback();
  1799. }
  1800. get w() {
  1801. return this._w;
  1802. }
  1803. set w(value) {
  1804. this._w = value;
  1805. this._onChangeCallback();
  1806. }
  1807. set(x, y, z, w) {
  1808. this._x = x;
  1809. this._y = y;
  1810. this._z = z;
  1811. this._w = w;
  1812. this._onChangeCallback();
  1813. return this;
  1814. }
  1815. clone() {
  1816. return new this.constructor(this._x, this._y, this._z, this._w);
  1817. }
  1818. copy(quaternion) {
  1819. this._x = quaternion.x;
  1820. this._y = quaternion.y;
  1821. this._z = quaternion.z;
  1822. this._w = quaternion.w;
  1823. this._onChangeCallback();
  1824. return this;
  1825. }
  1826. setFromEuler(euler, update) {
  1827. if (!(euler && euler.isEuler)) {
  1828. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  1829. }
  1830. const x = euler._x,
  1831. y = euler._y,
  1832. z = euler._z,
  1833. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  1834. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1835. // content/SpinCalc.m
  1836. const cos = Math.cos;
  1837. const sin = Math.sin;
  1838. const c1 = cos(x / 2);
  1839. const c2 = cos(y / 2);
  1840. const c3 = cos(z / 2);
  1841. const s1 = sin(x / 2);
  1842. const s2 = sin(y / 2);
  1843. const s3 = sin(z / 2);
  1844. switch (order) {
  1845. case 'XYZ':
  1846. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1847. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1848. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1849. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1850. break;
  1851. case 'YXZ':
  1852. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1853. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1854. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1855. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1856. break;
  1857. case 'ZXY':
  1858. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1859. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1860. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1861. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1862. break;
  1863. case 'ZYX':
  1864. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1865. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1866. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1867. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1868. break;
  1869. case 'YZX':
  1870. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1871. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1872. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1873. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1874. break;
  1875. case 'XZY':
  1876. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1877. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1878. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1879. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1880. break;
  1881. default:
  1882. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  1883. }
  1884. if (update !== false) this._onChangeCallback();
  1885. return this;
  1886. }
  1887. setFromAxisAngle(axis, angle) {
  1888. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1889. // assumes axis is normalized
  1890. const halfAngle = angle / 2,
  1891. s = Math.sin(halfAngle);
  1892. this._x = axis.x * s;
  1893. this._y = axis.y * s;
  1894. this._z = axis.z * s;
  1895. this._w = Math.cos(halfAngle);
  1896. this._onChangeCallback();
  1897. return this;
  1898. }
  1899. setFromRotationMatrix(m) {
  1900. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1901. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1902. const te = m.elements,
  1903. m11 = te[0],
  1904. m12 = te[4],
  1905. m13 = te[8],
  1906. m21 = te[1],
  1907. m22 = te[5],
  1908. m23 = te[9],
  1909. m31 = te[2],
  1910. m32 = te[6],
  1911. m33 = te[10],
  1912. trace = m11 + m22 + m33;
  1913. if (trace > 0) {
  1914. const s = 0.5 / Math.sqrt(trace + 1.0);
  1915. this._w = 0.25 / s;
  1916. this._x = (m32 - m23) * s;
  1917. this._y = (m13 - m31) * s;
  1918. this._z = (m21 - m12) * s;
  1919. } else if (m11 > m22 && m11 > m33) {
  1920. const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1921. this._w = (m32 - m23) / s;
  1922. this._x = 0.25 * s;
  1923. this._y = (m12 + m21) / s;
  1924. this._z = (m13 + m31) / s;
  1925. } else if (m22 > m33) {
  1926. const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1927. this._w = (m13 - m31) / s;
  1928. this._x = (m12 + m21) / s;
  1929. this._y = 0.25 * s;
  1930. this._z = (m23 + m32) / s;
  1931. } else {
  1932. const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1933. this._w = (m21 - m12) / s;
  1934. this._x = (m13 + m31) / s;
  1935. this._y = (m23 + m32) / s;
  1936. this._z = 0.25 * s;
  1937. }
  1938. this._onChangeCallback();
  1939. return this;
  1940. }
  1941. setFromUnitVectors(vFrom, vTo) {
  1942. // assumes direction vectors vFrom and vTo are normalized
  1943. let r = vFrom.dot(vTo) + 1;
  1944. if (r < Number.EPSILON) {
  1945. // vFrom and vTo point in opposite directions
  1946. r = 0;
  1947. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  1948. this._x = -vFrom.y;
  1949. this._y = vFrom.x;
  1950. this._z = 0;
  1951. this._w = r;
  1952. } else {
  1953. this._x = 0;
  1954. this._y = -vFrom.z;
  1955. this._z = vFrom.y;
  1956. this._w = r;
  1957. }
  1958. } else {
  1959. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  1960. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  1961. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  1962. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  1963. this._w = r;
  1964. }
  1965. return this.normalize();
  1966. }
  1967. angleTo(q) {
  1968. return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1)));
  1969. }
  1970. rotateTowards(q, step) {
  1971. const angle = this.angleTo(q);
  1972. if (angle === 0) return this;
  1973. const t = Math.min(1, step / angle);
  1974. this.slerp(q, t);
  1975. return this;
  1976. }
  1977. identity() {
  1978. return this.set(0, 0, 0, 1);
  1979. }
  1980. invert() {
  1981. // quaternion is assumed to have unit length
  1982. return this.conjugate();
  1983. }
  1984. conjugate() {
  1985. this._x *= -1;
  1986. this._y *= -1;
  1987. this._z *= -1;
  1988. this._onChangeCallback();
  1989. return this;
  1990. }
  1991. dot(v) {
  1992. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1993. }
  1994. lengthSq() {
  1995. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1996. }
  1997. length() {
  1998. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  1999. }
  2000. normalize() {
  2001. let l = this.length();
  2002. if (l === 0) {
  2003. this._x = 0;
  2004. this._y = 0;
  2005. this._z = 0;
  2006. this._w = 1;
  2007. } else {
  2008. l = 1 / l;
  2009. this._x = this._x * l;
  2010. this._y = this._y * l;
  2011. this._z = this._z * l;
  2012. this._w = this._w * l;
  2013. }
  2014. this._onChangeCallback();
  2015. return this;
  2016. }
  2017. multiply(q, p) {
  2018. if (p !== undefined) {
  2019. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2020. return this.multiplyQuaternions(q, p);
  2021. }
  2022. return this.multiplyQuaternions(this, q);
  2023. }
  2024. premultiply(q) {
  2025. return this.multiplyQuaternions(q, this);
  2026. }
  2027. multiplyQuaternions(a, b) {
  2028. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2029. const qax = a._x,
  2030. qay = a._y,
  2031. qaz = a._z,
  2032. qaw = a._w;
  2033. const qbx = b._x,
  2034. qby = b._y,
  2035. qbz = b._z,
  2036. qbw = b._w;
  2037. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2038. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2039. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2040. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2041. this._onChangeCallback();
  2042. return this;
  2043. }
  2044. slerp(qb, t) {
  2045. if (t === 0) return this;
  2046. if (t === 1) return this.copy(qb);
  2047. const x = this._x,
  2048. y = this._y,
  2049. z = this._z,
  2050. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2051. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2052. if (cosHalfTheta < 0) {
  2053. this._w = -qb._w;
  2054. this._x = -qb._x;
  2055. this._y = -qb._y;
  2056. this._z = -qb._z;
  2057. cosHalfTheta = -cosHalfTheta;
  2058. } else {
  2059. this.copy(qb);
  2060. }
  2061. if (cosHalfTheta >= 1.0) {
  2062. this._w = w;
  2063. this._x = x;
  2064. this._y = y;
  2065. this._z = z;
  2066. return this;
  2067. }
  2068. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2069. if (sqrSinHalfTheta <= Number.EPSILON) {
  2070. const s = 1 - t;
  2071. this._w = s * w + t * this._w;
  2072. this._x = s * x + t * this._x;
  2073. this._y = s * y + t * this._y;
  2074. this._z = s * z + t * this._z;
  2075. this.normalize();
  2076. this._onChangeCallback();
  2077. return this;
  2078. }
  2079. const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2080. const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2081. const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2082. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2083. this._w = w * ratioA + this._w * ratioB;
  2084. this._x = x * ratioA + this._x * ratioB;
  2085. this._y = y * ratioA + this._y * ratioB;
  2086. this._z = z * ratioA + this._z * ratioB;
  2087. this._onChangeCallback();
  2088. return this;
  2089. }
  2090. slerpQuaternions(qa, qb, t) {
  2091. this.copy(qa).slerp(qb, t);
  2092. }
  2093. equals(quaternion) {
  2094. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2095. }
  2096. fromArray(array, offset = 0) {
  2097. this._x = array[offset];
  2098. this._y = array[offset + 1];
  2099. this._z = array[offset + 2];
  2100. this._w = array[offset + 3];
  2101. this._onChangeCallback();
  2102. return this;
  2103. }
  2104. toArray(array = [], offset = 0) {
  2105. array[offset] = this._x;
  2106. array[offset + 1] = this._y;
  2107. array[offset + 2] = this._z;
  2108. array[offset + 3] = this._w;
  2109. return array;
  2110. }
  2111. fromBufferAttribute(attribute, index) {
  2112. this._x = attribute.getX(index);
  2113. this._y = attribute.getY(index);
  2114. this._z = attribute.getZ(index);
  2115. this._w = attribute.getW(index);
  2116. return this;
  2117. }
  2118. _onChange(callback) {
  2119. this._onChangeCallback = callback;
  2120. return this;
  2121. }
  2122. _onChangeCallback() {}
  2123. }
  2124. Quaternion.prototype.isQuaternion = true;
  2125. class Vector3 {
  2126. constructor(x = 0, y = 0, z = 0) {
  2127. this.x = x;
  2128. this.y = y;
  2129. this.z = z;
  2130. }
  2131. set(x, y, z) {
  2132. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  2133. this.x = x;
  2134. this.y = y;
  2135. this.z = z;
  2136. return this;
  2137. }
  2138. setScalar(scalar) {
  2139. this.x = scalar;
  2140. this.y = scalar;
  2141. this.z = scalar;
  2142. return this;
  2143. }
  2144. setX(x) {
  2145. this.x = x;
  2146. return this;
  2147. }
  2148. setY(y) {
  2149. this.y = y;
  2150. return this;
  2151. }
  2152. setZ(z) {
  2153. this.z = z;
  2154. return this;
  2155. }
  2156. setComponent(index, value) {
  2157. switch (index) {
  2158. case 0:
  2159. this.x = value;
  2160. break;
  2161. case 1:
  2162. this.y = value;
  2163. break;
  2164. case 2:
  2165. this.z = value;
  2166. break;
  2167. default:
  2168. throw new Error('index is out of range: ' + index);
  2169. }
  2170. return this;
  2171. }
  2172. getComponent(index) {
  2173. switch (index) {
  2174. case 0:
  2175. return this.x;
  2176. case 1:
  2177. return this.y;
  2178. case 2:
  2179. return this.z;
  2180. default:
  2181. throw new Error('index is out of range: ' + index);
  2182. }
  2183. }
  2184. clone() {
  2185. return new this.constructor(this.x, this.y, this.z);
  2186. }
  2187. copy(v) {
  2188. this.x = v.x;
  2189. this.y = v.y;
  2190. this.z = v.z;
  2191. return this;
  2192. }
  2193. add(v, w) {
  2194. if (w !== undefined) {
  2195. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2196. return this.addVectors(v, w);
  2197. }
  2198. this.x += v.x;
  2199. this.y += v.y;
  2200. this.z += v.z;
  2201. return this;
  2202. }
  2203. addScalar(s) {
  2204. this.x += s;
  2205. this.y += s;
  2206. this.z += s;
  2207. return this;
  2208. }
  2209. addVectors(a, b) {
  2210. this.x = a.x + b.x;
  2211. this.y = a.y + b.y;
  2212. this.z = a.z + b.z;
  2213. return this;
  2214. }
  2215. addScaledVector(v, s) {
  2216. this.x += v.x * s;
  2217. this.y += v.y * s;
  2218. this.z += v.z * s;
  2219. return this;
  2220. }
  2221. sub(v, w) {
  2222. if (w !== undefined) {
  2223. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2224. return this.subVectors(v, w);
  2225. }
  2226. this.x -= v.x;
  2227. this.y -= v.y;
  2228. this.z -= v.z;
  2229. return this;
  2230. }
  2231. subScalar(s) {
  2232. this.x -= s;
  2233. this.y -= s;
  2234. this.z -= s;
  2235. return this;
  2236. }
  2237. subVectors(a, b) {
  2238. this.x = a.x - b.x;
  2239. this.y = a.y - b.y;
  2240. this.z = a.z - b.z;
  2241. return this;
  2242. }
  2243. multiply(v, w) {
  2244. if (w !== undefined) {
  2245. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2246. return this.multiplyVectors(v, w);
  2247. }
  2248. this.x *= v.x;
  2249. this.y *= v.y;
  2250. this.z *= v.z;
  2251. return this;
  2252. }
  2253. multiplyScalar(scalar) {
  2254. this.x *= scalar;
  2255. this.y *= scalar;
  2256. this.z *= scalar;
  2257. return this;
  2258. }
  2259. multiplyVectors(a, b) {
  2260. this.x = a.x * b.x;
  2261. this.y = a.y * b.y;
  2262. this.z = a.z * b.z;
  2263. return this;
  2264. }
  2265. applyEuler(euler) {
  2266. if (!(euler && euler.isEuler)) {
  2267. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2268. }
  2269. return this.applyQuaternion(_quaternion$4.setFromEuler(euler));
  2270. }
  2271. applyAxisAngle(axis, angle) {
  2272. return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle));
  2273. }
  2274. applyMatrix3(m) {
  2275. const x = this.x,
  2276. y = this.y,
  2277. z = this.z;
  2278. const e = m.elements;
  2279. this.x = e[0] * x + e[3] * y + e[6] * z;
  2280. this.y = e[1] * x + e[4] * y + e[7] * z;
  2281. this.z = e[2] * x + e[5] * y + e[8] * z;
  2282. return this;
  2283. }
  2284. applyNormalMatrix(m) {
  2285. return this.applyMatrix3(m).normalize();
  2286. }
  2287. applyMatrix4(m) {
  2288. const x = this.x,
  2289. y = this.y,
  2290. z = this.z;
  2291. const e = m.elements;
  2292. const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2293. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2294. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2295. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2296. return this;
  2297. }
  2298. applyQuaternion(q) {
  2299. const x = this.x,
  2300. y = this.y,
  2301. z = this.z;
  2302. const qx = q.x,
  2303. qy = q.y,
  2304. qz = q.z,
  2305. qw = q.w; // calculate quat * vector
  2306. const ix = qw * x + qy * z - qz * y;
  2307. const iy = qw * y + qz * x - qx * z;
  2308. const iz = qw * z + qx * y - qy * x;
  2309. const iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2310. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2311. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2312. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2313. return this;
  2314. }
  2315. project(camera) {
  2316. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2317. }
  2318. unproject(camera) {
  2319. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2320. }
  2321. transformDirection(m) {
  2322. // input: THREE.Matrix4 affine matrix
  2323. // vector interpreted as a direction
  2324. const x = this.x,
  2325. y = this.y,
  2326. z = this.z;
  2327. const e = m.elements;
  2328. this.x = e[0] * x + e[4] * y + e[8] * z;
  2329. this.y = e[1] * x + e[5] * y + e[9] * z;
  2330. this.z = e[2] * x + e[6] * y + e[10] * z;
  2331. return this.normalize();
  2332. }
  2333. divide(v) {
  2334. this.x /= v.x;
  2335. this.y /= v.y;
  2336. this.z /= v.z;
  2337. return this;
  2338. }
  2339. divideScalar(scalar) {
  2340. return this.multiplyScalar(1 / scalar);
  2341. }
  2342. min(v) {
  2343. this.x = Math.min(this.x, v.x);
  2344. this.y = Math.min(this.y, v.y);
  2345. this.z = Math.min(this.z, v.z);
  2346. return this;
  2347. }
  2348. max(v) {
  2349. this.x = Math.max(this.x, v.x);
  2350. this.y = Math.max(this.y, v.y);
  2351. this.z = Math.max(this.z, v.z);
  2352. return this;
  2353. }
  2354. clamp(min, max) {
  2355. // assumes min < max, componentwise
  2356. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2357. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2358. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2359. return this;
  2360. }
  2361. clampScalar(minVal, maxVal) {
  2362. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2363. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2364. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2365. return this;
  2366. }
  2367. clampLength(min, max) {
  2368. const length = this.length();
  2369. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2370. }
  2371. floor() {
  2372. this.x = Math.floor(this.x);
  2373. this.y = Math.floor(this.y);
  2374. this.z = Math.floor(this.z);
  2375. return this;
  2376. }
  2377. ceil() {
  2378. this.x = Math.ceil(this.x);
  2379. this.y = Math.ceil(this.y);
  2380. this.z = Math.ceil(this.z);
  2381. return this;
  2382. }
  2383. round() {
  2384. this.x = Math.round(this.x);
  2385. this.y = Math.round(this.y);
  2386. this.z = Math.round(this.z);
  2387. return this;
  2388. }
  2389. roundToZero() {
  2390. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2391. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2392. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2393. return this;
  2394. }
  2395. negate() {
  2396. this.x = -this.x;
  2397. this.y = -this.y;
  2398. this.z = -this.z;
  2399. return this;
  2400. }
  2401. dot(v) {
  2402. return this.x * v.x + this.y * v.y + this.z * v.z;
  2403. } // TODO lengthSquared?
  2404. lengthSq() {
  2405. return this.x * this.x + this.y * this.y + this.z * this.z;
  2406. }
  2407. length() {
  2408. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2409. }
  2410. manhattanLength() {
  2411. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2412. }
  2413. normalize() {
  2414. return this.divideScalar(this.length() || 1);
  2415. }
  2416. setLength(length) {
  2417. return this.normalize().multiplyScalar(length);
  2418. }
  2419. lerp(v, alpha) {
  2420. this.x += (v.x - this.x) * alpha;
  2421. this.y += (v.y - this.y) * alpha;
  2422. this.z += (v.z - this.z) * alpha;
  2423. return this;
  2424. }
  2425. lerpVectors(v1, v2, alpha) {
  2426. this.x = v1.x + (v2.x - v1.x) * alpha;
  2427. this.y = v1.y + (v2.y - v1.y) * alpha;
  2428. this.z = v1.z + (v2.z - v1.z) * alpha;
  2429. return this;
  2430. }
  2431. cross(v, w) {
  2432. if (w !== undefined) {
  2433. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2434. return this.crossVectors(v, w);
  2435. }
  2436. return this.crossVectors(this, v);
  2437. }
  2438. crossVectors(a, b) {
  2439. const ax = a.x,
  2440. ay = a.y,
  2441. az = a.z;
  2442. const bx = b.x,
  2443. by = b.y,
  2444. bz = b.z;
  2445. this.x = ay * bz - az * by;
  2446. this.y = az * bx - ax * bz;
  2447. this.z = ax * by - ay * bx;
  2448. return this;
  2449. }
  2450. projectOnVector(v) {
  2451. const denominator = v.lengthSq();
  2452. if (denominator === 0) return this.set(0, 0, 0);
  2453. const scalar = v.dot(this) / denominator;
  2454. return this.copy(v).multiplyScalar(scalar);
  2455. }
  2456. projectOnPlane(planeNormal) {
  2457. _vector$c.copy(this).projectOnVector(planeNormal);
  2458. return this.sub(_vector$c);
  2459. }
  2460. reflect(normal) {
  2461. // reflect incident vector off plane orthogonal to normal
  2462. // normal is assumed to have unit length
  2463. return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal)));
  2464. }
  2465. angleTo(v) {
  2466. const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  2467. if (denominator === 0) return Math.PI / 2;
  2468. const theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  2469. return Math.acos(clamp(theta, -1, 1));
  2470. }
  2471. distanceTo(v) {
  2472. return Math.sqrt(this.distanceToSquared(v));
  2473. }
  2474. distanceToSquared(v) {
  2475. const dx = this.x - v.x,
  2476. dy = this.y - v.y,
  2477. dz = this.z - v.z;
  2478. return dx * dx + dy * dy + dz * dz;
  2479. }
  2480. manhattanDistanceTo(v) {
  2481. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  2482. }
  2483. setFromSpherical(s) {
  2484. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  2485. }
  2486. setFromSphericalCoords(radius, phi, theta) {
  2487. const sinPhiRadius = Math.sin(phi) * radius;
  2488. this.x = sinPhiRadius * Math.sin(theta);
  2489. this.y = Math.cos(phi) * radius;
  2490. this.z = sinPhiRadius * Math.cos(theta);
  2491. return this;
  2492. }
  2493. setFromCylindrical(c) {
  2494. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  2495. }
  2496. setFromCylindricalCoords(radius, theta, y) {
  2497. this.x = radius * Math.sin(theta);
  2498. this.y = y;
  2499. this.z = radius * Math.cos(theta);
  2500. return this;
  2501. }
  2502. setFromMatrixPosition(m) {
  2503. const e = m.elements;
  2504. this.x = e[12];
  2505. this.y = e[13];
  2506. this.z = e[14];
  2507. return this;
  2508. }
  2509. setFromMatrixScale(m) {
  2510. const sx = this.setFromMatrixColumn(m, 0).length();
  2511. const sy = this.setFromMatrixColumn(m, 1).length();
  2512. const sz = this.setFromMatrixColumn(m, 2).length();
  2513. this.x = sx;
  2514. this.y = sy;
  2515. this.z = sz;
  2516. return this;
  2517. }
  2518. setFromMatrixColumn(m, index) {
  2519. return this.fromArray(m.elements, index * 4);
  2520. }
  2521. setFromMatrix3Column(m, index) {
  2522. return this.fromArray(m.elements, index * 3);
  2523. }
  2524. equals(v) {
  2525. return v.x === this.x && v.y === this.y && v.z === this.z;
  2526. }
  2527. fromArray(array, offset = 0) {
  2528. this.x = array[offset];
  2529. this.y = array[offset + 1];
  2530. this.z = array[offset + 2];
  2531. return this;
  2532. }
  2533. toArray(array = [], offset = 0) {
  2534. array[offset] = this.x;
  2535. array[offset + 1] = this.y;
  2536. array[offset + 2] = this.z;
  2537. return array;
  2538. }
  2539. fromBufferAttribute(attribute, index, offset) {
  2540. if (offset !== undefined) {
  2541. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  2542. }
  2543. this.x = attribute.getX(index);
  2544. this.y = attribute.getY(index);
  2545. this.z = attribute.getZ(index);
  2546. return this;
  2547. }
  2548. random() {
  2549. this.x = Math.random();
  2550. this.y = Math.random();
  2551. this.z = Math.random();
  2552. return this;
  2553. }
  2554. }
  2555. Vector3.prototype.isVector3 = true;
  2556. const _vector$c = /*@__PURE__*/new Vector3();
  2557. const _quaternion$4 = /*@__PURE__*/new Quaternion();
  2558. class Box3 {
  2559. constructor(min = new Vector3(+Infinity, +Infinity, +Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) {
  2560. this.min = min;
  2561. this.max = max;
  2562. }
  2563. set(min, max) {
  2564. this.min.copy(min);
  2565. this.max.copy(max);
  2566. return this;
  2567. }
  2568. setFromArray(array) {
  2569. let minX = +Infinity;
  2570. let minY = +Infinity;
  2571. let minZ = +Infinity;
  2572. let maxX = -Infinity;
  2573. let maxY = -Infinity;
  2574. let maxZ = -Infinity;
  2575. for (let i = 0, l = array.length; i < l; i += 3) {
  2576. const x = array[i];
  2577. const y = array[i + 1];
  2578. const z = array[i + 2];
  2579. if (x < minX) minX = x;
  2580. if (y < minY) minY = y;
  2581. if (z < minZ) minZ = z;
  2582. if (x > maxX) maxX = x;
  2583. if (y > maxY) maxY = y;
  2584. if (z > maxZ) maxZ = z;
  2585. }
  2586. this.min.set(minX, minY, minZ);
  2587. this.max.set(maxX, maxY, maxZ);
  2588. return this;
  2589. }
  2590. setFromBufferAttribute(attribute) {
  2591. let minX = +Infinity;
  2592. let minY = +Infinity;
  2593. let minZ = +Infinity;
  2594. let maxX = -Infinity;
  2595. let maxY = -Infinity;
  2596. let maxZ = -Infinity;
  2597. for (let i = 0, l = attribute.count; i < l; i++) {
  2598. const x = attribute.getX(i);
  2599. const y = attribute.getY(i);
  2600. const z = attribute.getZ(i);
  2601. if (x < minX) minX = x;
  2602. if (y < minY) minY = y;
  2603. if (z < minZ) minZ = z;
  2604. if (x > maxX) maxX = x;
  2605. if (y > maxY) maxY = y;
  2606. if (z > maxZ) maxZ = z;
  2607. }
  2608. this.min.set(minX, minY, minZ);
  2609. this.max.set(maxX, maxY, maxZ);
  2610. return this;
  2611. }
  2612. setFromPoints(points) {
  2613. this.makeEmpty();
  2614. for (let i = 0, il = points.length; i < il; i++) {
  2615. this.expandByPoint(points[i]);
  2616. }
  2617. return this;
  2618. }
  2619. setFromCenterAndSize(center, size) {
  2620. const halfSize = _vector$b.copy(size).multiplyScalar(0.5);
  2621. this.min.copy(center).sub(halfSize);
  2622. this.max.copy(center).add(halfSize);
  2623. return this;
  2624. }
  2625. setFromObject(object) {
  2626. this.makeEmpty();
  2627. return this.expandByObject(object);
  2628. }
  2629. clone() {
  2630. return new this.constructor().copy(this);
  2631. }
  2632. copy(box) {
  2633. this.min.copy(box.min);
  2634. this.max.copy(box.max);
  2635. return this;
  2636. }
  2637. makeEmpty() {
  2638. this.min.x = this.min.y = this.min.z = +Infinity;
  2639. this.max.x = this.max.y = this.max.z = -Infinity;
  2640. return this;
  2641. }
  2642. isEmpty() {
  2643. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2644. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  2645. }
  2646. getCenter(target) {
  2647. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  2648. }
  2649. getSize(target) {
  2650. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  2651. }
  2652. expandByPoint(point) {
  2653. this.min.min(point);
  2654. this.max.max(point);
  2655. return this;
  2656. }
  2657. expandByVector(vector) {
  2658. this.min.sub(vector);
  2659. this.max.add(vector);
  2660. return this;
  2661. }
  2662. expandByScalar(scalar) {
  2663. this.min.addScalar(-scalar);
  2664. this.max.addScalar(scalar);
  2665. return this;
  2666. }
  2667. expandByObject(object) {
  2668. // Computes the world-axis-aligned bounding box of an object (including its children),
  2669. // accounting for both the object's, and children's, world transforms
  2670. object.updateWorldMatrix(false, false);
  2671. const geometry = object.geometry;
  2672. if (geometry !== undefined) {
  2673. if (geometry.boundingBox === null) {
  2674. geometry.computeBoundingBox();
  2675. }
  2676. _box$3.copy(geometry.boundingBox);
  2677. _box$3.applyMatrix4(object.matrixWorld);
  2678. this.union(_box$3);
  2679. }
  2680. const children = object.children;
  2681. for (let i = 0, l = children.length; i < l; i++) {
  2682. this.expandByObject(children[i]);
  2683. }
  2684. return this;
  2685. }
  2686. containsPoint(point) {
  2687. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y || point.z < this.min.z || point.z > this.max.z ? false : true;
  2688. }
  2689. containsBox(box) {
  2690. return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z;
  2691. }
  2692. getParameter(point, target) {
  2693. // This can potentially have a divide by zero if the box
  2694. // has a size dimension of 0.
  2695. return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y), (point.z - this.min.z) / (this.max.z - this.min.z));
  2696. }
  2697. intersectsBox(box) {
  2698. // using 6 splitting planes to rule out intersections.
  2699. return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y || box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2700. }
  2701. intersectsSphere(sphere) {
  2702. // Find the point on the AABB closest to the sphere center.
  2703. this.clampPoint(sphere.center, _vector$b); // If that point is inside the sphere, the AABB and sphere intersect.
  2704. return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  2705. }
  2706. intersectsPlane(plane) {
  2707. // We compute the minimum and maximum dot product values. If those values
  2708. // are on the same side (back or front) of the plane, then there is no intersection.
  2709. let min, max;
  2710. if (plane.normal.x > 0) {
  2711. min = plane.normal.x * this.min.x;
  2712. max = plane.normal.x * this.max.x;
  2713. } else {
  2714. min = plane.normal.x * this.max.x;
  2715. max = plane.normal.x * this.min.x;
  2716. }
  2717. if (plane.normal.y > 0) {
  2718. min += plane.normal.y * this.min.y;
  2719. max += plane.normal.y * this.max.y;
  2720. } else {
  2721. min += plane.normal.y * this.max.y;
  2722. max += plane.normal.y * this.min.y;
  2723. }
  2724. if (plane.normal.z > 0) {
  2725. min += plane.normal.z * this.min.z;
  2726. max += plane.normal.z * this.max.z;
  2727. } else {
  2728. min += plane.normal.z * this.max.z;
  2729. max += plane.normal.z * this.min.z;
  2730. }
  2731. return min <= -plane.constant && max >= -plane.constant;
  2732. }
  2733. intersectsTriangle(triangle) {
  2734. if (this.isEmpty()) {
  2735. return false;
  2736. } // compute box center and extents
  2737. this.getCenter(_center);
  2738. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  2739. _v0$2.subVectors(triangle.a, _center);
  2740. _v1$7.subVectors(triangle.b, _center);
  2741. _v2$3.subVectors(triangle.c, _center); // compute edge vectors for triangle
  2742. _f0.subVectors(_v1$7, _v0$2);
  2743. _f1.subVectors(_v2$3, _v1$7);
  2744. _f2.subVectors(_v0$2, _v2$3); // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2745. // 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
  2746. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2747. let axes = [0, -_f0.z, _f0.y, 0, -_f1.z, _f1.y, 0, -_f2.z, _f2.y, _f0.z, 0, -_f0.x, _f1.z, 0, -_f1.x, _f2.z, 0, -_f2.x, -_f0.y, _f0.x, 0, -_f1.y, _f1.x, 0, -_f2.y, _f2.x, 0];
  2748. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2749. return false;
  2750. } // test 3 face normals from the aabb
  2751. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  2752. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2753. return false;
  2754. } // finally testing the face normal of the triangle
  2755. // use already existing triangle edge vectors here
  2756. _triangleNormal.crossVectors(_f0, _f1);
  2757. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  2758. return satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents);
  2759. }
  2760. clampPoint(point, target) {
  2761. return target.copy(point).clamp(this.min, this.max);
  2762. }
  2763. distanceToPoint(point) {
  2764. const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max);
  2765. return clampedPoint.sub(point).length();
  2766. }
  2767. getBoundingSphere(target) {
  2768. this.getCenter(target.center);
  2769. target.radius = this.getSize(_vector$b).length() * 0.5;
  2770. return target;
  2771. }
  2772. intersect(box) {
  2773. this.min.max(box.min);
  2774. this.max.min(box.max); // 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.
  2775. if (this.isEmpty()) this.makeEmpty();
  2776. return this;
  2777. }
  2778. union(box) {
  2779. this.min.min(box.min);
  2780. this.max.max(box.max);
  2781. return this;
  2782. }
  2783. applyMatrix4(matrix) {
  2784. // transform of empty box is an empty box.
  2785. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2786. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  2787. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  2788. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  2789. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  2790. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  2791. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  2792. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  2793. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  2794. this.setFromPoints(_points);
  2795. return this;
  2796. }
  2797. translate(offset) {
  2798. this.min.add(offset);
  2799. this.max.add(offset);
  2800. return this;
  2801. }
  2802. equals(box) {
  2803. return box.min.equals(this.min) && box.max.equals(this.max);
  2804. }
  2805. }
  2806. Box3.prototype.isBox3 = true;
  2807. const _points = [/*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3()];
  2808. const _vector$b = /*@__PURE__*/new Vector3();
  2809. const _box$3 = /*@__PURE__*/new Box3(); // triangle centered vertices
  2810. const _v0$2 = /*@__PURE__*/new Vector3();
  2811. const _v1$7 = /*@__PURE__*/new Vector3();
  2812. const _v2$3 = /*@__PURE__*/new Vector3(); // triangle edge vectors
  2813. const _f0 = /*@__PURE__*/new Vector3();
  2814. const _f1 = /*@__PURE__*/new Vector3();
  2815. const _f2 = /*@__PURE__*/new Vector3();
  2816. const _center = /*@__PURE__*/new Vector3();
  2817. const _extents = /*@__PURE__*/new Vector3();
  2818. const _triangleNormal = /*@__PURE__*/new Vector3();
  2819. const _testAxis = /*@__PURE__*/new Vector3();
  2820. function satForAxes(axes, v0, v1, v2, extents) {
  2821. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  2822. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  2823. const r = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z); // project all 3 vertices of the triangle onto the seperating axis
  2824. const p0 = v0.dot(_testAxis);
  2825. const p1 = v1.dot(_testAxis);
  2826. const p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  2827. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  2828. // points of the projected triangle are outside the projected half-length of the aabb
  2829. // the axis is seperating and we can exit
  2830. return false;
  2831. }
  2832. }
  2833. return true;
  2834. }
  2835. const _box$2 = /*@__PURE__*/new Box3();
  2836. const _v1$6 = /*@__PURE__*/new Vector3();
  2837. const _toFarthestPoint = /*@__PURE__*/new Vector3();
  2838. const _toPoint = /*@__PURE__*/new Vector3();
  2839. class Sphere {
  2840. constructor(center = new Vector3(), radius = -1) {
  2841. this.center = center;
  2842. this.radius = radius;
  2843. }
  2844. set(center, radius) {
  2845. this.center.copy(center);
  2846. this.radius = radius;
  2847. return this;
  2848. }
  2849. setFromPoints(points, optionalCenter) {
  2850. const center = this.center;
  2851. if (optionalCenter !== undefined) {
  2852. center.copy(optionalCenter);
  2853. } else {
  2854. _box$2.setFromPoints(points).getCenter(center);
  2855. }
  2856. let maxRadiusSq = 0;
  2857. for (let i = 0, il = points.length; i < il; i++) {
  2858. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  2859. }
  2860. this.radius = Math.sqrt(maxRadiusSq);
  2861. return this;
  2862. }
  2863. copy(sphere) {
  2864. this.center.copy(sphere.center);
  2865. this.radius = sphere.radius;
  2866. return this;
  2867. }
  2868. isEmpty() {
  2869. return this.radius < 0;
  2870. }
  2871. makeEmpty() {
  2872. this.center.set(0, 0, 0);
  2873. this.radius = -1;
  2874. return this;
  2875. }
  2876. containsPoint(point) {
  2877. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  2878. }
  2879. distanceToPoint(point) {
  2880. return point.distanceTo(this.center) - this.radius;
  2881. }
  2882. intersectsSphere(sphere) {
  2883. const radiusSum = this.radius + sphere.radius;
  2884. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  2885. }
  2886. intersectsBox(box) {
  2887. return box.intersectsSphere(this);
  2888. }
  2889. intersectsPlane(plane) {
  2890. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  2891. }
  2892. clampPoint(point, target) {
  2893. const deltaLengthSq = this.center.distanceToSquared(point);
  2894. target.copy(point);
  2895. if (deltaLengthSq > this.radius * this.radius) {
  2896. target.sub(this.center).normalize();
  2897. target.multiplyScalar(this.radius).add(this.center);
  2898. }
  2899. return target;
  2900. }
  2901. getBoundingBox(target) {
  2902. if (this.isEmpty()) {
  2903. // Empty sphere produces empty bounding box
  2904. target.makeEmpty();
  2905. return target;
  2906. }
  2907. target.set(this.center, this.center);
  2908. target.expandByScalar(this.radius);
  2909. return target;
  2910. }
  2911. applyMatrix4(matrix) {
  2912. this.center.applyMatrix4(matrix);
  2913. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2914. return this;
  2915. }
  2916. translate(offset) {
  2917. this.center.add(offset);
  2918. return this;
  2919. }
  2920. expandByPoint(point) {
  2921. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  2922. _toPoint.subVectors(point, this.center);
  2923. const lengthSq = _toPoint.lengthSq();
  2924. if (lengthSq > this.radius * this.radius) {
  2925. const length = Math.sqrt(lengthSq);
  2926. const missingRadiusHalf = (length - this.radius) * 0.5; // Nudge this sphere towards the target point. Add half the missing distance to radius,
  2927. // and the other half to position. This gives a tighter enclosure, instead of if
  2928. // the whole missing distance were just added to radius.
  2929. this.center.add(_toPoint.multiplyScalar(missingRadiusHalf / length));
  2930. this.radius += missingRadiusHalf;
  2931. }
  2932. return this;
  2933. }
  2934. union(sphere) {
  2935. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  2936. // To enclose another sphere into this sphere, we only need to enclose two points:
  2937. // 1) Enclose the farthest point on the other sphere into this sphere.
  2938. // 2) Enclose the opposite point of the farthest point into this sphere.
  2939. _toFarthestPoint.subVectors(sphere.center, this.center).normalize().multiplyScalar(sphere.radius);
  2940. this.expandByPoint(_v1$6.copy(sphere.center).add(_toFarthestPoint));
  2941. this.expandByPoint(_v1$6.copy(sphere.center).sub(_toFarthestPoint));
  2942. return this;
  2943. }
  2944. equals(sphere) {
  2945. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  2946. }
  2947. clone() {
  2948. return new this.constructor().copy(this);
  2949. }
  2950. }
  2951. const _vector$a = /*@__PURE__*/new Vector3();
  2952. const _segCenter = /*@__PURE__*/new Vector3();
  2953. const _segDir = /*@__PURE__*/new Vector3();
  2954. const _diff = /*@__PURE__*/new Vector3();
  2955. const _edge1 = /*@__PURE__*/new Vector3();
  2956. const _edge2 = /*@__PURE__*/new Vector3();
  2957. const _normal$1 = /*@__PURE__*/new Vector3();
  2958. class Ray {
  2959. constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) {
  2960. this.origin = origin;
  2961. this.direction = direction;
  2962. }
  2963. set(origin, direction) {
  2964. this.origin.copy(origin);
  2965. this.direction.copy(direction);
  2966. return this;
  2967. }
  2968. copy(ray) {
  2969. this.origin.copy(ray.origin);
  2970. this.direction.copy(ray.direction);
  2971. return this;
  2972. }
  2973. at(t, target) {
  2974. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  2975. }
  2976. lookAt(v) {
  2977. this.direction.copy(v).sub(this.origin).normalize();
  2978. return this;
  2979. }
  2980. recast(t) {
  2981. this.origin.copy(this.at(t, _vector$a));
  2982. return this;
  2983. }
  2984. closestPointToPoint(point, target) {
  2985. target.subVectors(point, this.origin);
  2986. const directionDistance = target.dot(this.direction);
  2987. if (directionDistance < 0) {
  2988. return target.copy(this.origin);
  2989. }
  2990. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  2991. }
  2992. distanceToPoint(point) {
  2993. return Math.sqrt(this.distanceSqToPoint(point));
  2994. }
  2995. distanceSqToPoint(point) {
  2996. const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  2997. if (directionDistance < 0) {
  2998. return this.origin.distanceToSquared(point);
  2999. }
  3000. _vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3001. return _vector$a.distanceToSquared(point);
  3002. }
  3003. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  3004. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3005. // It returns the min distance between the ray and the segment
  3006. // defined by v0 and v1
  3007. // It can also set two optional targets :
  3008. // - The closest point on the ray
  3009. // - The closest point on the segment
  3010. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  3011. _segDir.copy(v1).sub(v0).normalize();
  3012. _diff.copy(this.origin).sub(_segCenter);
  3013. const segExtent = v0.distanceTo(v1) * 0.5;
  3014. const a01 = -this.direction.dot(_segDir);
  3015. const b0 = _diff.dot(this.direction);
  3016. const b1 = -_diff.dot(_segDir);
  3017. const c = _diff.lengthSq();
  3018. const det = Math.abs(1 - a01 * a01);
  3019. let s0, s1, sqrDist, extDet;
  3020. if (det > 0) {
  3021. // The ray and segment are not parallel.
  3022. s0 = a01 * b1 - b0;
  3023. s1 = a01 * b0 - b1;
  3024. extDet = segExtent * det;
  3025. if (s0 >= 0) {
  3026. if (s1 >= -extDet) {
  3027. if (s1 <= extDet) {
  3028. // region 0
  3029. // Minimum at interior points of ray and segment.
  3030. const invDet = 1 / det;
  3031. s0 *= invDet;
  3032. s1 *= invDet;
  3033. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  3034. } else {
  3035. // region 1
  3036. s1 = segExtent;
  3037. s0 = Math.max(0, -(a01 * s1 + b0));
  3038. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3039. }
  3040. } else {
  3041. // region 5
  3042. s1 = -segExtent;
  3043. s0 = Math.max(0, -(a01 * s1 + b0));
  3044. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3045. }
  3046. } else {
  3047. if (s1 <= -extDet) {
  3048. // region 4
  3049. s0 = Math.max(0, -(-a01 * segExtent + b0));
  3050. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3051. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3052. } else if (s1 <= extDet) {
  3053. // region 3
  3054. s0 = 0;
  3055. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  3056. sqrDist = s1 * (s1 + 2 * b1) + c;
  3057. } else {
  3058. // region 2
  3059. s0 = Math.max(0, -(a01 * segExtent + b0));
  3060. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3061. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3062. }
  3063. }
  3064. } else {
  3065. // Ray and segment are parallel.
  3066. s1 = a01 > 0 ? -segExtent : segExtent;
  3067. s0 = Math.max(0, -(a01 * s1 + b0));
  3068. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3069. }
  3070. if (optionalPointOnRay) {
  3071. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  3072. }
  3073. if (optionalPointOnSegment) {
  3074. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  3075. }
  3076. return sqrDist;
  3077. }
  3078. intersectSphere(sphere, target) {
  3079. _vector$a.subVectors(sphere.center, this.origin);
  3080. const tca = _vector$a.dot(this.direction);
  3081. const d2 = _vector$a.dot(_vector$a) - tca * tca;
  3082. const radius2 = sphere.radius * sphere.radius;
  3083. if (d2 > radius2) return null;
  3084. const thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  3085. const t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  3086. const t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  3087. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  3088. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3089. // in order to always return an intersect point that is in front of the ray.
  3090. if (t0 < 0) return this.at(t1, target); // else t0 is in front of the ray, so return the first collision point scaled by t0
  3091. return this.at(t0, target);
  3092. }
  3093. intersectsSphere(sphere) {
  3094. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  3095. }
  3096. distanceToPlane(plane) {
  3097. const denominator = plane.normal.dot(this.direction);
  3098. if (denominator === 0) {
  3099. // line is coplanar, return origin
  3100. if (plane.distanceToPoint(this.origin) === 0) {
  3101. return 0;
  3102. } // Null is preferable to undefined since undefined means.... it is undefined
  3103. return null;
  3104. }
  3105. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  3106. return t >= 0 ? t : null;
  3107. }
  3108. intersectPlane(plane, target) {
  3109. const t = this.distanceToPlane(plane);
  3110. if (t === null) {
  3111. return null;
  3112. }
  3113. return this.at(t, target);
  3114. }
  3115. intersectsPlane(plane) {
  3116. // check if the ray lies on the plane first
  3117. const distToPoint = plane.distanceToPoint(this.origin);
  3118. if (distToPoint === 0) {
  3119. return true;
  3120. }
  3121. const denominator = plane.normal.dot(this.direction);
  3122. if (denominator * distToPoint < 0) {
  3123. return true;
  3124. } // ray origin is behind the plane (and is pointing behind it)
  3125. return false;
  3126. }
  3127. intersectBox(box, target) {
  3128. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3129. const invdirx = 1 / this.direction.x,
  3130. invdiry = 1 / this.direction.y,
  3131. invdirz = 1 / this.direction.z;
  3132. const origin = this.origin;
  3133. if (invdirx >= 0) {
  3134. tmin = (box.min.x - origin.x) * invdirx;
  3135. tmax = (box.max.x - origin.x) * invdirx;
  3136. } else {
  3137. tmin = (box.max.x - origin.x) * invdirx;
  3138. tmax = (box.min.x - origin.x) * invdirx;
  3139. }
  3140. if (invdiry >= 0) {
  3141. tymin = (box.min.y - origin.y) * invdiry;
  3142. tymax = (box.max.y - origin.y) * invdiry;
  3143. } else {
  3144. tymin = (box.max.y - origin.y) * invdiry;
  3145. tymax = (box.min.y - origin.y) * invdiry;
  3146. }
  3147. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  3148. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3149. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  3150. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  3151. if (invdirz >= 0) {
  3152. tzmin = (box.min.z - origin.z) * invdirz;
  3153. tzmax = (box.max.z - origin.z) * invdirz;
  3154. } else {
  3155. tzmin = (box.max.z - origin.z) * invdirz;
  3156. tzmax = (box.min.z - origin.z) * invdirz;
  3157. }
  3158. if (tmin > tzmax || tzmin > tmax) return null;
  3159. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  3160. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  3161. if (tmax < 0) return null;
  3162. return this.at(tmin >= 0 ? tmin : tmax, target);
  3163. }
  3164. intersectsBox(box) {
  3165. return this.intersectBox(box, _vector$a) !== null;
  3166. }
  3167. intersectTriangle(a, b, c, backfaceCulling, target) {
  3168. // Compute the offset origin, edges, and normal.
  3169. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3170. _edge1.subVectors(b, a);
  3171. _edge2.subVectors(c, a);
  3172. _normal$1.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3173. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3174. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3175. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3176. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3177. let DdN = this.direction.dot(_normal$1);
  3178. let sign;
  3179. if (DdN > 0) {
  3180. if (backfaceCulling) return null;
  3181. sign = 1;
  3182. } else if (DdN < 0) {
  3183. sign = -1;
  3184. DdN = -DdN;
  3185. } else {
  3186. return null;
  3187. }
  3188. _diff.subVectors(this.origin, a);
  3189. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  3190. if (DdQxE2 < 0) {
  3191. return null;
  3192. }
  3193. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  3194. if (DdE1xQ < 0) {
  3195. return null;
  3196. } // b1+b2 > 1, no intersection
  3197. if (DdQxE2 + DdE1xQ > DdN) {
  3198. return null;
  3199. } // Line intersects triangle, check if ray does.
  3200. const QdN = -sign * _diff.dot(_normal$1); // t < 0, no intersection
  3201. if (QdN < 0) {
  3202. return null;
  3203. } // Ray intersects triangle.
  3204. return this.at(QdN / DdN, target);
  3205. }
  3206. applyMatrix4(matrix4) {
  3207. this.origin.applyMatrix4(matrix4);
  3208. this.direction.transformDirection(matrix4);
  3209. return this;
  3210. }
  3211. equals(ray) {
  3212. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  3213. }
  3214. clone() {
  3215. return new this.constructor().copy(this);
  3216. }
  3217. }
  3218. class Matrix4 {
  3219. constructor() {
  3220. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3221. if (arguments.length > 0) {
  3222. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  3223. }
  3224. }
  3225. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3226. const te = this.elements;
  3227. te[0] = n11;
  3228. te[4] = n12;
  3229. te[8] = n13;
  3230. te[12] = n14;
  3231. te[1] = n21;
  3232. te[5] = n22;
  3233. te[9] = n23;
  3234. te[13] = n24;
  3235. te[2] = n31;
  3236. te[6] = n32;
  3237. te[10] = n33;
  3238. te[14] = n34;
  3239. te[3] = n41;
  3240. te[7] = n42;
  3241. te[11] = n43;
  3242. te[15] = n44;
  3243. return this;
  3244. }
  3245. identity() {
  3246. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3247. return this;
  3248. }
  3249. clone() {
  3250. return new Matrix4().fromArray(this.elements);
  3251. }
  3252. copy(m) {
  3253. const te = this.elements;
  3254. const me = m.elements;
  3255. te[0] = me[0];
  3256. te[1] = me[1];
  3257. te[2] = me[2];
  3258. te[3] = me[3];
  3259. te[4] = me[4];
  3260. te[5] = me[5];
  3261. te[6] = me[6];
  3262. te[7] = me[7];
  3263. te[8] = me[8];
  3264. te[9] = me[9];
  3265. te[10] = me[10];
  3266. te[11] = me[11];
  3267. te[12] = me[12];
  3268. te[13] = me[13];
  3269. te[14] = me[14];
  3270. te[15] = me[15];
  3271. return this;
  3272. }
  3273. copyPosition(m) {
  3274. const te = this.elements,
  3275. me = m.elements;
  3276. te[12] = me[12];
  3277. te[13] = me[13];
  3278. te[14] = me[14];
  3279. return this;
  3280. }
  3281. setFromMatrix3(m) {
  3282. const me = m.elements;
  3283. this.set(me[0], me[3], me[6], 0, me[1], me[4], me[7], 0, me[2], me[5], me[8], 0, 0, 0, 0, 1);
  3284. return this;
  3285. }
  3286. extractBasis(xAxis, yAxis, zAxis) {
  3287. xAxis.setFromMatrixColumn(this, 0);
  3288. yAxis.setFromMatrixColumn(this, 1);
  3289. zAxis.setFromMatrixColumn(this, 2);
  3290. return this;
  3291. }
  3292. makeBasis(xAxis, yAxis, zAxis) {
  3293. this.set(xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0, 0, 0, 0, 1);
  3294. return this;
  3295. }
  3296. extractRotation(m) {
  3297. // this method does not support reflection matrices
  3298. const te = this.elements;
  3299. const me = m.elements;
  3300. const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length();
  3301. const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length();
  3302. const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length();
  3303. te[0] = me[0] * scaleX;
  3304. te[1] = me[1] * scaleX;
  3305. te[2] = me[2] * scaleX;
  3306. te[3] = 0;
  3307. te[4] = me[4] * scaleY;
  3308. te[5] = me[5] * scaleY;
  3309. te[6] = me[6] * scaleY;
  3310. te[7] = 0;
  3311. te[8] = me[8] * scaleZ;
  3312. te[9] = me[9] * scaleZ;
  3313. te[10] = me[10] * scaleZ;
  3314. te[11] = 0;
  3315. te[12] = 0;
  3316. te[13] = 0;
  3317. te[14] = 0;
  3318. te[15] = 1;
  3319. return this;
  3320. }
  3321. makeRotationFromEuler(euler) {
  3322. if (!(euler && euler.isEuler)) {
  3323. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  3324. }
  3325. const te = this.elements;
  3326. const x = euler.x,
  3327. y = euler.y,
  3328. z = euler.z;
  3329. const a = Math.cos(x),
  3330. b = Math.sin(x);
  3331. const c = Math.cos(y),
  3332. d = Math.sin(y);
  3333. const e = Math.cos(z),
  3334. f = Math.sin(z);
  3335. if (euler.order === 'XYZ') {
  3336. const ae = a * e,
  3337. af = a * f,
  3338. be = b * e,
  3339. bf = b * f;
  3340. te[0] = c * e;
  3341. te[4] = -c * f;
  3342. te[8] = d;
  3343. te[1] = af + be * d;
  3344. te[5] = ae - bf * d;
  3345. te[9] = -b * c;
  3346. te[2] = bf - ae * d;
  3347. te[6] = be + af * d;
  3348. te[10] = a * c;
  3349. } else if (euler.order === 'YXZ') {
  3350. const ce = c * e,
  3351. cf = c * f,
  3352. de = d * e,
  3353. df = d * f;
  3354. te[0] = ce + df * b;
  3355. te[4] = de * b - cf;
  3356. te[8] = a * d;
  3357. te[1] = a * f;
  3358. te[5] = a * e;
  3359. te[9] = -b;
  3360. te[2] = cf * b - de;
  3361. te[6] = df + ce * b;
  3362. te[10] = a * c;
  3363. } else if (euler.order === 'ZXY') {
  3364. const ce = c * e,
  3365. cf = c * f,
  3366. de = d * e,
  3367. df = d * f;
  3368. te[0] = ce - df * b;
  3369. te[4] = -a * f;
  3370. te[8] = de + cf * b;
  3371. te[1] = cf + de * b;
  3372. te[5] = a * e;
  3373. te[9] = df - ce * b;
  3374. te[2] = -a * d;
  3375. te[6] = b;
  3376. te[10] = a * c;
  3377. } else if (euler.order === 'ZYX') {
  3378. const ae = a * e,
  3379. af = a * f,
  3380. be = b * e,
  3381. bf = b * f;
  3382. te[0] = c * e;
  3383. te[4] = be * d - af;
  3384. te[8] = ae * d + bf;
  3385. te[1] = c * f;
  3386. te[5] = bf * d + ae;
  3387. te[9] = af * d - be;
  3388. te[2] = -d;
  3389. te[6] = b * c;
  3390. te[10] = a * c;
  3391. } else if (euler.order === 'YZX') {
  3392. const ac = a * c,
  3393. ad = a * d,
  3394. bc = b * c,
  3395. bd = b * d;
  3396. te[0] = c * e;
  3397. te[4] = bd - ac * f;
  3398. te[8] = bc * f + ad;
  3399. te[1] = f;
  3400. te[5] = a * e;
  3401. te[9] = -b * e;
  3402. te[2] = -d * e;
  3403. te[6] = ad * f + bc;
  3404. te[10] = ac - bd * f;
  3405. } else if (euler.order === 'XZY') {
  3406. const ac = a * c,
  3407. ad = a * d,
  3408. bc = b * c,
  3409. bd = b * d;
  3410. te[0] = c * e;
  3411. te[4] = -f;
  3412. te[8] = d * e;
  3413. te[1] = ac * f + bd;
  3414. te[5] = a * e;
  3415. te[9] = ad * f - bc;
  3416. te[2] = bc * f - ad;
  3417. te[6] = b * e;
  3418. te[10] = bd * f + ac;
  3419. } // bottom row
  3420. te[3] = 0;
  3421. te[7] = 0;
  3422. te[11] = 0; // last column
  3423. te[12] = 0;
  3424. te[13] = 0;
  3425. te[14] = 0;
  3426. te[15] = 1;
  3427. return this;
  3428. }
  3429. makeRotationFromQuaternion(q) {
  3430. return this.compose(_zero, q, _one);
  3431. }
  3432. lookAt(eye, target, up) {
  3433. const te = this.elements;
  3434. _z.subVectors(eye, target);
  3435. if (_z.lengthSq() === 0) {
  3436. // eye and target are in the same position
  3437. _z.z = 1;
  3438. }
  3439. _z.normalize();
  3440. _x.crossVectors(up, _z);
  3441. if (_x.lengthSq() === 0) {
  3442. // up and z are parallel
  3443. if (Math.abs(up.z) === 1) {
  3444. _z.x += 0.0001;
  3445. } else {
  3446. _z.z += 0.0001;
  3447. }
  3448. _z.normalize();
  3449. _x.crossVectors(up, _z);
  3450. }
  3451. _x.normalize();
  3452. _y.crossVectors(_z, _x);
  3453. te[0] = _x.x;
  3454. te[4] = _y.x;
  3455. te[8] = _z.x;
  3456. te[1] = _x.y;
  3457. te[5] = _y.y;
  3458. te[9] = _z.y;
  3459. te[2] = _x.z;
  3460. te[6] = _y.z;
  3461. te[10] = _z.z;
  3462. return this;
  3463. }
  3464. multiply(m, n) {
  3465. if (n !== undefined) {
  3466. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  3467. return this.multiplyMatrices(m, n);
  3468. }
  3469. return this.multiplyMatrices(this, m);
  3470. }
  3471. premultiply(m) {
  3472. return this.multiplyMatrices(m, this);
  3473. }
  3474. multiplyMatrices(a, b) {
  3475. const ae = a.elements;
  3476. const be = b.elements;
  3477. const te = this.elements;
  3478. const a11 = ae[0],
  3479. a12 = ae[4],
  3480. a13 = ae[8],
  3481. a14 = ae[12];
  3482. const a21 = ae[1],
  3483. a22 = ae[5],
  3484. a23 = ae[9],
  3485. a24 = ae[13];
  3486. const a31 = ae[2],
  3487. a32 = ae[6],
  3488. a33 = ae[10],
  3489. a34 = ae[14];
  3490. const a41 = ae[3],
  3491. a42 = ae[7],
  3492. a43 = ae[11],
  3493. a44 = ae[15];
  3494. const b11 = be[0],
  3495. b12 = be[4],
  3496. b13 = be[8],
  3497. b14 = be[12];
  3498. const b21 = be[1],
  3499. b22 = be[5],
  3500. b23 = be[9],
  3501. b24 = be[13];
  3502. const b31 = be[2],
  3503. b32 = be[6],
  3504. b33 = be[10],
  3505. b34 = be[14];
  3506. const b41 = be[3],
  3507. b42 = be[7],
  3508. b43 = be[11],
  3509. b44 = be[15];
  3510. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3511. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3512. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3513. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3514. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3515. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3516. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3517. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3518. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3519. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3520. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3521. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3522. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3523. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3524. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3525. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3526. return this;
  3527. }
  3528. multiplyScalar(s) {
  3529. const te = this.elements;
  3530. te[0] *= s;
  3531. te[4] *= s;
  3532. te[8] *= s;
  3533. te[12] *= s;
  3534. te[1] *= s;
  3535. te[5] *= s;
  3536. te[9] *= s;
  3537. te[13] *= s;
  3538. te[2] *= s;
  3539. te[6] *= s;
  3540. te[10] *= s;
  3541. te[14] *= s;
  3542. te[3] *= s;
  3543. te[7] *= s;
  3544. te[11] *= s;
  3545. te[15] *= s;
  3546. return this;
  3547. }
  3548. determinant() {
  3549. const te = this.elements;
  3550. const n11 = te[0],
  3551. n12 = te[4],
  3552. n13 = te[8],
  3553. n14 = te[12];
  3554. const n21 = te[1],
  3555. n22 = te[5],
  3556. n23 = te[9],
  3557. n24 = te[13];
  3558. const n31 = te[2],
  3559. n32 = te[6],
  3560. n33 = te[10],
  3561. n34 = te[14];
  3562. const n41 = te[3],
  3563. n42 = te[7],
  3564. n43 = te[11],
  3565. n44 = te[15]; //TODO: make this more efficient
  3566. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3567. return n41 * (+n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) + n42 * (+n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) + n43 * (+n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31);
  3568. }
  3569. transpose() {
  3570. const te = this.elements;
  3571. let tmp;
  3572. tmp = te[1];
  3573. te[1] = te[4];
  3574. te[4] = tmp;
  3575. tmp = te[2];
  3576. te[2] = te[8];
  3577. te[8] = tmp;
  3578. tmp = te[6];
  3579. te[6] = te[9];
  3580. te[9] = tmp;
  3581. tmp = te[3];
  3582. te[3] = te[12];
  3583. te[12] = tmp;
  3584. tmp = te[7];
  3585. te[7] = te[13];
  3586. te[13] = tmp;
  3587. tmp = te[11];
  3588. te[11] = te[14];
  3589. te[14] = tmp;
  3590. return this;
  3591. }
  3592. setPosition(x, y, z) {
  3593. const te = this.elements;
  3594. if (x.isVector3) {
  3595. te[12] = x.x;
  3596. te[13] = x.y;
  3597. te[14] = x.z;
  3598. } else {
  3599. te[12] = x;
  3600. te[13] = y;
  3601. te[14] = z;
  3602. }
  3603. return this;
  3604. }
  3605. invert() {
  3606. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3607. const te = this.elements,
  3608. n11 = te[0],
  3609. n21 = te[1],
  3610. n31 = te[2],
  3611. n41 = te[3],
  3612. n12 = te[4],
  3613. n22 = te[5],
  3614. n32 = te[6],
  3615. n42 = te[7],
  3616. n13 = te[8],
  3617. n23 = te[9],
  3618. n33 = te[10],
  3619. n43 = te[11],
  3620. n14 = te[12],
  3621. n24 = te[13],
  3622. n34 = te[14],
  3623. n44 = te[15],
  3624. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3625. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3626. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3627. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3628. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3629. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  3630. const detInv = 1 / det;
  3631. te[0] = t11 * detInv;
  3632. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  3633. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  3634. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  3635. te[4] = t12 * detInv;
  3636. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  3637. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  3638. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  3639. te[8] = t13 * detInv;
  3640. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  3641. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  3642. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  3643. te[12] = t14 * detInv;
  3644. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  3645. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  3646. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  3647. return this;
  3648. }
  3649. scale(v) {
  3650. const te = this.elements;
  3651. const x = v.x,
  3652. y = v.y,
  3653. z = v.z;
  3654. te[0] *= x;
  3655. te[4] *= y;
  3656. te[8] *= z;
  3657. te[1] *= x;
  3658. te[5] *= y;
  3659. te[9] *= z;
  3660. te[2] *= x;
  3661. te[6] *= y;
  3662. te[10] *= z;
  3663. te[3] *= x;
  3664. te[7] *= y;
  3665. te[11] *= z;
  3666. return this;
  3667. }
  3668. getMaxScaleOnAxis() {
  3669. const te = this.elements;
  3670. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  3671. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  3672. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  3673. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  3674. }
  3675. makeTranslation(x, y, z) {
  3676. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  3677. return this;
  3678. }
  3679. makeRotationX(theta) {
  3680. const c = Math.cos(theta),
  3681. s = Math.sin(theta);
  3682. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  3683. return this;
  3684. }
  3685. makeRotationY(theta) {
  3686. const c = Math.cos(theta),
  3687. s = Math.sin(theta);
  3688. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  3689. return this;
  3690. }
  3691. makeRotationZ(theta) {
  3692. const c = Math.cos(theta),
  3693. s = Math.sin(theta);
  3694. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3695. return this;
  3696. }
  3697. makeRotationAxis(axis, angle) {
  3698. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3699. const c = Math.cos(angle);
  3700. const s = Math.sin(angle);
  3701. const t = 1 - c;
  3702. const x = axis.x,
  3703. y = axis.y,
  3704. z = axis.z;
  3705. const tx = t * x,
  3706. ty = t * y;
  3707. this.set(tx * x + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x, 0, tx * z - s * y, ty * z + s * x, t * z * z + c, 0, 0, 0, 0, 1);
  3708. return this;
  3709. }
  3710. makeScale(x, y, z) {
  3711. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  3712. return this;
  3713. }
  3714. makeShear(xy, xz, yx, yz, zx, zy) {
  3715. this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1);
  3716. return this;
  3717. }
  3718. compose(position, quaternion, scale) {
  3719. const te = this.elements;
  3720. const x = quaternion._x,
  3721. y = quaternion._y,
  3722. z = quaternion._z,
  3723. w = quaternion._w;
  3724. const x2 = x + x,
  3725. y2 = y + y,
  3726. z2 = z + z;
  3727. const xx = x * x2,
  3728. xy = x * y2,
  3729. xz = x * z2;
  3730. const yy = y * y2,
  3731. yz = y * z2,
  3732. zz = z * z2;
  3733. const wx = w * x2,
  3734. wy = w * y2,
  3735. wz = w * z2;
  3736. const sx = scale.x,
  3737. sy = scale.y,
  3738. sz = scale.z;
  3739. te[0] = (1 - (yy + zz)) * sx;
  3740. te[1] = (xy + wz) * sx;
  3741. te[2] = (xz - wy) * sx;
  3742. te[3] = 0;
  3743. te[4] = (xy - wz) * sy;
  3744. te[5] = (1 - (xx + zz)) * sy;
  3745. te[6] = (yz + wx) * sy;
  3746. te[7] = 0;
  3747. te[8] = (xz + wy) * sz;
  3748. te[9] = (yz - wx) * sz;
  3749. te[10] = (1 - (xx + yy)) * sz;
  3750. te[11] = 0;
  3751. te[12] = position.x;
  3752. te[13] = position.y;
  3753. te[14] = position.z;
  3754. te[15] = 1;
  3755. return this;
  3756. }
  3757. decompose(position, quaternion, scale) {
  3758. const te = this.elements;
  3759. let sx = _v1$5.set(te[0], te[1], te[2]).length();
  3760. const sy = _v1$5.set(te[4], te[5], te[6]).length();
  3761. const sz = _v1$5.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  3762. const det = this.determinant();
  3763. if (det < 0) sx = -sx;
  3764. position.x = te[12];
  3765. position.y = te[13];
  3766. position.z = te[14]; // scale the rotation part
  3767. _m1$2.copy(this);
  3768. const invSX = 1 / sx;
  3769. const invSY = 1 / sy;
  3770. const invSZ = 1 / sz;
  3771. _m1$2.elements[0] *= invSX;
  3772. _m1$2.elements[1] *= invSX;
  3773. _m1$2.elements[2] *= invSX;
  3774. _m1$2.elements[4] *= invSY;
  3775. _m1$2.elements[5] *= invSY;
  3776. _m1$2.elements[6] *= invSY;
  3777. _m1$2.elements[8] *= invSZ;
  3778. _m1$2.elements[9] *= invSZ;
  3779. _m1$2.elements[10] *= invSZ;
  3780. quaternion.setFromRotationMatrix(_m1$2);
  3781. scale.x = sx;
  3782. scale.y = sy;
  3783. scale.z = sz;
  3784. return this;
  3785. }
  3786. makePerspective(left, right, top, bottom, near, far) {
  3787. if (far === undefined) {
  3788. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  3789. }
  3790. const te = this.elements;
  3791. const x = 2 * near / (right - left);
  3792. const y = 2 * near / (top - bottom);
  3793. const a = (right + left) / (right - left);
  3794. const b = (top + bottom) / (top - bottom);
  3795. const c = -(far + near) / (far - near);
  3796. const d = -2 * far * near / (far - near);
  3797. te[0] = x;
  3798. te[4] = 0;
  3799. te[8] = a;
  3800. te[12] = 0;
  3801. te[1] = 0;
  3802. te[5] = y;
  3803. te[9] = b;
  3804. te[13] = 0;
  3805. te[2] = 0;
  3806. te[6] = 0;
  3807. te[10] = c;
  3808. te[14] = d;
  3809. te[3] = 0;
  3810. te[7] = 0;
  3811. te[11] = -1;
  3812. te[15] = 0;
  3813. return this;
  3814. }
  3815. makeOrthographic(left, right, top, bottom, near, far) {
  3816. const te = this.elements;
  3817. const w = 1.0 / (right - left);
  3818. const h = 1.0 / (top - bottom);
  3819. const p = 1.0 / (far - near);
  3820. const x = (right + left) * w;
  3821. const y = (top + bottom) * h;
  3822. const z = (far + near) * p;
  3823. te[0] = 2 * w;
  3824. te[4] = 0;
  3825. te[8] = 0;
  3826. te[12] = -x;
  3827. te[1] = 0;
  3828. te[5] = 2 * h;
  3829. te[9] = 0;
  3830. te[13] = -y;
  3831. te[2] = 0;
  3832. te[6] = 0;
  3833. te[10] = -2 * p;
  3834. te[14] = -z;
  3835. te[3] = 0;
  3836. te[7] = 0;
  3837. te[11] = 0;
  3838. te[15] = 1;
  3839. return this;
  3840. }
  3841. equals(matrix) {
  3842. const te = this.elements;
  3843. const me = matrix.elements;
  3844. for (let i = 0; i < 16; i++) {
  3845. if (te[i] !== me[i]) return false;
  3846. }
  3847. return true;
  3848. }
  3849. fromArray(array, offset = 0) {
  3850. for (let i = 0; i < 16; i++) {
  3851. this.elements[i] = array[i + offset];
  3852. }
  3853. return this;
  3854. }
  3855. toArray(array = [], offset = 0) {
  3856. const te = this.elements;
  3857. array[offset] = te[0];
  3858. array[offset + 1] = te[1];
  3859. array[offset + 2] = te[2];
  3860. array[offset + 3] = te[3];
  3861. array[offset + 4] = te[4];
  3862. array[offset + 5] = te[5];
  3863. array[offset + 6] = te[6];
  3864. array[offset + 7] = te[7];
  3865. array[offset + 8] = te[8];
  3866. array[offset + 9] = te[9];
  3867. array[offset + 10] = te[10];
  3868. array[offset + 11] = te[11];
  3869. array[offset + 12] = te[12];
  3870. array[offset + 13] = te[13];
  3871. array[offset + 14] = te[14];
  3872. array[offset + 15] = te[15];
  3873. return array;
  3874. }
  3875. }
  3876. Matrix4.prototype.isMatrix4 = true;
  3877. const _v1$5 = /*@__PURE__*/new Vector3();
  3878. const _m1$2 = /*@__PURE__*/new Matrix4();
  3879. const _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  3880. const _one = /*@__PURE__*/new Vector3(1, 1, 1);
  3881. const _x = /*@__PURE__*/new Vector3();
  3882. const _y = /*@__PURE__*/new Vector3();
  3883. const _z = /*@__PURE__*/new Vector3();
  3884. const _matrix$1 = /*@__PURE__*/new Matrix4();
  3885. const _quaternion$3 = /*@__PURE__*/new Quaternion();
  3886. class Euler {
  3887. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  3888. this._x = x;
  3889. this._y = y;
  3890. this._z = z;
  3891. this._order = order;
  3892. }
  3893. get x() {
  3894. return this._x;
  3895. }
  3896. set x(value) {
  3897. this._x = value;
  3898. this._onChangeCallback();
  3899. }
  3900. get y() {
  3901. return this._y;
  3902. }
  3903. set y(value) {
  3904. this._y = value;
  3905. this._onChangeCallback();
  3906. }
  3907. get z() {
  3908. return this._z;
  3909. }
  3910. set z(value) {
  3911. this._z = value;
  3912. this._onChangeCallback();
  3913. }
  3914. get order() {
  3915. return this._order;
  3916. }
  3917. set order(value) {
  3918. this._order = value;
  3919. this._onChangeCallback();
  3920. }
  3921. set(x, y, z, order = this._order) {
  3922. this._x = x;
  3923. this._y = y;
  3924. this._z = z;
  3925. this._order = order;
  3926. this._onChangeCallback();
  3927. return this;
  3928. }
  3929. clone() {
  3930. return new this.constructor(this._x, this._y, this._z, this._order);
  3931. }
  3932. copy(euler) {
  3933. this._x = euler._x;
  3934. this._y = euler._y;
  3935. this._z = euler._z;
  3936. this._order = euler._order;
  3937. this._onChangeCallback();
  3938. return this;
  3939. }
  3940. setFromRotationMatrix(m, order = this._order, update = true) {
  3941. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3942. const te = m.elements;
  3943. const m11 = te[0],
  3944. m12 = te[4],
  3945. m13 = te[8];
  3946. const m21 = te[1],
  3947. m22 = te[5],
  3948. m23 = te[9];
  3949. const m31 = te[2],
  3950. m32 = te[6],
  3951. m33 = te[10];
  3952. switch (order) {
  3953. case 'XYZ':
  3954. this._y = Math.asin(clamp(m13, -1, 1));
  3955. if (Math.abs(m13) < 0.9999999) {
  3956. this._x = Math.atan2(-m23, m33);
  3957. this._z = Math.atan2(-m12, m11);
  3958. } else {
  3959. this._x = Math.atan2(m32, m22);
  3960. this._z = 0;
  3961. }
  3962. break;
  3963. case 'YXZ':
  3964. this._x = Math.asin(-clamp(m23, -1, 1));
  3965. if (Math.abs(m23) < 0.9999999) {
  3966. this._y = Math.atan2(m13, m33);
  3967. this._z = Math.atan2(m21, m22);
  3968. } else {
  3969. this._y = Math.atan2(-m31, m11);
  3970. this._z = 0;
  3971. }
  3972. break;
  3973. case 'ZXY':
  3974. this._x = Math.asin(clamp(m32, -1, 1));
  3975. if (Math.abs(m32) < 0.9999999) {
  3976. this._y = Math.atan2(-m31, m33);
  3977. this._z = Math.atan2(-m12, m22);
  3978. } else {
  3979. this._y = 0;
  3980. this._z = Math.atan2(m21, m11);
  3981. }
  3982. break;
  3983. case 'ZYX':
  3984. this._y = Math.asin(-clamp(m31, -1, 1));
  3985. if (Math.abs(m31) < 0.9999999) {
  3986. this._x = Math.atan2(m32, m33);
  3987. this._z = Math.atan2(m21, m11);
  3988. } else {
  3989. this._x = 0;
  3990. this._z = Math.atan2(-m12, m22);
  3991. }
  3992. break;
  3993. case 'YZX':
  3994. this._z = Math.asin(clamp(m21, -1, 1));
  3995. if (Math.abs(m21) < 0.9999999) {
  3996. this._x = Math.atan2(-m23, m22);
  3997. this._y = Math.atan2(-m31, m11);
  3998. } else {
  3999. this._x = 0;
  4000. this._y = Math.atan2(m13, m33);
  4001. }
  4002. break;
  4003. case 'XZY':
  4004. this._z = Math.asin(-clamp(m12, -1, 1));
  4005. if (Math.abs(m12) < 0.9999999) {
  4006. this._x = Math.atan2(m32, m22);
  4007. this._y = Math.atan2(m13, m11);
  4008. } else {
  4009. this._x = Math.atan2(-m23, m33);
  4010. this._y = 0;
  4011. }
  4012. break;
  4013. default:
  4014. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  4015. }
  4016. this._order = order;
  4017. if (update === true) this._onChangeCallback();
  4018. return this;
  4019. }
  4020. setFromQuaternion(q, order, update) {
  4021. _matrix$1.makeRotationFromQuaternion(q);
  4022. return this.setFromRotationMatrix(_matrix$1, order, update);
  4023. }
  4024. setFromVector3(v, order = this._order) {
  4025. return this.set(v.x, v.y, v.z, order);
  4026. }
  4027. reorder(newOrder) {
  4028. // WARNING: this discards revolution information -bhouston
  4029. _quaternion$3.setFromEuler(this);
  4030. return this.setFromQuaternion(_quaternion$3, newOrder);
  4031. }
  4032. equals(euler) {
  4033. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4034. }
  4035. fromArray(array) {
  4036. this._x = array[0];
  4037. this._y = array[1];
  4038. this._z = array[2];
  4039. if (array[3] !== undefined) this._order = array[3];
  4040. this._onChangeCallback();
  4041. return this;
  4042. }
  4043. toArray(array = [], offset = 0) {
  4044. array[offset] = this._x;
  4045. array[offset + 1] = this._y;
  4046. array[offset + 2] = this._z;
  4047. array[offset + 3] = this._order;
  4048. return array;
  4049. }
  4050. toVector3(optionalResult) {
  4051. if (optionalResult) {
  4052. return optionalResult.set(this._x, this._y, this._z);
  4053. } else {
  4054. return new Vector3(this._x, this._y, this._z);
  4055. }
  4056. }
  4057. _onChange(callback) {
  4058. this._onChangeCallback = callback;
  4059. return this;
  4060. }
  4061. _onChangeCallback() {}
  4062. }
  4063. Euler.prototype.isEuler = true;
  4064. Euler.DefaultOrder = 'XYZ';
  4065. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4066. class Layers {
  4067. constructor() {
  4068. this.mask = 1 | 0;
  4069. }
  4070. set(channel) {
  4071. this.mask = 1 << channel | 0;
  4072. }
  4073. enable(channel) {
  4074. this.mask |= 1 << channel | 0;
  4075. }
  4076. enableAll() {
  4077. this.mask = 0xffffffff | 0;
  4078. }
  4079. toggle(channel) {
  4080. this.mask ^= 1 << channel | 0;
  4081. }
  4082. disable(channel) {
  4083. this.mask &= ~(1 << channel | 0);
  4084. }
  4085. disableAll() {
  4086. this.mask = 0;
  4087. }
  4088. test(layers) {
  4089. return (this.mask & layers.mask) !== 0;
  4090. }
  4091. }
  4092. let _object3DId = 0;
  4093. const _v1$4 = /*@__PURE__*/new Vector3();
  4094. const _q1 = /*@__PURE__*/new Quaternion();
  4095. const _m1$1 = /*@__PURE__*/new Matrix4();
  4096. const _target = /*@__PURE__*/new Vector3();
  4097. const _position$3 = /*@__PURE__*/new Vector3();
  4098. const _scale$2 = /*@__PURE__*/new Vector3();
  4099. const _quaternion$2 = /*@__PURE__*/new Quaternion();
  4100. const _xAxis = /*@__PURE__*/new Vector3(1, 0, 0);
  4101. const _yAxis = /*@__PURE__*/new Vector3(0, 1, 0);
  4102. const _zAxis = /*@__PURE__*/new Vector3(0, 0, 1);
  4103. const _addedEvent = {
  4104. type: 'added'
  4105. };
  4106. const _removedEvent = {
  4107. type: 'removed'
  4108. };
  4109. class Object3D extends EventDispatcher {
  4110. constructor() {
  4111. super();
  4112. Object.defineProperty(this, 'id', {
  4113. value: _object3DId++
  4114. });
  4115. this.uuid = generateUUID();
  4116. this.name = '';
  4117. this.type = 'Object3D';
  4118. this.parent = null;
  4119. this.children = [];
  4120. this.up = Object3D.DefaultUp.clone();
  4121. const position = new Vector3();
  4122. const rotation = new Euler();
  4123. const quaternion = new Quaternion();
  4124. const scale = new Vector3(1, 1, 1);
  4125. function onRotationChange() {
  4126. quaternion.setFromEuler(rotation, false);
  4127. }
  4128. function onQuaternionChange() {
  4129. rotation.setFromQuaternion(quaternion, undefined, false);
  4130. }
  4131. rotation._onChange(onRotationChange);
  4132. quaternion._onChange(onQuaternionChange);
  4133. Object.defineProperties(this, {
  4134. position: {
  4135. configurable: true,
  4136. enumerable: true,
  4137. value: position
  4138. },
  4139. rotation: {
  4140. configurable: true,
  4141. enumerable: true,
  4142. value: rotation
  4143. },
  4144. quaternion: {
  4145. configurable: true,
  4146. enumerable: true,
  4147. value: quaternion
  4148. },
  4149. scale: {
  4150. configurable: true,
  4151. enumerable: true,
  4152. value: scale
  4153. },
  4154. modelViewMatrix: {
  4155. value: new Matrix4()
  4156. },
  4157. normalMatrix: {
  4158. value: new Matrix3()
  4159. }
  4160. });
  4161. this.matrix = new Matrix4();
  4162. this.matrixWorld = new Matrix4();
  4163. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4164. this.matrixWorldNeedsUpdate = false;
  4165. this.layers = new Layers();
  4166. this.visible = true;
  4167. this.castShadow = false;
  4168. this.receiveShadow = false;
  4169. this.frustumCulled = true;
  4170. this.renderOrder = 0;
  4171. this.animations = [];
  4172. this.userData = {};
  4173. }
  4174. onBeforeRender() {}
  4175. onAfterRender() {}
  4176. applyMatrix4(matrix) {
  4177. if (this.matrixAutoUpdate) this.updateMatrix();
  4178. this.matrix.premultiply(matrix);
  4179. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4180. }
  4181. applyQuaternion(q) {
  4182. this.quaternion.premultiply(q);
  4183. return this;
  4184. }
  4185. setRotationFromAxisAngle(axis, angle) {
  4186. // assumes axis is normalized
  4187. this.quaternion.setFromAxisAngle(axis, angle);
  4188. }
  4189. setRotationFromEuler(euler) {
  4190. this.quaternion.setFromEuler(euler, true);
  4191. }
  4192. setRotationFromMatrix(m) {
  4193. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4194. this.quaternion.setFromRotationMatrix(m);
  4195. }
  4196. setRotationFromQuaternion(q) {
  4197. // assumes q is normalized
  4198. this.quaternion.copy(q);
  4199. }
  4200. rotateOnAxis(axis, angle) {
  4201. // rotate object on axis in object space
  4202. // axis is assumed to be normalized
  4203. _q1.setFromAxisAngle(axis, angle);
  4204. this.quaternion.multiply(_q1);
  4205. return this;
  4206. }
  4207. rotateOnWorldAxis(axis, angle) {
  4208. // rotate object on axis in world space
  4209. // axis is assumed to be normalized
  4210. // method assumes no rotated parent
  4211. _q1.setFromAxisAngle(axis, angle);
  4212. this.quaternion.premultiply(_q1);
  4213. return this;
  4214. }
  4215. rotateX(angle) {
  4216. return this.rotateOnAxis(_xAxis, angle);
  4217. }
  4218. rotateY(angle) {
  4219. return this.rotateOnAxis(_yAxis, angle);
  4220. }
  4221. rotateZ(angle) {
  4222. return this.rotateOnAxis(_zAxis, angle);
  4223. }
  4224. translateOnAxis(axis, distance) {
  4225. // translate object by distance along axis in object space
  4226. // axis is assumed to be normalized
  4227. _v1$4.copy(axis).applyQuaternion(this.quaternion);
  4228. this.position.add(_v1$4.multiplyScalar(distance));
  4229. return this;
  4230. }
  4231. translateX(distance) {
  4232. return this.translateOnAxis(_xAxis, distance);
  4233. }
  4234. translateY(distance) {
  4235. return this.translateOnAxis(_yAxis, distance);
  4236. }
  4237. translateZ(distance) {
  4238. return this.translateOnAxis(_zAxis, distance);
  4239. }
  4240. localToWorld(vector) {
  4241. return vector.applyMatrix4(this.matrixWorld);
  4242. }
  4243. worldToLocal(vector) {
  4244. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  4245. }
  4246. lookAt(x, y, z) {
  4247. // This method does not support objects having non-uniformly-scaled parent(s)
  4248. if (x.isVector3) {
  4249. _target.copy(x);
  4250. } else {
  4251. _target.set(x, y, z);
  4252. }
  4253. const parent = this.parent;
  4254. this.updateWorldMatrix(true, false);
  4255. _position$3.setFromMatrixPosition(this.matrixWorld);
  4256. if (this.isCamera || this.isLight) {
  4257. _m1$1.lookAt(_position$3, _target, this.up);
  4258. } else {
  4259. _m1$1.lookAt(_target, _position$3, this.up);
  4260. }
  4261. this.quaternion.setFromRotationMatrix(_m1$1);
  4262. if (parent) {
  4263. _m1$1.extractRotation(parent.matrixWorld);
  4264. _q1.setFromRotationMatrix(_m1$1);
  4265. this.quaternion.premultiply(_q1.invert());
  4266. }
  4267. }
  4268. add(object) {
  4269. if (arguments.length > 1) {
  4270. for (let i = 0; i < arguments.length; i++) {
  4271. this.add(arguments[i]);
  4272. }
  4273. return this;
  4274. }
  4275. if (object === this) {
  4276. console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
  4277. return this;
  4278. }
  4279. if (object && object.isObject3D) {
  4280. if (object.parent !== null) {
  4281. object.parent.remove(object);
  4282. }
  4283. object.parent = this;
  4284. this.children.push(object);
  4285. object.dispatchEvent(_addedEvent);
  4286. } else {
  4287. console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
  4288. }
  4289. return this;
  4290. }
  4291. remove(object) {
  4292. if (arguments.length > 1) {
  4293. for (let i = 0; i < arguments.length; i++) {
  4294. this.remove(arguments[i]);
  4295. }
  4296. return this;
  4297. }
  4298. const index = this.children.indexOf(object);
  4299. if (index !== -1) {
  4300. object.parent = null;
  4301. this.children.splice(index, 1);
  4302. object.dispatchEvent(_removedEvent);
  4303. }
  4304. return this;
  4305. }
  4306. removeFromParent() {
  4307. const parent = this.parent;
  4308. if (parent !== null) {
  4309. parent.remove(this);
  4310. }
  4311. return this;
  4312. }
  4313. clear() {
  4314. for (let i = 0; i < this.children.length; i++) {
  4315. const object = this.children[i];
  4316. object.parent = null;
  4317. object.dispatchEvent(_removedEvent);
  4318. }
  4319. this.children.length = 0;
  4320. return this;
  4321. }
  4322. attach(object) {
  4323. // adds object as a child of this, while maintaining the object's world transform
  4324. this.updateWorldMatrix(true, false);
  4325. _m1$1.copy(this.matrixWorld).invert();
  4326. if (object.parent !== null) {
  4327. object.parent.updateWorldMatrix(true, false);
  4328. _m1$1.multiply(object.parent.matrixWorld);
  4329. }
  4330. object.applyMatrix4(_m1$1);
  4331. this.add(object);
  4332. object.updateWorldMatrix(false, true);
  4333. return this;
  4334. }
  4335. getObjectById(id) {
  4336. return this.getObjectByProperty('id', id);
  4337. }
  4338. getObjectByName(name) {
  4339. return this.getObjectByProperty('name', name);
  4340. }
  4341. getObjectByProperty(name, value) {
  4342. if (this[name] === value) return this;
  4343. for (let i = 0, l = this.children.length; i < l; i++) {
  4344. const child = this.children[i];
  4345. const object = child.getObjectByProperty(name, value);
  4346. if (object !== undefined) {
  4347. return object;
  4348. }
  4349. }
  4350. return undefined;
  4351. }
  4352. getWorldPosition(target) {
  4353. this.updateWorldMatrix(true, false);
  4354. return target.setFromMatrixPosition(this.matrixWorld);
  4355. }
  4356. getWorldQuaternion(target) {
  4357. this.updateWorldMatrix(true, false);
  4358. this.matrixWorld.decompose(_position$3, target, _scale$2);
  4359. return target;
  4360. }
  4361. getWorldScale(target) {
  4362. this.updateWorldMatrix(true, false);
  4363. this.matrixWorld.decompose(_position$3, _quaternion$2, target);
  4364. return target;
  4365. }
  4366. getWorldDirection(target) {
  4367. this.updateWorldMatrix(true, false);
  4368. const e = this.matrixWorld.elements;
  4369. return target.set(e[8], e[9], e[10]).normalize();
  4370. }
  4371. raycast() {}
  4372. traverse(callback) {
  4373. callback(this);
  4374. const children = this.children;
  4375. for (let i = 0, l = children.length; i < l; i++) {
  4376. children[i].traverse(callback);
  4377. }
  4378. }
  4379. traverseVisible(callback) {
  4380. if (this.visible === false) return;
  4381. callback(this);
  4382. const children = this.children;
  4383. for (let i = 0, l = children.length; i < l; i++) {
  4384. children[i].traverseVisible(callback);
  4385. }
  4386. }
  4387. traverseAncestors(callback) {
  4388. const parent = this.parent;
  4389. if (parent !== null) {
  4390. callback(parent);
  4391. parent.traverseAncestors(callback);
  4392. }
  4393. }
  4394. updateMatrix() {
  4395. this.matrix.compose(this.position, this.quaternion, this.scale);
  4396. this.matrixWorldNeedsUpdate = true;
  4397. }
  4398. updateMatrixWorld(force) {
  4399. if (this.matrixAutoUpdate) this.updateMatrix();
  4400. if (this.matrixWorldNeedsUpdate || force) {
  4401. if (this.parent === null) {
  4402. this.matrixWorld.copy(this.matrix);
  4403. } else {
  4404. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4405. }
  4406. this.matrixWorldNeedsUpdate = false;
  4407. force = true;
  4408. } // update children
  4409. const children = this.children;
  4410. for (let i = 0, l = children.length; i < l; i++) {
  4411. children[i].updateMatrixWorld(force);
  4412. }
  4413. }
  4414. updateWorldMatrix(updateParents, updateChildren) {
  4415. const parent = this.parent;
  4416. if (updateParents === true && parent !== null) {
  4417. parent.updateWorldMatrix(true, false);
  4418. }
  4419. if (this.matrixAutoUpdate) this.updateMatrix();
  4420. if (this.parent === null) {
  4421. this.matrixWorld.copy(this.matrix);
  4422. } else {
  4423. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4424. } // update children
  4425. if (updateChildren === true) {
  4426. const children = this.children;
  4427. for (let i = 0, l = children.length; i < l; i++) {
  4428. children[i].updateWorldMatrix(false, true);
  4429. }
  4430. }
  4431. }
  4432. toJSON(meta) {
  4433. // meta is a string when called from JSON.stringify
  4434. const isRootObject = meta === undefined || typeof meta === 'string';
  4435. const output = {}; // meta is a hash used to collect geometries, materials.
  4436. // not providing it implies that this is the root object
  4437. // being serialized.
  4438. if (isRootObject) {
  4439. // initialize meta obj
  4440. meta = {
  4441. geometries: {},
  4442. materials: {},
  4443. textures: {},
  4444. images: {},
  4445. shapes: {},
  4446. skeletons: {},
  4447. animations: {}
  4448. };
  4449. output.metadata = {
  4450. version: 4.5,
  4451. type: 'Object',
  4452. generator: 'Object3D.toJSON'
  4453. };
  4454. } // standard Object3D serialization
  4455. const object = {};
  4456. object.uuid = this.uuid;
  4457. object.type = this.type;
  4458. if (this.name !== '') object.name = this.name;
  4459. if (this.castShadow === true) object.castShadow = true;
  4460. if (this.receiveShadow === true) object.receiveShadow = true;
  4461. if (this.visible === false) object.visible = false;
  4462. if (this.frustumCulled === false) object.frustumCulled = false;
  4463. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  4464. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  4465. object.layers = this.layers.mask;
  4466. object.matrix = this.matrix.toArray();
  4467. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  4468. if (this.isInstancedMesh) {
  4469. object.type = 'InstancedMesh';
  4470. object.count = this.count;
  4471. object.instanceMatrix = this.instanceMatrix.toJSON();
  4472. if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON();
  4473. } //
  4474. function serialize(library, element) {
  4475. if (library[element.uuid] === undefined) {
  4476. library[element.uuid] = element.toJSON(meta);
  4477. }
  4478. return element.uuid;
  4479. }
  4480. if (this.isScene) {
  4481. if (this.background) {
  4482. if (this.background.isColor) {
  4483. object.background = this.background.toJSON();
  4484. } else if (this.background.isTexture) {
  4485. object.background = this.background.toJSON(meta).uuid;
  4486. }
  4487. }
  4488. if (this.environment && this.environment.isTexture) {
  4489. object.environment = this.environment.toJSON(meta).uuid;
  4490. }
  4491. } else if (this.isMesh || this.isLine || this.isPoints) {
  4492. object.geometry = serialize(meta.geometries, this.geometry);
  4493. const parameters = this.geometry.parameters;
  4494. if (parameters !== undefined && parameters.shapes !== undefined) {
  4495. const shapes = parameters.shapes;
  4496. if (Array.isArray(shapes)) {
  4497. for (let i = 0, l = shapes.length; i < l; i++) {
  4498. const shape = shapes[i];
  4499. serialize(meta.shapes, shape);
  4500. }
  4501. } else {
  4502. serialize(meta.shapes, shapes);
  4503. }
  4504. }
  4505. }
  4506. if (this.isSkinnedMesh) {
  4507. object.bindMode = this.bindMode;
  4508. object.bindMatrix = this.bindMatrix.toArray();
  4509. if (this.skeleton !== undefined) {
  4510. serialize(meta.skeletons, this.skeleton);
  4511. object.skeleton = this.skeleton.uuid;
  4512. }
  4513. }
  4514. if (this.material !== undefined) {
  4515. if (Array.isArray(this.material)) {
  4516. const uuids = [];
  4517. for (let i = 0, l = this.material.length; i < l; i++) {
  4518. uuids.push(serialize(meta.materials, this.material[i]));
  4519. }
  4520. object.material = uuids;
  4521. } else {
  4522. object.material = serialize(meta.materials, this.material);
  4523. }
  4524. } //
  4525. if (this.children.length > 0) {
  4526. object.children = [];
  4527. for (let i = 0; i < this.children.length; i++) {
  4528. object.children.push(this.children[i].toJSON(meta).object);
  4529. }
  4530. } //
  4531. if (this.animations.length > 0) {
  4532. object.animations = [];
  4533. for (let i = 0; i < this.animations.length; i++) {
  4534. const animation = this.animations[i];
  4535. object.animations.push(serialize(meta.animations, animation));
  4536. }
  4537. }
  4538. if (isRootObject) {
  4539. const geometries = extractFromCache(meta.geometries);
  4540. const materials = extractFromCache(meta.materials);
  4541. const textures = extractFromCache(meta.textures);
  4542. const images = extractFromCache(meta.images);
  4543. const shapes = extractFromCache(meta.shapes);
  4544. const skeletons = extractFromCache(meta.skeletons);
  4545. const animations = extractFromCache(meta.animations);
  4546. if (geometries.length > 0) output.geometries = geometries;
  4547. if (materials.length > 0) output.materials = materials;
  4548. if (textures.length > 0) output.textures = textures;
  4549. if (images.length > 0) output.images = images;
  4550. if (shapes.length > 0) output.shapes = shapes;
  4551. if (skeletons.length > 0) output.skeletons = skeletons;
  4552. if (animations.length > 0) output.animations = animations;
  4553. }
  4554. output.object = object;
  4555. return output; // extract data from the cache hash
  4556. // remove metadata on each item
  4557. // and return as array
  4558. function extractFromCache(cache) {
  4559. const values = [];
  4560. for (const key in cache) {
  4561. const data = cache[key];
  4562. delete data.metadata;
  4563. values.push(data);
  4564. }
  4565. return values;
  4566. }
  4567. }
  4568. clone(recursive) {
  4569. return new this.constructor().copy(this, recursive);
  4570. }
  4571. copy(source, recursive = true) {
  4572. this.name = source.name;
  4573. this.up.copy(source.up);
  4574. this.position.copy(source.position);
  4575. this.rotation.order = source.rotation.order;
  4576. this.quaternion.copy(source.quaternion);
  4577. this.scale.copy(source.scale);
  4578. this.matrix.copy(source.matrix);
  4579. this.matrixWorld.copy(source.matrixWorld);
  4580. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4581. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4582. this.layers.mask = source.layers.mask;
  4583. this.visible = source.visible;
  4584. this.castShadow = source.castShadow;
  4585. this.receiveShadow = source.receiveShadow;
  4586. this.frustumCulled = source.frustumCulled;
  4587. this.renderOrder = source.renderOrder;
  4588. this.userData = JSON.parse(JSON.stringify(source.userData));
  4589. if (recursive === true) {
  4590. for (let i = 0; i < source.children.length; i++) {
  4591. const child = source.children[i];
  4592. this.add(child.clone());
  4593. }
  4594. }
  4595. return this;
  4596. }
  4597. }
  4598. Object3D.DefaultUp = new Vector3(0, 1, 0);
  4599. Object3D.DefaultMatrixAutoUpdate = true;
  4600. Object3D.prototype.isObject3D = true;
  4601. const _v0$1 = /*@__PURE__*/new Vector3();
  4602. const _v1$3 = /*@__PURE__*/new Vector3();
  4603. const _v2$2 = /*@__PURE__*/new Vector3();
  4604. const _v3$1 = /*@__PURE__*/new Vector3();
  4605. const _vab = /*@__PURE__*/new Vector3();
  4606. const _vac = /*@__PURE__*/new Vector3();
  4607. const _vbc = /*@__PURE__*/new Vector3();
  4608. const _vap = /*@__PURE__*/new Vector3();
  4609. const _vbp = /*@__PURE__*/new Vector3();
  4610. const _vcp = /*@__PURE__*/new Vector3();
  4611. class Triangle {
  4612. constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) {
  4613. this.a = a;
  4614. this.b = b;
  4615. this.c = c;
  4616. }
  4617. static getNormal(a, b, c, target) {
  4618. target.subVectors(c, b);
  4619. _v0$1.subVectors(a, b);
  4620. target.cross(_v0$1);
  4621. const targetLengthSq = target.lengthSq();
  4622. if (targetLengthSq > 0) {
  4623. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  4624. }
  4625. return target.set(0, 0, 0);
  4626. } // static/instance method to calculate barycentric coordinates
  4627. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4628. static getBarycoord(point, a, b, c, target) {
  4629. _v0$1.subVectors(c, a);
  4630. _v1$3.subVectors(b, a);
  4631. _v2$2.subVectors(point, a);
  4632. const dot00 = _v0$1.dot(_v0$1);
  4633. const dot01 = _v0$1.dot(_v1$3);
  4634. const dot02 = _v0$1.dot(_v2$2);
  4635. const dot11 = _v1$3.dot(_v1$3);
  4636. const dot12 = _v1$3.dot(_v2$2);
  4637. const denom = dot00 * dot11 - dot01 * dot01; // collinear or singular triangle
  4638. if (denom === 0) {
  4639. // arbitrary location outside of triangle?
  4640. // not sure if this is the best idea, maybe should be returning undefined
  4641. return target.set(-2, -1, -1);
  4642. }
  4643. const invDenom = 1 / denom;
  4644. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  4645. const v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  4646. return target.set(1 - u - v, v, u);
  4647. }
  4648. static containsPoint(point, a, b, c) {
  4649. this.getBarycoord(point, a, b, c, _v3$1);
  4650. return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1;
  4651. }
  4652. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  4653. this.getBarycoord(point, p1, p2, p3, _v3$1);
  4654. target.set(0, 0);
  4655. target.addScaledVector(uv1, _v3$1.x);
  4656. target.addScaledVector(uv2, _v3$1.y);
  4657. target.addScaledVector(uv3, _v3$1.z);
  4658. return target;
  4659. }
  4660. static isFrontFacing(a, b, c, direction) {
  4661. _v0$1.subVectors(c, b);
  4662. _v1$3.subVectors(a, b); // strictly front facing
  4663. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  4664. }
  4665. set(a, b, c) {
  4666. this.a.copy(a);
  4667. this.b.copy(b);
  4668. this.c.copy(c);
  4669. return this;
  4670. }
  4671. setFromPointsAndIndices(points, i0, i1, i2) {
  4672. this.a.copy(points[i0]);
  4673. this.b.copy(points[i1]);
  4674. this.c.copy(points[i2]);
  4675. return this;
  4676. }
  4677. clone() {
  4678. return new this.constructor().copy(this);
  4679. }
  4680. copy(triangle) {
  4681. this.a.copy(triangle.a);
  4682. this.b.copy(triangle.b);
  4683. this.c.copy(triangle.c);
  4684. return this;
  4685. }
  4686. getArea() {
  4687. _v0$1.subVectors(this.c, this.b);
  4688. _v1$3.subVectors(this.a, this.b);
  4689. return _v0$1.cross(_v1$3).length() * 0.5;
  4690. }
  4691. getMidpoint(target) {
  4692. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  4693. }
  4694. getNormal(target) {
  4695. return Triangle.getNormal(this.a, this.b, this.c, target);
  4696. }
  4697. getPlane(target) {
  4698. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  4699. }
  4700. getBarycoord(point, target) {
  4701. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  4702. }
  4703. getUV(point, uv1, uv2, uv3, target) {
  4704. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  4705. }
  4706. containsPoint(point) {
  4707. return Triangle.containsPoint(point, this.a, this.b, this.c);
  4708. }
  4709. isFrontFacing(direction) {
  4710. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  4711. }
  4712. intersectsBox(box) {
  4713. return box.intersectsTriangle(this);
  4714. }
  4715. closestPointToPoint(p, target) {
  4716. const a = this.a,
  4717. b = this.b,
  4718. c = this.c;
  4719. let v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4720. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4721. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4722. // basically, we're distinguishing which of the voronoi regions of the triangle
  4723. // the point lies in with the minimum amount of redundant computation.
  4724. _vab.subVectors(b, a);
  4725. _vac.subVectors(c, a);
  4726. _vap.subVectors(p, a);
  4727. const d1 = _vab.dot(_vap);
  4728. const d2 = _vac.dot(_vap);
  4729. if (d1 <= 0 && d2 <= 0) {
  4730. // vertex region of A; barycentric coords (1, 0, 0)
  4731. return target.copy(a);
  4732. }
  4733. _vbp.subVectors(p, b);
  4734. const d3 = _vab.dot(_vbp);
  4735. const d4 = _vac.dot(_vbp);
  4736. if (d3 >= 0 && d4 <= d3) {
  4737. // vertex region of B; barycentric coords (0, 1, 0)
  4738. return target.copy(b);
  4739. }
  4740. const vc = d1 * d4 - d3 * d2;
  4741. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  4742. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  4743. return target.copy(a).addScaledVector(_vab, v);
  4744. }
  4745. _vcp.subVectors(p, c);
  4746. const d5 = _vab.dot(_vcp);
  4747. const d6 = _vac.dot(_vcp);
  4748. if (d6 >= 0 && d5 <= d6) {
  4749. // vertex region of C; barycentric coords (0, 0, 1)
  4750. return target.copy(c);
  4751. }
  4752. const vb = d5 * d2 - d1 * d6;
  4753. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  4754. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  4755. return target.copy(a).addScaledVector(_vac, w);
  4756. }
  4757. const va = d3 * d6 - d5 * d4;
  4758. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  4759. _vbc.subVectors(c, b);
  4760. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  4761. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  4762. } // face region
  4763. const denom = 1 / (va + vb + vc); // u = va * denom
  4764. v = vb * denom;
  4765. w = vc * denom;
  4766. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  4767. }
  4768. equals(triangle) {
  4769. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  4770. }
  4771. }
  4772. let materialId = 0;
  4773. class Material extends EventDispatcher {
  4774. constructor() {
  4775. super();
  4776. Object.defineProperty(this, 'id', {
  4777. value: materialId++
  4778. });
  4779. this.uuid = generateUUID();
  4780. this.name = '';
  4781. this.type = 'Material';
  4782. this.fog = true;
  4783. this.blending = NormalBlending;
  4784. this.side = FrontSide;
  4785. this.vertexColors = false;
  4786. this.opacity = 1;
  4787. this.format = RGBAFormat;
  4788. this.transparent = false;
  4789. this.blendSrc = SrcAlphaFactor;
  4790. this.blendDst = OneMinusSrcAlphaFactor;
  4791. this.blendEquation = AddEquation;
  4792. this.blendSrcAlpha = null;
  4793. this.blendDstAlpha = null;
  4794. this.blendEquationAlpha = null;
  4795. this.depthFunc = LessEqualDepth;
  4796. this.depthTest = true;
  4797. this.depthWrite = true;
  4798. this.stencilWriteMask = 0xff;
  4799. this.stencilFunc = AlwaysStencilFunc;
  4800. this.stencilRef = 0;
  4801. this.stencilFuncMask = 0xff;
  4802. this.stencilFail = KeepStencilOp;
  4803. this.stencilZFail = KeepStencilOp;
  4804. this.stencilZPass = KeepStencilOp;
  4805. this.stencilWrite = false;
  4806. this.clippingPlanes = null;
  4807. this.clipIntersection = false;
  4808. this.clipShadows = false;
  4809. this.shadowSide = null;
  4810. this.colorWrite = true;
  4811. this.precision = null; // override the renderer's default precision for this material
  4812. this.polygonOffset = false;
  4813. this.polygonOffsetFactor = 0;
  4814. this.polygonOffsetUnits = 0;
  4815. this.dithering = false;
  4816. this.alphaToCoverage = false;
  4817. this.premultipliedAlpha = false;
  4818. this.visible = true;
  4819. this.toneMapped = true;
  4820. this.userData = {};
  4821. this.version = 0;
  4822. this._alphaTest = 0;
  4823. }
  4824. get alphaTest() {
  4825. return this._alphaTest;
  4826. }
  4827. set alphaTest(value) {
  4828. if (this._alphaTest > 0 !== value > 0) {
  4829. this.version++;
  4830. }
  4831. this._alphaTest = value;
  4832. }
  4833. onBuild() {}
  4834. onBeforeCompile() {}
  4835. customProgramCacheKey() {
  4836. return this.onBeforeCompile.toString();
  4837. }
  4838. setValues(values) {
  4839. if (values === undefined) return;
  4840. for (const key in values) {
  4841. const newValue = values[key];
  4842. if (newValue === undefined) {
  4843. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  4844. continue;
  4845. } // for backward compatability if shading is set in the constructor
  4846. if (key === 'shading') {
  4847. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  4848. this.flatShading = newValue === FlatShading ? true : false;
  4849. continue;
  4850. }
  4851. const currentValue = this[key];
  4852. if (currentValue === undefined) {
  4853. console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
  4854. continue;
  4855. }
  4856. if (currentValue && currentValue.isColor) {
  4857. currentValue.set(newValue);
  4858. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  4859. currentValue.copy(newValue);
  4860. } else {
  4861. this[key] = newValue;
  4862. }
  4863. }
  4864. }
  4865. toJSON(meta) {
  4866. const isRoot = meta === undefined || typeof meta === 'string';
  4867. if (isRoot) {
  4868. meta = {
  4869. textures: {},
  4870. images: {}
  4871. };
  4872. }
  4873. const data = {
  4874. metadata: {
  4875. version: 4.5,
  4876. type: 'Material',
  4877. generator: 'Material.toJSON'
  4878. }
  4879. }; // standard Material serialization
  4880. data.uuid = this.uuid;
  4881. data.type = this.type;
  4882. if (this.name !== '') data.name = this.name;
  4883. if (this.color && this.color.isColor) data.color = this.color.getHex();
  4884. if (this.roughness !== undefined) data.roughness = this.roughness;
  4885. if (this.metalness !== undefined) data.metalness = this.metalness;
  4886. if (this.sheen !== undefined) data.sheen = this.sheen;
  4887. if (this.sheenTint && this.sheenTint.isColor) data.sheenTint = this.sheenTint.getHex();
  4888. if (this.sheenRoughness !== undefined) data.sheenRoughness = this.sheenRoughness;
  4889. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  4890. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  4891. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  4892. if (this.specularIntensity !== undefined) data.specularIntensity = this.specularIntensity;
  4893. if (this.specularTint && this.specularTint.isColor) data.specularTint = this.specularTint.getHex();
  4894. if (this.shininess !== undefined) data.shininess = this.shininess;
  4895. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  4896. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  4897. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  4898. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  4899. }
  4900. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  4901. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  4902. }
  4903. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  4904. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  4905. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  4906. }
  4907. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  4908. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  4909. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  4910. if (this.lightMap && this.lightMap.isTexture) {
  4911. data.lightMap = this.lightMap.toJSON(meta).uuid;
  4912. data.lightMapIntensity = this.lightMapIntensity;
  4913. }
  4914. if (this.aoMap && this.aoMap.isTexture) {
  4915. data.aoMap = this.aoMap.toJSON(meta).uuid;
  4916. data.aoMapIntensity = this.aoMapIntensity;
  4917. }
  4918. if (this.bumpMap && this.bumpMap.isTexture) {
  4919. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  4920. data.bumpScale = this.bumpScale;
  4921. }
  4922. if (this.normalMap && this.normalMap.isTexture) {
  4923. data.normalMap = this.normalMap.toJSON(meta).uuid;
  4924. data.normalMapType = this.normalMapType;
  4925. data.normalScale = this.normalScale.toArray();
  4926. }
  4927. if (this.displacementMap && this.displacementMap.isTexture) {
  4928. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  4929. data.displacementScale = this.displacementScale;
  4930. data.displacementBias = this.displacementBias;
  4931. }
  4932. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  4933. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  4934. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  4935. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  4936. if (this.specularIntensityMap && this.specularIntensityMap.isTexture) data.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid;
  4937. if (this.specularTintMap && this.specularTintMap.isTexture) data.specularTintMap = this.specularTintMap.toJSON(meta).uuid;
  4938. if (this.envMap && this.envMap.isTexture) {
  4939. data.envMap = this.envMap.toJSON(meta).uuid;
  4940. if (this.combine !== undefined) data.combine = this.combine;
  4941. }
  4942. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  4943. if (this.reflectivity !== undefined) data.reflectivity = this.reflectivity;
  4944. if (this.refractionRatio !== undefined) data.refractionRatio = this.refractionRatio;
  4945. if (this.gradientMap && this.gradientMap.isTexture) {
  4946. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  4947. }
  4948. if (this.transmission !== undefined) data.transmission = this.transmission;
  4949. if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid;
  4950. if (this.thickness !== undefined) data.thickness = this.thickness;
  4951. if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid;
  4952. if (this.attenuationDistance !== undefined) data.attenuationDistance = this.attenuationDistance;
  4953. if (this.attenuationTint !== undefined) data.attenuationTint = this.attenuationTint.getHex();
  4954. if (this.size !== undefined) data.size = this.size;
  4955. if (this.shadowSide !== null) data.shadowSide = this.shadowSide;
  4956. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  4957. if (this.blending !== NormalBlending) data.blending = this.blending;
  4958. if (this.side !== FrontSide) data.side = this.side;
  4959. if (this.vertexColors) data.vertexColors = true;
  4960. if (this.opacity < 1) data.opacity = this.opacity;
  4961. if (this.format !== RGBAFormat) data.format = this.format;
  4962. if (this.transparent === true) data.transparent = this.transparent;
  4963. data.depthFunc = this.depthFunc;
  4964. data.depthTest = this.depthTest;
  4965. data.depthWrite = this.depthWrite;
  4966. data.colorWrite = this.colorWrite;
  4967. data.stencilWrite = this.stencilWrite;
  4968. data.stencilWriteMask = this.stencilWriteMask;
  4969. data.stencilFunc = this.stencilFunc;
  4970. data.stencilRef = this.stencilRef;
  4971. data.stencilFuncMask = this.stencilFuncMask;
  4972. data.stencilFail = this.stencilFail;
  4973. data.stencilZFail = this.stencilZFail;
  4974. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  4975. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  4976. if (this.polygonOffset === true) data.polygonOffset = true;
  4977. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  4978. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  4979. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  4980. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  4981. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  4982. if (this.scale !== undefined) data.scale = this.scale;
  4983. if (this.dithering === true) data.dithering = true;
  4984. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  4985. if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage;
  4986. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  4987. if (this.wireframe === true) data.wireframe = this.wireframe;
  4988. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  4989. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  4990. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  4991. if (this.flatShading === true) data.flatShading = this.flatShading;
  4992. if (this.visible === false) data.visible = false;
  4993. if (this.toneMapped === false) data.toneMapped = false;
  4994. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  4995. function extractFromCache(cache) {
  4996. const values = [];
  4997. for (const key in cache) {
  4998. const data = cache[key];
  4999. delete data.metadata;
  5000. values.push(data);
  5001. }
  5002. return values;
  5003. }
  5004. if (isRoot) {
  5005. const textures = extractFromCache(meta.textures);
  5006. const images = extractFromCache(meta.images);
  5007. if (textures.length > 0) data.textures = textures;
  5008. if (images.length > 0) data.images = images;
  5009. }
  5010. return data;
  5011. }
  5012. clone() {
  5013. return new this.constructor().copy(this);
  5014. }
  5015. copy(source) {
  5016. this.name = source.name;
  5017. this.fog = source.fog;
  5018. this.blending = source.blending;
  5019. this.side = source.side;
  5020. this.vertexColors = source.vertexColors;
  5021. this.opacity = source.opacity;
  5022. this.format = source.format;
  5023. this.transparent = source.transparent;
  5024. this.blendSrc = source.blendSrc;
  5025. this.blendDst = source.blendDst;
  5026. this.blendEquation = source.blendEquation;
  5027. this.blendSrcAlpha = source.blendSrcAlpha;
  5028. this.blendDstAlpha = source.blendDstAlpha;
  5029. this.blendEquationAlpha = source.blendEquationAlpha;
  5030. this.depthFunc = source.depthFunc;
  5031. this.depthTest = source.depthTest;
  5032. this.depthWrite = source.depthWrite;
  5033. this.stencilWriteMask = source.stencilWriteMask;
  5034. this.stencilFunc = source.stencilFunc;
  5035. this.stencilRef = source.stencilRef;
  5036. this.stencilFuncMask = source.stencilFuncMask;
  5037. this.stencilFail = source.stencilFail;
  5038. this.stencilZFail = source.stencilZFail;
  5039. this.stencilZPass = source.stencilZPass;
  5040. this.stencilWrite = source.stencilWrite;
  5041. const srcPlanes = source.clippingPlanes;
  5042. let dstPlanes = null;
  5043. if (srcPlanes !== null) {
  5044. const n = srcPlanes.length;
  5045. dstPlanes = new Array(n);
  5046. for (let i = 0; i !== n; ++i) {
  5047. dstPlanes[i] = srcPlanes[i].clone();
  5048. }
  5049. }
  5050. this.clippingPlanes = dstPlanes;
  5051. this.clipIntersection = source.clipIntersection;
  5052. this.clipShadows = source.clipShadows;
  5053. this.shadowSide = source.shadowSide;
  5054. this.colorWrite = source.colorWrite;
  5055. this.precision = source.precision;
  5056. this.polygonOffset = source.polygonOffset;
  5057. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5058. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5059. this.dithering = source.dithering;
  5060. this.alphaTest = source.alphaTest;
  5061. this.alphaToCoverage = source.alphaToCoverage;
  5062. this.premultipliedAlpha = source.premultipliedAlpha;
  5063. this.visible = source.visible;
  5064. this.toneMapped = source.toneMapped;
  5065. this.userData = JSON.parse(JSON.stringify(source.userData));
  5066. return this;
  5067. }
  5068. dispose() {
  5069. this.dispatchEvent({
  5070. type: 'dispose'
  5071. });
  5072. }
  5073. set needsUpdate(value) {
  5074. if (value === true) this.version++;
  5075. }
  5076. }
  5077. Material.prototype.isMaterial = true;
  5078. const _colorKeywords = {
  5079. 'aliceblue': 0xF0F8FF,
  5080. 'antiquewhite': 0xFAEBD7,
  5081. 'aqua': 0x00FFFF,
  5082. 'aquamarine': 0x7FFFD4,
  5083. 'azure': 0xF0FFFF,
  5084. 'beige': 0xF5F5DC,
  5085. 'bisque': 0xFFE4C4,
  5086. 'black': 0x000000,
  5087. 'blanchedalmond': 0xFFEBCD,
  5088. 'blue': 0x0000FF,
  5089. 'blueviolet': 0x8A2BE2,
  5090. 'brown': 0xA52A2A,
  5091. 'burlywood': 0xDEB887,
  5092. 'cadetblue': 0x5F9EA0,
  5093. 'chartreuse': 0x7FFF00,
  5094. 'chocolate': 0xD2691E,
  5095. 'coral': 0xFF7F50,
  5096. 'cornflowerblue': 0x6495ED,
  5097. 'cornsilk': 0xFFF8DC,
  5098. 'crimson': 0xDC143C,
  5099. 'cyan': 0x00FFFF,
  5100. 'darkblue': 0x00008B,
  5101. 'darkcyan': 0x008B8B,
  5102. 'darkgoldenrod': 0xB8860B,
  5103. 'darkgray': 0xA9A9A9,
  5104. 'darkgreen': 0x006400,
  5105. 'darkgrey': 0xA9A9A9,
  5106. 'darkkhaki': 0xBDB76B,
  5107. 'darkmagenta': 0x8B008B,
  5108. 'darkolivegreen': 0x556B2F,
  5109. 'darkorange': 0xFF8C00,
  5110. 'darkorchid': 0x9932CC,
  5111. 'darkred': 0x8B0000,
  5112. 'darksalmon': 0xE9967A,
  5113. 'darkseagreen': 0x8FBC8F,
  5114. 'darkslateblue': 0x483D8B,
  5115. 'darkslategray': 0x2F4F4F,
  5116. 'darkslategrey': 0x2F4F4F,
  5117. 'darkturquoise': 0x00CED1,
  5118. 'darkviolet': 0x9400D3,
  5119. 'deeppink': 0xFF1493,
  5120. 'deepskyblue': 0x00BFFF,
  5121. 'dimgray': 0x696969,
  5122. 'dimgrey': 0x696969,
  5123. 'dodgerblue': 0x1E90FF,
  5124. 'firebrick': 0xB22222,
  5125. 'floralwhite': 0xFFFAF0,
  5126. 'forestgreen': 0x228B22,
  5127. 'fuchsia': 0xFF00FF,
  5128. 'gainsboro': 0xDCDCDC,
  5129. 'ghostwhite': 0xF8F8FF,
  5130. 'gold': 0xFFD700,
  5131. 'goldenrod': 0xDAA520,
  5132. 'gray': 0x808080,
  5133. 'green': 0x008000,
  5134. 'greenyellow': 0xADFF2F,
  5135. 'grey': 0x808080,
  5136. 'honeydew': 0xF0FFF0,
  5137. 'hotpink': 0xFF69B4,
  5138. 'indianred': 0xCD5C5C,
  5139. 'indigo': 0x4B0082,
  5140. 'ivory': 0xFFFFF0,
  5141. 'khaki': 0xF0E68C,
  5142. 'lavender': 0xE6E6FA,
  5143. 'lavenderblush': 0xFFF0F5,
  5144. 'lawngreen': 0x7CFC00,
  5145. 'lemonchiffon': 0xFFFACD,
  5146. 'lightblue': 0xADD8E6,
  5147. 'lightcoral': 0xF08080,
  5148. 'lightcyan': 0xE0FFFF,
  5149. 'lightgoldenrodyellow': 0xFAFAD2,
  5150. 'lightgray': 0xD3D3D3,
  5151. 'lightgreen': 0x90EE90,
  5152. 'lightgrey': 0xD3D3D3,
  5153. 'lightpink': 0xFFB6C1,
  5154. 'lightsalmon': 0xFFA07A,
  5155. 'lightseagreen': 0x20B2AA,
  5156. 'lightskyblue': 0x87CEFA,
  5157. 'lightslategray': 0x778899,
  5158. 'lightslategrey': 0x778899,
  5159. 'lightsteelblue': 0xB0C4DE,
  5160. 'lightyellow': 0xFFFFE0,
  5161. 'lime': 0x00FF00,
  5162. 'limegreen': 0x32CD32,
  5163. 'linen': 0xFAF0E6,
  5164. 'magenta': 0xFF00FF,
  5165. 'maroon': 0x800000,
  5166. 'mediumaquamarine': 0x66CDAA,
  5167. 'mediumblue': 0x0000CD,
  5168. 'mediumorchid': 0xBA55D3,
  5169. 'mediumpurple': 0x9370DB,
  5170. 'mediumseagreen': 0x3CB371,
  5171. 'mediumslateblue': 0x7B68EE,
  5172. 'mediumspringgreen': 0x00FA9A,
  5173. 'mediumturquoise': 0x48D1CC,
  5174. 'mediumvioletred': 0xC71585,
  5175. 'midnightblue': 0x191970,
  5176. 'mintcream': 0xF5FFFA,
  5177. 'mistyrose': 0xFFE4E1,
  5178. 'moccasin': 0xFFE4B5,
  5179. 'navajowhite': 0xFFDEAD,
  5180. 'navy': 0x000080,
  5181. 'oldlace': 0xFDF5E6,
  5182. 'olive': 0x808000,
  5183. 'olivedrab': 0x6B8E23,
  5184. 'orange': 0xFFA500,
  5185. 'orangered': 0xFF4500,
  5186. 'orchid': 0xDA70D6,
  5187. 'palegoldenrod': 0xEEE8AA,
  5188. 'palegreen': 0x98FB98,
  5189. 'paleturquoise': 0xAFEEEE,
  5190. 'palevioletred': 0xDB7093,
  5191. 'papayawhip': 0xFFEFD5,
  5192. 'peachpuff': 0xFFDAB9,
  5193. 'peru': 0xCD853F,
  5194. 'pink': 0xFFC0CB,
  5195. 'plum': 0xDDA0DD,
  5196. 'powderblue': 0xB0E0E6,
  5197. 'purple': 0x800080,
  5198. 'rebeccapurple': 0x663399,
  5199. 'red': 0xFF0000,
  5200. 'rosybrown': 0xBC8F8F,
  5201. 'royalblue': 0x4169E1,
  5202. 'saddlebrown': 0x8B4513,
  5203. 'salmon': 0xFA8072,
  5204. 'sandybrown': 0xF4A460,
  5205. 'seagreen': 0x2E8B57,
  5206. 'seashell': 0xFFF5EE,
  5207. 'sienna': 0xA0522D,
  5208. 'silver': 0xC0C0C0,
  5209. 'skyblue': 0x87CEEB,
  5210. 'slateblue': 0x6A5ACD,
  5211. 'slategray': 0x708090,
  5212. 'slategrey': 0x708090,
  5213. 'snow': 0xFFFAFA,
  5214. 'springgreen': 0x00FF7F,
  5215. 'steelblue': 0x4682B4,
  5216. 'tan': 0xD2B48C,
  5217. 'teal': 0x008080,
  5218. 'thistle': 0xD8BFD8,
  5219. 'tomato': 0xFF6347,
  5220. 'turquoise': 0x40E0D0,
  5221. 'violet': 0xEE82EE,
  5222. 'wheat': 0xF5DEB3,
  5223. 'white': 0xFFFFFF,
  5224. 'whitesmoke': 0xF5F5F5,
  5225. 'yellow': 0xFFFF00,
  5226. 'yellowgreen': 0x9ACD32
  5227. };
  5228. const _hslA = {
  5229. h: 0,
  5230. s: 0,
  5231. l: 0
  5232. };
  5233. const _hslB = {
  5234. h: 0,
  5235. s: 0,
  5236. l: 0
  5237. };
  5238. function hue2rgb(p, q, t) {
  5239. if (t < 0) t += 1;
  5240. if (t > 1) t -= 1;
  5241. if (t < 1 / 6) return p + (q - p) * 6 * t;
  5242. if (t < 1 / 2) return q;
  5243. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  5244. return p;
  5245. }
  5246. function SRGBToLinear(c) {
  5247. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  5248. }
  5249. function LinearToSRGB(c) {
  5250. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  5251. }
  5252. class Color {
  5253. constructor(r, g, b) {
  5254. if (g === undefined && b === undefined) {
  5255. // r is THREE.Color, hex or string
  5256. return this.set(r);
  5257. }
  5258. return this.setRGB(r, g, b);
  5259. }
  5260. set(value) {
  5261. if (value && value.isColor) {
  5262. this.copy(value);
  5263. } else if (typeof value === 'number') {
  5264. this.setHex(value);
  5265. } else if (typeof value === 'string') {
  5266. this.setStyle(value);
  5267. }
  5268. return this;
  5269. }
  5270. setScalar(scalar) {
  5271. this.r = scalar;
  5272. this.g = scalar;
  5273. this.b = scalar;
  5274. return this;
  5275. }
  5276. setHex(hex) {
  5277. hex = Math.floor(hex);
  5278. this.r = (hex >> 16 & 255) / 255;
  5279. this.g = (hex >> 8 & 255) / 255;
  5280. this.b = (hex & 255) / 255;
  5281. return this;
  5282. }
  5283. setRGB(r, g, b) {
  5284. this.r = r;
  5285. this.g = g;
  5286. this.b = b;
  5287. return this;
  5288. }
  5289. setHSL(h, s, l) {
  5290. // h,s,l ranges are in 0.0 - 1.0
  5291. h = euclideanModulo(h, 1);
  5292. s = clamp(s, 0, 1);
  5293. l = clamp(l, 0, 1);
  5294. if (s === 0) {
  5295. this.r = this.g = this.b = l;
  5296. } else {
  5297. const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  5298. const q = 2 * l - p;
  5299. this.r = hue2rgb(q, p, h + 1 / 3);
  5300. this.g = hue2rgb(q, p, h);
  5301. this.b = hue2rgb(q, p, h - 1 / 3);
  5302. }
  5303. return this;
  5304. }
  5305. setStyle(style) {
  5306. function handleAlpha(string) {
  5307. if (string === undefined) return;
  5308. if (parseFloat(string) < 1) {
  5309. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  5310. }
  5311. }
  5312. let m;
  5313. if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
  5314. // rgb / hsl
  5315. let color;
  5316. const name = m[1];
  5317. const components = m[2];
  5318. switch (name) {
  5319. case 'rgb':
  5320. case 'rgba':
  5321. if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5322. // rgb(255,0,0) rgba(255,0,0,0.5)
  5323. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  5324. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  5325. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  5326. handleAlpha(color[4]);
  5327. return this;
  5328. }
  5329. if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5330. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5331. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  5332. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  5333. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  5334. handleAlpha(color[4]);
  5335. return this;
  5336. }
  5337. break;
  5338. case 'hsl':
  5339. case 'hsla':
  5340. if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5341. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5342. const h = parseFloat(color[1]) / 360;
  5343. const s = parseInt(color[2], 10) / 100;
  5344. const l = parseInt(color[3], 10) / 100;
  5345. handleAlpha(color[4]);
  5346. return this.setHSL(h, s, l);
  5347. }
  5348. break;
  5349. }
  5350. } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
  5351. // hex color
  5352. const hex = m[1];
  5353. const size = hex.length;
  5354. if (size === 3) {
  5355. // #ff0
  5356. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  5357. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  5358. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  5359. return this;
  5360. } else if (size === 6) {
  5361. // #ff0000
  5362. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  5363. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  5364. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  5365. return this;
  5366. }
  5367. }
  5368. if (style && style.length > 0) {
  5369. return this.setColorName(style);
  5370. }
  5371. return this;
  5372. }
  5373. setColorName(style) {
  5374. // color keywords
  5375. const hex = _colorKeywords[style.toLowerCase()];
  5376. if (hex !== undefined) {
  5377. // red
  5378. this.setHex(hex);
  5379. } else {
  5380. // unknown color
  5381. console.warn('THREE.Color: Unknown color ' + style);
  5382. }
  5383. return this;
  5384. }
  5385. clone() {
  5386. return new this.constructor(this.r, this.g, this.b);
  5387. }
  5388. copy(color) {
  5389. this.r = color.r;
  5390. this.g = color.g;
  5391. this.b = color.b;
  5392. return this;
  5393. }
  5394. copyGammaToLinear(color, gammaFactor = 2.0) {
  5395. this.r = Math.pow(color.r, gammaFactor);
  5396. this.g = Math.pow(color.g, gammaFactor);
  5397. this.b = Math.pow(color.b, gammaFactor);
  5398. return this;
  5399. }
  5400. copyLinearToGamma(color, gammaFactor = 2.0) {
  5401. const safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  5402. this.r = Math.pow(color.r, safeInverse);
  5403. this.g = Math.pow(color.g, safeInverse);
  5404. this.b = Math.pow(color.b, safeInverse);
  5405. return this;
  5406. }
  5407. convertGammaToLinear(gammaFactor) {
  5408. this.copyGammaToLinear(this, gammaFactor);
  5409. return this;
  5410. }
  5411. convertLinearToGamma(gammaFactor) {
  5412. this.copyLinearToGamma(this, gammaFactor);
  5413. return this;
  5414. }
  5415. copySRGBToLinear(color) {
  5416. this.r = SRGBToLinear(color.r);
  5417. this.g = SRGBToLinear(color.g);
  5418. this.b = SRGBToLinear(color.b);
  5419. return this;
  5420. }
  5421. copyLinearToSRGB(color) {
  5422. this.r = LinearToSRGB(color.r);
  5423. this.g = LinearToSRGB(color.g);
  5424. this.b = LinearToSRGB(color.b);
  5425. return this;
  5426. }
  5427. convertSRGBToLinear() {
  5428. this.copySRGBToLinear(this);
  5429. return this;
  5430. }
  5431. convertLinearToSRGB() {
  5432. this.copyLinearToSRGB(this);
  5433. return this;
  5434. }
  5435. getHex() {
  5436. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  5437. }
  5438. getHexString() {
  5439. return ('000000' + this.getHex().toString(16)).slice(-6);
  5440. }
  5441. getHSL(target) {
  5442. // h,s,l ranges are in 0.0 - 1.0
  5443. const r = this.r,
  5444. g = this.g,
  5445. b = this.b;
  5446. const max = Math.max(r, g, b);
  5447. const min = Math.min(r, g, b);
  5448. let hue, saturation;
  5449. const lightness = (min + max) / 2.0;
  5450. if (min === max) {
  5451. hue = 0;
  5452. saturation = 0;
  5453. } else {
  5454. const delta = max - min;
  5455. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  5456. switch (max) {
  5457. case r:
  5458. hue = (g - b) / delta + (g < b ? 6 : 0);
  5459. break;
  5460. case g:
  5461. hue = (b - r) / delta + 2;
  5462. break;
  5463. case b:
  5464. hue = (r - g) / delta + 4;
  5465. break;
  5466. }
  5467. hue /= 6;
  5468. }
  5469. target.h = hue;
  5470. target.s = saturation;
  5471. target.l = lightness;
  5472. return target;
  5473. }
  5474. getStyle() {
  5475. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  5476. }
  5477. offsetHSL(h, s, l) {
  5478. this.getHSL(_hslA);
  5479. _hslA.h += h;
  5480. _hslA.s += s;
  5481. _hslA.l += l;
  5482. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  5483. return this;
  5484. }
  5485. add(color) {
  5486. this.r += color.r;
  5487. this.g += color.g;
  5488. this.b += color.b;
  5489. return this;
  5490. }
  5491. addColors(color1, color2) {
  5492. this.r = color1.r + color2.r;
  5493. this.g = color1.g + color2.g;
  5494. this.b = color1.b + color2.b;
  5495. return this;
  5496. }
  5497. addScalar(s) {
  5498. this.r += s;
  5499. this.g += s;
  5500. this.b += s;
  5501. return this;
  5502. }
  5503. sub(color) {
  5504. this.r = Math.max(0, this.r - color.r);
  5505. this.g = Math.max(0, this.g - color.g);
  5506. this.b = Math.max(0, this.b - color.b);
  5507. return this;
  5508. }
  5509. multiply(color) {
  5510. this.r *= color.r;
  5511. this.g *= color.g;
  5512. this.b *= color.b;
  5513. return this;
  5514. }
  5515. multiplyScalar(s) {
  5516. this.r *= s;
  5517. this.g *= s;
  5518. this.b *= s;
  5519. return this;
  5520. }
  5521. lerp(color, alpha) {
  5522. this.r += (color.r - this.r) * alpha;
  5523. this.g += (color.g - this.g) * alpha;
  5524. this.b += (color.b - this.b) * alpha;
  5525. return this;
  5526. }
  5527. lerpColors(color1, color2, alpha) {
  5528. this.r = color1.r + (color2.r - color1.r) * alpha;
  5529. this.g = color1.g + (color2.g - color1.g) * alpha;
  5530. this.b = color1.b + (color2.b - color1.b) * alpha;
  5531. return this;
  5532. }
  5533. lerpHSL(color, alpha) {
  5534. this.getHSL(_hslA);
  5535. color.getHSL(_hslB);
  5536. const h = lerp(_hslA.h, _hslB.h, alpha);
  5537. const s = lerp(_hslA.s, _hslB.s, alpha);
  5538. const l = lerp(_hslA.l, _hslB.l, alpha);
  5539. this.setHSL(h, s, l);
  5540. return this;
  5541. }
  5542. equals(c) {
  5543. return c.r === this.r && c.g === this.g && c.b === this.b;
  5544. }
  5545. fromArray(array, offset = 0) {
  5546. this.r = array[offset];
  5547. this.g = array[offset + 1];
  5548. this.b = array[offset + 2];
  5549. return this;
  5550. }
  5551. toArray(array = [], offset = 0) {
  5552. array[offset] = this.r;
  5553. array[offset + 1] = this.g;
  5554. array[offset + 2] = this.b;
  5555. return array;
  5556. }
  5557. fromBufferAttribute(attribute, index) {
  5558. this.r = attribute.getX(index);
  5559. this.g = attribute.getY(index);
  5560. this.b = attribute.getZ(index);
  5561. if (attribute.normalized === true) {
  5562. // assuming Uint8Array
  5563. this.r /= 255;
  5564. this.g /= 255;
  5565. this.b /= 255;
  5566. }
  5567. return this;
  5568. }
  5569. toJSON() {
  5570. return this.getHex();
  5571. }
  5572. }
  5573. Color.NAMES = _colorKeywords;
  5574. Color.prototype.isColor = true;
  5575. Color.prototype.r = 1;
  5576. Color.prototype.g = 1;
  5577. Color.prototype.b = 1;
  5578. /**
  5579. * parameters = {
  5580. * color: <hex>,
  5581. * opacity: <float>,
  5582. * map: new THREE.Texture( <Image> ),
  5583. *
  5584. * lightMap: new THREE.Texture( <Image> ),
  5585. * lightMapIntensity: <float>
  5586. *
  5587. * aoMap: new THREE.Texture( <Image> ),
  5588. * aoMapIntensity: <float>
  5589. *
  5590. * specularMap: new THREE.Texture( <Image> ),
  5591. *
  5592. * alphaMap: new THREE.Texture( <Image> ),
  5593. *
  5594. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  5595. * combine: THREE.Multiply,
  5596. * reflectivity: <float>,
  5597. * refractionRatio: <float>,
  5598. *
  5599. * depthTest: <bool>,
  5600. * depthWrite: <bool>,
  5601. *
  5602. * wireframe: <boolean>,
  5603. * wireframeLinewidth: <float>,
  5604. * }
  5605. */
  5606. class MeshBasicMaterial extends Material {
  5607. constructor(parameters) {
  5608. super();
  5609. this.type = 'MeshBasicMaterial';
  5610. this.color = new Color(0xffffff); // emissive
  5611. this.map = null;
  5612. this.lightMap = null;
  5613. this.lightMapIntensity = 1.0;
  5614. this.aoMap = null;
  5615. this.aoMapIntensity = 1.0;
  5616. this.specularMap = null;
  5617. this.alphaMap = null;
  5618. this.envMap = null;
  5619. this.combine = MultiplyOperation;
  5620. this.reflectivity = 1;
  5621. this.refractionRatio = 0.98;
  5622. this.wireframe = false;
  5623. this.wireframeLinewidth = 1;
  5624. this.wireframeLinecap = 'round';
  5625. this.wireframeLinejoin = 'round';
  5626. this.setValues(parameters);
  5627. }
  5628. copy(source) {
  5629. super.copy(source);
  5630. this.color.copy(source.color);
  5631. this.map = source.map;
  5632. this.lightMap = source.lightMap;
  5633. this.lightMapIntensity = source.lightMapIntensity;
  5634. this.aoMap = source.aoMap;
  5635. this.aoMapIntensity = source.aoMapIntensity;
  5636. this.specularMap = source.specularMap;
  5637. this.alphaMap = source.alphaMap;
  5638. this.envMap = source.envMap;
  5639. this.combine = source.combine;
  5640. this.reflectivity = source.reflectivity;
  5641. this.refractionRatio = source.refractionRatio;
  5642. this.wireframe = source.wireframe;
  5643. this.wireframeLinewidth = source.wireframeLinewidth;
  5644. this.wireframeLinecap = source.wireframeLinecap;
  5645. this.wireframeLinejoin = source.wireframeLinejoin;
  5646. return this;
  5647. }
  5648. }
  5649. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  5650. const _vector$9 = /*@__PURE__*/new Vector3();
  5651. const _vector2$1 = /*@__PURE__*/new Vector2();
  5652. class BufferAttribute {
  5653. constructor(array, itemSize, normalized) {
  5654. if (Array.isArray(array)) {
  5655. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  5656. }
  5657. this.name = '';
  5658. this.array = array;
  5659. this.itemSize = itemSize;
  5660. this.count = array !== undefined ? array.length / itemSize : 0;
  5661. this.normalized = normalized === true;
  5662. this.usage = StaticDrawUsage;
  5663. this.updateRange = {
  5664. offset: 0,
  5665. count: -1
  5666. };
  5667. this.version = 0;
  5668. }
  5669. onUploadCallback() {}
  5670. set needsUpdate(value) {
  5671. if (value === true) this.version++;
  5672. }
  5673. setUsage(value) {
  5674. this.usage = value;
  5675. return this;
  5676. }
  5677. copy(source) {
  5678. this.name = source.name;
  5679. this.array = new source.array.constructor(source.array);
  5680. this.itemSize = source.itemSize;
  5681. this.count = source.count;
  5682. this.normalized = source.normalized;
  5683. this.usage = source.usage;
  5684. return this;
  5685. }
  5686. copyAt(index1, attribute, index2) {
  5687. index1 *= this.itemSize;
  5688. index2 *= attribute.itemSize;
  5689. for (let i = 0, l = this.itemSize; i < l; i++) {
  5690. this.array[index1 + i] = attribute.array[index2 + i];
  5691. }
  5692. return this;
  5693. }
  5694. copyArray(array) {
  5695. this.array.set(array);
  5696. return this;
  5697. }
  5698. copyColorsArray(colors) {
  5699. const array = this.array;
  5700. let offset = 0;
  5701. for (let i = 0, l = colors.length; i < l; i++) {
  5702. let color = colors[i];
  5703. if (color === undefined) {
  5704. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  5705. color = new Color();
  5706. }
  5707. array[offset++] = color.r;
  5708. array[offset++] = color.g;
  5709. array[offset++] = color.b;
  5710. }
  5711. return this;
  5712. }
  5713. copyVector2sArray(vectors) {
  5714. const array = this.array;
  5715. let offset = 0;
  5716. for (let i = 0, l = vectors.length; i < l; i++) {
  5717. let vector = vectors[i];
  5718. if (vector === undefined) {
  5719. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  5720. vector = new Vector2();
  5721. }
  5722. array[offset++] = vector.x;
  5723. array[offset++] = vector.y;
  5724. }
  5725. return this;
  5726. }
  5727. copyVector3sArray(vectors) {
  5728. const array = this.array;
  5729. let offset = 0;
  5730. for (let i = 0, l = vectors.length; i < l; i++) {
  5731. let vector = vectors[i];
  5732. if (vector === undefined) {
  5733. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  5734. vector = new Vector3();
  5735. }
  5736. array[offset++] = vector.x;
  5737. array[offset++] = vector.y;
  5738. array[offset++] = vector.z;
  5739. }
  5740. return this;
  5741. }
  5742. copyVector4sArray(vectors) {
  5743. const array = this.array;
  5744. let offset = 0;
  5745. for (let i = 0, l = vectors.length; i < l; i++) {
  5746. let vector = vectors[i];
  5747. if (vector === undefined) {
  5748. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  5749. vector = new Vector4();
  5750. }
  5751. array[offset++] = vector.x;
  5752. array[offset++] = vector.y;
  5753. array[offset++] = vector.z;
  5754. array[offset++] = vector.w;
  5755. }
  5756. return this;
  5757. }
  5758. applyMatrix3(m) {
  5759. if (this.itemSize === 2) {
  5760. for (let i = 0, l = this.count; i < l; i++) {
  5761. _vector2$1.fromBufferAttribute(this, i);
  5762. _vector2$1.applyMatrix3(m);
  5763. this.setXY(i, _vector2$1.x, _vector2$1.y);
  5764. }
  5765. } else if (this.itemSize === 3) {
  5766. for (let i = 0, l = this.count; i < l; i++) {
  5767. _vector$9.fromBufferAttribute(this, i);
  5768. _vector$9.applyMatrix3(m);
  5769. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5770. }
  5771. }
  5772. return this;
  5773. }
  5774. applyMatrix4(m) {
  5775. for (let i = 0, l = this.count; i < l; i++) {
  5776. _vector$9.x = this.getX(i);
  5777. _vector$9.y = this.getY(i);
  5778. _vector$9.z = this.getZ(i);
  5779. _vector$9.applyMatrix4(m);
  5780. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5781. }
  5782. return this;
  5783. }
  5784. applyNormalMatrix(m) {
  5785. for (let i = 0, l = this.count; i < l; i++) {
  5786. _vector$9.x = this.getX(i);
  5787. _vector$9.y = this.getY(i);
  5788. _vector$9.z = this.getZ(i);
  5789. _vector$9.applyNormalMatrix(m);
  5790. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5791. }
  5792. return this;
  5793. }
  5794. transformDirection(m) {
  5795. for (let i = 0, l = this.count; i < l; i++) {
  5796. _vector$9.x = this.getX(i);
  5797. _vector$9.y = this.getY(i);
  5798. _vector$9.z = this.getZ(i);
  5799. _vector$9.transformDirection(m);
  5800. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5801. }
  5802. return this;
  5803. }
  5804. set(value, offset = 0) {
  5805. this.array.set(value, offset);
  5806. return this;
  5807. }
  5808. getX(index) {
  5809. return this.array[index * this.itemSize];
  5810. }
  5811. setX(index, x) {
  5812. this.array[index * this.itemSize] = x;
  5813. return this;
  5814. }
  5815. getY(index) {
  5816. return this.array[index * this.itemSize + 1];
  5817. }
  5818. setY(index, y) {
  5819. this.array[index * this.itemSize + 1] = y;
  5820. return this;
  5821. }
  5822. getZ(index) {
  5823. return this.array[index * this.itemSize + 2];
  5824. }
  5825. setZ(index, z) {
  5826. this.array[index * this.itemSize + 2] = z;
  5827. return this;
  5828. }
  5829. getW(index) {
  5830. return this.array[index * this.itemSize + 3];
  5831. }
  5832. setW(index, w) {
  5833. this.array[index * this.itemSize + 3] = w;
  5834. return this;
  5835. }
  5836. setXY(index, x, y) {
  5837. index *= this.itemSize;
  5838. this.array[index + 0] = x;
  5839. this.array[index + 1] = y;
  5840. return this;
  5841. }
  5842. setXYZ(index, x, y, z) {
  5843. index *= this.itemSize;
  5844. this.array[index + 0] = x;
  5845. this.array[index + 1] = y;
  5846. this.array[index + 2] = z;
  5847. return this;
  5848. }
  5849. setXYZW(index, x, y, z, w) {
  5850. index *= this.itemSize;
  5851. this.array[index + 0] = x;
  5852. this.array[index + 1] = y;
  5853. this.array[index + 2] = z;
  5854. this.array[index + 3] = w;
  5855. return this;
  5856. }
  5857. onUpload(callback) {
  5858. this.onUploadCallback = callback;
  5859. return this;
  5860. }
  5861. clone() {
  5862. return new this.constructor(this.array, this.itemSize).copy(this);
  5863. }
  5864. toJSON() {
  5865. const data = {
  5866. itemSize: this.itemSize,
  5867. type: this.array.constructor.name,
  5868. array: Array.prototype.slice.call(this.array),
  5869. normalized: this.normalized
  5870. };
  5871. if (this.name !== '') data.name = this.name;
  5872. if (this.usage !== StaticDrawUsage) data.usage = this.usage;
  5873. if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange;
  5874. return data;
  5875. }
  5876. }
  5877. BufferAttribute.prototype.isBufferAttribute = true; //
  5878. class Int8BufferAttribute extends BufferAttribute {
  5879. constructor(array, itemSize, normalized) {
  5880. super(new Int8Array(array), itemSize, normalized);
  5881. }
  5882. }
  5883. class Uint8BufferAttribute extends BufferAttribute {
  5884. constructor(array, itemSize, normalized) {
  5885. super(new Uint8Array(array), itemSize, normalized);
  5886. }
  5887. }
  5888. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5889. constructor(array, itemSize, normalized) {
  5890. super(new Uint8ClampedArray(array), itemSize, normalized);
  5891. }
  5892. }
  5893. class Int16BufferAttribute extends BufferAttribute {
  5894. constructor(array, itemSize, normalized) {
  5895. super(new Int16Array(array), itemSize, normalized);
  5896. }
  5897. }
  5898. class Uint16BufferAttribute extends BufferAttribute {
  5899. constructor(array, itemSize, normalized) {
  5900. super(new Uint16Array(array), itemSize, normalized);
  5901. }
  5902. }
  5903. class Int32BufferAttribute extends BufferAttribute {
  5904. constructor(array, itemSize, normalized) {
  5905. super(new Int32Array(array), itemSize, normalized);
  5906. }
  5907. }
  5908. class Uint32BufferAttribute extends BufferAttribute {
  5909. constructor(array, itemSize, normalized) {
  5910. super(new Uint32Array(array), itemSize, normalized);
  5911. }
  5912. }
  5913. class Float16BufferAttribute extends BufferAttribute {
  5914. constructor(array, itemSize, normalized) {
  5915. super(new Uint16Array(array), itemSize, normalized);
  5916. }
  5917. }
  5918. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  5919. class Float32BufferAttribute extends BufferAttribute {
  5920. constructor(array, itemSize, normalized) {
  5921. super(new Float32Array(array), itemSize, normalized);
  5922. }
  5923. }
  5924. class Float64BufferAttribute extends BufferAttribute {
  5925. constructor(array, itemSize, normalized) {
  5926. super(new Float64Array(array), itemSize, normalized);
  5927. }
  5928. } //
  5929. function arrayMax(array) {
  5930. if (array.length === 0) return -Infinity;
  5931. let max = array[0];
  5932. for (let i = 1, l = array.length; i < l; ++i) {
  5933. if (array[i] > max) max = array[i];
  5934. }
  5935. return max;
  5936. }
  5937. const TYPED_ARRAYS = {
  5938. Int8Array: Int8Array,
  5939. Uint8Array: Uint8Array,
  5940. Uint8ClampedArray: Uint8ClampedArray,
  5941. Int16Array: Int16Array,
  5942. Uint16Array: Uint16Array,
  5943. Int32Array: Int32Array,
  5944. Uint32Array: Uint32Array,
  5945. Float32Array: Float32Array,
  5946. Float64Array: Float64Array
  5947. };
  5948. function getTypedArray(type, buffer) {
  5949. return new TYPED_ARRAYS[type](buffer);
  5950. }
  5951. let _id = 0;
  5952. const _m1 = /*@__PURE__*/new Matrix4();
  5953. const _obj = /*@__PURE__*/new Object3D();
  5954. const _offset = /*@__PURE__*/new Vector3();
  5955. const _box$1 = /*@__PURE__*/new Box3();
  5956. const _boxMorphTargets = /*@__PURE__*/new Box3();
  5957. const _vector$8 = /*@__PURE__*/new Vector3();
  5958. class BufferGeometry extends EventDispatcher {
  5959. constructor() {
  5960. super();
  5961. Object.defineProperty(this, 'id', {
  5962. value: _id++
  5963. });
  5964. this.uuid = generateUUID();
  5965. this.name = '';
  5966. this.type = 'BufferGeometry';
  5967. this.index = null;
  5968. this.attributes = {};
  5969. this.morphAttributes = {};
  5970. this.morphTargetsRelative = false;
  5971. this.groups = [];
  5972. this.boundingBox = null;
  5973. this.boundingSphere = null;
  5974. this.drawRange = {
  5975. start: 0,
  5976. count: Infinity
  5977. };
  5978. this.userData = {};
  5979. }
  5980. getIndex() {
  5981. return this.index;
  5982. }
  5983. setIndex(index) {
  5984. if (Array.isArray(index)) {
  5985. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  5986. } else {
  5987. this.index = index;
  5988. }
  5989. return this;
  5990. }
  5991. getAttribute(name) {
  5992. return this.attributes[name];
  5993. }
  5994. setAttribute(name, attribute) {
  5995. this.attributes[name] = attribute;
  5996. return this;
  5997. }
  5998. deleteAttribute(name) {
  5999. delete this.attributes[name];
  6000. return this;
  6001. }
  6002. hasAttribute(name) {
  6003. return this.attributes[name] !== undefined;
  6004. }
  6005. addGroup(start, count, materialIndex = 0) {
  6006. this.groups.push({
  6007. start: start,
  6008. count: count,
  6009. materialIndex: materialIndex
  6010. });
  6011. }
  6012. clearGroups() {
  6013. this.groups = [];
  6014. }
  6015. setDrawRange(start, count) {
  6016. this.drawRange.start = start;
  6017. this.drawRange.count = count;
  6018. }
  6019. applyMatrix4(matrix) {
  6020. const position = this.attributes.position;
  6021. if (position !== undefined) {
  6022. position.applyMatrix4(matrix);
  6023. position.needsUpdate = true;
  6024. }
  6025. const normal = this.attributes.normal;
  6026. if (normal !== undefined) {
  6027. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6028. normal.applyNormalMatrix(normalMatrix);
  6029. normal.needsUpdate = true;
  6030. }
  6031. const tangent = this.attributes.tangent;
  6032. if (tangent !== undefined) {
  6033. tangent.transformDirection(matrix);
  6034. tangent.needsUpdate = true;
  6035. }
  6036. if (this.boundingBox !== null) {
  6037. this.computeBoundingBox();
  6038. }
  6039. if (this.boundingSphere !== null) {
  6040. this.computeBoundingSphere();
  6041. }
  6042. return this;
  6043. }
  6044. applyQuaternion(q) {
  6045. _m1.makeRotationFromQuaternion(q);
  6046. this.applyMatrix4(_m1);
  6047. return this;
  6048. }
  6049. rotateX(angle) {
  6050. // rotate geometry around world x-axis
  6051. _m1.makeRotationX(angle);
  6052. this.applyMatrix4(_m1);
  6053. return this;
  6054. }
  6055. rotateY(angle) {
  6056. // rotate geometry around world y-axis
  6057. _m1.makeRotationY(angle);
  6058. this.applyMatrix4(_m1);
  6059. return this;
  6060. }
  6061. rotateZ(angle) {
  6062. // rotate geometry around world z-axis
  6063. _m1.makeRotationZ(angle);
  6064. this.applyMatrix4(_m1);
  6065. return this;
  6066. }
  6067. translate(x, y, z) {
  6068. // translate geometry
  6069. _m1.makeTranslation(x, y, z);
  6070. this.applyMatrix4(_m1);
  6071. return this;
  6072. }
  6073. scale(x, y, z) {
  6074. // scale geometry
  6075. _m1.makeScale(x, y, z);
  6076. this.applyMatrix4(_m1);
  6077. return this;
  6078. }
  6079. lookAt(vector) {
  6080. _obj.lookAt(vector);
  6081. _obj.updateMatrix();
  6082. this.applyMatrix4(_obj.matrix);
  6083. return this;
  6084. }
  6085. center() {
  6086. this.computeBoundingBox();
  6087. this.boundingBox.getCenter(_offset).negate();
  6088. this.translate(_offset.x, _offset.y, _offset.z);
  6089. return this;
  6090. }
  6091. setFromPoints(points) {
  6092. const position = [];
  6093. for (let i = 0, l = points.length; i < l; i++) {
  6094. const point = points[i];
  6095. position.push(point.x, point.y, point.z || 0);
  6096. }
  6097. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6098. return this;
  6099. }
  6100. computeBoundingBox() {
  6101. if (this.boundingBox === null) {
  6102. this.boundingBox = new Box3();
  6103. }
  6104. const position = this.attributes.position;
  6105. const morphAttributesPosition = this.morphAttributes.position;
  6106. if (position && position.isGLBufferAttribute) {
  6107. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  6108. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  6109. return;
  6110. }
  6111. if (position !== undefined) {
  6112. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  6113. if (morphAttributesPosition) {
  6114. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6115. const morphAttribute = morphAttributesPosition[i];
  6116. _box$1.setFromBufferAttribute(morphAttribute);
  6117. if (this.morphTargetsRelative) {
  6118. _vector$8.addVectors(this.boundingBox.min, _box$1.min);
  6119. this.boundingBox.expandByPoint(_vector$8);
  6120. _vector$8.addVectors(this.boundingBox.max, _box$1.max);
  6121. this.boundingBox.expandByPoint(_vector$8);
  6122. } else {
  6123. this.boundingBox.expandByPoint(_box$1.min);
  6124. this.boundingBox.expandByPoint(_box$1.max);
  6125. }
  6126. }
  6127. }
  6128. } else {
  6129. this.boundingBox.makeEmpty();
  6130. }
  6131. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  6132. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  6133. }
  6134. }
  6135. computeBoundingSphere() {
  6136. if (this.boundingSphere === null) {
  6137. this.boundingSphere = new Sphere();
  6138. }
  6139. const position = this.attributes.position;
  6140. const morphAttributesPosition = this.morphAttributes.position;
  6141. if (position && position.isGLBufferAttribute) {
  6142. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  6143. this.boundingSphere.set(new Vector3(), Infinity);
  6144. return;
  6145. }
  6146. if (position) {
  6147. // first, find the center of the bounding sphere
  6148. const center = this.boundingSphere.center;
  6149. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  6150. if (morphAttributesPosition) {
  6151. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6152. const morphAttribute = morphAttributesPosition[i];
  6153. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  6154. if (this.morphTargetsRelative) {
  6155. _vector$8.addVectors(_box$1.min, _boxMorphTargets.min);
  6156. _box$1.expandByPoint(_vector$8);
  6157. _vector$8.addVectors(_box$1.max, _boxMorphTargets.max);
  6158. _box$1.expandByPoint(_vector$8);
  6159. } else {
  6160. _box$1.expandByPoint(_boxMorphTargets.min);
  6161. _box$1.expandByPoint(_boxMorphTargets.max);
  6162. }
  6163. }
  6164. }
  6165. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  6166. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6167. let maxRadiusSq = 0;
  6168. for (let i = 0, il = position.count; i < il; i++) {
  6169. _vector$8.fromBufferAttribute(position, i);
  6170. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6171. } // process morph attributes if present
  6172. if (morphAttributesPosition) {
  6173. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6174. const morphAttribute = morphAttributesPosition[i];
  6175. const morphTargetsRelative = this.morphTargetsRelative;
  6176. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  6177. _vector$8.fromBufferAttribute(morphAttribute, j);
  6178. if (morphTargetsRelative) {
  6179. _offset.fromBufferAttribute(position, j);
  6180. _vector$8.add(_offset);
  6181. }
  6182. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6183. }
  6184. }
  6185. }
  6186. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  6187. if (isNaN(this.boundingSphere.radius)) {
  6188. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  6189. }
  6190. }
  6191. }
  6192. computeTangents() {
  6193. const index = this.index;
  6194. const attributes = this.attributes; // based on http://www.terathon.com/code/tangent.html
  6195. // (per vertex tangents)
  6196. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  6197. console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  6198. return;
  6199. }
  6200. const indices = index.array;
  6201. const positions = attributes.position.array;
  6202. const normals = attributes.normal.array;
  6203. const uvs = attributes.uv.array;
  6204. const nVertices = positions.length / 3;
  6205. if (attributes.tangent === undefined) {
  6206. this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
  6207. }
  6208. const tangents = attributes.tangent.array;
  6209. const tan1 = [],
  6210. tan2 = [];
  6211. for (let i = 0; i < nVertices; i++) {
  6212. tan1[i] = new Vector3();
  6213. tan2[i] = new Vector3();
  6214. }
  6215. const vA = new Vector3(),
  6216. vB = new Vector3(),
  6217. vC = new Vector3(),
  6218. uvA = new Vector2(),
  6219. uvB = new Vector2(),
  6220. uvC = new Vector2(),
  6221. sdir = new Vector3(),
  6222. tdir = new Vector3();
  6223. function handleTriangle(a, b, c) {
  6224. vA.fromArray(positions, a * 3);
  6225. vB.fromArray(positions, b * 3);
  6226. vC.fromArray(positions, c * 3);
  6227. uvA.fromArray(uvs, a * 2);
  6228. uvB.fromArray(uvs, b * 2);
  6229. uvC.fromArray(uvs, c * 2);
  6230. vB.sub(vA);
  6231. vC.sub(vA);
  6232. uvB.sub(uvA);
  6233. uvC.sub(uvA);
  6234. const r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  6235. if (!isFinite(r)) return;
  6236. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  6237. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  6238. tan1[a].add(sdir);
  6239. tan1[b].add(sdir);
  6240. tan1[c].add(sdir);
  6241. tan2[a].add(tdir);
  6242. tan2[b].add(tdir);
  6243. tan2[c].add(tdir);
  6244. }
  6245. let groups = this.groups;
  6246. if (groups.length === 0) {
  6247. groups = [{
  6248. start: 0,
  6249. count: indices.length
  6250. }];
  6251. }
  6252. for (let i = 0, il = groups.length; i < il; ++i) {
  6253. const group = groups[i];
  6254. const start = group.start;
  6255. const count = group.count;
  6256. for (let j = start, jl = start + count; j < jl; j += 3) {
  6257. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  6258. }
  6259. }
  6260. const tmp = new Vector3(),
  6261. tmp2 = new Vector3();
  6262. const n = new Vector3(),
  6263. n2 = new Vector3();
  6264. function handleVertex(v) {
  6265. n.fromArray(normals, v * 3);
  6266. n2.copy(n);
  6267. const t = tan1[v]; // Gram-Schmidt orthogonalize
  6268. tmp.copy(t);
  6269. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  6270. tmp2.crossVectors(n2, t);
  6271. const test = tmp2.dot(tan2[v]);
  6272. const w = test < 0.0 ? -1.0 : 1.0;
  6273. tangents[v * 4] = tmp.x;
  6274. tangents[v * 4 + 1] = tmp.y;
  6275. tangents[v * 4 + 2] = tmp.z;
  6276. tangents[v * 4 + 3] = w;
  6277. }
  6278. for (let i = 0, il = groups.length; i < il; ++i) {
  6279. const group = groups[i];
  6280. const start = group.start;
  6281. const count = group.count;
  6282. for (let j = start, jl = start + count; j < jl; j += 3) {
  6283. handleVertex(indices[j + 0]);
  6284. handleVertex(indices[j + 1]);
  6285. handleVertex(indices[j + 2]);
  6286. }
  6287. }
  6288. }
  6289. computeVertexNormals() {
  6290. const index = this.index;
  6291. const positionAttribute = this.getAttribute('position');
  6292. if (positionAttribute !== undefined) {
  6293. let normalAttribute = this.getAttribute('normal');
  6294. if (normalAttribute === undefined) {
  6295. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  6296. this.setAttribute('normal', normalAttribute);
  6297. } else {
  6298. // reset existing normals to zero
  6299. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  6300. normalAttribute.setXYZ(i, 0, 0, 0);
  6301. }
  6302. }
  6303. const pA = new Vector3(),
  6304. pB = new Vector3(),
  6305. pC = new Vector3();
  6306. const nA = new Vector3(),
  6307. nB = new Vector3(),
  6308. nC = new Vector3();
  6309. const cb = new Vector3(),
  6310. ab = new Vector3(); // indexed elements
  6311. if (index) {
  6312. for (let i = 0, il = index.count; i < il; i += 3) {
  6313. const vA = index.getX(i + 0);
  6314. const vB = index.getX(i + 1);
  6315. const vC = index.getX(i + 2);
  6316. pA.fromBufferAttribute(positionAttribute, vA);
  6317. pB.fromBufferAttribute(positionAttribute, vB);
  6318. pC.fromBufferAttribute(positionAttribute, vC);
  6319. cb.subVectors(pC, pB);
  6320. ab.subVectors(pA, pB);
  6321. cb.cross(ab);
  6322. nA.fromBufferAttribute(normalAttribute, vA);
  6323. nB.fromBufferAttribute(normalAttribute, vB);
  6324. nC.fromBufferAttribute(normalAttribute, vC);
  6325. nA.add(cb);
  6326. nB.add(cb);
  6327. nC.add(cb);
  6328. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  6329. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  6330. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  6331. }
  6332. } else {
  6333. // non-indexed elements (unconnected triangle soup)
  6334. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  6335. pA.fromBufferAttribute(positionAttribute, i + 0);
  6336. pB.fromBufferAttribute(positionAttribute, i + 1);
  6337. pC.fromBufferAttribute(positionAttribute, i + 2);
  6338. cb.subVectors(pC, pB);
  6339. ab.subVectors(pA, pB);
  6340. cb.cross(ab);
  6341. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  6342. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  6343. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  6344. }
  6345. }
  6346. this.normalizeNormals();
  6347. normalAttribute.needsUpdate = true;
  6348. }
  6349. }
  6350. merge(geometry, offset) {
  6351. if (!(geometry && geometry.isBufferGeometry)) {
  6352. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  6353. return;
  6354. }
  6355. if (offset === undefined) {
  6356. offset = 0;
  6357. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  6358. }
  6359. const attributes = this.attributes;
  6360. for (const key in attributes) {
  6361. if (geometry.attributes[key] === undefined) continue;
  6362. const attribute1 = attributes[key];
  6363. const attributeArray1 = attribute1.array;
  6364. const attribute2 = geometry.attributes[key];
  6365. const attributeArray2 = attribute2.array;
  6366. const attributeOffset = attribute2.itemSize * offset;
  6367. const length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  6368. for (let i = 0, j = attributeOffset; i < length; i++, j++) {
  6369. attributeArray1[j] = attributeArray2[i];
  6370. }
  6371. }
  6372. return this;
  6373. }
  6374. normalizeNormals() {
  6375. const normals = this.attributes.normal;
  6376. for (let i = 0, il = normals.count; i < il; i++) {
  6377. _vector$8.fromBufferAttribute(normals, i);
  6378. _vector$8.normalize();
  6379. normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z);
  6380. }
  6381. }
  6382. toNonIndexed() {
  6383. function convertBufferAttribute(attribute, indices) {
  6384. const array = attribute.array;
  6385. const itemSize = attribute.itemSize;
  6386. const normalized = attribute.normalized;
  6387. const array2 = new array.constructor(indices.length * itemSize);
  6388. let index = 0,
  6389. index2 = 0;
  6390. for (let i = 0, l = indices.length; i < l; i++) {
  6391. if (attribute.isInterleavedBufferAttribute) {
  6392. index = indices[i] * attribute.data.stride + attribute.offset;
  6393. } else {
  6394. index = indices[i] * itemSize;
  6395. }
  6396. for (let j = 0; j < itemSize; j++) {
  6397. array2[index2++] = array[index++];
  6398. }
  6399. }
  6400. return new BufferAttribute(array2, itemSize, normalized);
  6401. } //
  6402. if (this.index === null) {
  6403. console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
  6404. return this;
  6405. }
  6406. const geometry2 = new BufferGeometry();
  6407. const indices = this.index.array;
  6408. const attributes = this.attributes; // attributes
  6409. for (const name in attributes) {
  6410. const attribute = attributes[name];
  6411. const newAttribute = convertBufferAttribute(attribute, indices);
  6412. geometry2.setAttribute(name, newAttribute);
  6413. } // morph attributes
  6414. const morphAttributes = this.morphAttributes;
  6415. for (const name in morphAttributes) {
  6416. const morphArray = [];
  6417. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6418. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  6419. const attribute = morphAttribute[i];
  6420. const newAttribute = convertBufferAttribute(attribute, indices);
  6421. morphArray.push(newAttribute);
  6422. }
  6423. geometry2.morphAttributes[name] = morphArray;
  6424. }
  6425. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  6426. const groups = this.groups;
  6427. for (let i = 0, l = groups.length; i < l; i++) {
  6428. const group = groups[i];
  6429. geometry2.addGroup(group.start, group.count, group.materialIndex);
  6430. }
  6431. return geometry2;
  6432. }
  6433. toJSON() {
  6434. const data = {
  6435. metadata: {
  6436. version: 4.5,
  6437. type: 'BufferGeometry',
  6438. generator: 'BufferGeometry.toJSON'
  6439. }
  6440. }; // standard BufferGeometry serialization
  6441. data.uuid = this.uuid;
  6442. data.type = this.type;
  6443. if (this.name !== '') data.name = this.name;
  6444. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  6445. if (this.parameters !== undefined) {
  6446. const parameters = this.parameters;
  6447. for (const key in parameters) {
  6448. if (parameters[key] !== undefined) data[key] = parameters[key];
  6449. }
  6450. return data;
  6451. } // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6452. data.data = {
  6453. attributes: {}
  6454. };
  6455. const index = this.index;
  6456. if (index !== null) {
  6457. data.data.index = {
  6458. type: index.array.constructor.name,
  6459. array: Array.prototype.slice.call(index.array)
  6460. };
  6461. }
  6462. const attributes = this.attributes;
  6463. for (const key in attributes) {
  6464. const attribute = attributes[key];
  6465. data.data.attributes[key] = attribute.toJSON(data.data);
  6466. }
  6467. const morphAttributes = {};
  6468. let hasMorphAttributes = false;
  6469. for (const key in this.morphAttributes) {
  6470. const attributeArray = this.morphAttributes[key];
  6471. const array = [];
  6472. for (let i = 0, il = attributeArray.length; i < il; i++) {
  6473. const attribute = attributeArray[i];
  6474. array.push(attribute.toJSON(data.data));
  6475. }
  6476. if (array.length > 0) {
  6477. morphAttributes[key] = array;
  6478. hasMorphAttributes = true;
  6479. }
  6480. }
  6481. if (hasMorphAttributes) {
  6482. data.data.morphAttributes = morphAttributes;
  6483. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6484. }
  6485. const groups = this.groups;
  6486. if (groups.length > 0) {
  6487. data.data.groups = JSON.parse(JSON.stringify(groups));
  6488. }
  6489. const boundingSphere = this.boundingSphere;
  6490. if (boundingSphere !== null) {
  6491. data.data.boundingSphere = {
  6492. center: boundingSphere.center.toArray(),
  6493. radius: boundingSphere.radius
  6494. };
  6495. }
  6496. return data;
  6497. }
  6498. clone() {
  6499. /*
  6500. // Handle primitives
  6501. const parameters = this.parameters;
  6502. if ( parameters !== undefined ) {
  6503. const values = [];
  6504. for ( const key in parameters ) {
  6505. values.push( parameters[ key ] );
  6506. }
  6507. const geometry = Object.create( this.constructor.prototype );
  6508. this.constructor.apply( geometry, values );
  6509. return geometry;
  6510. }
  6511. return new this.constructor().copy( this );
  6512. */
  6513. return new BufferGeometry().copy(this);
  6514. }
  6515. copy(source) {
  6516. // reset
  6517. this.index = null;
  6518. this.attributes = {};
  6519. this.morphAttributes = {};
  6520. this.groups = [];
  6521. this.boundingBox = null;
  6522. this.boundingSphere = null; // used for storing cloned, shared data
  6523. const data = {}; // name
  6524. this.name = source.name; // index
  6525. const index = source.index;
  6526. if (index !== null) {
  6527. this.setIndex(index.clone(data));
  6528. } // attributes
  6529. const attributes = source.attributes;
  6530. for (const name in attributes) {
  6531. const attribute = attributes[name];
  6532. this.setAttribute(name, attribute.clone(data));
  6533. } // morph attributes
  6534. const morphAttributes = source.morphAttributes;
  6535. for (const name in morphAttributes) {
  6536. const array = [];
  6537. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6538. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  6539. array.push(morphAttribute[i].clone(data));
  6540. }
  6541. this.morphAttributes[name] = array;
  6542. }
  6543. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  6544. const groups = source.groups;
  6545. for (let i = 0, l = groups.length; i < l; i++) {
  6546. const group = groups[i];
  6547. this.addGroup(group.start, group.count, group.materialIndex);
  6548. } // bounding box
  6549. const boundingBox = source.boundingBox;
  6550. if (boundingBox !== null) {
  6551. this.boundingBox = boundingBox.clone();
  6552. } // bounding sphere
  6553. const boundingSphere = source.boundingSphere;
  6554. if (boundingSphere !== null) {
  6555. this.boundingSphere = boundingSphere.clone();
  6556. } // draw range
  6557. this.drawRange.start = source.drawRange.start;
  6558. this.drawRange.count = source.drawRange.count; // user data
  6559. this.userData = source.userData;
  6560. return this;
  6561. }
  6562. dispose() {
  6563. this.dispatchEvent({
  6564. type: 'dispose'
  6565. });
  6566. }
  6567. }
  6568. BufferGeometry.prototype.isBufferGeometry = true;
  6569. const _inverseMatrix$2 = /*@__PURE__*/new Matrix4();
  6570. const _ray$2 = /*@__PURE__*/new Ray();
  6571. const _sphere$3 = /*@__PURE__*/new Sphere();
  6572. const _vA$1 = /*@__PURE__*/new Vector3();
  6573. const _vB$1 = /*@__PURE__*/new Vector3();
  6574. const _vC$1 = /*@__PURE__*/new Vector3();
  6575. const _tempA = /*@__PURE__*/new Vector3();
  6576. const _tempB = /*@__PURE__*/new Vector3();
  6577. const _tempC = /*@__PURE__*/new Vector3();
  6578. const _morphA = /*@__PURE__*/new Vector3();
  6579. const _morphB = /*@__PURE__*/new Vector3();
  6580. const _morphC = /*@__PURE__*/new Vector3();
  6581. const _uvA$1 = /*@__PURE__*/new Vector2();
  6582. const _uvB$1 = /*@__PURE__*/new Vector2();
  6583. const _uvC$1 = /*@__PURE__*/new Vector2();
  6584. const _intersectionPoint = /*@__PURE__*/new Vector3();
  6585. const _intersectionPointWorld = /*@__PURE__*/new Vector3();
  6586. class Mesh extends Object3D {
  6587. constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) {
  6588. super();
  6589. this.type = 'Mesh';
  6590. this.geometry = geometry;
  6591. this.material = material;
  6592. this.updateMorphTargets();
  6593. }
  6594. copy(source) {
  6595. super.copy(source);
  6596. if (source.morphTargetInfluences !== undefined) {
  6597. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6598. }
  6599. if (source.morphTargetDictionary !== undefined) {
  6600. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  6601. }
  6602. this.material = source.material;
  6603. this.geometry = source.geometry;
  6604. return this;
  6605. }
  6606. updateMorphTargets() {
  6607. const geometry = this.geometry;
  6608. if (geometry.isBufferGeometry) {
  6609. const morphAttributes = geometry.morphAttributes;
  6610. const keys = Object.keys(morphAttributes);
  6611. if (keys.length > 0) {
  6612. const morphAttribute = morphAttributes[keys[0]];
  6613. if (morphAttribute !== undefined) {
  6614. this.morphTargetInfluences = [];
  6615. this.morphTargetDictionary = {};
  6616. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  6617. const name = morphAttribute[m].name || String(m);
  6618. this.morphTargetInfluences.push(0);
  6619. this.morphTargetDictionary[name] = m;
  6620. }
  6621. }
  6622. }
  6623. } else {
  6624. const morphTargets = geometry.morphTargets;
  6625. if (morphTargets !== undefined && morphTargets.length > 0) {
  6626. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6627. }
  6628. }
  6629. }
  6630. raycast(raycaster, intersects) {
  6631. const geometry = this.geometry;
  6632. const material = this.material;
  6633. const matrixWorld = this.matrixWorld;
  6634. if (material === undefined) return; // Checking boundingSphere distance to ray
  6635. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  6636. _sphere$3.copy(geometry.boundingSphere);
  6637. _sphere$3.applyMatrix4(matrixWorld);
  6638. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  6639. _inverseMatrix$2.copy(matrixWorld).invert();
  6640. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); // Check boundingBox before continuing
  6641. if (geometry.boundingBox !== null) {
  6642. if (_ray$2.intersectsBox(geometry.boundingBox) === false) return;
  6643. }
  6644. let intersection;
  6645. if (geometry.isBufferGeometry) {
  6646. const index = geometry.index;
  6647. const position = geometry.attributes.position;
  6648. const morphPosition = geometry.morphAttributes.position;
  6649. const morphTargetsRelative = geometry.morphTargetsRelative;
  6650. const uv = geometry.attributes.uv;
  6651. const uv2 = geometry.attributes.uv2;
  6652. const groups = geometry.groups;
  6653. const drawRange = geometry.drawRange;
  6654. if (index !== null) {
  6655. // indexed buffer geometry
  6656. if (Array.isArray(material)) {
  6657. for (let i = 0, il = groups.length; i < il; i++) {
  6658. const group = groups[i];
  6659. const groupMaterial = material[group.materialIndex];
  6660. const start = Math.max(group.start, drawRange.start);
  6661. const end = Math.min(index.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  6662. for (let j = start, jl = end; j < jl; j += 3) {
  6663. const a = index.getX(j);
  6664. const b = index.getX(j + 1);
  6665. const c = index.getX(j + 2);
  6666. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6667. if (intersection) {
  6668. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  6669. intersection.face.materialIndex = group.materialIndex;
  6670. intersects.push(intersection);
  6671. }
  6672. }
  6673. }
  6674. } else {
  6675. const start = Math.max(0, drawRange.start);
  6676. const end = Math.min(index.count, drawRange.start + drawRange.count);
  6677. for (let i = start, il = end; i < il; i += 3) {
  6678. const a = index.getX(i);
  6679. const b = index.getX(i + 1);
  6680. const c = index.getX(i + 2);
  6681. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6682. if (intersection) {
  6683. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  6684. intersects.push(intersection);
  6685. }
  6686. }
  6687. }
  6688. } else if (position !== undefined) {
  6689. // non-indexed buffer geometry
  6690. if (Array.isArray(material)) {
  6691. for (let i = 0, il = groups.length; i < il; i++) {
  6692. const group = groups[i];
  6693. const groupMaterial = material[group.materialIndex];
  6694. const start = Math.max(group.start, drawRange.start);
  6695. const end = Math.min(position.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  6696. for (let j = start, jl = end; j < jl; j += 3) {
  6697. const a = j;
  6698. const b = j + 1;
  6699. const c = j + 2;
  6700. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6701. if (intersection) {
  6702. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  6703. intersection.face.materialIndex = group.materialIndex;
  6704. intersects.push(intersection);
  6705. }
  6706. }
  6707. }
  6708. } else {
  6709. const start = Math.max(0, drawRange.start);
  6710. const end = Math.min(position.count, drawRange.start + drawRange.count);
  6711. for (let i = start, il = end; i < il; i += 3) {
  6712. const a = i;
  6713. const b = i + 1;
  6714. const c = i + 2;
  6715. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6716. if (intersection) {
  6717. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  6718. intersects.push(intersection);
  6719. }
  6720. }
  6721. }
  6722. }
  6723. } else if (geometry.isGeometry) {
  6724. console.error('THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6725. }
  6726. }
  6727. }
  6728. Mesh.prototype.isMesh = true;
  6729. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  6730. let intersect;
  6731. if (material.side === BackSide) {
  6732. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  6733. } else {
  6734. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  6735. }
  6736. if (intersect === null) return null;
  6737. _intersectionPointWorld.copy(point);
  6738. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  6739. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  6740. if (distance < raycaster.near || distance > raycaster.far) return null;
  6741. return {
  6742. distance: distance,
  6743. point: _intersectionPointWorld.clone(),
  6744. object: object
  6745. };
  6746. }
  6747. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  6748. _vA$1.fromBufferAttribute(position, a);
  6749. _vB$1.fromBufferAttribute(position, b);
  6750. _vC$1.fromBufferAttribute(position, c);
  6751. const morphInfluences = object.morphTargetInfluences;
  6752. if (morphPosition && morphInfluences) {
  6753. _morphA.set(0, 0, 0);
  6754. _morphB.set(0, 0, 0);
  6755. _morphC.set(0, 0, 0);
  6756. for (let i = 0, il = morphPosition.length; i < il; i++) {
  6757. const influence = morphInfluences[i];
  6758. const morphAttribute = morphPosition[i];
  6759. if (influence === 0) continue;
  6760. _tempA.fromBufferAttribute(morphAttribute, a);
  6761. _tempB.fromBufferAttribute(morphAttribute, b);
  6762. _tempC.fromBufferAttribute(morphAttribute, c);
  6763. if (morphTargetsRelative) {
  6764. _morphA.addScaledVector(_tempA, influence);
  6765. _morphB.addScaledVector(_tempB, influence);
  6766. _morphC.addScaledVector(_tempC, influence);
  6767. } else {
  6768. _morphA.addScaledVector(_tempA.sub(_vA$1), influence);
  6769. _morphB.addScaledVector(_tempB.sub(_vB$1), influence);
  6770. _morphC.addScaledVector(_tempC.sub(_vC$1), influence);
  6771. }
  6772. }
  6773. _vA$1.add(_morphA);
  6774. _vB$1.add(_morphB);
  6775. _vC$1.add(_morphC);
  6776. }
  6777. if (object.isSkinnedMesh) {
  6778. object.boneTransform(a, _vA$1);
  6779. object.boneTransform(b, _vB$1);
  6780. object.boneTransform(c, _vC$1);
  6781. }
  6782. const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
  6783. if (intersection) {
  6784. if (uv) {
  6785. _uvA$1.fromBufferAttribute(uv, a);
  6786. _uvB$1.fromBufferAttribute(uv, b);
  6787. _uvC$1.fromBufferAttribute(uv, c);
  6788. intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6789. }
  6790. if (uv2) {
  6791. _uvA$1.fromBufferAttribute(uv2, a);
  6792. _uvB$1.fromBufferAttribute(uv2, b);
  6793. _uvC$1.fromBufferAttribute(uv2, c);
  6794. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6795. }
  6796. const face = {
  6797. a: a,
  6798. b: b,
  6799. c: c,
  6800. normal: new Vector3(),
  6801. materialIndex: 0
  6802. };
  6803. Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
  6804. intersection.face = face;
  6805. }
  6806. return intersection;
  6807. }
  6808. class BoxGeometry extends BufferGeometry {
  6809. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  6810. super();
  6811. this.type = 'BoxGeometry';
  6812. this.parameters = {
  6813. width: width,
  6814. height: height,
  6815. depth: depth,
  6816. widthSegments: widthSegments,
  6817. heightSegments: heightSegments,
  6818. depthSegments: depthSegments
  6819. };
  6820. const scope = this; // segments
  6821. widthSegments = Math.floor(widthSegments);
  6822. heightSegments = Math.floor(heightSegments);
  6823. depthSegments = Math.floor(depthSegments); // buffers
  6824. const indices = [];
  6825. const vertices = [];
  6826. const normals = [];
  6827. const uvs = []; // helper variables
  6828. let numberOfVertices = 0;
  6829. let groupStart = 0; // build each side of the box geometry
  6830. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  6831. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  6832. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  6833. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  6834. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  6835. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  6836. // build geometry
  6837. this.setIndex(indices);
  6838. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  6839. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  6840. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  6841. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  6842. const segmentWidth = width / gridX;
  6843. const segmentHeight = height / gridY;
  6844. const widthHalf = width / 2;
  6845. const heightHalf = height / 2;
  6846. const depthHalf = depth / 2;
  6847. const gridX1 = gridX + 1;
  6848. const gridY1 = gridY + 1;
  6849. let vertexCounter = 0;
  6850. let groupCount = 0;
  6851. const vector = new Vector3(); // generate vertices, normals and uvs
  6852. for (let iy = 0; iy < gridY1; iy++) {
  6853. const y = iy * segmentHeight - heightHalf;
  6854. for (let ix = 0; ix < gridX1; ix++) {
  6855. const x = ix * segmentWidth - widthHalf; // set values to correct vector component
  6856. vector[u] = x * udir;
  6857. vector[v] = y * vdir;
  6858. vector[w] = depthHalf; // now apply vector to vertex buffer
  6859. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  6860. vector[u] = 0;
  6861. vector[v] = 0;
  6862. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  6863. normals.push(vector.x, vector.y, vector.z); // uvs
  6864. uvs.push(ix / gridX);
  6865. uvs.push(1 - iy / gridY); // counters
  6866. vertexCounter += 1;
  6867. }
  6868. } // indices
  6869. // 1. you need three indices to draw a single face
  6870. // 2. a single segment consists of two faces
  6871. // 3. so we need to generate six (2*3) indices per segment
  6872. for (let iy = 0; iy < gridY; iy++) {
  6873. for (let ix = 0; ix < gridX; ix++) {
  6874. const a = numberOfVertices + ix + gridX1 * iy;
  6875. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  6876. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  6877. const d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  6878. indices.push(a, b, d);
  6879. indices.push(b, c, d); // increase counter
  6880. groupCount += 6;
  6881. }
  6882. } // add a group to the geometry. this will ensure multi material support
  6883. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  6884. groupStart += groupCount; // update total number of vertices
  6885. numberOfVertices += vertexCounter;
  6886. }
  6887. }
  6888. static fromJSON(data) {
  6889. return new BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  6890. }
  6891. }
  6892. /**
  6893. * Uniform Utilities
  6894. */
  6895. function cloneUniforms(src) {
  6896. const dst = {};
  6897. for (const u in src) {
  6898. dst[u] = {};
  6899. for (const p in src[u]) {
  6900. const property = src[u][p];
  6901. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
  6902. dst[u][p] = property.clone();
  6903. } else if (Array.isArray(property)) {
  6904. dst[u][p] = property.slice();
  6905. } else {
  6906. dst[u][p] = property;
  6907. }
  6908. }
  6909. }
  6910. return dst;
  6911. }
  6912. function mergeUniforms(uniforms) {
  6913. const merged = {};
  6914. for (let u = 0; u < uniforms.length; u++) {
  6915. const tmp = cloneUniforms(uniforms[u]);
  6916. for (const p in tmp) {
  6917. merged[p] = tmp[p];
  6918. }
  6919. }
  6920. return merged;
  6921. } // Legacy
  6922. const UniformsUtils = {
  6923. clone: cloneUniforms,
  6924. merge: mergeUniforms
  6925. };
  6926. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6927. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6928. /**
  6929. * parameters = {
  6930. * defines: { "label" : "value" },
  6931. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  6932. *
  6933. * fragmentShader: <string>,
  6934. * vertexShader: <string>,
  6935. *
  6936. * wireframe: <boolean>,
  6937. * wireframeLinewidth: <float>,
  6938. *
  6939. * lights: <bool>
  6940. * }
  6941. */
  6942. class ShaderMaterial extends Material {
  6943. constructor(parameters) {
  6944. super();
  6945. this.type = 'ShaderMaterial';
  6946. this.defines = {};
  6947. this.uniforms = {};
  6948. this.vertexShader = default_vertex;
  6949. this.fragmentShader = default_fragment;
  6950. this.linewidth = 1;
  6951. this.wireframe = false;
  6952. this.wireframeLinewidth = 1;
  6953. this.fog = false; // set to use scene fog
  6954. this.lights = false; // set to use scene lights
  6955. this.clipping = false; // set to use user-defined clipping planes
  6956. this.extensions = {
  6957. derivatives: false,
  6958. // set to use derivatives
  6959. fragDepth: false,
  6960. // set to use fragment depth values
  6961. drawBuffers: false,
  6962. // set to use draw buffers
  6963. shaderTextureLOD: false // set to use shader texture LOD
  6964. }; // When rendered geometry doesn't include these attributes but the material does,
  6965. // use these default values in WebGL. This avoids errors when buffer data is missing.
  6966. this.defaultAttributeValues = {
  6967. 'color': [1, 1, 1],
  6968. 'uv': [0, 0],
  6969. 'uv2': [0, 0]
  6970. };
  6971. this.index0AttributeName = undefined;
  6972. this.uniformsNeedUpdate = false;
  6973. this.glslVersion = null;
  6974. if (parameters !== undefined) {
  6975. if (parameters.attributes !== undefined) {
  6976. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  6977. }
  6978. this.setValues(parameters);
  6979. }
  6980. }
  6981. copy(source) {
  6982. super.copy(source);
  6983. this.fragmentShader = source.fragmentShader;
  6984. this.vertexShader = source.vertexShader;
  6985. this.uniforms = cloneUniforms(source.uniforms);
  6986. this.defines = Object.assign({}, source.defines);
  6987. this.wireframe = source.wireframe;
  6988. this.wireframeLinewidth = source.wireframeLinewidth;
  6989. this.lights = source.lights;
  6990. this.clipping = source.clipping;
  6991. this.extensions = Object.assign({}, source.extensions);
  6992. this.glslVersion = source.glslVersion;
  6993. return this;
  6994. }
  6995. toJSON(meta) {
  6996. const data = super.toJSON(meta);
  6997. data.glslVersion = this.glslVersion;
  6998. data.uniforms = {};
  6999. for (const name in this.uniforms) {
  7000. const uniform = this.uniforms[name];
  7001. const value = uniform.value;
  7002. if (value && value.isTexture) {
  7003. data.uniforms[name] = {
  7004. type: 't',
  7005. value: value.toJSON(meta).uuid
  7006. };
  7007. } else if (value && value.isColor) {
  7008. data.uniforms[name] = {
  7009. type: 'c',
  7010. value: value.getHex()
  7011. };
  7012. } else if (value && value.isVector2) {
  7013. data.uniforms[name] = {
  7014. type: 'v2',
  7015. value: value.toArray()
  7016. };
  7017. } else if (value && value.isVector3) {
  7018. data.uniforms[name] = {
  7019. type: 'v3',
  7020. value: value.toArray()
  7021. };
  7022. } else if (value && value.isVector4) {
  7023. data.uniforms[name] = {
  7024. type: 'v4',
  7025. value: value.toArray()
  7026. };
  7027. } else if (value && value.isMatrix3) {
  7028. data.uniforms[name] = {
  7029. type: 'm3',
  7030. value: value.toArray()
  7031. };
  7032. } else if (value && value.isMatrix4) {
  7033. data.uniforms[name] = {
  7034. type: 'm4',
  7035. value: value.toArray()
  7036. };
  7037. } else {
  7038. data.uniforms[name] = {
  7039. value: value
  7040. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7041. }
  7042. }
  7043. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  7044. data.vertexShader = this.vertexShader;
  7045. data.fragmentShader = this.fragmentShader;
  7046. const extensions = {};
  7047. for (const key in this.extensions) {
  7048. if (this.extensions[key] === true) extensions[key] = true;
  7049. }
  7050. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  7051. return data;
  7052. }
  7053. }
  7054. ShaderMaterial.prototype.isShaderMaterial = true;
  7055. class Camera extends Object3D {
  7056. constructor() {
  7057. super();
  7058. this.type = 'Camera';
  7059. this.matrixWorldInverse = new Matrix4();
  7060. this.projectionMatrix = new Matrix4();
  7061. this.projectionMatrixInverse = new Matrix4();
  7062. }
  7063. copy(source, recursive) {
  7064. super.copy(source, recursive);
  7065. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  7066. this.projectionMatrix.copy(source.projectionMatrix);
  7067. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  7068. return this;
  7069. }
  7070. getWorldDirection(target) {
  7071. this.updateWorldMatrix(true, false);
  7072. const e = this.matrixWorld.elements;
  7073. return target.set(-e[8], -e[9], -e[10]).normalize();
  7074. }
  7075. updateMatrixWorld(force) {
  7076. super.updateMatrixWorld(force);
  7077. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7078. }
  7079. updateWorldMatrix(updateParents, updateChildren) {
  7080. super.updateWorldMatrix(updateParents, updateChildren);
  7081. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7082. }
  7083. clone() {
  7084. return new this.constructor().copy(this);
  7085. }
  7086. }
  7087. Camera.prototype.isCamera = true;
  7088. class PerspectiveCamera extends Camera {
  7089. constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  7090. super();
  7091. this.type = 'PerspectiveCamera';
  7092. this.fov = fov;
  7093. this.zoom = 1;
  7094. this.near = near;
  7095. this.far = far;
  7096. this.focus = 10;
  7097. this.aspect = aspect;
  7098. this.view = null;
  7099. this.filmGauge = 35; // width of the film (default in millimeters)
  7100. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7101. this.updateProjectionMatrix();
  7102. }
  7103. copy(source, recursive) {
  7104. super.copy(source, recursive);
  7105. this.fov = source.fov;
  7106. this.zoom = source.zoom;
  7107. this.near = source.near;
  7108. this.far = source.far;
  7109. this.focus = source.focus;
  7110. this.aspect = source.aspect;
  7111. this.view = source.view === null ? null : Object.assign({}, source.view);
  7112. this.filmGauge = source.filmGauge;
  7113. this.filmOffset = source.filmOffset;
  7114. return this;
  7115. }
  7116. /**
  7117. * Sets the FOV by focal length in respect to the current .filmGauge.
  7118. *
  7119. * The default film gauge is 35, so that the focal length can be specified for
  7120. * a 35mm (full frame) camera.
  7121. *
  7122. * Values for focal length and film gauge must have the same unit.
  7123. */
  7124. setFocalLength(focalLength) {
  7125. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7126. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7127. this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope);
  7128. this.updateProjectionMatrix();
  7129. }
  7130. /**
  7131. * Calculates the focal length from the current .fov and .filmGauge.
  7132. */
  7133. getFocalLength() {
  7134. const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov);
  7135. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7136. }
  7137. getEffectiveFOV() {
  7138. return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom);
  7139. }
  7140. getFilmWidth() {
  7141. // film not completely covered in portrait format (aspect < 1)
  7142. return this.filmGauge * Math.min(this.aspect, 1);
  7143. }
  7144. getFilmHeight() {
  7145. // film not completely covered in landscape format (aspect > 1)
  7146. return this.filmGauge / Math.max(this.aspect, 1);
  7147. }
  7148. /**
  7149. * Sets an offset in a larger frustum. This is useful for multi-window or
  7150. * multi-monitor/multi-machine setups.
  7151. *
  7152. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7153. * the monitors are in grid like this
  7154. *
  7155. * +---+---+---+
  7156. * | A | B | C |
  7157. * +---+---+---+
  7158. * | D | E | F |
  7159. * +---+---+---+
  7160. *
  7161. * then for each monitor you would call it like this
  7162. *
  7163. * const w = 1920;
  7164. * const h = 1080;
  7165. * const fullWidth = w * 3;
  7166. * const fullHeight = h * 2;
  7167. *
  7168. * --A--
  7169. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7170. * --B--
  7171. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7172. * --C--
  7173. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7174. * --D--
  7175. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7176. * --E--
  7177. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7178. * --F--
  7179. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7180. *
  7181. * Note there is no reason monitors have to be the same size or in a grid.
  7182. */
  7183. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  7184. this.aspect = fullWidth / fullHeight;
  7185. if (this.view === null) {
  7186. this.view = {
  7187. enabled: true,
  7188. fullWidth: 1,
  7189. fullHeight: 1,
  7190. offsetX: 0,
  7191. offsetY: 0,
  7192. width: 1,
  7193. height: 1
  7194. };
  7195. }
  7196. this.view.enabled = true;
  7197. this.view.fullWidth = fullWidth;
  7198. this.view.fullHeight = fullHeight;
  7199. this.view.offsetX = x;
  7200. this.view.offsetY = y;
  7201. this.view.width = width;
  7202. this.view.height = height;
  7203. this.updateProjectionMatrix();
  7204. }
  7205. clearViewOffset() {
  7206. if (this.view !== null) {
  7207. this.view.enabled = false;
  7208. }
  7209. this.updateProjectionMatrix();
  7210. }
  7211. updateProjectionMatrix() {
  7212. const near = this.near;
  7213. let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom;
  7214. let height = 2 * top;
  7215. let width = this.aspect * height;
  7216. let left = -0.5 * width;
  7217. const view = this.view;
  7218. if (this.view !== null && this.view.enabled) {
  7219. const fullWidth = view.fullWidth,
  7220. fullHeight = view.fullHeight;
  7221. left += view.offsetX * width / fullWidth;
  7222. top -= view.offsetY * height / fullHeight;
  7223. width *= view.width / fullWidth;
  7224. height *= view.height / fullHeight;
  7225. }
  7226. const skew = this.filmOffset;
  7227. if (skew !== 0) left += near * skew / this.getFilmWidth();
  7228. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  7229. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  7230. }
  7231. toJSON(meta) {
  7232. const data = super.toJSON(meta);
  7233. data.object.fov = this.fov;
  7234. data.object.zoom = this.zoom;
  7235. data.object.near = this.near;
  7236. data.object.far = this.far;
  7237. data.object.focus = this.focus;
  7238. data.object.aspect = this.aspect;
  7239. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  7240. data.object.filmGauge = this.filmGauge;
  7241. data.object.filmOffset = this.filmOffset;
  7242. return data;
  7243. }
  7244. }
  7245. PerspectiveCamera.prototype.isPerspectiveCamera = true;
  7246. const fov = 90,
  7247. aspect = 1;
  7248. class CubeCamera extends Object3D {
  7249. constructor(near, far, renderTarget) {
  7250. super();
  7251. this.type = 'CubeCamera';
  7252. if (renderTarget.isWebGLCubeRenderTarget !== true) {
  7253. console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
  7254. return;
  7255. }
  7256. this.renderTarget = renderTarget;
  7257. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  7258. cameraPX.layers = this.layers;
  7259. cameraPX.up.set(0, -1, 0);
  7260. cameraPX.lookAt(new Vector3(1, 0, 0));
  7261. this.add(cameraPX);
  7262. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  7263. cameraNX.layers = this.layers;
  7264. cameraNX.up.set(0, -1, 0);
  7265. cameraNX.lookAt(new Vector3(-1, 0, 0));
  7266. this.add(cameraNX);
  7267. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  7268. cameraPY.layers = this.layers;
  7269. cameraPY.up.set(0, 0, 1);
  7270. cameraPY.lookAt(new Vector3(0, 1, 0));
  7271. this.add(cameraPY);
  7272. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  7273. cameraNY.layers = this.layers;
  7274. cameraNY.up.set(0, 0, -1);
  7275. cameraNY.lookAt(new Vector3(0, -1, 0));
  7276. this.add(cameraNY);
  7277. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  7278. cameraPZ.layers = this.layers;
  7279. cameraPZ.up.set(0, -1, 0);
  7280. cameraPZ.lookAt(new Vector3(0, 0, 1));
  7281. this.add(cameraPZ);
  7282. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  7283. cameraNZ.layers = this.layers;
  7284. cameraNZ.up.set(0, -1, 0);
  7285. cameraNZ.lookAt(new Vector3(0, 0, -1));
  7286. this.add(cameraNZ);
  7287. }
  7288. update(renderer, scene) {
  7289. if (this.parent === null) this.updateMatrixWorld();
  7290. const renderTarget = this.renderTarget;
  7291. const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children;
  7292. const currentXrEnabled = renderer.xr.enabled;
  7293. const currentRenderTarget = renderer.getRenderTarget();
  7294. renderer.xr.enabled = false;
  7295. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7296. renderTarget.texture.generateMipmaps = false;
  7297. renderer.setRenderTarget(renderTarget, 0);
  7298. renderer.render(scene, cameraPX);
  7299. renderer.setRenderTarget(renderTarget, 1);
  7300. renderer.render(scene, cameraNX);
  7301. renderer.setRenderTarget(renderTarget, 2);
  7302. renderer.render(scene, cameraPY);
  7303. renderer.setRenderTarget(renderTarget, 3);
  7304. renderer.render(scene, cameraNY);
  7305. renderer.setRenderTarget(renderTarget, 4);
  7306. renderer.render(scene, cameraPZ);
  7307. renderTarget.texture.generateMipmaps = generateMipmaps;
  7308. renderer.setRenderTarget(renderTarget, 5);
  7309. renderer.render(scene, cameraNZ);
  7310. renderer.setRenderTarget(currentRenderTarget);
  7311. renderer.xr.enabled = currentXrEnabled;
  7312. }
  7313. }
  7314. class CubeTexture extends Texture {
  7315. constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  7316. images = images !== undefined ? images : [];
  7317. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7318. format = format !== undefined ? format : RGBFormat;
  7319. super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  7320. this.flipY = false;
  7321. }
  7322. get images() {
  7323. return this.image;
  7324. }
  7325. set images(value) {
  7326. this.image = value;
  7327. }
  7328. }
  7329. CubeTexture.prototype.isCubeTexture = true;
  7330. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7331. constructor(size, options, dummy) {
  7332. if (Number.isInteger(options)) {
  7333. console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
  7334. options = dummy;
  7335. }
  7336. super(size, size, options);
  7337. options = options || {}; // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7338. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7339. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7340. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7341. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7342. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7343. this.texture = new CubeTexture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  7344. this.texture.isRenderTargetTexture = true;
  7345. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7346. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7347. this.texture._needsFlipEnvMap = false;
  7348. }
  7349. fromEquirectangularTexture(renderer, texture) {
  7350. this.texture.type = texture.type;
  7351. this.texture.format = RGBAFormat; // see #18859
  7352. this.texture.encoding = texture.encoding;
  7353. this.texture.generateMipmaps = texture.generateMipmaps;
  7354. this.texture.minFilter = texture.minFilter;
  7355. this.texture.magFilter = texture.magFilter;
  7356. const shader = {
  7357. uniforms: {
  7358. tEquirect: {
  7359. value: null
  7360. }
  7361. },
  7362. vertexShader:
  7363. /* glsl */
  7364. `
  7365. varying vec3 vWorldDirection;
  7366. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7367. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7368. }
  7369. void main() {
  7370. vWorldDirection = transformDirection( position, modelMatrix );
  7371. #include <begin_vertex>
  7372. #include <project_vertex>
  7373. }
  7374. `,
  7375. fragmentShader:
  7376. /* glsl */
  7377. `
  7378. uniform sampler2D tEquirect;
  7379. varying vec3 vWorldDirection;
  7380. #include <common>
  7381. void main() {
  7382. vec3 direction = normalize( vWorldDirection );
  7383. vec2 sampleUV = equirectUv( direction );
  7384. gl_FragColor = texture2D( tEquirect, sampleUV );
  7385. }
  7386. `
  7387. };
  7388. const geometry = new BoxGeometry(5, 5, 5);
  7389. const material = new ShaderMaterial({
  7390. name: 'CubemapFromEquirect',
  7391. uniforms: cloneUniforms(shader.uniforms),
  7392. vertexShader: shader.vertexShader,
  7393. fragmentShader: shader.fragmentShader,
  7394. side: BackSide,
  7395. blending: NoBlending
  7396. });
  7397. material.uniforms.tEquirect.value = texture;
  7398. const mesh = new Mesh(geometry, material);
  7399. const currentMinFilter = texture.minFilter; // Avoid blurred poles
  7400. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  7401. const camera = new CubeCamera(1, 10, this);
  7402. camera.update(renderer, mesh);
  7403. texture.minFilter = currentMinFilter;
  7404. mesh.geometry.dispose();
  7405. mesh.material.dispose();
  7406. return this;
  7407. }
  7408. clear(renderer, color, depth, stencil) {
  7409. const currentRenderTarget = renderer.getRenderTarget();
  7410. for (let i = 0; i < 6; i++) {
  7411. renderer.setRenderTarget(this, i);
  7412. renderer.clear(color, depth, stencil);
  7413. }
  7414. renderer.setRenderTarget(currentRenderTarget);
  7415. }
  7416. }
  7417. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  7418. const _vector1 = /*@__PURE__*/new Vector3();
  7419. const _vector2 = /*@__PURE__*/new Vector3();
  7420. const _normalMatrix = /*@__PURE__*/new Matrix3();
  7421. class Plane {
  7422. constructor(normal = new Vector3(1, 0, 0), constant = 0) {
  7423. // normal is assumed to be normalized
  7424. this.normal = normal;
  7425. this.constant = constant;
  7426. }
  7427. set(normal, constant) {
  7428. this.normal.copy(normal);
  7429. this.constant = constant;
  7430. return this;
  7431. }
  7432. setComponents(x, y, z, w) {
  7433. this.normal.set(x, y, z);
  7434. this.constant = w;
  7435. return this;
  7436. }
  7437. setFromNormalAndCoplanarPoint(normal, point) {
  7438. this.normal.copy(normal);
  7439. this.constant = -point.dot(this.normal);
  7440. return this;
  7441. }
  7442. setFromCoplanarPoints(a, b, c) {
  7443. const normal = _vector1.subVectors(c, b).cross(_vector2.subVectors(a, b)).normalize(); // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7444. this.setFromNormalAndCoplanarPoint(normal, a);
  7445. return this;
  7446. }
  7447. copy(plane) {
  7448. this.normal.copy(plane.normal);
  7449. this.constant = plane.constant;
  7450. return this;
  7451. }
  7452. normalize() {
  7453. // Note: will lead to a divide by zero if the plane is invalid.
  7454. const inverseNormalLength = 1.0 / this.normal.length();
  7455. this.normal.multiplyScalar(inverseNormalLength);
  7456. this.constant *= inverseNormalLength;
  7457. return this;
  7458. }
  7459. negate() {
  7460. this.constant *= -1;
  7461. this.normal.negate();
  7462. return this;
  7463. }
  7464. distanceToPoint(point) {
  7465. return this.normal.dot(point) + this.constant;
  7466. }
  7467. distanceToSphere(sphere) {
  7468. return this.distanceToPoint(sphere.center) - sphere.radius;
  7469. }
  7470. projectPoint(point, target) {
  7471. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  7472. }
  7473. intersectLine(line, target) {
  7474. const direction = line.delta(_vector1);
  7475. const denominator = this.normal.dot(direction);
  7476. if (denominator === 0) {
  7477. // line is coplanar, return origin
  7478. if (this.distanceToPoint(line.start) === 0) {
  7479. return target.copy(line.start);
  7480. } // Unsure if this is the correct method to handle this case.
  7481. return null;
  7482. }
  7483. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  7484. if (t < 0 || t > 1) {
  7485. return null;
  7486. }
  7487. return target.copy(direction).multiplyScalar(t).add(line.start);
  7488. }
  7489. intersectsLine(line) {
  7490. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7491. const startSign = this.distanceToPoint(line.start);
  7492. const endSign = this.distanceToPoint(line.end);
  7493. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  7494. }
  7495. intersectsBox(box) {
  7496. return box.intersectsPlane(this);
  7497. }
  7498. intersectsSphere(sphere) {
  7499. return sphere.intersectsPlane(this);
  7500. }
  7501. coplanarPoint(target) {
  7502. return target.copy(this.normal).multiplyScalar(-this.constant);
  7503. }
  7504. applyMatrix4(matrix, optionalNormalMatrix) {
  7505. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  7506. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  7507. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  7508. this.constant = -referencePoint.dot(normal);
  7509. return this;
  7510. }
  7511. translate(offset) {
  7512. this.constant -= offset.dot(this.normal);
  7513. return this;
  7514. }
  7515. equals(plane) {
  7516. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  7517. }
  7518. clone() {
  7519. return new this.constructor().copy(this);
  7520. }
  7521. }
  7522. Plane.prototype.isPlane = true;
  7523. const _sphere$2 = /*@__PURE__*/new Sphere();
  7524. const _vector$7 = /*@__PURE__*/new Vector3();
  7525. class Frustum {
  7526. constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) {
  7527. this.planes = [p0, p1, p2, p3, p4, p5];
  7528. }
  7529. set(p0, p1, p2, p3, p4, p5) {
  7530. const planes = this.planes;
  7531. planes[0].copy(p0);
  7532. planes[1].copy(p1);
  7533. planes[2].copy(p2);
  7534. planes[3].copy(p3);
  7535. planes[4].copy(p4);
  7536. planes[5].copy(p5);
  7537. return this;
  7538. }
  7539. copy(frustum) {
  7540. const planes = this.planes;
  7541. for (let i = 0; i < 6; i++) {
  7542. planes[i].copy(frustum.planes[i]);
  7543. }
  7544. return this;
  7545. }
  7546. setFromProjectionMatrix(m) {
  7547. const planes = this.planes;
  7548. const me = m.elements;
  7549. const me0 = me[0],
  7550. me1 = me[1],
  7551. me2 = me[2],
  7552. me3 = me[3];
  7553. const me4 = me[4],
  7554. me5 = me[5],
  7555. me6 = me[6],
  7556. me7 = me[7];
  7557. const me8 = me[8],
  7558. me9 = me[9],
  7559. me10 = me[10],
  7560. me11 = me[11];
  7561. const me12 = me[12],
  7562. me13 = me[13],
  7563. me14 = me[14],
  7564. me15 = me[15];
  7565. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  7566. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  7567. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  7568. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  7569. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  7570. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  7571. return this;
  7572. }
  7573. intersectsObject(object) {
  7574. const geometry = object.geometry;
  7575. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7576. _sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  7577. return this.intersectsSphere(_sphere$2);
  7578. }
  7579. intersectsSprite(sprite) {
  7580. _sphere$2.center.set(0, 0, 0);
  7581. _sphere$2.radius = 0.7071067811865476;
  7582. _sphere$2.applyMatrix4(sprite.matrixWorld);
  7583. return this.intersectsSphere(_sphere$2);
  7584. }
  7585. intersectsSphere(sphere) {
  7586. const planes = this.planes;
  7587. const center = sphere.center;
  7588. const negRadius = -sphere.radius;
  7589. for (let i = 0; i < 6; i++) {
  7590. const distance = planes[i].distanceToPoint(center);
  7591. if (distance < negRadius) {
  7592. return false;
  7593. }
  7594. }
  7595. return true;
  7596. }
  7597. intersectsBox(box) {
  7598. const planes = this.planes;
  7599. for (let i = 0; i < 6; i++) {
  7600. const plane = planes[i]; // corner at max distance
  7601. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7602. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7603. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7604. if (plane.distanceToPoint(_vector$7) < 0) {
  7605. return false;
  7606. }
  7607. }
  7608. return true;
  7609. }
  7610. containsPoint(point) {
  7611. const planes = this.planes;
  7612. for (let i = 0; i < 6; i++) {
  7613. if (planes[i].distanceToPoint(point) < 0) {
  7614. return false;
  7615. }
  7616. }
  7617. return true;
  7618. }
  7619. clone() {
  7620. return new this.constructor().copy(this);
  7621. }
  7622. }
  7623. function WebGLAnimation() {
  7624. let context = null;
  7625. let isAnimating = false;
  7626. let animationLoop = null;
  7627. let requestId = null;
  7628. function onAnimationFrame(time, frame) {
  7629. animationLoop(time, frame);
  7630. requestId = context.requestAnimationFrame(onAnimationFrame);
  7631. }
  7632. return {
  7633. start: function () {
  7634. if (isAnimating === true) return;
  7635. if (animationLoop === null) return;
  7636. requestId = context.requestAnimationFrame(onAnimationFrame);
  7637. isAnimating = true;
  7638. },
  7639. stop: function () {
  7640. context.cancelAnimationFrame(requestId);
  7641. isAnimating = false;
  7642. },
  7643. setAnimationLoop: function (callback) {
  7644. animationLoop = callback;
  7645. },
  7646. setContext: function (value) {
  7647. context = value;
  7648. }
  7649. };
  7650. }
  7651. function WebGLAttributes(gl, capabilities) {
  7652. const isWebGL2 = capabilities.isWebGL2;
  7653. const buffers = new WeakMap();
  7654. function createBuffer(attribute, bufferType) {
  7655. const array = attribute.array;
  7656. const usage = attribute.usage;
  7657. const buffer = gl.createBuffer();
  7658. gl.bindBuffer(bufferType, buffer);
  7659. gl.bufferData(bufferType, array, usage);
  7660. attribute.onUploadCallback();
  7661. let type = gl.FLOAT;
  7662. if (array instanceof Float32Array) {
  7663. type = gl.FLOAT;
  7664. } else if (array instanceof Float64Array) {
  7665. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  7666. } else if (array instanceof Uint16Array) {
  7667. if (attribute.isFloat16BufferAttribute) {
  7668. if (isWebGL2) {
  7669. type = gl.HALF_FLOAT;
  7670. } else {
  7671. console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  7672. }
  7673. } else {
  7674. type = gl.UNSIGNED_SHORT;
  7675. }
  7676. } else if (array instanceof Int16Array) {
  7677. type = gl.SHORT;
  7678. } else if (array instanceof Uint32Array) {
  7679. type = gl.UNSIGNED_INT;
  7680. } else if (array instanceof Int32Array) {
  7681. type = gl.INT;
  7682. } else if (array instanceof Int8Array) {
  7683. type = gl.BYTE;
  7684. } else if (array instanceof Uint8Array) {
  7685. type = gl.UNSIGNED_BYTE;
  7686. } else if (array instanceof Uint8ClampedArray) {
  7687. type = gl.UNSIGNED_BYTE;
  7688. }
  7689. return {
  7690. buffer: buffer,
  7691. type: type,
  7692. bytesPerElement: array.BYTES_PER_ELEMENT,
  7693. version: attribute.version
  7694. };
  7695. }
  7696. function updateBuffer(buffer, attribute, bufferType) {
  7697. const array = attribute.array;
  7698. const updateRange = attribute.updateRange;
  7699. gl.bindBuffer(bufferType, buffer);
  7700. if (updateRange.count === -1) {
  7701. // Not using update ranges
  7702. gl.bufferSubData(bufferType, 0, array);
  7703. } else {
  7704. if (isWebGL2) {
  7705. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  7706. } else {
  7707. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  7708. }
  7709. updateRange.count = -1; // reset range
  7710. }
  7711. } //
  7712. function get(attribute) {
  7713. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7714. return buffers.get(attribute);
  7715. }
  7716. function remove(attribute) {
  7717. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7718. const data = buffers.get(attribute);
  7719. if (data) {
  7720. gl.deleteBuffer(data.buffer);
  7721. buffers.delete(attribute);
  7722. }
  7723. }
  7724. function update(attribute, bufferType) {
  7725. if (attribute.isGLBufferAttribute) {
  7726. const cached = buffers.get(attribute);
  7727. if (!cached || cached.version < attribute.version) {
  7728. buffers.set(attribute, {
  7729. buffer: attribute.buffer,
  7730. type: attribute.type,
  7731. bytesPerElement: attribute.elementSize,
  7732. version: attribute.version
  7733. });
  7734. }
  7735. return;
  7736. }
  7737. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7738. const data = buffers.get(attribute);
  7739. if (data === undefined) {
  7740. buffers.set(attribute, createBuffer(attribute, bufferType));
  7741. } else if (data.version < attribute.version) {
  7742. updateBuffer(data.buffer, attribute, bufferType);
  7743. data.version = attribute.version;
  7744. }
  7745. }
  7746. return {
  7747. get: get,
  7748. remove: remove,
  7749. update: update
  7750. };
  7751. }
  7752. class PlaneGeometry extends BufferGeometry {
  7753. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  7754. super();
  7755. this.type = 'PlaneGeometry';
  7756. this.parameters = {
  7757. width: width,
  7758. height: height,
  7759. widthSegments: widthSegments,
  7760. heightSegments: heightSegments
  7761. };
  7762. const width_half = width / 2;
  7763. const height_half = height / 2;
  7764. const gridX = Math.floor(widthSegments);
  7765. const gridY = Math.floor(heightSegments);
  7766. const gridX1 = gridX + 1;
  7767. const gridY1 = gridY + 1;
  7768. const segment_width = width / gridX;
  7769. const segment_height = height / gridY; //
  7770. const indices = [];
  7771. const vertices = [];
  7772. const normals = [];
  7773. const uvs = [];
  7774. for (let iy = 0; iy < gridY1; iy++) {
  7775. const y = iy * segment_height - height_half;
  7776. for (let ix = 0; ix < gridX1; ix++) {
  7777. const x = ix * segment_width - width_half;
  7778. vertices.push(x, -y, 0);
  7779. normals.push(0, 0, 1);
  7780. uvs.push(ix / gridX);
  7781. uvs.push(1 - iy / gridY);
  7782. }
  7783. }
  7784. for (let iy = 0; iy < gridY; iy++) {
  7785. for (let ix = 0; ix < gridX; ix++) {
  7786. const a = ix + gridX1 * iy;
  7787. const b = ix + gridX1 * (iy + 1);
  7788. const c = ix + 1 + gridX1 * (iy + 1);
  7789. const d = ix + 1 + gridX1 * iy;
  7790. indices.push(a, b, d);
  7791. indices.push(b, c, d);
  7792. }
  7793. }
  7794. this.setIndex(indices);
  7795. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7796. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7797. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7798. }
  7799. static fromJSON(data) {
  7800. return new PlaneGeometry(data.width, data.height, data.widthSegments, data.heightSegments);
  7801. }
  7802. }
  7803. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7804. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7805. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7806. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7807. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif";
  7808. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7809. var begin_vertex = "vec3 transformed = vec3( position );";
  7810. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7811. var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotVH = saturate( dot( geometry.viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenTint, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenTint * ( D * V );\n}\n#endif";
  7812. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";
  7813. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
  7814. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7815. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7816. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7817. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7818. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7819. var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7820. var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif";
  7821. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
  7822. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_maxMipLevel 8.0\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_maxTileSize 256.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tfloat texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 );\n\t\tvec2 f = fract( uv );\n\t\tuv += 0.5 - f;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tif ( mipInt < cubeUV_maxMipLevel ) {\n\t\t\tuv.y += 2.0 * cubeUV_maxTileSize;\n\t\t}\n\t\tuv.y += filterInt * 2.0 * cubeUV_minTileSize;\n\t\tuv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize );\n\t\tuv *= texelSize;\n\t\tvec3 tl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x += texelSize;\n\t\tvec3 tr = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.y += texelSize;\n\t\tvec3 br = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x -= texelSize;\n\t\tvec3 bl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tvec3 tm = mix( tl, tr, f.x );\n\t\tvec3 bm = mix( bl, br, f.x );\n\t\treturn mix( tm, bm, f.y );\n\t}\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, cubeUV_maxMipLevel );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif";
  7823. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  7824. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7825. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7826. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7827. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7828. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7829. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}";
  7830. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  7831. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";
  7832. var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif";
  7833. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif";
  7834. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif";
  7835. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7836. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7837. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  7838. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  7839. var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
  7840. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tlightMapIrradiance *= PI;\n\t#endif\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7841. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7842. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointLightInfo( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotLightInfo( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalLightInfo( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
  7843. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif";
  7844. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getIBLIrradiance( const in GeometricContext geometry ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec;\n\t\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\t\treflectVec = reflect( - viewDir, normal );\n\t\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\t#else\n\t\t\t\treflectVec = refract( - viewDir, normal, refractionRatio );\n\t\t\t#endif\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif";
  7845. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7846. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
  7847. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7848. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
  7849. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularTintFactor = specularTint;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARTINTMAP\n\t\t\tspecularTintFactor *= specularTintMapTexelToLinear( texture2D( specularTintMap, vUv ) ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularTintFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularTintFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenTint = sheenTint;\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n#endif";
  7850. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenTint;\n\t\tfloat sheenRoughness;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\tvec3 FssEss = specularColor * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenTint, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  7851. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  7852. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  7853. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif";
  7854. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  7855. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  7856. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";
  7857. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif";
  7858. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  7859. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7860. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  7861. var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7862. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7863. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7864. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif";
  7865. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\t\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\t\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  7866. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";
  7867. var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
  7868. var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( - vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif";
  7869. var normal_pars_fragment = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
  7870. var normal_pars_vertex = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
  7871. var normal_vertex = "#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif";
  7872. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif";
  7873. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7874. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );\n\t#endif\n#endif";
  7875. var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  7876. var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  7877. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";
  7878. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7879. var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
  7880. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7881. var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif";
  7882. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7883. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7884. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
  7885. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
  7886. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";
  7887. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  7888. var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";
  7889. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif";
  7890. var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif";
  7891. var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif";
  7892. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  7893. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7894. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7895. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  7896. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tfloat transmissionAlpha = 1.0;\n\tfloat transmissionFactor = transmission;\n\tfloat thicknessFactor = thickness;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\ttransmissionFactor *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tthicknessFactor *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, roughnessFactor, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationTint, attenuationDistance );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, transmissionFactor );\n\ttransmissionAlpha = transmission.a;\n#endif";
  7897. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationTint;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( vec3 n, vec3 v, float thickness, float ior, mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( float roughness, float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( vec2 fragCoord, float roughness, float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( vec3 radiance, float transmissionDistance, vec3 attenuationColor, float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( vec3 n, vec3 v, float roughness, vec3 diffuseColor, vec3 specularColor, float specularF90,\n\t\tvec3 position, mat4 modelMatrix, mat4 viewMatrix, mat4 projMatrix, float ior, float thickness,\n\t\tvec3 attenuationColor, float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif";
  7898. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7899. var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif";
  7900. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7901. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7902. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif";
  7903. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7904. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  7905. var background_frag = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7906. var background_vert = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
  7907. var cube_frag = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7908. var cube_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
  7909. var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  7910. var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
  7911. var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  7912. var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
  7913. var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7914. var equirect_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  7915. var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7916. var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  7917. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7918. var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  7919. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7920. var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7921. var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7922. var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  7923. var meshnormal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";
  7924. var meshnormal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  7925. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7926. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7927. var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularTint;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARTINTMAP\n\t\tuniform sampler2D specularTintMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenTint;\n\tuniform float sheenRoughness;\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - clearcoat * Fcc ) + clearcoatSpecular * clearcoat;\n\t#endif\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7928. var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}";
  7929. var meshtoon_frag = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7930. var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7931. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7932. var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  7933. var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  7934. var shadow_vert = "#include <common>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7935. var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  7936. var sprite_vert = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  7937. const ShaderChunk = {
  7938. alphamap_fragment: alphamap_fragment,
  7939. alphamap_pars_fragment: alphamap_pars_fragment,
  7940. alphatest_fragment: alphatest_fragment,
  7941. alphatest_pars_fragment: alphatest_pars_fragment,
  7942. aomap_fragment: aomap_fragment,
  7943. aomap_pars_fragment: aomap_pars_fragment,
  7944. begin_vertex: begin_vertex,
  7945. beginnormal_vertex: beginnormal_vertex,
  7946. bsdfs: bsdfs,
  7947. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7948. clipping_planes_fragment: clipping_planes_fragment,
  7949. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7950. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7951. clipping_planes_vertex: clipping_planes_vertex,
  7952. color_fragment: color_fragment,
  7953. color_pars_fragment: color_pars_fragment,
  7954. color_pars_vertex: color_pars_vertex,
  7955. color_vertex: color_vertex,
  7956. common: common,
  7957. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7958. defaultnormal_vertex: defaultnormal_vertex,
  7959. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7960. displacementmap_vertex: displacementmap_vertex,
  7961. emissivemap_fragment: emissivemap_fragment,
  7962. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7963. encodings_fragment: encodings_fragment,
  7964. encodings_pars_fragment: encodings_pars_fragment,
  7965. envmap_fragment: envmap_fragment,
  7966. envmap_common_pars_fragment: envmap_common_pars_fragment,
  7967. envmap_pars_fragment: envmap_pars_fragment,
  7968. envmap_pars_vertex: envmap_pars_vertex,
  7969. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  7970. envmap_vertex: envmap_vertex,
  7971. fog_vertex: fog_vertex,
  7972. fog_pars_vertex: fog_pars_vertex,
  7973. fog_fragment: fog_fragment,
  7974. fog_pars_fragment: fog_pars_fragment,
  7975. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7976. lightmap_fragment: lightmap_fragment,
  7977. lightmap_pars_fragment: lightmap_pars_fragment,
  7978. lights_lambert_vertex: lights_lambert_vertex,
  7979. lights_pars_begin: lights_pars_begin,
  7980. lights_toon_fragment: lights_toon_fragment,
  7981. lights_toon_pars_fragment: lights_toon_pars_fragment,
  7982. lights_phong_fragment: lights_phong_fragment,
  7983. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7984. lights_physical_fragment: lights_physical_fragment,
  7985. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7986. lights_fragment_begin: lights_fragment_begin,
  7987. lights_fragment_maps: lights_fragment_maps,
  7988. lights_fragment_end: lights_fragment_end,
  7989. logdepthbuf_fragment: logdepthbuf_fragment,
  7990. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7991. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7992. logdepthbuf_vertex: logdepthbuf_vertex,
  7993. map_fragment: map_fragment,
  7994. map_pars_fragment: map_pars_fragment,
  7995. map_particle_fragment: map_particle_fragment,
  7996. map_particle_pars_fragment: map_particle_pars_fragment,
  7997. metalnessmap_fragment: metalnessmap_fragment,
  7998. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7999. morphnormal_vertex: morphnormal_vertex,
  8000. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8001. morphtarget_vertex: morphtarget_vertex,
  8002. normal_fragment_begin: normal_fragment_begin,
  8003. normal_fragment_maps: normal_fragment_maps,
  8004. normal_pars_fragment: normal_pars_fragment,
  8005. normal_pars_vertex: normal_pars_vertex,
  8006. normal_vertex: normal_vertex,
  8007. normalmap_pars_fragment: normalmap_pars_fragment,
  8008. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8009. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8010. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8011. output_fragment: output_fragment,
  8012. packing: packing,
  8013. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8014. project_vertex: project_vertex,
  8015. dithering_fragment: dithering_fragment,
  8016. dithering_pars_fragment: dithering_pars_fragment,
  8017. roughnessmap_fragment: roughnessmap_fragment,
  8018. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8019. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8020. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8021. shadowmap_vertex: shadowmap_vertex,
  8022. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8023. skinbase_vertex: skinbase_vertex,
  8024. skinning_pars_vertex: skinning_pars_vertex,
  8025. skinning_vertex: skinning_vertex,
  8026. skinnormal_vertex: skinnormal_vertex,
  8027. specularmap_fragment: specularmap_fragment,
  8028. specularmap_pars_fragment: specularmap_pars_fragment,
  8029. tonemapping_fragment: tonemapping_fragment,
  8030. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8031. transmission_fragment: transmission_fragment,
  8032. transmission_pars_fragment: transmission_pars_fragment,
  8033. uv_pars_fragment: uv_pars_fragment,
  8034. uv_pars_vertex: uv_pars_vertex,
  8035. uv_vertex: uv_vertex,
  8036. uv2_pars_fragment: uv2_pars_fragment,
  8037. uv2_pars_vertex: uv2_pars_vertex,
  8038. uv2_vertex: uv2_vertex,
  8039. worldpos_vertex: worldpos_vertex,
  8040. background_frag: background_frag,
  8041. background_vert: background_vert,
  8042. cube_frag: cube_frag,
  8043. cube_vert: cube_vert,
  8044. depth_frag: depth_frag,
  8045. depth_vert: depth_vert,
  8046. distanceRGBA_frag: distanceRGBA_frag,
  8047. distanceRGBA_vert: distanceRGBA_vert,
  8048. equirect_frag: equirect_frag,
  8049. equirect_vert: equirect_vert,
  8050. linedashed_frag: linedashed_frag,
  8051. linedashed_vert: linedashed_vert,
  8052. meshbasic_frag: meshbasic_frag,
  8053. meshbasic_vert: meshbasic_vert,
  8054. meshlambert_frag: meshlambert_frag,
  8055. meshlambert_vert: meshlambert_vert,
  8056. meshmatcap_frag: meshmatcap_frag,
  8057. meshmatcap_vert: meshmatcap_vert,
  8058. meshnormal_frag: meshnormal_frag,
  8059. meshnormal_vert: meshnormal_vert,
  8060. meshphong_frag: meshphong_frag,
  8061. meshphong_vert: meshphong_vert,
  8062. meshphysical_frag: meshphysical_frag,
  8063. meshphysical_vert: meshphysical_vert,
  8064. meshtoon_frag: meshtoon_frag,
  8065. meshtoon_vert: meshtoon_vert,
  8066. points_frag: points_frag,
  8067. points_vert: points_vert,
  8068. shadow_frag: shadow_frag,
  8069. shadow_vert: shadow_vert,
  8070. sprite_frag: sprite_frag,
  8071. sprite_vert: sprite_vert
  8072. };
  8073. /**
  8074. * Uniforms library for shared webgl shaders
  8075. */
  8076. const UniformsLib = {
  8077. common: {
  8078. diffuse: {
  8079. value: new Color(0xffffff)
  8080. },
  8081. opacity: {
  8082. value: 1.0
  8083. },
  8084. map: {
  8085. value: null
  8086. },
  8087. uvTransform: {
  8088. value: new Matrix3()
  8089. },
  8090. uv2Transform: {
  8091. value: new Matrix3()
  8092. },
  8093. alphaMap: {
  8094. value: null
  8095. },
  8096. alphaTest: {
  8097. value: 0
  8098. }
  8099. },
  8100. specularmap: {
  8101. specularMap: {
  8102. value: null
  8103. }
  8104. },
  8105. envmap: {
  8106. envMap: {
  8107. value: null
  8108. },
  8109. flipEnvMap: {
  8110. value: -1
  8111. },
  8112. reflectivity: {
  8113. value: 1.0
  8114. },
  8115. // basic, lambert, phong
  8116. ior: {
  8117. value: 1.5
  8118. },
  8119. // standard, physical
  8120. refractionRatio: {
  8121. value: 0.98
  8122. },
  8123. maxMipLevel: {
  8124. value: 0
  8125. }
  8126. },
  8127. aomap: {
  8128. aoMap: {
  8129. value: null
  8130. },
  8131. aoMapIntensity: {
  8132. value: 1
  8133. }
  8134. },
  8135. lightmap: {
  8136. lightMap: {
  8137. value: null
  8138. },
  8139. lightMapIntensity: {
  8140. value: 1
  8141. }
  8142. },
  8143. emissivemap: {
  8144. emissiveMap: {
  8145. value: null
  8146. }
  8147. },
  8148. bumpmap: {
  8149. bumpMap: {
  8150. value: null
  8151. },
  8152. bumpScale: {
  8153. value: 1
  8154. }
  8155. },
  8156. normalmap: {
  8157. normalMap: {
  8158. value: null
  8159. },
  8160. normalScale: {
  8161. value: new Vector2(1, 1)
  8162. }
  8163. },
  8164. displacementmap: {
  8165. displacementMap: {
  8166. value: null
  8167. },
  8168. displacementScale: {
  8169. value: 1
  8170. },
  8171. displacementBias: {
  8172. value: 0
  8173. }
  8174. },
  8175. roughnessmap: {
  8176. roughnessMap: {
  8177. value: null
  8178. }
  8179. },
  8180. metalnessmap: {
  8181. metalnessMap: {
  8182. value: null
  8183. }
  8184. },
  8185. gradientmap: {
  8186. gradientMap: {
  8187. value: null
  8188. }
  8189. },
  8190. fog: {
  8191. fogDensity: {
  8192. value: 0.00025
  8193. },
  8194. fogNear: {
  8195. value: 1
  8196. },
  8197. fogFar: {
  8198. value: 2000
  8199. },
  8200. fogColor: {
  8201. value: new Color(0xffffff)
  8202. }
  8203. },
  8204. lights: {
  8205. ambientLightColor: {
  8206. value: []
  8207. },
  8208. lightProbe: {
  8209. value: []
  8210. },
  8211. directionalLights: {
  8212. value: [],
  8213. properties: {
  8214. direction: {},
  8215. color: {}
  8216. }
  8217. },
  8218. directionalLightShadows: {
  8219. value: [],
  8220. properties: {
  8221. shadowBias: {},
  8222. shadowNormalBias: {},
  8223. shadowRadius: {},
  8224. shadowMapSize: {}
  8225. }
  8226. },
  8227. directionalShadowMap: {
  8228. value: []
  8229. },
  8230. directionalShadowMatrix: {
  8231. value: []
  8232. },
  8233. spotLights: {
  8234. value: [],
  8235. properties: {
  8236. color: {},
  8237. position: {},
  8238. direction: {},
  8239. distance: {},
  8240. coneCos: {},
  8241. penumbraCos: {},
  8242. decay: {}
  8243. }
  8244. },
  8245. spotLightShadows: {
  8246. value: [],
  8247. properties: {
  8248. shadowBias: {},
  8249. shadowNormalBias: {},
  8250. shadowRadius: {},
  8251. shadowMapSize: {}
  8252. }
  8253. },
  8254. spotShadowMap: {
  8255. value: []
  8256. },
  8257. spotShadowMatrix: {
  8258. value: []
  8259. },
  8260. pointLights: {
  8261. value: [],
  8262. properties: {
  8263. color: {},
  8264. position: {},
  8265. decay: {},
  8266. distance: {}
  8267. }
  8268. },
  8269. pointLightShadows: {
  8270. value: [],
  8271. properties: {
  8272. shadowBias: {},
  8273. shadowNormalBias: {},
  8274. shadowRadius: {},
  8275. shadowMapSize: {},
  8276. shadowCameraNear: {},
  8277. shadowCameraFar: {}
  8278. }
  8279. },
  8280. pointShadowMap: {
  8281. value: []
  8282. },
  8283. pointShadowMatrix: {
  8284. value: []
  8285. },
  8286. hemisphereLights: {
  8287. value: [],
  8288. properties: {
  8289. direction: {},
  8290. skyColor: {},
  8291. groundColor: {}
  8292. }
  8293. },
  8294. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8295. rectAreaLights: {
  8296. value: [],
  8297. properties: {
  8298. color: {},
  8299. position: {},
  8300. width: {},
  8301. height: {}
  8302. }
  8303. },
  8304. ltc_1: {
  8305. value: null
  8306. },
  8307. ltc_2: {
  8308. value: null
  8309. }
  8310. },
  8311. points: {
  8312. diffuse: {
  8313. value: new Color(0xffffff)
  8314. },
  8315. opacity: {
  8316. value: 1.0
  8317. },
  8318. size: {
  8319. value: 1.0
  8320. },
  8321. scale: {
  8322. value: 1.0
  8323. },
  8324. map: {
  8325. value: null
  8326. },
  8327. alphaMap: {
  8328. value: null
  8329. },
  8330. alphaTest: {
  8331. value: 0
  8332. },
  8333. uvTransform: {
  8334. value: new Matrix3()
  8335. }
  8336. },
  8337. sprite: {
  8338. diffuse: {
  8339. value: new Color(0xffffff)
  8340. },
  8341. opacity: {
  8342. value: 1.0
  8343. },
  8344. center: {
  8345. value: new Vector2(0.5, 0.5)
  8346. },
  8347. rotation: {
  8348. value: 0.0
  8349. },
  8350. map: {
  8351. value: null
  8352. },
  8353. alphaMap: {
  8354. value: null
  8355. },
  8356. alphaTest: {
  8357. value: 0
  8358. },
  8359. uvTransform: {
  8360. value: new Matrix3()
  8361. }
  8362. }
  8363. };
  8364. const ShaderLib = {
  8365. basic: {
  8366. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  8367. vertexShader: ShaderChunk.meshbasic_vert,
  8368. fragmentShader: ShaderChunk.meshbasic_frag
  8369. },
  8370. lambert: {
  8371. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  8372. emissive: {
  8373. value: new Color(0x000000)
  8374. }
  8375. }]),
  8376. vertexShader: ShaderChunk.meshlambert_vert,
  8377. fragmentShader: ShaderChunk.meshlambert_frag
  8378. },
  8379. phong: {
  8380. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  8381. emissive: {
  8382. value: new Color(0x000000)
  8383. },
  8384. specular: {
  8385. value: new Color(0x111111)
  8386. },
  8387. shininess: {
  8388. value: 30
  8389. }
  8390. }]),
  8391. vertexShader: ShaderChunk.meshphong_vert,
  8392. fragmentShader: ShaderChunk.meshphong_frag
  8393. },
  8394. standard: {
  8395. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.roughnessmap, UniformsLib.metalnessmap, UniformsLib.fog, UniformsLib.lights, {
  8396. emissive: {
  8397. value: new Color(0x000000)
  8398. },
  8399. roughness: {
  8400. value: 1.0
  8401. },
  8402. metalness: {
  8403. value: 0.0
  8404. },
  8405. envMapIntensity: {
  8406. value: 1
  8407. } // temporary
  8408. }]),
  8409. vertexShader: ShaderChunk.meshphysical_vert,
  8410. fragmentShader: ShaderChunk.meshphysical_frag
  8411. },
  8412. toon: {
  8413. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  8414. emissive: {
  8415. value: new Color(0x000000)
  8416. }
  8417. }]),
  8418. vertexShader: ShaderChunk.meshtoon_vert,
  8419. fragmentShader: ShaderChunk.meshtoon_frag
  8420. },
  8421. matcap: {
  8422. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  8423. matcap: {
  8424. value: null
  8425. }
  8426. }]),
  8427. vertexShader: ShaderChunk.meshmatcap_vert,
  8428. fragmentShader: ShaderChunk.meshmatcap_frag
  8429. },
  8430. points: {
  8431. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  8432. vertexShader: ShaderChunk.points_vert,
  8433. fragmentShader: ShaderChunk.points_frag
  8434. },
  8435. dashed: {
  8436. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  8437. scale: {
  8438. value: 1
  8439. },
  8440. dashSize: {
  8441. value: 1
  8442. },
  8443. totalSize: {
  8444. value: 2
  8445. }
  8446. }]),
  8447. vertexShader: ShaderChunk.linedashed_vert,
  8448. fragmentShader: ShaderChunk.linedashed_frag
  8449. },
  8450. depth: {
  8451. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  8452. vertexShader: ShaderChunk.depth_vert,
  8453. fragmentShader: ShaderChunk.depth_frag
  8454. },
  8455. normal: {
  8456. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  8457. opacity: {
  8458. value: 1.0
  8459. }
  8460. }]),
  8461. vertexShader: ShaderChunk.meshnormal_vert,
  8462. fragmentShader: ShaderChunk.meshnormal_frag
  8463. },
  8464. sprite: {
  8465. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  8466. vertexShader: ShaderChunk.sprite_vert,
  8467. fragmentShader: ShaderChunk.sprite_frag
  8468. },
  8469. background: {
  8470. uniforms: {
  8471. uvTransform: {
  8472. value: new Matrix3()
  8473. },
  8474. t2D: {
  8475. value: null
  8476. }
  8477. },
  8478. vertexShader: ShaderChunk.background_vert,
  8479. fragmentShader: ShaderChunk.background_frag
  8480. },
  8481. /* -------------------------------------------------------------------------
  8482. // Cube map shader
  8483. ------------------------------------------------------------------------- */
  8484. cube: {
  8485. uniforms: mergeUniforms([UniformsLib.envmap, {
  8486. opacity: {
  8487. value: 1.0
  8488. }
  8489. }]),
  8490. vertexShader: ShaderChunk.cube_vert,
  8491. fragmentShader: ShaderChunk.cube_frag
  8492. },
  8493. equirect: {
  8494. uniforms: {
  8495. tEquirect: {
  8496. value: null
  8497. }
  8498. },
  8499. vertexShader: ShaderChunk.equirect_vert,
  8500. fragmentShader: ShaderChunk.equirect_frag
  8501. },
  8502. distanceRGBA: {
  8503. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  8504. referencePosition: {
  8505. value: new Vector3()
  8506. },
  8507. nearDistance: {
  8508. value: 1
  8509. },
  8510. farDistance: {
  8511. value: 1000
  8512. }
  8513. }]),
  8514. vertexShader: ShaderChunk.distanceRGBA_vert,
  8515. fragmentShader: ShaderChunk.distanceRGBA_frag
  8516. },
  8517. shadow: {
  8518. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  8519. color: {
  8520. value: new Color(0x00000)
  8521. },
  8522. opacity: {
  8523. value: 1.0
  8524. }
  8525. }]),
  8526. vertexShader: ShaderChunk.shadow_vert,
  8527. fragmentShader: ShaderChunk.shadow_frag
  8528. }
  8529. };
  8530. ShaderLib.physical = {
  8531. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  8532. clearcoat: {
  8533. value: 0
  8534. },
  8535. clearcoatMap: {
  8536. value: null
  8537. },
  8538. clearcoatRoughness: {
  8539. value: 0
  8540. },
  8541. clearcoatRoughnessMap: {
  8542. value: null
  8543. },
  8544. clearcoatNormalScale: {
  8545. value: new Vector2(1, 1)
  8546. },
  8547. clearcoatNormalMap: {
  8548. value: null
  8549. },
  8550. sheen: {
  8551. value: 0
  8552. },
  8553. sheenTint: {
  8554. value: new Color(0x000000)
  8555. },
  8556. sheenRoughness: {
  8557. value: 0
  8558. },
  8559. transmission: {
  8560. value: 0
  8561. },
  8562. transmissionMap: {
  8563. value: null
  8564. },
  8565. transmissionSamplerSize: {
  8566. value: new Vector2()
  8567. },
  8568. transmissionSamplerMap: {
  8569. value: null
  8570. },
  8571. thickness: {
  8572. value: 0
  8573. },
  8574. thicknessMap: {
  8575. value: null
  8576. },
  8577. attenuationDistance: {
  8578. value: 0
  8579. },
  8580. attenuationTint: {
  8581. value: new Color(0x000000)
  8582. },
  8583. specularIntensity: {
  8584. value: 0
  8585. },
  8586. specularIntensityMap: {
  8587. value: null
  8588. },
  8589. specularTint: {
  8590. value: new Color(1, 1, 1)
  8591. },
  8592. specularTintMap: {
  8593. value: null
  8594. }
  8595. }]),
  8596. vertexShader: ShaderChunk.meshphysical_vert,
  8597. fragmentShader: ShaderChunk.meshphysical_frag
  8598. };
  8599. function WebGLBackground(renderer, cubemaps, state, objects, premultipliedAlpha) {
  8600. const clearColor = new Color(0x000000);
  8601. let clearAlpha = 0;
  8602. let planeMesh;
  8603. let boxMesh;
  8604. let currentBackground = null;
  8605. let currentBackgroundVersion = 0;
  8606. let currentTonemapping = null;
  8607. function render(renderList, scene) {
  8608. let forceClear = false;
  8609. let background = scene.isScene === true ? scene.background : null;
  8610. if (background && background.isTexture) {
  8611. background = cubemaps.get(background);
  8612. } // Ignore background in AR
  8613. // TODO: Reconsider this.
  8614. const xr = renderer.xr;
  8615. const session = xr.getSession && xr.getSession();
  8616. if (session && session.environmentBlendMode === 'additive') {
  8617. background = null;
  8618. }
  8619. if (background === null) {
  8620. setClear(clearColor, clearAlpha);
  8621. } else if (background && background.isColor) {
  8622. setClear(background, 1);
  8623. forceClear = true;
  8624. }
  8625. if (renderer.autoClear || forceClear) {
  8626. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  8627. }
  8628. if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
  8629. if (boxMesh === undefined) {
  8630. boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
  8631. name: 'BackgroundCubeMaterial',
  8632. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  8633. vertexShader: ShaderLib.cube.vertexShader,
  8634. fragmentShader: ShaderLib.cube.fragmentShader,
  8635. side: BackSide,
  8636. depthTest: false,
  8637. depthWrite: false,
  8638. fog: false
  8639. }));
  8640. boxMesh.geometry.deleteAttribute('normal');
  8641. boxMesh.geometry.deleteAttribute('uv');
  8642. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  8643. this.matrixWorld.copyPosition(camera.matrixWorld);
  8644. }; // enable code injection for non-built-in material
  8645. Object.defineProperty(boxMesh.material, 'envMap', {
  8646. get: function () {
  8647. return this.uniforms.envMap.value;
  8648. }
  8649. });
  8650. objects.update(boxMesh);
  8651. }
  8652. boxMesh.material.uniforms.envMap.value = background;
  8653. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1;
  8654. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8655. boxMesh.material.needsUpdate = true;
  8656. currentBackground = background;
  8657. currentBackgroundVersion = background.version;
  8658. currentTonemapping = renderer.toneMapping;
  8659. } // push to the pre-sorted opaque render list
  8660. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  8661. } else if (background && background.isTexture) {
  8662. if (planeMesh === undefined) {
  8663. planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
  8664. name: 'BackgroundMaterial',
  8665. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  8666. vertexShader: ShaderLib.background.vertexShader,
  8667. fragmentShader: ShaderLib.background.fragmentShader,
  8668. side: FrontSide,
  8669. depthTest: false,
  8670. depthWrite: false,
  8671. fog: false
  8672. }));
  8673. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  8674. Object.defineProperty(planeMesh.material, 'map', {
  8675. get: function () {
  8676. return this.uniforms.t2D.value;
  8677. }
  8678. });
  8679. objects.update(planeMesh);
  8680. }
  8681. planeMesh.material.uniforms.t2D.value = background;
  8682. if (background.matrixAutoUpdate === true) {
  8683. background.updateMatrix();
  8684. }
  8685. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  8686. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8687. planeMesh.material.needsUpdate = true;
  8688. currentBackground = background;
  8689. currentBackgroundVersion = background.version;
  8690. currentTonemapping = renderer.toneMapping;
  8691. } // push to the pre-sorted opaque render list
  8692. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  8693. }
  8694. }
  8695. function setClear(color, alpha) {
  8696. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  8697. }
  8698. return {
  8699. getClearColor: function () {
  8700. return clearColor;
  8701. },
  8702. setClearColor: function (color, alpha = 1) {
  8703. clearColor.set(color);
  8704. clearAlpha = alpha;
  8705. setClear(clearColor, clearAlpha);
  8706. },
  8707. getClearAlpha: function () {
  8708. return clearAlpha;
  8709. },
  8710. setClearAlpha: function (alpha) {
  8711. clearAlpha = alpha;
  8712. setClear(clearColor, clearAlpha);
  8713. },
  8714. render: render
  8715. };
  8716. }
  8717. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  8718. const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  8719. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  8720. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8721. const bindingStates = {};
  8722. const defaultState = createBindingState(null);
  8723. let currentState = defaultState;
  8724. function setup(object, material, program, geometry, index) {
  8725. let updateBuffers = false;
  8726. if (vaoAvailable) {
  8727. const state = getBindingState(geometry, program, material);
  8728. if (currentState !== state) {
  8729. currentState = state;
  8730. bindVertexArrayObject(currentState.object);
  8731. }
  8732. updateBuffers = needsUpdate(geometry, index);
  8733. if (updateBuffers) saveCache(geometry, index);
  8734. } else {
  8735. const wireframe = material.wireframe === true;
  8736. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  8737. currentState.geometry = geometry.id;
  8738. currentState.program = program.id;
  8739. currentState.wireframe = wireframe;
  8740. updateBuffers = true;
  8741. }
  8742. }
  8743. if (object.isInstancedMesh === true) {
  8744. updateBuffers = true;
  8745. }
  8746. if (index !== null) {
  8747. attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
  8748. }
  8749. if (updateBuffers) {
  8750. setupVertexAttributes(object, material, program, geometry);
  8751. if (index !== null) {
  8752. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
  8753. }
  8754. }
  8755. }
  8756. function createVertexArrayObject() {
  8757. if (capabilities.isWebGL2) return gl.createVertexArray();
  8758. return extension.createVertexArrayOES();
  8759. }
  8760. function bindVertexArrayObject(vao) {
  8761. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  8762. return extension.bindVertexArrayOES(vao);
  8763. }
  8764. function deleteVertexArrayObject(vao) {
  8765. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  8766. return extension.deleteVertexArrayOES(vao);
  8767. }
  8768. function getBindingState(geometry, program, material) {
  8769. const wireframe = material.wireframe === true;
  8770. let programMap = bindingStates[geometry.id];
  8771. if (programMap === undefined) {
  8772. programMap = {};
  8773. bindingStates[geometry.id] = programMap;
  8774. }
  8775. let stateMap = programMap[program.id];
  8776. if (stateMap === undefined) {
  8777. stateMap = {};
  8778. programMap[program.id] = stateMap;
  8779. }
  8780. let state = stateMap[wireframe];
  8781. if (state === undefined) {
  8782. state = createBindingState(createVertexArrayObject());
  8783. stateMap[wireframe] = state;
  8784. }
  8785. return state;
  8786. }
  8787. function createBindingState(vao) {
  8788. const newAttributes = [];
  8789. const enabledAttributes = [];
  8790. const attributeDivisors = [];
  8791. for (let i = 0; i < maxVertexAttributes; i++) {
  8792. newAttributes[i] = 0;
  8793. enabledAttributes[i] = 0;
  8794. attributeDivisors[i] = 0;
  8795. }
  8796. return {
  8797. // for backward compatibility on non-VAO support browser
  8798. geometry: null,
  8799. program: null,
  8800. wireframe: false,
  8801. newAttributes: newAttributes,
  8802. enabledAttributes: enabledAttributes,
  8803. attributeDivisors: attributeDivisors,
  8804. object: vao,
  8805. attributes: {},
  8806. index: null
  8807. };
  8808. }
  8809. function needsUpdate(geometry, index) {
  8810. const cachedAttributes = currentState.attributes;
  8811. const geometryAttributes = geometry.attributes;
  8812. let attributesNum = 0;
  8813. for (const key in geometryAttributes) {
  8814. const cachedAttribute = cachedAttributes[key];
  8815. const geometryAttribute = geometryAttributes[key];
  8816. if (cachedAttribute === undefined) return true;
  8817. if (cachedAttribute.attribute !== geometryAttribute) return true;
  8818. if (cachedAttribute.data !== geometryAttribute.data) return true;
  8819. attributesNum++;
  8820. }
  8821. if (currentState.attributesNum !== attributesNum) return true;
  8822. if (currentState.index !== index) return true;
  8823. return false;
  8824. }
  8825. function saveCache(geometry, index) {
  8826. const cache = {};
  8827. const attributes = geometry.attributes;
  8828. let attributesNum = 0;
  8829. for (const key in attributes) {
  8830. const attribute = attributes[key];
  8831. const data = {};
  8832. data.attribute = attribute;
  8833. if (attribute.data) {
  8834. data.data = attribute.data;
  8835. }
  8836. cache[key] = data;
  8837. attributesNum++;
  8838. }
  8839. currentState.attributes = cache;
  8840. currentState.attributesNum = attributesNum;
  8841. currentState.index = index;
  8842. }
  8843. function initAttributes() {
  8844. const newAttributes = currentState.newAttributes;
  8845. for (let i = 0, il = newAttributes.length; i < il; i++) {
  8846. newAttributes[i] = 0;
  8847. }
  8848. }
  8849. function enableAttribute(attribute) {
  8850. enableAttributeAndDivisor(attribute, 0);
  8851. }
  8852. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  8853. const newAttributes = currentState.newAttributes;
  8854. const enabledAttributes = currentState.enabledAttributes;
  8855. const attributeDivisors = currentState.attributeDivisors;
  8856. newAttributes[attribute] = 1;
  8857. if (enabledAttributes[attribute] === 0) {
  8858. gl.enableVertexAttribArray(attribute);
  8859. enabledAttributes[attribute] = 1;
  8860. }
  8861. if (attributeDivisors[attribute] !== meshPerAttribute) {
  8862. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  8863. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  8864. attributeDivisors[attribute] = meshPerAttribute;
  8865. }
  8866. }
  8867. function disableUnusedAttributes() {
  8868. const newAttributes = currentState.newAttributes;
  8869. const enabledAttributes = currentState.enabledAttributes;
  8870. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  8871. if (enabledAttributes[i] !== newAttributes[i]) {
  8872. gl.disableVertexAttribArray(i);
  8873. enabledAttributes[i] = 0;
  8874. }
  8875. }
  8876. }
  8877. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  8878. if (capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT)) {
  8879. gl.vertexAttribIPointer(index, size, type, stride, offset);
  8880. } else {
  8881. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  8882. }
  8883. }
  8884. function setupVertexAttributes(object, material, program, geometry) {
  8885. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  8886. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  8887. }
  8888. initAttributes();
  8889. const geometryAttributes = geometry.attributes;
  8890. const programAttributes = program.getAttributes();
  8891. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8892. for (const name in programAttributes) {
  8893. const programAttribute = programAttributes[name];
  8894. if (programAttribute.location >= 0) {
  8895. let geometryAttribute = geometryAttributes[name];
  8896. if (geometryAttribute === undefined) {
  8897. if (name === 'instanceMatrix' && object.instanceMatrix) geometryAttribute = object.instanceMatrix;
  8898. if (name === 'instanceColor' && object.instanceColor) geometryAttribute = object.instanceColor;
  8899. }
  8900. if (geometryAttribute !== undefined) {
  8901. const normalized = geometryAttribute.normalized;
  8902. const size = geometryAttribute.itemSize;
  8903. const attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  8904. if (attribute === undefined) continue;
  8905. const buffer = attribute.buffer;
  8906. const type = attribute.type;
  8907. const bytesPerElement = attribute.bytesPerElement;
  8908. if (geometryAttribute.isInterleavedBufferAttribute) {
  8909. const data = geometryAttribute.data;
  8910. const stride = data.stride;
  8911. const offset = geometryAttribute.offset;
  8912. if (data && data.isInstancedInterleavedBuffer) {
  8913. for (let i = 0; i < programAttribute.locationSize; i++) {
  8914. enableAttributeAndDivisor(programAttribute.location + i, data.meshPerAttribute);
  8915. }
  8916. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  8917. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8918. }
  8919. } else {
  8920. for (let i = 0; i < programAttribute.locationSize; i++) {
  8921. enableAttribute(programAttribute.location + i);
  8922. }
  8923. }
  8924. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8925. for (let i = 0; i < programAttribute.locationSize; i++) {
  8926. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, stride * bytesPerElement, (offset + size / programAttribute.locationSize * i) * bytesPerElement);
  8927. }
  8928. } else {
  8929. if (geometryAttribute.isInstancedBufferAttribute) {
  8930. for (let i = 0; i < programAttribute.locationSize; i++) {
  8931. enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute);
  8932. }
  8933. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  8934. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8935. }
  8936. } else {
  8937. for (let i = 0; i < programAttribute.locationSize; i++) {
  8938. enableAttribute(programAttribute.location + i);
  8939. }
  8940. }
  8941. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8942. for (let i = 0; i < programAttribute.locationSize; i++) {
  8943. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, size * bytesPerElement, size / programAttribute.locationSize * i * bytesPerElement);
  8944. }
  8945. }
  8946. } else if (materialDefaultAttributeValues !== undefined) {
  8947. const value = materialDefaultAttributeValues[name];
  8948. if (value !== undefined) {
  8949. switch (value.length) {
  8950. case 2:
  8951. gl.vertexAttrib2fv(programAttribute.location, value);
  8952. break;
  8953. case 3:
  8954. gl.vertexAttrib3fv(programAttribute.location, value);
  8955. break;
  8956. case 4:
  8957. gl.vertexAttrib4fv(programAttribute.location, value);
  8958. break;
  8959. default:
  8960. gl.vertexAttrib1fv(programAttribute.location, value);
  8961. }
  8962. }
  8963. }
  8964. }
  8965. }
  8966. disableUnusedAttributes();
  8967. }
  8968. function dispose() {
  8969. reset();
  8970. for (const geometryId in bindingStates) {
  8971. const programMap = bindingStates[geometryId];
  8972. for (const programId in programMap) {
  8973. const stateMap = programMap[programId];
  8974. for (const wireframe in stateMap) {
  8975. deleteVertexArrayObject(stateMap[wireframe].object);
  8976. delete stateMap[wireframe];
  8977. }
  8978. delete programMap[programId];
  8979. }
  8980. delete bindingStates[geometryId];
  8981. }
  8982. }
  8983. function releaseStatesOfGeometry(geometry) {
  8984. if (bindingStates[geometry.id] === undefined) return;
  8985. const programMap = bindingStates[geometry.id];
  8986. for (const programId in programMap) {
  8987. const stateMap = programMap[programId];
  8988. for (const wireframe in stateMap) {
  8989. deleteVertexArrayObject(stateMap[wireframe].object);
  8990. delete stateMap[wireframe];
  8991. }
  8992. delete programMap[programId];
  8993. }
  8994. delete bindingStates[geometry.id];
  8995. }
  8996. function releaseStatesOfProgram(program) {
  8997. for (const geometryId in bindingStates) {
  8998. const programMap = bindingStates[geometryId];
  8999. if (programMap[program.id] === undefined) continue;
  9000. const stateMap = programMap[program.id];
  9001. for (const wireframe in stateMap) {
  9002. deleteVertexArrayObject(stateMap[wireframe].object);
  9003. delete stateMap[wireframe];
  9004. }
  9005. delete programMap[program.id];
  9006. }
  9007. }
  9008. function reset() {
  9009. resetDefaultState();
  9010. if (currentState === defaultState) return;
  9011. currentState = defaultState;
  9012. bindVertexArrayObject(currentState.object);
  9013. } // for backward-compatilibity
  9014. function resetDefaultState() {
  9015. defaultState.geometry = null;
  9016. defaultState.program = null;
  9017. defaultState.wireframe = false;
  9018. }
  9019. return {
  9020. setup: setup,
  9021. reset: reset,
  9022. resetDefaultState: resetDefaultState,
  9023. dispose: dispose,
  9024. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9025. releaseStatesOfProgram: releaseStatesOfProgram,
  9026. initAttributes: initAttributes,
  9027. enableAttribute: enableAttribute,
  9028. disableUnusedAttributes: disableUnusedAttributes
  9029. };
  9030. }
  9031. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  9032. const isWebGL2 = capabilities.isWebGL2;
  9033. let mode;
  9034. function setMode(value) {
  9035. mode = value;
  9036. }
  9037. function render(start, count) {
  9038. gl.drawArrays(mode, start, count);
  9039. info.update(count, mode, 1);
  9040. }
  9041. function renderInstances(start, count, primcount) {
  9042. if (primcount === 0) return;
  9043. let extension, methodName;
  9044. if (isWebGL2) {
  9045. extension = gl;
  9046. methodName = 'drawArraysInstanced';
  9047. } else {
  9048. extension = extensions.get('ANGLE_instanced_arrays');
  9049. methodName = 'drawArraysInstancedANGLE';
  9050. if (extension === null) {
  9051. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9052. return;
  9053. }
  9054. }
  9055. extension[methodName](mode, start, count, primcount);
  9056. info.update(count, mode, primcount);
  9057. } //
  9058. this.setMode = setMode;
  9059. this.render = render;
  9060. this.renderInstances = renderInstances;
  9061. }
  9062. function WebGLCapabilities(gl, extensions, parameters) {
  9063. let maxAnisotropy;
  9064. function getMaxAnisotropy() {
  9065. if (maxAnisotropy !== undefined) return maxAnisotropy;
  9066. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  9067. const extension = extensions.get('EXT_texture_filter_anisotropic');
  9068. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  9069. } else {
  9070. maxAnisotropy = 0;
  9071. }
  9072. return maxAnisotropy;
  9073. }
  9074. function getMaxPrecision(precision) {
  9075. if (precision === 'highp') {
  9076. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
  9077. return 'highp';
  9078. }
  9079. precision = 'mediump';
  9080. }
  9081. if (precision === 'mediump') {
  9082. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
  9083. return 'mediump';
  9084. }
  9085. }
  9086. return 'lowp';
  9087. }
  9088. /* eslint-disable no-undef */
  9089. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  9090. /* eslint-enable no-undef */
  9091. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9092. const maxPrecision = getMaxPrecision(precision);
  9093. if (maxPrecision !== precision) {
  9094. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  9095. precision = maxPrecision;
  9096. }
  9097. const drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers');
  9098. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9099. const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  9100. const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9101. const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  9102. const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9103. const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  9104. const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
  9105. const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
  9106. const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9107. const vertexTextures = maxVertexTextures > 0;
  9108. const floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float');
  9109. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9110. const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
  9111. return {
  9112. isWebGL2: isWebGL2,
  9113. drawBuffers: drawBuffers,
  9114. getMaxAnisotropy: getMaxAnisotropy,
  9115. getMaxPrecision: getMaxPrecision,
  9116. precision: precision,
  9117. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9118. maxTextures: maxTextures,
  9119. maxVertexTextures: maxVertexTextures,
  9120. maxTextureSize: maxTextureSize,
  9121. maxCubemapSize: maxCubemapSize,
  9122. maxAttributes: maxAttributes,
  9123. maxVertexUniforms: maxVertexUniforms,
  9124. maxVaryings: maxVaryings,
  9125. maxFragmentUniforms: maxFragmentUniforms,
  9126. vertexTextures: vertexTextures,
  9127. floatFragmentTextures: floatFragmentTextures,
  9128. floatVertexTextures: floatVertexTextures,
  9129. maxSamples: maxSamples
  9130. };
  9131. }
  9132. function WebGLClipping(properties) {
  9133. const scope = this;
  9134. let globalState = null,
  9135. numGlobalPlanes = 0,
  9136. localClippingEnabled = false,
  9137. renderingShadows = false;
  9138. const plane = new Plane(),
  9139. viewNormalMatrix = new Matrix3(),
  9140. uniform = {
  9141. value: null,
  9142. needsUpdate: false
  9143. };
  9144. this.uniform = uniform;
  9145. this.numPlanes = 0;
  9146. this.numIntersection = 0;
  9147. this.init = function (planes, enableLocalClipping, camera) {
  9148. const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  9149. // run another frame in order to reset the state:
  9150. numGlobalPlanes !== 0 || localClippingEnabled;
  9151. localClippingEnabled = enableLocalClipping;
  9152. globalState = projectPlanes(planes, camera, 0);
  9153. numGlobalPlanes = planes.length;
  9154. return enabled;
  9155. };
  9156. this.beginShadows = function () {
  9157. renderingShadows = true;
  9158. projectPlanes(null);
  9159. };
  9160. this.endShadows = function () {
  9161. renderingShadows = false;
  9162. resetGlobalState();
  9163. };
  9164. this.setState = function (material, camera, useCache) {
  9165. const planes = material.clippingPlanes,
  9166. clipIntersection = material.clipIntersection,
  9167. clipShadows = material.clipShadows;
  9168. const materialProperties = properties.get(material);
  9169. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  9170. // there's no local clipping
  9171. if (renderingShadows) {
  9172. // there's no global clipping
  9173. projectPlanes(null);
  9174. } else {
  9175. resetGlobalState();
  9176. }
  9177. } else {
  9178. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9179. lGlobal = nGlobal * 4;
  9180. let dstArray = materialProperties.clippingState || null;
  9181. uniform.value = dstArray; // ensure unique state
  9182. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  9183. for (let i = 0; i !== lGlobal; ++i) {
  9184. dstArray[i] = globalState[i];
  9185. }
  9186. materialProperties.clippingState = dstArray;
  9187. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9188. this.numPlanes += nGlobal;
  9189. }
  9190. };
  9191. function resetGlobalState() {
  9192. if (uniform.value !== globalState) {
  9193. uniform.value = globalState;
  9194. uniform.needsUpdate = numGlobalPlanes > 0;
  9195. }
  9196. scope.numPlanes = numGlobalPlanes;
  9197. scope.numIntersection = 0;
  9198. }
  9199. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  9200. const nPlanes = planes !== null ? planes.length : 0;
  9201. let dstArray = null;
  9202. if (nPlanes !== 0) {
  9203. dstArray = uniform.value;
  9204. if (skipTransform !== true || dstArray === null) {
  9205. const flatSize = dstOffset + nPlanes * 4,
  9206. viewMatrix = camera.matrixWorldInverse;
  9207. viewNormalMatrix.getNormalMatrix(viewMatrix);
  9208. if (dstArray === null || dstArray.length < flatSize) {
  9209. dstArray = new Float32Array(flatSize);
  9210. }
  9211. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  9212. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  9213. plane.normal.toArray(dstArray, i4);
  9214. dstArray[i4 + 3] = plane.constant;
  9215. }
  9216. }
  9217. uniform.value = dstArray;
  9218. uniform.needsUpdate = true;
  9219. }
  9220. scope.numPlanes = nPlanes;
  9221. scope.numIntersection = 0;
  9222. return dstArray;
  9223. }
  9224. }
  9225. function WebGLCubeMaps(renderer) {
  9226. let cubemaps = new WeakMap();
  9227. function mapTextureMapping(texture, mapping) {
  9228. if (mapping === EquirectangularReflectionMapping) {
  9229. texture.mapping = CubeReflectionMapping;
  9230. } else if (mapping === EquirectangularRefractionMapping) {
  9231. texture.mapping = CubeRefractionMapping;
  9232. }
  9233. return texture;
  9234. }
  9235. function get(texture) {
  9236. if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
  9237. const mapping = texture.mapping;
  9238. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  9239. if (cubemaps.has(texture)) {
  9240. const cubemap = cubemaps.get(texture).texture;
  9241. return mapTextureMapping(cubemap, texture.mapping);
  9242. } else {
  9243. const image = texture.image;
  9244. if (image && image.height > 0) {
  9245. const currentRenderTarget = renderer.getRenderTarget();
  9246. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  9247. renderTarget.fromEquirectangularTexture(renderer, texture);
  9248. cubemaps.set(texture, renderTarget);
  9249. renderer.setRenderTarget(currentRenderTarget);
  9250. texture.addEventListener('dispose', onTextureDispose);
  9251. return mapTextureMapping(renderTarget.texture, texture.mapping);
  9252. } else {
  9253. // image not yet ready. try the conversion next frame
  9254. return null;
  9255. }
  9256. }
  9257. }
  9258. }
  9259. return texture;
  9260. }
  9261. function onTextureDispose(event) {
  9262. const texture = event.target;
  9263. texture.removeEventListener('dispose', onTextureDispose);
  9264. const cubemap = cubemaps.get(texture);
  9265. if (cubemap !== undefined) {
  9266. cubemaps.delete(texture);
  9267. cubemap.dispose();
  9268. }
  9269. }
  9270. function dispose() {
  9271. cubemaps = new WeakMap();
  9272. }
  9273. return {
  9274. get: get,
  9275. dispose: dispose
  9276. };
  9277. }
  9278. class OrthographicCamera extends Camera {
  9279. constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) {
  9280. super();
  9281. this.type = 'OrthographicCamera';
  9282. this.zoom = 1;
  9283. this.view = null;
  9284. this.left = left;
  9285. this.right = right;
  9286. this.top = top;
  9287. this.bottom = bottom;
  9288. this.near = near;
  9289. this.far = far;
  9290. this.updateProjectionMatrix();
  9291. }
  9292. copy(source, recursive) {
  9293. super.copy(source, recursive);
  9294. this.left = source.left;
  9295. this.right = source.right;
  9296. this.top = source.top;
  9297. this.bottom = source.bottom;
  9298. this.near = source.near;
  9299. this.far = source.far;
  9300. this.zoom = source.zoom;
  9301. this.view = source.view === null ? null : Object.assign({}, source.view);
  9302. return this;
  9303. }
  9304. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  9305. if (this.view === null) {
  9306. this.view = {
  9307. enabled: true,
  9308. fullWidth: 1,
  9309. fullHeight: 1,
  9310. offsetX: 0,
  9311. offsetY: 0,
  9312. width: 1,
  9313. height: 1
  9314. };
  9315. }
  9316. this.view.enabled = true;
  9317. this.view.fullWidth = fullWidth;
  9318. this.view.fullHeight = fullHeight;
  9319. this.view.offsetX = x;
  9320. this.view.offsetY = y;
  9321. this.view.width = width;
  9322. this.view.height = height;
  9323. this.updateProjectionMatrix();
  9324. }
  9325. clearViewOffset() {
  9326. if (this.view !== null) {
  9327. this.view.enabled = false;
  9328. }
  9329. this.updateProjectionMatrix();
  9330. }
  9331. updateProjectionMatrix() {
  9332. const dx = (this.right - this.left) / (2 * this.zoom);
  9333. const dy = (this.top - this.bottom) / (2 * this.zoom);
  9334. const cx = (this.right + this.left) / 2;
  9335. const cy = (this.top + this.bottom) / 2;
  9336. let left = cx - dx;
  9337. let right = cx + dx;
  9338. let top = cy + dy;
  9339. let bottom = cy - dy;
  9340. if (this.view !== null && this.view.enabled) {
  9341. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  9342. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  9343. left += scaleW * this.view.offsetX;
  9344. right = left + scaleW * this.view.width;
  9345. top -= scaleH * this.view.offsetY;
  9346. bottom = top - scaleH * this.view.height;
  9347. }
  9348. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  9349. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  9350. }
  9351. toJSON(meta) {
  9352. const data = super.toJSON(meta);
  9353. data.object.zoom = this.zoom;
  9354. data.object.left = this.left;
  9355. data.object.right = this.right;
  9356. data.object.top = this.top;
  9357. data.object.bottom = this.bottom;
  9358. data.object.near = this.near;
  9359. data.object.far = this.far;
  9360. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  9361. return data;
  9362. }
  9363. }
  9364. OrthographicCamera.prototype.isOrthographicCamera = true;
  9365. class RawShaderMaterial extends ShaderMaterial {
  9366. constructor(parameters) {
  9367. super(parameters);
  9368. this.type = 'RawShaderMaterial';
  9369. }
  9370. }
  9371. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  9372. const LOD_MIN = 4;
  9373. const LOD_MAX = 8;
  9374. const SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
  9375. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9376. // geometric shadowing function. These sigma values squared must match the
  9377. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9378. const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  9379. const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9380. // samples and exit early, but not recompile the shader.
  9381. const MAX_SAMPLES = 20;
  9382. const ENCODINGS = {
  9383. [LinearEncoding]: 0,
  9384. [sRGBEncoding]: 1,
  9385. [RGBEEncoding]: 2,
  9386. [RGBM7Encoding]: 3,
  9387. [RGBM16Encoding]: 4,
  9388. [RGBDEncoding]: 5,
  9389. [GammaEncoding]: 6
  9390. };
  9391. const _flatCamera = /*@__PURE__*/new OrthographicCamera();
  9392. const {
  9393. _lodPlanes,
  9394. _sizeLods,
  9395. _sigmas
  9396. } = /*@__PURE__*/_createPlanes();
  9397. const _clearColor = /*@__PURE__*/new Color();
  9398. let _oldTarget = null; // Golden Ratio
  9399. const PHI = (1 + Math.sqrt(5)) / 2;
  9400. const INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  9401. // same axis), used as axis directions evenly spread on a sphere.
  9402. const _axisDirections = [/*@__PURE__*/new Vector3(1, 1, 1), /*@__PURE__*/new Vector3(-1, 1, 1), /*@__PURE__*/new Vector3(1, 1, -1), /*@__PURE__*/new Vector3(-1, 1, -1), /*@__PURE__*/new Vector3(0, PHI, INV_PHI), /*@__PURE__*/new Vector3(0, PHI, -INV_PHI), /*@__PURE__*/new Vector3(INV_PHI, 0, PHI), /*@__PURE__*/new Vector3(-INV_PHI, 0, PHI), /*@__PURE__*/new Vector3(PHI, INV_PHI, 0), /*@__PURE__*/new Vector3(-PHI, INV_PHI, 0)];
  9403. /**
  9404. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9405. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9406. * blur to be quickly accessed based on material roughness. It is packed into a
  9407. * special CubeUV format that allows us to perform custom interpolation so that
  9408. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9409. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9410. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9411. * higher roughness levels. In this way we maintain resolution to smoothly
  9412. * interpolate diffuse lighting while limiting sampling computation.
  9413. *
  9414. * Paper: Fast, Accurate Image-Based Lighting
  9415. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9416. */
  9417. class PMREMGenerator {
  9418. constructor(renderer) {
  9419. this._renderer = renderer;
  9420. this._pingPongRenderTarget = null;
  9421. this._blurMaterial = _getBlurShader(MAX_SAMPLES);
  9422. this._equirectShader = null;
  9423. this._cubemapShader = null;
  9424. this._compileMaterial(this._blurMaterial);
  9425. }
  9426. /**
  9427. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9428. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9429. * in radians to be applied to the scene before PMREM generation. Optional near
  9430. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9431. * is placed at the origin).
  9432. */
  9433. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  9434. _oldTarget = this._renderer.getRenderTarget();
  9435. const cubeUVRenderTarget = this._allocateTargets();
  9436. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  9437. if (sigma > 0) {
  9438. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  9439. }
  9440. this._applyPMREM(cubeUVRenderTarget);
  9441. this._cleanup(cubeUVRenderTarget);
  9442. return cubeUVRenderTarget;
  9443. }
  9444. /**
  9445. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9446. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  9447. * as this matches best with the 256 x 256 cubemap output.
  9448. */
  9449. fromEquirectangular(equirectangular) {
  9450. return this._fromTexture(equirectangular);
  9451. }
  9452. /**
  9453. * Generates a PMREM from an cubemap texture, which can be either LDR
  9454. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  9455. * as this matches best with the 256 x 256 cubemap output.
  9456. */
  9457. fromCubemap(cubemap) {
  9458. return this._fromTexture(cubemap);
  9459. }
  9460. /**
  9461. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9462. * your texture's network fetch for increased concurrency.
  9463. */
  9464. compileCubemapShader() {
  9465. if (this._cubemapShader === null) {
  9466. this._cubemapShader = _getCubemapShader();
  9467. this._compileMaterial(this._cubemapShader);
  9468. }
  9469. }
  9470. /**
  9471. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9472. * your texture's network fetch for increased concurrency.
  9473. */
  9474. compileEquirectangularShader() {
  9475. if (this._equirectShader === null) {
  9476. this._equirectShader = _getEquirectShader();
  9477. this._compileMaterial(this._equirectShader);
  9478. }
  9479. }
  9480. /**
  9481. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9482. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9483. * one of them will cause any others to also become unusable.
  9484. */
  9485. dispose() {
  9486. this._blurMaterial.dispose();
  9487. if (this._cubemapShader !== null) this._cubemapShader.dispose();
  9488. if (this._equirectShader !== null) this._equirectShader.dispose();
  9489. for (let i = 0; i < _lodPlanes.length; i++) {
  9490. _lodPlanes[i].dispose();
  9491. }
  9492. } // private interface
  9493. _cleanup(outputTarget) {
  9494. this._pingPongRenderTarget.dispose();
  9495. this._renderer.setRenderTarget(_oldTarget);
  9496. outputTarget.scissorTest = false;
  9497. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  9498. }
  9499. _fromTexture(texture) {
  9500. _oldTarget = this._renderer.getRenderTarget();
  9501. const cubeUVRenderTarget = this._allocateTargets(texture);
  9502. this._textureToCubeUV(texture, cubeUVRenderTarget);
  9503. this._applyPMREM(cubeUVRenderTarget);
  9504. this._cleanup(cubeUVRenderTarget);
  9505. return cubeUVRenderTarget;
  9506. }
  9507. _allocateTargets(texture) {
  9508. // warning: null texture is valid
  9509. const params = {
  9510. magFilter: NearestFilter,
  9511. minFilter: NearestFilter,
  9512. generateMipmaps: false,
  9513. type: UnsignedByteType,
  9514. format: RGBEFormat,
  9515. encoding: _isLDR(texture) ? texture.encoding : RGBEEncoding,
  9516. depthBuffer: false
  9517. };
  9518. const cubeUVRenderTarget = _createRenderTarget(params);
  9519. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  9520. this._pingPongRenderTarget = _createRenderTarget(params);
  9521. return cubeUVRenderTarget;
  9522. }
  9523. _compileMaterial(material) {
  9524. const tmpMesh = new Mesh(_lodPlanes[0], material);
  9525. this._renderer.compile(tmpMesh, _flatCamera);
  9526. }
  9527. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  9528. const fov = 90;
  9529. const aspect = 1;
  9530. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  9531. const upSign = [1, -1, 1, 1, 1, 1];
  9532. const forwardSign = [1, 1, 1, -1, -1, -1];
  9533. const renderer = this._renderer;
  9534. const originalAutoClear = renderer.autoClear;
  9535. const outputEncoding = renderer.outputEncoding;
  9536. const toneMapping = renderer.toneMapping;
  9537. renderer.getClearColor(_clearColor);
  9538. renderer.toneMapping = NoToneMapping;
  9539. renderer.outputEncoding = LinearEncoding;
  9540. renderer.autoClear = false;
  9541. const backgroundMaterial = new MeshBasicMaterial({
  9542. name: 'PMREM.Background',
  9543. side: BackSide,
  9544. depthWrite: false,
  9545. depthTest: false
  9546. });
  9547. const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
  9548. let useSolidColor = false;
  9549. const background = scene.background;
  9550. if (background) {
  9551. if (background.isColor) {
  9552. backgroundMaterial.color.copy(background);
  9553. scene.background = null;
  9554. useSolidColor = true;
  9555. }
  9556. } else {
  9557. backgroundMaterial.color.copy(_clearColor);
  9558. useSolidColor = true;
  9559. }
  9560. for (let i = 0; i < 6; i++) {
  9561. const col = i % 3;
  9562. if (col == 0) {
  9563. cubeCamera.up.set(0, upSign[i], 0);
  9564. cubeCamera.lookAt(forwardSign[i], 0, 0);
  9565. } else if (col == 1) {
  9566. cubeCamera.up.set(0, 0, upSign[i]);
  9567. cubeCamera.lookAt(0, forwardSign[i], 0);
  9568. } else {
  9569. cubeCamera.up.set(0, upSign[i], 0);
  9570. cubeCamera.lookAt(0, 0, forwardSign[i]);
  9571. }
  9572. _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
  9573. renderer.setRenderTarget(cubeUVRenderTarget);
  9574. if (useSolidColor) {
  9575. renderer.render(backgroundBox, cubeCamera);
  9576. }
  9577. renderer.render(scene, cubeCamera);
  9578. }
  9579. backgroundBox.geometry.dispose();
  9580. backgroundBox.material.dispose();
  9581. renderer.toneMapping = toneMapping;
  9582. renderer.outputEncoding = outputEncoding;
  9583. renderer.autoClear = originalAutoClear;
  9584. scene.background = background;
  9585. }
  9586. _textureToCubeUV(texture, cubeUVRenderTarget) {
  9587. const renderer = this._renderer;
  9588. if (texture.isCubeTexture) {
  9589. if (this._cubemapShader == null) {
  9590. this._cubemapShader = _getCubemapShader();
  9591. }
  9592. } else {
  9593. if (this._equirectShader == null) {
  9594. this._equirectShader = _getEquirectShader();
  9595. }
  9596. }
  9597. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  9598. const mesh = new Mesh(_lodPlanes[0], material);
  9599. const uniforms = material.uniforms;
  9600. uniforms['envMap'].value = texture;
  9601. if (!texture.isCubeTexture) {
  9602. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  9603. }
  9604. uniforms['inputEncoding'].value = ENCODINGS[texture.encoding];
  9605. uniforms['outputEncoding'].value = ENCODINGS[cubeUVRenderTarget.texture.encoding];
  9606. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  9607. renderer.setRenderTarget(cubeUVRenderTarget);
  9608. renderer.render(mesh, _flatCamera);
  9609. }
  9610. _applyPMREM(cubeUVRenderTarget) {
  9611. const renderer = this._renderer;
  9612. const autoClear = renderer.autoClear;
  9613. renderer.autoClear = false;
  9614. for (let i = 1; i < TOTAL_LODS; i++) {
  9615. const sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  9616. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  9617. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  9618. }
  9619. renderer.autoClear = autoClear;
  9620. }
  9621. /**
  9622. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9623. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9624. * the blur latitudinally (around the poles), and then longitudinally (towards
  9625. * the poles) to approximate the orthogonally-separable blur. It is least
  9626. * accurate at the poles, but still does a decent job.
  9627. */
  9628. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  9629. const pingPongRenderTarget = this._pingPongRenderTarget;
  9630. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  9631. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  9632. }
  9633. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  9634. const renderer = this._renderer;
  9635. const blurMaterial = this._blurMaterial;
  9636. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  9637. console.error('blur direction must be either latitudinal or longitudinal!');
  9638. } // Number of standard deviations at which to cut off the discrete approximation.
  9639. const STANDARD_DEVIATIONS = 3;
  9640. const blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
  9641. const blurUniforms = blurMaterial.uniforms;
  9642. const pixels = _sizeLods[lodIn] - 1;
  9643. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  9644. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9645. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  9646. if (samples > MAX_SAMPLES) {
  9647. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  9648. }
  9649. const weights = [];
  9650. let sum = 0;
  9651. for (let i = 0; i < MAX_SAMPLES; ++i) {
  9652. const x = i / sigmaPixels;
  9653. const weight = Math.exp(-x * x / 2);
  9654. weights.push(weight);
  9655. if (i == 0) {
  9656. sum += weight;
  9657. } else if (i < samples) {
  9658. sum += 2 * weight;
  9659. }
  9660. }
  9661. for (let i = 0; i < weights.length; i++) {
  9662. weights[i] = weights[i] / sum;
  9663. }
  9664. blurUniforms['envMap'].value = targetIn.texture;
  9665. blurUniforms['samples'].value = samples;
  9666. blurUniforms['weights'].value = weights;
  9667. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  9668. if (poleAxis) {
  9669. blurUniforms['poleAxis'].value = poleAxis;
  9670. }
  9671. blurUniforms['dTheta'].value = radiansPerPixel;
  9672. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  9673. blurUniforms['inputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  9674. blurUniforms['outputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  9675. const outputSize = _sizeLods[lodOut];
  9676. const x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  9677. const y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  9678. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  9679. renderer.setRenderTarget(targetOut);
  9680. renderer.render(blurMesh, _flatCamera);
  9681. }
  9682. }
  9683. function _isLDR(texture) {
  9684. if (texture === undefined || texture.type !== UnsignedByteType) return false;
  9685. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  9686. }
  9687. function _createPlanes() {
  9688. const _lodPlanes = [];
  9689. const _sizeLods = [];
  9690. const _sigmas = [];
  9691. let lod = LOD_MAX;
  9692. for (let i = 0; i < TOTAL_LODS; i++) {
  9693. const sizeLod = Math.pow(2, lod);
  9694. _sizeLods.push(sizeLod);
  9695. let sigma = 1.0 / sizeLod;
  9696. if (i > LOD_MAX - LOD_MIN) {
  9697. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  9698. } else if (i == 0) {
  9699. sigma = 0;
  9700. }
  9701. _sigmas.push(sigma);
  9702. const texelSize = 1.0 / (sizeLod - 1);
  9703. const min = -texelSize / 2;
  9704. const max = 1 + texelSize / 2;
  9705. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  9706. const cubeFaces = 6;
  9707. const vertices = 6;
  9708. const positionSize = 3;
  9709. const uvSize = 2;
  9710. const faceIndexSize = 1;
  9711. const position = new Float32Array(positionSize * vertices * cubeFaces);
  9712. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  9713. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  9714. for (let face = 0; face < cubeFaces; face++) {
  9715. const x = face % 3 * 2 / 3 - 1;
  9716. const y = face > 2 ? 0 : -1;
  9717. const coordinates = [x, y, 0, x + 2 / 3, y, 0, x + 2 / 3, y + 1, 0, x, y, 0, x + 2 / 3, y + 1, 0, x, y + 1, 0];
  9718. position.set(coordinates, positionSize * vertices * face);
  9719. uv.set(uv1, uvSize * vertices * face);
  9720. const fill = [face, face, face, face, face, face];
  9721. faceIndex.set(fill, faceIndexSize * vertices * face);
  9722. }
  9723. const planes = new BufferGeometry();
  9724. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  9725. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  9726. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  9727. _lodPlanes.push(planes);
  9728. if (lod > LOD_MIN) {
  9729. lod--;
  9730. }
  9731. }
  9732. return {
  9733. _lodPlanes,
  9734. _sizeLods,
  9735. _sigmas
  9736. };
  9737. }
  9738. function _createRenderTarget(params) {
  9739. const cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  9740. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9741. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9742. cubeUVRenderTarget.scissorTest = true;
  9743. return cubeUVRenderTarget;
  9744. }
  9745. function _setViewport(target, x, y, width, height) {
  9746. target.viewport.set(x, y, width, height);
  9747. target.scissor.set(x, y, width, height);
  9748. }
  9749. function _getBlurShader(maxSamples) {
  9750. const weights = new Float32Array(maxSamples);
  9751. const poleAxis = new Vector3(0, 1, 0);
  9752. const shaderMaterial = new RawShaderMaterial({
  9753. name: 'SphericalGaussianBlur',
  9754. defines: {
  9755. 'n': maxSamples
  9756. },
  9757. uniforms: {
  9758. 'envMap': {
  9759. value: null
  9760. },
  9761. 'samples': {
  9762. value: 1
  9763. },
  9764. 'weights': {
  9765. value: weights
  9766. },
  9767. 'latitudinal': {
  9768. value: false
  9769. },
  9770. 'dTheta': {
  9771. value: 0
  9772. },
  9773. 'mipInt': {
  9774. value: 0
  9775. },
  9776. 'poleAxis': {
  9777. value: poleAxis
  9778. },
  9779. 'inputEncoding': {
  9780. value: ENCODINGS[LinearEncoding]
  9781. },
  9782. 'outputEncoding': {
  9783. value: ENCODINGS[LinearEncoding]
  9784. }
  9785. },
  9786. vertexShader: _getCommonVertexShader(),
  9787. fragmentShader:
  9788. /* glsl */
  9789. `
  9790. precision mediump float;
  9791. precision mediump int;
  9792. varying vec3 vOutputDirection;
  9793. uniform sampler2D envMap;
  9794. uniform int samples;
  9795. uniform float weights[ n ];
  9796. uniform bool latitudinal;
  9797. uniform float dTheta;
  9798. uniform float mipInt;
  9799. uniform vec3 poleAxis;
  9800. ${_getEncodings()}
  9801. #define ENVMAP_TYPE_CUBE_UV
  9802. #include <cube_uv_reflection_fragment>
  9803. vec3 getSample( float theta, vec3 axis ) {
  9804. float cosTheta = cos( theta );
  9805. // Rodrigues' axis-angle rotation
  9806. vec3 sampleDirection = vOutputDirection * cosTheta
  9807. + cross( axis, vOutputDirection ) * sin( theta )
  9808. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9809. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9810. }
  9811. void main() {
  9812. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9813. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9814. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9815. }
  9816. axis = normalize( axis );
  9817. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9818. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9819. for ( int i = 1; i < n; i++ ) {
  9820. if ( i >= samples ) {
  9821. break;
  9822. }
  9823. float theta = dTheta * float( i );
  9824. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9825. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9826. }
  9827. gl_FragColor = linearToOutputTexel( gl_FragColor );
  9828. }
  9829. `,
  9830. blending: NoBlending,
  9831. depthTest: false,
  9832. depthWrite: false
  9833. });
  9834. return shaderMaterial;
  9835. }
  9836. function _getEquirectShader() {
  9837. const texelSize = new Vector2(1, 1);
  9838. const shaderMaterial = new RawShaderMaterial({
  9839. name: 'EquirectangularToCubeUV',
  9840. uniforms: {
  9841. 'envMap': {
  9842. value: null
  9843. },
  9844. 'texelSize': {
  9845. value: texelSize
  9846. },
  9847. 'inputEncoding': {
  9848. value: ENCODINGS[LinearEncoding]
  9849. },
  9850. 'outputEncoding': {
  9851. value: ENCODINGS[LinearEncoding]
  9852. }
  9853. },
  9854. vertexShader: _getCommonVertexShader(),
  9855. fragmentShader:
  9856. /* glsl */
  9857. `
  9858. precision mediump float;
  9859. precision mediump int;
  9860. varying vec3 vOutputDirection;
  9861. uniform sampler2D envMap;
  9862. uniform vec2 texelSize;
  9863. ${_getEncodings()}
  9864. #include <common>
  9865. void main() {
  9866. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9867. vec3 outputDirection = normalize( vOutputDirection );
  9868. vec2 uv = equirectUv( outputDirection );
  9869. vec2 f = fract( uv / texelSize - 0.5 );
  9870. uv -= f * texelSize;
  9871. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9872. uv.x += texelSize.x;
  9873. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9874. uv.y += texelSize.y;
  9875. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9876. uv.x -= texelSize.x;
  9877. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9878. vec3 tm = mix( tl, tr, f.x );
  9879. vec3 bm = mix( bl, br, f.x );
  9880. gl_FragColor.rgb = mix( tm, bm, f.y );
  9881. gl_FragColor = linearToOutputTexel( gl_FragColor );
  9882. }
  9883. `,
  9884. blending: NoBlending,
  9885. depthTest: false,
  9886. depthWrite: false
  9887. });
  9888. return shaderMaterial;
  9889. }
  9890. function _getCubemapShader() {
  9891. const shaderMaterial = new RawShaderMaterial({
  9892. name: 'CubemapToCubeUV',
  9893. uniforms: {
  9894. 'envMap': {
  9895. value: null
  9896. },
  9897. 'inputEncoding': {
  9898. value: ENCODINGS[LinearEncoding]
  9899. },
  9900. 'outputEncoding': {
  9901. value: ENCODINGS[LinearEncoding]
  9902. }
  9903. },
  9904. vertexShader: _getCommonVertexShader(),
  9905. fragmentShader:
  9906. /* glsl */
  9907. `
  9908. precision mediump float;
  9909. precision mediump int;
  9910. varying vec3 vOutputDirection;
  9911. uniform samplerCube envMap;
  9912. ${_getEncodings()}
  9913. void main() {
  9914. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9915. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  9916. gl_FragColor = linearToOutputTexel( gl_FragColor );
  9917. }
  9918. `,
  9919. blending: NoBlending,
  9920. depthTest: false,
  9921. depthWrite: false
  9922. });
  9923. return shaderMaterial;
  9924. }
  9925. function _getCommonVertexShader() {
  9926. return (
  9927. /* glsl */
  9928. `
  9929. precision mediump float;
  9930. precision mediump int;
  9931. attribute vec3 position;
  9932. attribute vec2 uv;
  9933. attribute float faceIndex;
  9934. varying vec3 vOutputDirection;
  9935. // RH coordinate system; PMREM face-indexing convention
  9936. vec3 getDirection( vec2 uv, float face ) {
  9937. uv = 2.0 * uv - 1.0;
  9938. vec3 direction = vec3( uv, 1.0 );
  9939. if ( face == 0.0 ) {
  9940. direction = direction.zyx; // ( 1, v, u ) pos x
  9941. } else if ( face == 1.0 ) {
  9942. direction = direction.xzy;
  9943. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  9944. } else if ( face == 2.0 ) {
  9945. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  9946. } else if ( face == 3.0 ) {
  9947. direction = direction.zyx;
  9948. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  9949. } else if ( face == 4.0 ) {
  9950. direction = direction.xzy;
  9951. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  9952. } else if ( face == 5.0 ) {
  9953. direction.z *= -1.0; // ( u, v, -1 ) neg z
  9954. }
  9955. return direction;
  9956. }
  9957. void main() {
  9958. vOutputDirection = getDirection( uv, faceIndex );
  9959. gl_Position = vec4( position, 1.0 );
  9960. }
  9961. `
  9962. );
  9963. }
  9964. function _getEncodings() {
  9965. return (
  9966. /* glsl */
  9967. `
  9968. uniform int inputEncoding;
  9969. uniform int outputEncoding;
  9970. #include <encodings_pars_fragment>
  9971. vec4 inputTexelToLinear( vec4 value ) {
  9972. if ( inputEncoding == 0 ) {
  9973. return value;
  9974. } else if ( inputEncoding == 1 ) {
  9975. return sRGBToLinear( value );
  9976. } else if ( inputEncoding == 2 ) {
  9977. return RGBEToLinear( value );
  9978. } else if ( inputEncoding == 3 ) {
  9979. return RGBMToLinear( value, 7.0 );
  9980. } else if ( inputEncoding == 4 ) {
  9981. return RGBMToLinear( value, 16.0 );
  9982. } else if ( inputEncoding == 5 ) {
  9983. return RGBDToLinear( value, 256.0 );
  9984. } else {
  9985. return GammaToLinear( value, 2.2 );
  9986. }
  9987. }
  9988. vec4 linearToOutputTexel( vec4 value ) {
  9989. if ( outputEncoding == 0 ) {
  9990. return value;
  9991. } else if ( outputEncoding == 1 ) {
  9992. return LinearTosRGB( value );
  9993. } else if ( outputEncoding == 2 ) {
  9994. return LinearToRGBE( value );
  9995. } else if ( outputEncoding == 3 ) {
  9996. return LinearToRGBM( value, 7.0 );
  9997. } else if ( outputEncoding == 4 ) {
  9998. return LinearToRGBM( value, 16.0 );
  9999. } else if ( outputEncoding == 5 ) {
  10000. return LinearToRGBD( value, 256.0 );
  10001. } else {
  10002. return LinearToGamma( value, 2.2 );
  10003. }
  10004. }
  10005. vec4 envMapTexelToLinear( vec4 color ) {
  10006. return inputTexelToLinear( color );
  10007. }
  10008. `
  10009. );
  10010. }
  10011. function WebGLCubeUVMaps(renderer) {
  10012. let cubeUVmaps = new WeakMap();
  10013. let pmremGenerator = null;
  10014. function get(texture) {
  10015. if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
  10016. const mapping = texture.mapping;
  10017. const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping;
  10018. const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping;
  10019. if (isEquirectMap || isCubeMap) {
  10020. // equirect/cube map to cubeUV conversion
  10021. if (cubeUVmaps.has(texture)) {
  10022. return cubeUVmaps.get(texture).texture;
  10023. } else {
  10024. const image = texture.image;
  10025. if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) {
  10026. const currentRenderTarget = renderer.getRenderTarget();
  10027. if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
  10028. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture);
  10029. cubeUVmaps.set(texture, renderTarget);
  10030. renderer.setRenderTarget(currentRenderTarget);
  10031. texture.addEventListener('dispose', onTextureDispose);
  10032. return renderTarget.texture;
  10033. } else {
  10034. // image not yet ready. try the conversion next frame
  10035. return null;
  10036. }
  10037. }
  10038. }
  10039. }
  10040. return texture;
  10041. }
  10042. function isCubeTextureComplete(image) {
  10043. let count = 0;
  10044. const length = 6;
  10045. for (let i = 0; i < length; i++) {
  10046. if (image[i] !== undefined) count++;
  10047. }
  10048. return count === length;
  10049. }
  10050. function onTextureDispose(event) {
  10051. const texture = event.target;
  10052. texture.removeEventListener('dispose', onTextureDispose);
  10053. const cubemapUV = cubeUVmaps.get(texture);
  10054. if (cubemapUV !== undefined) {
  10055. cubeUVmaps.delete(texture);
  10056. cubemapUV.dispose();
  10057. }
  10058. }
  10059. function dispose() {
  10060. cubeUVmaps = new WeakMap();
  10061. if (pmremGenerator !== null) {
  10062. pmremGenerator.dispose();
  10063. pmremGenerator = null;
  10064. }
  10065. }
  10066. return {
  10067. get: get,
  10068. dispose: dispose
  10069. };
  10070. }
  10071. function WebGLExtensions(gl) {
  10072. const extensions = {};
  10073. function getExtension(name) {
  10074. if (extensions[name] !== undefined) {
  10075. return extensions[name];
  10076. }
  10077. let extension;
  10078. switch (name) {
  10079. case 'WEBGL_depth_texture':
  10080. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  10081. break;
  10082. case 'EXT_texture_filter_anisotropic':
  10083. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  10084. break;
  10085. case 'WEBGL_compressed_texture_s3tc':
  10086. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10087. break;
  10088. case 'WEBGL_compressed_texture_pvrtc':
  10089. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10090. break;
  10091. default:
  10092. extension = gl.getExtension(name);
  10093. }
  10094. extensions[name] = extension;
  10095. return extension;
  10096. }
  10097. return {
  10098. has: function (name) {
  10099. return getExtension(name) !== null;
  10100. },
  10101. init: function (capabilities) {
  10102. if (capabilities.isWebGL2) {
  10103. getExtension('EXT_color_buffer_float');
  10104. } else {
  10105. getExtension('WEBGL_depth_texture');
  10106. getExtension('OES_texture_float');
  10107. getExtension('OES_texture_half_float');
  10108. getExtension('OES_texture_half_float_linear');
  10109. getExtension('OES_standard_derivatives');
  10110. getExtension('OES_element_index_uint');
  10111. getExtension('OES_vertex_array_object');
  10112. getExtension('ANGLE_instanced_arrays');
  10113. }
  10114. getExtension('OES_texture_float_linear');
  10115. getExtension('EXT_color_buffer_half_float');
  10116. },
  10117. get: function (name) {
  10118. const extension = getExtension(name);
  10119. if (extension === null) {
  10120. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  10121. }
  10122. return extension;
  10123. }
  10124. };
  10125. }
  10126. function WebGLGeometries(gl, attributes, info, bindingStates) {
  10127. const geometries = {};
  10128. const wireframeAttributes = new WeakMap();
  10129. function onGeometryDispose(event) {
  10130. const geometry = event.target;
  10131. if (geometry.index !== null) {
  10132. attributes.remove(geometry.index);
  10133. }
  10134. for (const name in geometry.attributes) {
  10135. attributes.remove(geometry.attributes[name]);
  10136. }
  10137. geometry.removeEventListener('dispose', onGeometryDispose);
  10138. delete geometries[geometry.id];
  10139. const attribute = wireframeAttributes.get(geometry);
  10140. if (attribute) {
  10141. attributes.remove(attribute);
  10142. wireframeAttributes.delete(geometry);
  10143. }
  10144. bindingStates.releaseStatesOfGeometry(geometry);
  10145. if (geometry.isInstancedBufferGeometry === true) {
  10146. delete geometry._maxInstanceCount;
  10147. } //
  10148. info.memory.geometries--;
  10149. }
  10150. function get(object, geometry) {
  10151. if (geometries[geometry.id] === true) return geometry;
  10152. geometry.addEventListener('dispose', onGeometryDispose);
  10153. geometries[geometry.id] = true;
  10154. info.memory.geometries++;
  10155. return geometry;
  10156. }
  10157. function update(geometry) {
  10158. const geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  10159. for (const name in geometryAttributes) {
  10160. attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
  10161. } // morph targets
  10162. const morphAttributes = geometry.morphAttributes;
  10163. for (const name in morphAttributes) {
  10164. const array = morphAttributes[name];
  10165. for (let i = 0, l = array.length; i < l; i++) {
  10166. attributes.update(array[i], gl.ARRAY_BUFFER);
  10167. }
  10168. }
  10169. }
  10170. function updateWireframeAttribute(geometry) {
  10171. const indices = [];
  10172. const geometryIndex = geometry.index;
  10173. const geometryPosition = geometry.attributes.position;
  10174. let version = 0;
  10175. if (geometryIndex !== null) {
  10176. const array = geometryIndex.array;
  10177. version = geometryIndex.version;
  10178. for (let i = 0, l = array.length; i < l; i += 3) {
  10179. const a = array[i + 0];
  10180. const b = array[i + 1];
  10181. const c = array[i + 2];
  10182. indices.push(a, b, b, c, c, a);
  10183. }
  10184. } else {
  10185. const array = geometryPosition.array;
  10186. version = geometryPosition.version;
  10187. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  10188. const a = i + 0;
  10189. const b = i + 1;
  10190. const c = i + 2;
  10191. indices.push(a, b, b, c, c, a);
  10192. }
  10193. }
  10194. const attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  10195. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  10196. //
  10197. const previousAttribute = wireframeAttributes.get(geometry);
  10198. if (previousAttribute) attributes.remove(previousAttribute); //
  10199. wireframeAttributes.set(geometry, attribute);
  10200. }
  10201. function getWireframeAttribute(geometry) {
  10202. const currentAttribute = wireframeAttributes.get(geometry);
  10203. if (currentAttribute) {
  10204. const geometryIndex = geometry.index;
  10205. if (geometryIndex !== null) {
  10206. // if the attribute is obsolete, create a new one
  10207. if (currentAttribute.version < geometryIndex.version) {
  10208. updateWireframeAttribute(geometry);
  10209. }
  10210. }
  10211. } else {
  10212. updateWireframeAttribute(geometry);
  10213. }
  10214. return wireframeAttributes.get(geometry);
  10215. }
  10216. return {
  10217. get: get,
  10218. update: update,
  10219. getWireframeAttribute: getWireframeAttribute
  10220. };
  10221. }
  10222. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  10223. const isWebGL2 = capabilities.isWebGL2;
  10224. let mode;
  10225. function setMode(value) {
  10226. mode = value;
  10227. }
  10228. let type, bytesPerElement;
  10229. function setIndex(value) {
  10230. type = value.type;
  10231. bytesPerElement = value.bytesPerElement;
  10232. }
  10233. function render(start, count) {
  10234. gl.drawElements(mode, count, type, start * bytesPerElement);
  10235. info.update(count, mode, 1);
  10236. }
  10237. function renderInstances(start, count, primcount) {
  10238. if (primcount === 0) return;
  10239. let extension, methodName;
  10240. if (isWebGL2) {
  10241. extension = gl;
  10242. methodName = 'drawElementsInstanced';
  10243. } else {
  10244. extension = extensions.get('ANGLE_instanced_arrays');
  10245. methodName = 'drawElementsInstancedANGLE';
  10246. if (extension === null) {
  10247. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10248. return;
  10249. }
  10250. }
  10251. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  10252. info.update(count, mode, primcount);
  10253. } //
  10254. this.setMode = setMode;
  10255. this.setIndex = setIndex;
  10256. this.render = render;
  10257. this.renderInstances = renderInstances;
  10258. }
  10259. function WebGLInfo(gl) {
  10260. const memory = {
  10261. geometries: 0,
  10262. textures: 0
  10263. };
  10264. const render = {
  10265. frame: 0,
  10266. calls: 0,
  10267. triangles: 0,
  10268. points: 0,
  10269. lines: 0
  10270. };
  10271. function update(count, mode, instanceCount) {
  10272. render.calls++;
  10273. switch (mode) {
  10274. case gl.TRIANGLES:
  10275. render.triangles += instanceCount * (count / 3);
  10276. break;
  10277. case gl.LINES:
  10278. render.lines += instanceCount * (count / 2);
  10279. break;
  10280. case gl.LINE_STRIP:
  10281. render.lines += instanceCount * (count - 1);
  10282. break;
  10283. case gl.LINE_LOOP:
  10284. render.lines += instanceCount * count;
  10285. break;
  10286. case gl.POINTS:
  10287. render.points += instanceCount * count;
  10288. break;
  10289. default:
  10290. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  10291. break;
  10292. }
  10293. }
  10294. function reset() {
  10295. render.frame++;
  10296. render.calls = 0;
  10297. render.triangles = 0;
  10298. render.points = 0;
  10299. render.lines = 0;
  10300. }
  10301. return {
  10302. memory: memory,
  10303. render: render,
  10304. programs: null,
  10305. autoReset: true,
  10306. reset: reset,
  10307. update: update
  10308. };
  10309. }
  10310. function numericalSort(a, b) {
  10311. return a[0] - b[0];
  10312. }
  10313. function absNumericalSort(a, b) {
  10314. return Math.abs(b[1]) - Math.abs(a[1]);
  10315. }
  10316. function WebGLMorphtargets(gl) {
  10317. const influencesList = {};
  10318. const morphInfluences = new Float32Array(8);
  10319. const workInfluences = [];
  10320. for (let i = 0; i < 8; i++) {
  10321. workInfluences[i] = [i, 0];
  10322. }
  10323. function update(object, geometry, material, program) {
  10324. const objectInfluences = object.morphTargetInfluences; // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10325. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10326. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10327. let influences = influencesList[geometry.id];
  10328. if (influences === undefined || influences.length !== length) {
  10329. // initialise list
  10330. influences = [];
  10331. for (let i = 0; i < length; i++) {
  10332. influences[i] = [i, 0];
  10333. }
  10334. influencesList[geometry.id] = influences;
  10335. } // Collect influences
  10336. for (let i = 0; i < length; i++) {
  10337. const influence = influences[i];
  10338. influence[0] = i;
  10339. influence[1] = objectInfluences[i];
  10340. }
  10341. influences.sort(absNumericalSort);
  10342. for (let i = 0; i < 8; i++) {
  10343. if (i < length && influences[i][1]) {
  10344. workInfluences[i][0] = influences[i][0];
  10345. workInfluences[i][1] = influences[i][1];
  10346. } else {
  10347. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  10348. workInfluences[i][1] = 0;
  10349. }
  10350. }
  10351. workInfluences.sort(numericalSort);
  10352. const morphTargets = geometry.morphAttributes.position;
  10353. const morphNormals = geometry.morphAttributes.normal;
  10354. let morphInfluencesSum = 0;
  10355. for (let i = 0; i < 8; i++) {
  10356. const influence = workInfluences[i];
  10357. const index = influence[0];
  10358. const value = influence[1];
  10359. if (index !== Number.MAX_SAFE_INTEGER && value) {
  10360. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  10361. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  10362. }
  10363. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  10364. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  10365. }
  10366. morphInfluences[i] = value;
  10367. morphInfluencesSum += value;
  10368. } else {
  10369. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  10370. geometry.deleteAttribute('morphTarget' + i);
  10371. }
  10372. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  10373. geometry.deleteAttribute('morphNormal' + i);
  10374. }
  10375. morphInfluences[i] = 0;
  10376. }
  10377. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10378. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10379. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10380. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10381. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10382. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  10383. }
  10384. return {
  10385. update: update
  10386. };
  10387. }
  10388. function WebGLObjects(gl, geometries, attributes, info) {
  10389. let updateMap = new WeakMap();
  10390. function update(object) {
  10391. const frame = info.render.frame;
  10392. const geometry = object.geometry;
  10393. const buffergeometry = geometries.get(object, geometry); // Update once per frame
  10394. if (updateMap.get(buffergeometry) !== frame) {
  10395. geometries.update(buffergeometry);
  10396. updateMap.set(buffergeometry, frame);
  10397. }
  10398. if (object.isInstancedMesh) {
  10399. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  10400. object.addEventListener('dispose', onInstancedMeshDispose);
  10401. }
  10402. attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
  10403. if (object.instanceColor !== null) {
  10404. attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
  10405. }
  10406. }
  10407. return buffergeometry;
  10408. }
  10409. function dispose() {
  10410. updateMap = new WeakMap();
  10411. }
  10412. function onInstancedMeshDispose(event) {
  10413. const instancedMesh = event.target;
  10414. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  10415. attributes.remove(instancedMesh.instanceMatrix);
  10416. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  10417. }
  10418. return {
  10419. update: update,
  10420. dispose: dispose
  10421. };
  10422. }
  10423. class DataTexture2DArray extends Texture {
  10424. constructor(data = null, width = 1, height = 1, depth = 1) {
  10425. super(null);
  10426. this.image = {
  10427. data,
  10428. width,
  10429. height,
  10430. depth
  10431. };
  10432. this.magFilter = NearestFilter;
  10433. this.minFilter = NearestFilter;
  10434. this.wrapR = ClampToEdgeWrapping;
  10435. this.generateMipmaps = false;
  10436. this.flipY = false;
  10437. this.unpackAlignment = 1;
  10438. this.needsUpdate = true;
  10439. }
  10440. }
  10441. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  10442. class DataTexture3D extends Texture {
  10443. constructor(data = null, width = 1, height = 1, depth = 1) {
  10444. // We're going to add .setXXX() methods for setting properties later.
  10445. // Users can still set in DataTexture3D directly.
  10446. //
  10447. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  10448. // texture.anisotropy = 16;
  10449. //
  10450. // See #14839
  10451. super(null);
  10452. this.image = {
  10453. data,
  10454. width,
  10455. height,
  10456. depth
  10457. };
  10458. this.magFilter = NearestFilter;
  10459. this.minFilter = NearestFilter;
  10460. this.wrapR = ClampToEdgeWrapping;
  10461. this.generateMipmaps = false;
  10462. this.flipY = false;
  10463. this.unpackAlignment = 1;
  10464. this.needsUpdate = true;
  10465. }
  10466. }
  10467. DataTexture3D.prototype.isDataTexture3D = true;
  10468. /**
  10469. * Uniforms of a program.
  10470. * Those form a tree structure with a special top-level container for the root,
  10471. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10472. *
  10473. *
  10474. * Properties of inner nodes including the top-level container:
  10475. *
  10476. * .seq - array of nested uniforms
  10477. * .map - nested uniforms by name
  10478. *
  10479. *
  10480. * Methods of all nodes except the top-level container:
  10481. *
  10482. * .setValue( gl, value, [textures] )
  10483. *
  10484. * uploads a uniform value(s)
  10485. * the 'textures' parameter is needed for sampler uniforms
  10486. *
  10487. *
  10488. * Static methods of the top-level container (textures factorizations):
  10489. *
  10490. * .upload( gl, seq, values, textures )
  10491. *
  10492. * sets uniforms in 'seq' to 'values[id].value'
  10493. *
  10494. * .seqWithValue( seq, values ) : filteredSeq
  10495. *
  10496. * filters 'seq' entries with corresponding entry in values
  10497. *
  10498. *
  10499. * Methods of the top-level container (textures factorizations):
  10500. *
  10501. * .setValue( gl, name, value, textures )
  10502. *
  10503. * sets uniform with name 'name' to 'value'
  10504. *
  10505. * .setOptional( gl, obj, prop )
  10506. *
  10507. * like .set for an optional property of the object
  10508. *
  10509. */
  10510. const emptyTexture = new Texture();
  10511. const emptyTexture2dArray = new DataTexture2DArray();
  10512. const emptyTexture3d = new DataTexture3D();
  10513. const emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  10514. // Array Caches (provide typed arrays for temporary by size)
  10515. const arrayCacheF32 = [];
  10516. const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  10517. const mat4array = new Float32Array(16);
  10518. const mat3array = new Float32Array(9);
  10519. const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  10520. function flatten(array, nBlocks, blockSize) {
  10521. const firstElem = array[0];
  10522. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  10523. // see http://jacksondunstan.com/articles/983
  10524. const n = nBlocks * blockSize;
  10525. let r = arrayCacheF32[n];
  10526. if (r === undefined) {
  10527. r = new Float32Array(n);
  10528. arrayCacheF32[n] = r;
  10529. }
  10530. if (nBlocks !== 0) {
  10531. firstElem.toArray(r, 0);
  10532. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  10533. offset += blockSize;
  10534. array[i].toArray(r, offset);
  10535. }
  10536. }
  10537. return r;
  10538. }
  10539. function arraysEqual(a, b) {
  10540. if (a.length !== b.length) return false;
  10541. for (let i = 0, l = a.length; i < l; i++) {
  10542. if (a[i] !== b[i]) return false;
  10543. }
  10544. return true;
  10545. }
  10546. function copyArray(a, b) {
  10547. for (let i = 0, l = b.length; i < l; i++) {
  10548. a[i] = b[i];
  10549. }
  10550. } // Texture unit allocation
  10551. function allocTexUnits(textures, n) {
  10552. let r = arrayCacheI32[n];
  10553. if (r === undefined) {
  10554. r = new Int32Array(n);
  10555. arrayCacheI32[n] = r;
  10556. }
  10557. for (let i = 0; i !== n; ++i) {
  10558. r[i] = textures.allocateTextureUnit();
  10559. }
  10560. return r;
  10561. } // --- Setters ---
  10562. // Note: Defining these methods externally, because they come in a bunch
  10563. // and this way their names minify.
  10564. // Single scalar
  10565. function setValueV1f(gl, v) {
  10566. const cache = this.cache;
  10567. if (cache[0] === v) return;
  10568. gl.uniform1f(this.addr, v);
  10569. cache[0] = v;
  10570. } // Single float vector (from flat array or THREE.VectorN)
  10571. function setValueV2f(gl, v) {
  10572. const cache = this.cache;
  10573. if (v.x !== undefined) {
  10574. if (cache[0] !== v.x || cache[1] !== v.y) {
  10575. gl.uniform2f(this.addr, v.x, v.y);
  10576. cache[0] = v.x;
  10577. cache[1] = v.y;
  10578. }
  10579. } else {
  10580. if (arraysEqual(cache, v)) return;
  10581. gl.uniform2fv(this.addr, v);
  10582. copyArray(cache, v);
  10583. }
  10584. }
  10585. function setValueV3f(gl, v) {
  10586. const cache = this.cache;
  10587. if (v.x !== undefined) {
  10588. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10589. gl.uniform3f(this.addr, v.x, v.y, v.z);
  10590. cache[0] = v.x;
  10591. cache[1] = v.y;
  10592. cache[2] = v.z;
  10593. }
  10594. } else if (v.r !== undefined) {
  10595. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  10596. gl.uniform3f(this.addr, v.r, v.g, v.b);
  10597. cache[0] = v.r;
  10598. cache[1] = v.g;
  10599. cache[2] = v.b;
  10600. }
  10601. } else {
  10602. if (arraysEqual(cache, v)) return;
  10603. gl.uniform3fv(this.addr, v);
  10604. copyArray(cache, v);
  10605. }
  10606. }
  10607. function setValueV4f(gl, v) {
  10608. const cache = this.cache;
  10609. if (v.x !== undefined) {
  10610. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  10611. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  10612. cache[0] = v.x;
  10613. cache[1] = v.y;
  10614. cache[2] = v.z;
  10615. cache[3] = v.w;
  10616. }
  10617. } else {
  10618. if (arraysEqual(cache, v)) return;
  10619. gl.uniform4fv(this.addr, v);
  10620. copyArray(cache, v);
  10621. }
  10622. } // Single matrix (from flat array or THREE.MatrixN)
  10623. function setValueM2(gl, v) {
  10624. const cache = this.cache;
  10625. const elements = v.elements;
  10626. if (elements === undefined) {
  10627. if (arraysEqual(cache, v)) return;
  10628. gl.uniformMatrix2fv(this.addr, false, v);
  10629. copyArray(cache, v);
  10630. } else {
  10631. if (arraysEqual(cache, elements)) return;
  10632. mat2array.set(elements);
  10633. gl.uniformMatrix2fv(this.addr, false, mat2array);
  10634. copyArray(cache, elements);
  10635. }
  10636. }
  10637. function setValueM3(gl, v) {
  10638. const cache = this.cache;
  10639. const elements = v.elements;
  10640. if (elements === undefined) {
  10641. if (arraysEqual(cache, v)) return;
  10642. gl.uniformMatrix3fv(this.addr, false, v);
  10643. copyArray(cache, v);
  10644. } else {
  10645. if (arraysEqual(cache, elements)) return;
  10646. mat3array.set(elements);
  10647. gl.uniformMatrix3fv(this.addr, false, mat3array);
  10648. copyArray(cache, elements);
  10649. }
  10650. }
  10651. function setValueM4(gl, v) {
  10652. const cache = this.cache;
  10653. const elements = v.elements;
  10654. if (elements === undefined) {
  10655. if (arraysEqual(cache, v)) return;
  10656. gl.uniformMatrix4fv(this.addr, false, v);
  10657. copyArray(cache, v);
  10658. } else {
  10659. if (arraysEqual(cache, elements)) return;
  10660. mat4array.set(elements);
  10661. gl.uniformMatrix4fv(this.addr, false, mat4array);
  10662. copyArray(cache, elements);
  10663. }
  10664. } // Single integer / boolean
  10665. function setValueV1i(gl, v) {
  10666. const cache = this.cache;
  10667. if (cache[0] === v) return;
  10668. gl.uniform1i(this.addr, v);
  10669. cache[0] = v;
  10670. } // Single integer / boolean vector (from flat array)
  10671. function setValueV2i(gl, v) {
  10672. const cache = this.cache;
  10673. if (arraysEqual(cache, v)) return;
  10674. gl.uniform2iv(this.addr, v);
  10675. copyArray(cache, v);
  10676. }
  10677. function setValueV3i(gl, v) {
  10678. const cache = this.cache;
  10679. if (arraysEqual(cache, v)) return;
  10680. gl.uniform3iv(this.addr, v);
  10681. copyArray(cache, v);
  10682. }
  10683. function setValueV4i(gl, v) {
  10684. const cache = this.cache;
  10685. if (arraysEqual(cache, v)) return;
  10686. gl.uniform4iv(this.addr, v);
  10687. copyArray(cache, v);
  10688. } // Single unsigned integer
  10689. function setValueV1ui(gl, v) {
  10690. const cache = this.cache;
  10691. if (cache[0] === v) return;
  10692. gl.uniform1ui(this.addr, v);
  10693. cache[0] = v;
  10694. } // Single unsigned integer vector (from flat array)
  10695. function setValueV2ui(gl, v) {
  10696. const cache = this.cache;
  10697. if (arraysEqual(cache, v)) return;
  10698. gl.uniform2uiv(this.addr, v);
  10699. copyArray(cache, v);
  10700. }
  10701. function setValueV3ui(gl, v) {
  10702. const cache = this.cache;
  10703. if (arraysEqual(cache, v)) return;
  10704. gl.uniform3uiv(this.addr, v);
  10705. copyArray(cache, v);
  10706. }
  10707. function setValueV4ui(gl, v) {
  10708. const cache = this.cache;
  10709. if (arraysEqual(cache, v)) return;
  10710. gl.uniform4uiv(this.addr, v);
  10711. copyArray(cache, v);
  10712. } // Single texture (2D / Cube)
  10713. function setValueT1(gl, v, textures) {
  10714. const cache = this.cache;
  10715. const unit = textures.allocateTextureUnit();
  10716. if (cache[0] !== unit) {
  10717. gl.uniform1i(this.addr, unit);
  10718. cache[0] = unit;
  10719. }
  10720. textures.safeSetTexture2D(v || emptyTexture, unit);
  10721. }
  10722. function setValueT3D1(gl, v, textures) {
  10723. const cache = this.cache;
  10724. const unit = textures.allocateTextureUnit();
  10725. if (cache[0] !== unit) {
  10726. gl.uniform1i(this.addr, unit);
  10727. cache[0] = unit;
  10728. }
  10729. textures.setTexture3D(v || emptyTexture3d, unit);
  10730. }
  10731. function setValueT6(gl, v, textures) {
  10732. const cache = this.cache;
  10733. const unit = textures.allocateTextureUnit();
  10734. if (cache[0] !== unit) {
  10735. gl.uniform1i(this.addr, unit);
  10736. cache[0] = unit;
  10737. }
  10738. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  10739. }
  10740. function setValueT2DArray1(gl, v, textures) {
  10741. const cache = this.cache;
  10742. const unit = textures.allocateTextureUnit();
  10743. if (cache[0] !== unit) {
  10744. gl.uniform1i(this.addr, unit);
  10745. cache[0] = unit;
  10746. }
  10747. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  10748. } // Helper to pick the right setter for the singular case
  10749. function getSingularSetter(type) {
  10750. switch (type) {
  10751. case 0x1406:
  10752. return setValueV1f;
  10753. // FLOAT
  10754. case 0x8b50:
  10755. return setValueV2f;
  10756. // _VEC2
  10757. case 0x8b51:
  10758. return setValueV3f;
  10759. // _VEC3
  10760. case 0x8b52:
  10761. return setValueV4f;
  10762. // _VEC4
  10763. case 0x8b5a:
  10764. return setValueM2;
  10765. // _MAT2
  10766. case 0x8b5b:
  10767. return setValueM3;
  10768. // _MAT3
  10769. case 0x8b5c:
  10770. return setValueM4;
  10771. // _MAT4
  10772. case 0x1404:
  10773. case 0x8b56:
  10774. return setValueV1i;
  10775. // INT, BOOL
  10776. case 0x8b53:
  10777. case 0x8b57:
  10778. return setValueV2i;
  10779. // _VEC2
  10780. case 0x8b54:
  10781. case 0x8b58:
  10782. return setValueV3i;
  10783. // _VEC3
  10784. case 0x8b55:
  10785. case 0x8b59:
  10786. return setValueV4i;
  10787. // _VEC4
  10788. case 0x1405:
  10789. return setValueV1ui;
  10790. // UINT
  10791. case 0x8dc6:
  10792. return setValueV2ui;
  10793. // _VEC2
  10794. case 0x8dc7:
  10795. return setValueV3ui;
  10796. // _VEC3
  10797. case 0x8dc8:
  10798. return setValueV4ui;
  10799. // _VEC4
  10800. case 0x8b5e: // SAMPLER_2D
  10801. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10802. case 0x8dca: // INT_SAMPLER_2D
  10803. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10804. case 0x8b62:
  10805. // SAMPLER_2D_SHADOW
  10806. return setValueT1;
  10807. case 0x8b5f: // SAMPLER_3D
  10808. case 0x8dcb: // INT_SAMPLER_3D
  10809. case 0x8dd3:
  10810. // UNSIGNED_INT_SAMPLER_3D
  10811. return setValueT3D1;
  10812. case 0x8b60: // SAMPLER_CUBE
  10813. case 0x8dcc: // INT_SAMPLER_CUBE
  10814. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10815. case 0x8dc5:
  10816. // SAMPLER_CUBE_SHADOW
  10817. return setValueT6;
  10818. case 0x8dc1: // SAMPLER_2D_ARRAY
  10819. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10820. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10821. case 0x8dc4:
  10822. // SAMPLER_2D_ARRAY_SHADOW
  10823. return setValueT2DArray1;
  10824. }
  10825. } // Array of scalars
  10826. function setValueV1fArray(gl, v) {
  10827. gl.uniform1fv(this.addr, v);
  10828. } // Array of vectors (from flat array or array of THREE.VectorN)
  10829. function setValueV2fArray(gl, v) {
  10830. const data = flatten(v, this.size, 2);
  10831. gl.uniform2fv(this.addr, data);
  10832. }
  10833. function setValueV3fArray(gl, v) {
  10834. const data = flatten(v, this.size, 3);
  10835. gl.uniform3fv(this.addr, data);
  10836. }
  10837. function setValueV4fArray(gl, v) {
  10838. const data = flatten(v, this.size, 4);
  10839. gl.uniform4fv(this.addr, data);
  10840. } // Array of matrices (from flat array or array of THREE.MatrixN)
  10841. function setValueM2Array(gl, v) {
  10842. const data = flatten(v, this.size, 4);
  10843. gl.uniformMatrix2fv(this.addr, false, data);
  10844. }
  10845. function setValueM3Array(gl, v) {
  10846. const data = flatten(v, this.size, 9);
  10847. gl.uniformMatrix3fv(this.addr, false, data);
  10848. }
  10849. function setValueM4Array(gl, v) {
  10850. const data = flatten(v, this.size, 16);
  10851. gl.uniformMatrix4fv(this.addr, false, data);
  10852. } // Array of integer / boolean
  10853. function setValueV1iArray(gl, v) {
  10854. gl.uniform1iv(this.addr, v);
  10855. } // Array of integer / boolean vectors (from flat array)
  10856. function setValueV2iArray(gl, v) {
  10857. gl.uniform2iv(this.addr, v);
  10858. }
  10859. function setValueV3iArray(gl, v) {
  10860. gl.uniform3iv(this.addr, v);
  10861. }
  10862. function setValueV4iArray(gl, v) {
  10863. gl.uniform4iv(this.addr, v);
  10864. } // Array of unsigned integer
  10865. function setValueV1uiArray(gl, v) {
  10866. gl.uniform1uiv(this.addr, v);
  10867. } // Array of unsigned integer vectors (from flat array)
  10868. function setValueV2uiArray(gl, v) {
  10869. gl.uniform2uiv(this.addr, v);
  10870. }
  10871. function setValueV3uiArray(gl, v) {
  10872. gl.uniform3uiv(this.addr, v);
  10873. }
  10874. function setValueV4uiArray(gl, v) {
  10875. gl.uniform4uiv(this.addr, v);
  10876. } // Array of textures (2D / Cube)
  10877. function setValueT1Array(gl, v, textures) {
  10878. const n = v.length;
  10879. const units = allocTexUnits(textures, n);
  10880. gl.uniform1iv(this.addr, units);
  10881. for (let i = 0; i !== n; ++i) {
  10882. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  10883. }
  10884. }
  10885. function setValueT6Array(gl, v, textures) {
  10886. const n = v.length;
  10887. const units = allocTexUnits(textures, n);
  10888. gl.uniform1iv(this.addr, units);
  10889. for (let i = 0; i !== n; ++i) {
  10890. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  10891. }
  10892. } // Helper to pick the right setter for a pure (bottom-level) array
  10893. function getPureArraySetter(type) {
  10894. switch (type) {
  10895. case 0x1406:
  10896. return setValueV1fArray;
  10897. // FLOAT
  10898. case 0x8b50:
  10899. return setValueV2fArray;
  10900. // _VEC2
  10901. case 0x8b51:
  10902. return setValueV3fArray;
  10903. // _VEC3
  10904. case 0x8b52:
  10905. return setValueV4fArray;
  10906. // _VEC4
  10907. case 0x8b5a:
  10908. return setValueM2Array;
  10909. // _MAT2
  10910. case 0x8b5b:
  10911. return setValueM3Array;
  10912. // _MAT3
  10913. case 0x8b5c:
  10914. return setValueM4Array;
  10915. // _MAT4
  10916. case 0x1404:
  10917. case 0x8b56:
  10918. return setValueV1iArray;
  10919. // INT, BOOL
  10920. case 0x8b53:
  10921. case 0x8b57:
  10922. return setValueV2iArray;
  10923. // _VEC2
  10924. case 0x8b54:
  10925. case 0x8b58:
  10926. return setValueV3iArray;
  10927. // _VEC3
  10928. case 0x8b55:
  10929. case 0x8b59:
  10930. return setValueV4iArray;
  10931. // _VEC4
  10932. case 0x1405:
  10933. return setValueV1uiArray;
  10934. // UINT
  10935. case 0x8dc6:
  10936. return setValueV2uiArray;
  10937. // _VEC2
  10938. case 0x8dc7:
  10939. return setValueV3uiArray;
  10940. // _VEC3
  10941. case 0x8dc8:
  10942. return setValueV4uiArray;
  10943. // _VEC4
  10944. case 0x8b5e: // SAMPLER_2D
  10945. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10946. case 0x8dca: // INT_SAMPLER_2D
  10947. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10948. case 0x8b62:
  10949. // SAMPLER_2D_SHADOW
  10950. return setValueT1Array;
  10951. case 0x8b60: // SAMPLER_CUBE
  10952. case 0x8dcc: // INT_SAMPLER_CUBE
  10953. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10954. case 0x8dc5:
  10955. // SAMPLER_CUBE_SHADOW
  10956. return setValueT6Array;
  10957. }
  10958. } // --- Uniform Classes ---
  10959. function SingleUniform(id, activeInfo, addr) {
  10960. this.id = id;
  10961. this.addr = addr;
  10962. this.cache = [];
  10963. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10964. }
  10965. function PureArrayUniform(id, activeInfo, addr) {
  10966. this.id = id;
  10967. this.addr = addr;
  10968. this.cache = [];
  10969. this.size = activeInfo.size;
  10970. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10971. }
  10972. PureArrayUniform.prototype.updateCache = function (data) {
  10973. const cache = this.cache;
  10974. if (data instanceof Float32Array && cache.length !== data.length) {
  10975. this.cache = new Float32Array(data.length);
  10976. }
  10977. copyArray(cache, data);
  10978. };
  10979. function StructuredUniform(id) {
  10980. this.id = id;
  10981. this.seq = [];
  10982. this.map = {};
  10983. }
  10984. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  10985. const seq = this.seq;
  10986. for (let i = 0, n = seq.length; i !== n; ++i) {
  10987. const u = seq[i];
  10988. u.setValue(gl, value[u.id], textures);
  10989. }
  10990. }; // --- Top-level ---
  10991. // Parser - builds up the property tree from the path strings
  10992. const RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
  10993. // - the identifier (member name or array index)
  10994. // - followed by an optional right bracket (found when array index)
  10995. // - followed by an optional left bracket or dot (type of subscript)
  10996. //
  10997. // Note: These portions can be read in a non-overlapping fashion and
  10998. // allow straightforward parsing of the hierarchy that WebGL encodes
  10999. // in the uniform names.
  11000. function addUniform(container, uniformObject) {
  11001. container.seq.push(uniformObject);
  11002. container.map[uniformObject.id] = uniformObject;
  11003. }
  11004. function parseUniform(activeInfo, addr, container) {
  11005. const path = activeInfo.name,
  11006. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  11007. RePathPart.lastIndex = 0;
  11008. while (true) {
  11009. const match = RePathPart.exec(path),
  11010. matchEnd = RePathPart.lastIndex;
  11011. let id = match[1];
  11012. const idIsIndex = match[2] === ']',
  11013. subscript = match[3];
  11014. if (idIsIndex) id = id | 0; // convert to integer
  11015. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  11016. // bare name or "pure" bottom-level array "[0]" suffix
  11017. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  11018. break;
  11019. } else {
  11020. // step into inner node / create it in case it doesn't exist
  11021. const map = container.map;
  11022. let next = map[id];
  11023. if (next === undefined) {
  11024. next = new StructuredUniform(id);
  11025. addUniform(container, next);
  11026. }
  11027. container = next;
  11028. }
  11029. }
  11030. } // Root Container
  11031. function WebGLUniforms(gl, program) {
  11032. this.seq = [];
  11033. this.map = {};
  11034. const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  11035. for (let i = 0; i < n; ++i) {
  11036. const info = gl.getActiveUniform(program, i),
  11037. addr = gl.getUniformLocation(program, info.name);
  11038. parseUniform(info, addr, this);
  11039. }
  11040. }
  11041. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  11042. const u = this.map[name];
  11043. if (u !== undefined) u.setValue(gl, value, textures);
  11044. };
  11045. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  11046. const v = object[name];
  11047. if (v !== undefined) this.setValue(gl, name, v);
  11048. }; // Static interface
  11049. WebGLUniforms.upload = function (gl, seq, values, textures) {
  11050. for (let i = 0, n = seq.length; i !== n; ++i) {
  11051. const u = seq[i],
  11052. v = values[u.id];
  11053. if (v.needsUpdate !== false) {
  11054. // note: always updating when .needsUpdate is undefined
  11055. u.setValue(gl, v.value, textures);
  11056. }
  11057. }
  11058. };
  11059. WebGLUniforms.seqWithValue = function (seq, values) {
  11060. const r = [];
  11061. for (let i = 0, n = seq.length; i !== n; ++i) {
  11062. const u = seq[i];
  11063. if (u.id in values) r.push(u);
  11064. }
  11065. return r;
  11066. };
  11067. function WebGLShader(gl, type, string) {
  11068. const shader = gl.createShader(type);
  11069. gl.shaderSource(shader, string);
  11070. gl.compileShader(shader);
  11071. return shader;
  11072. }
  11073. let programIdCount = 0;
  11074. function addLineNumbers(string) {
  11075. const lines = string.split('\n');
  11076. for (let i = 0; i < lines.length; i++) {
  11077. lines[i] = i + 1 + ': ' + lines[i];
  11078. }
  11079. return lines.join('\n');
  11080. }
  11081. function getEncodingComponents(encoding) {
  11082. switch (encoding) {
  11083. case LinearEncoding:
  11084. return ['Linear', '( value )'];
  11085. case sRGBEncoding:
  11086. return ['sRGB', '( value )'];
  11087. case RGBEEncoding:
  11088. return ['RGBE', '( value )'];
  11089. case RGBM7Encoding:
  11090. return ['RGBM', '( value, 7.0 )'];
  11091. case RGBM16Encoding:
  11092. return ['RGBM', '( value, 16.0 )'];
  11093. case RGBDEncoding:
  11094. return ['RGBD', '( value, 256.0 )'];
  11095. case GammaEncoding:
  11096. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  11097. case LogLuvEncoding:
  11098. return ['LogLuv', '( value )'];
  11099. default:
  11100. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  11101. return ['Linear', '( value )'];
  11102. }
  11103. }
  11104. function getShaderErrors(gl, shader, type) {
  11105. const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  11106. const errors = gl.getShaderInfoLog(shader).trim();
  11107. if (status && errors === '') return ''; // --enable-privileged-webgl-extension
  11108. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11109. return type.toUpperCase() + '\n\n' + errors + '\n\n' + addLineNumbers(gl.getShaderSource(shader));
  11110. }
  11111. function getTexelDecodingFunction(functionName, encoding) {
  11112. const components = getEncodingComponents(encoding);
  11113. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  11114. }
  11115. function getTexelEncodingFunction(functionName, encoding) {
  11116. const components = getEncodingComponents(encoding);
  11117. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  11118. }
  11119. function getToneMappingFunction(functionName, toneMapping) {
  11120. let toneMappingName;
  11121. switch (toneMapping) {
  11122. case LinearToneMapping:
  11123. toneMappingName = 'Linear';
  11124. break;
  11125. case ReinhardToneMapping:
  11126. toneMappingName = 'Reinhard';
  11127. break;
  11128. case CineonToneMapping:
  11129. toneMappingName = 'OptimizedCineon';
  11130. break;
  11131. case ACESFilmicToneMapping:
  11132. toneMappingName = 'ACESFilmic';
  11133. break;
  11134. case CustomToneMapping:
  11135. toneMappingName = 'Custom';
  11136. break;
  11137. default:
  11138. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  11139. toneMappingName = 'Linear';
  11140. }
  11141. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11142. }
  11143. function generateExtensions(parameters) {
  11144. const chunks = [parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ? '#extension GL_OES_standard_derivatives : enable' : '', (parameters.extensionFragDepth || parameters.logarithmicDepthBuffer) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ? '#extension GL_EXT_draw_buffers : require' : '', (parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  11145. return chunks.filter(filterEmptyLine).join('\n');
  11146. }
  11147. function generateDefines(defines) {
  11148. const chunks = [];
  11149. for (const name in defines) {
  11150. const value = defines[name];
  11151. if (value === false) continue;
  11152. chunks.push('#define ' + name + ' ' + value);
  11153. }
  11154. return chunks.join('\n');
  11155. }
  11156. function fetchAttributeLocations(gl, program) {
  11157. const attributes = {};
  11158. const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  11159. for (let i = 0; i < n; i++) {
  11160. const info = gl.getActiveAttrib(program, i);
  11161. const name = info.name;
  11162. let locationSize = 1;
  11163. if (info.type === gl.FLOAT_MAT2) locationSize = 2;
  11164. if (info.type === gl.FLOAT_MAT3) locationSize = 3;
  11165. if (info.type === gl.FLOAT_MAT4) locationSize = 4; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11166. attributes[name] = {
  11167. type: info.type,
  11168. location: gl.getAttribLocation(program, name),
  11169. locationSize: locationSize
  11170. };
  11171. }
  11172. return attributes;
  11173. }
  11174. function filterEmptyLine(string) {
  11175. return string !== '';
  11176. }
  11177. function replaceLightNums(string, parameters) {
  11178. return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows);
  11179. }
  11180. function replaceClippingPlaneNums(string, parameters) {
  11181. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  11182. } // Resolve Includes
  11183. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11184. function resolveIncludes(string) {
  11185. return string.replace(includePattern, includeReplacer);
  11186. }
  11187. function includeReplacer(match, include) {
  11188. const string = ShaderChunk[include];
  11189. if (string === undefined) {
  11190. throw new Error('Can not resolve #include <' + include + '>');
  11191. }
  11192. return resolveIncludes(string);
  11193. } // Unroll Loops
  11194. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  11195. const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;
  11196. function unrollLoops(string) {
  11197. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  11198. }
  11199. function deprecatedLoopReplacer(match, start, end, snippet) {
  11200. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  11201. return loopReplacer(match, start, end, snippet);
  11202. }
  11203. function loopReplacer(match, start, end, snippet) {
  11204. let string = '';
  11205. for (let i = parseInt(start); i < parseInt(end); i++) {
  11206. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  11207. }
  11208. return string;
  11209. } //
  11210. function generatePrecision(parameters) {
  11211. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11212. if (parameters.precision === 'highp') {
  11213. precisionstring += '\n#define HIGH_PRECISION';
  11214. } else if (parameters.precision === 'mediump') {
  11215. precisionstring += '\n#define MEDIUM_PRECISION';
  11216. } else if (parameters.precision === 'lowp') {
  11217. precisionstring += '\n#define LOW_PRECISION';
  11218. }
  11219. return precisionstring;
  11220. }
  11221. function generateShadowMapTypeDefine(parameters) {
  11222. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11223. if (parameters.shadowMapType === PCFShadowMap) {
  11224. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11225. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  11226. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11227. } else if (parameters.shadowMapType === VSMShadowMap) {
  11228. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11229. }
  11230. return shadowMapTypeDefine;
  11231. }
  11232. function generateEnvMapTypeDefine(parameters) {
  11233. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11234. if (parameters.envMap) {
  11235. switch (parameters.envMapMode) {
  11236. case CubeReflectionMapping:
  11237. case CubeRefractionMapping:
  11238. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11239. break;
  11240. case CubeUVReflectionMapping:
  11241. case CubeUVRefractionMapping:
  11242. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11243. break;
  11244. }
  11245. }
  11246. return envMapTypeDefine;
  11247. }
  11248. function generateEnvMapModeDefine(parameters) {
  11249. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11250. if (parameters.envMap) {
  11251. switch (parameters.envMapMode) {
  11252. case CubeRefractionMapping:
  11253. case CubeUVRefractionMapping:
  11254. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11255. break;
  11256. }
  11257. }
  11258. return envMapModeDefine;
  11259. }
  11260. function generateEnvMapBlendingDefine(parameters) {
  11261. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11262. if (parameters.envMap) {
  11263. switch (parameters.combine) {
  11264. case MultiplyOperation:
  11265. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11266. break;
  11267. case MixOperation:
  11268. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11269. break;
  11270. case AddOperation:
  11271. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11272. break;
  11273. }
  11274. }
  11275. return envMapBlendingDefine;
  11276. }
  11277. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  11278. // TODO Send this event to Three.js DevTools
  11279. // console.log( 'WebGLProgram', cacheKey );
  11280. const gl = renderer.getContext();
  11281. const defines = parameters.defines;
  11282. let vertexShader = parameters.vertexShader;
  11283. let fragmentShader = parameters.fragmentShader;
  11284. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  11285. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  11286. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  11287. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  11288. const gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  11289. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  11290. const customDefines = generateDefines(defines);
  11291. const program = gl.createProgram();
  11292. let prefixVertex, prefixFragment;
  11293. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11294. if (parameters.isRawShaderMaterial) {
  11295. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  11296. if (prefixVertex.length > 0) {
  11297. prefixVertex += '\n';
  11298. }
  11299. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  11300. if (prefixFragment.length > 0) {
  11301. prefixFragment += '\n';
  11302. }
  11303. } else {
  11304. prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', '#define GAMMA_FACTOR ' + gammaFactorDefine, '#define MAX_BONES ' + parameters.maxBones, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularTintMap ? '#define USE_SPECULARTINTMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 modelMatrix;', 'uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', '#ifdef USE_INSTANCING', ' attribute mat4 instanceMatrix;', '#endif', '#ifdef USE_INSTANCING_COLOR', ' attribute vec3 instanceColor;', '#endif', 'attribute vec3 position;', 'attribute vec3 normal;', 'attribute vec2 uv;', '#ifdef USE_TANGENT', ' attribute vec4 tangent;', '#endif', '#if defined( USE_COLOR_ALPHA )', ' attribute vec4 color;', '#elif defined( USE_COLOR )', ' attribute vec3 color;', '#endif', '#ifdef USE_MORPHTARGETS', ' attribute vec3 morphTarget0;', ' attribute vec3 morphTarget1;', ' attribute vec3 morphTarget2;', ' attribute vec3 morphTarget3;', ' #ifdef USE_MORPHNORMALS', ' attribute vec3 morphNormal0;', ' attribute vec3 morphNormal1;', ' attribute vec3 morphNormal2;', ' attribute vec3 morphNormal3;', ' #else', ' attribute vec3 morphTarget4;', ' attribute vec3 morphTarget5;', ' attribute vec3 morphTarget6;', ' attribute vec3 morphTarget7;', ' #endif', '#endif', '#ifdef USE_SKINNING', ' attribute vec4 skinIndex;', ' attribute vec4 skinWeight;', '#endif', '\n'].filter(filterEmptyLine).join('\n');
  11305. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, '#define GAMMA_FACTOR ' + gammaFactorDefine, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapTypeDefine : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.envMap ? '#define ' + envMapBlendingDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoat ? '#define USE_CLEARCOAT' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularTintMap ? '#define USE_SPECULARTINTMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.alphaTest ? '#define USE_ALPHATEST' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', (parameters.extensionShaderTextureLOD || parameters.envMap) && parameters.rendererExtensionShaderTextureLod ? '#define TEXTURE_LOD_EXT' : '', 'uniform mat4 viewMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', parameters.toneMapping !== NoToneMapping ? '#define TONE_MAPPING' : '', parameters.toneMapping !== NoToneMapping ? ShaderChunk['tonemapping_pars_fragment'] : '', // this code is required here because it is used by the toneMapping() function defined below
  11306. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', parameters.format === RGBFormat ? '#define OPAQUE' : '', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
  11307. parameters.map ? getTexelDecodingFunction('mapTexelToLinear', parameters.mapEncoding) : '', parameters.matcap ? getTexelDecodingFunction('matcapTexelToLinear', parameters.matcapEncoding) : '', parameters.envMap ? getTexelDecodingFunction('envMapTexelToLinear', parameters.envMapEncoding) : '', parameters.emissiveMap ? getTexelDecodingFunction('emissiveMapTexelToLinear', parameters.emissiveMapEncoding) : '', parameters.specularTintMap ? getTexelDecodingFunction('specularTintMapTexelToLinear', parameters.specularTintMapEncoding) : '', parameters.lightMap ? getTexelDecodingFunction('lightMapTexelToLinear', parameters.lightMapEncoding) : '', getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  11308. }
  11309. vertexShader = resolveIncludes(vertexShader);
  11310. vertexShader = replaceLightNums(vertexShader, parameters);
  11311. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  11312. fragmentShader = resolveIncludes(fragmentShader);
  11313. fragmentShader = replaceLightNums(fragmentShader, parameters);
  11314. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  11315. vertexShader = unrollLoops(vertexShader);
  11316. fragmentShader = unrollLoops(fragmentShader);
  11317. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  11318. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11319. versionString = '#version 300 es\n';
  11320. prefixVertex = ['#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  11321. prefixFragment = ['#define varying in', parameters.glslVersion === GLSL3 ? '' : 'out highp vec4 pc_fragColor;', parameters.glslVersion === GLSL3 ? '' : '#define gl_FragColor pc_fragColor', '#define gl_FragDepthEXT gl_FragDepth', '#define texture2D texture', '#define textureCube texture', '#define texture2DProj textureProj', '#define texture2DLodEXT textureLod', '#define texture2DProjLodEXT textureProjLod', '#define textureCubeLodEXT textureLod', '#define texture2DGradEXT textureGrad', '#define texture2DProjGradEXT textureProjGrad', '#define textureCubeGradEXT textureGrad'].join('\n') + '\n' + prefixFragment;
  11322. }
  11323. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11324. const fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  11325. // console.log( '*FRAGMENT*', fragmentGlsl );
  11326. const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl);
  11327. const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl);
  11328. gl.attachShader(program, glVertexShader);
  11329. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  11330. if (parameters.index0AttributeName !== undefined) {
  11331. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  11332. } else if (parameters.morphTargets === true) {
  11333. // programs with morphTargets displace position out of attribute 0
  11334. gl.bindAttribLocation(program, 0, 'position');
  11335. }
  11336. gl.linkProgram(program); // check for link errors
  11337. if (renderer.debug.checkShaderErrors) {
  11338. const programLog = gl.getProgramInfoLog(program).trim();
  11339. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  11340. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  11341. let runnable = true;
  11342. let haveDiagnostics = true;
  11343. if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
  11344. runnable = false;
  11345. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  11346. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  11347. console.error('THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' + 'VALIDATE_STATUS ' + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + '\n\n' + 'Program Info Log: ' + programLog + '\n' + vertexErrors + '\n' + fragmentErrors);
  11348. } else if (programLog !== '') {
  11349. console.warn('THREE.WebGLProgram: Program Info Log:', programLog);
  11350. } else if (vertexLog === '' || fragmentLog === '') {
  11351. haveDiagnostics = false;
  11352. }
  11353. if (haveDiagnostics) {
  11354. this.diagnostics = {
  11355. runnable: runnable,
  11356. programLog: programLog,
  11357. vertexShader: {
  11358. log: vertexLog,
  11359. prefix: prefixVertex
  11360. },
  11361. fragmentShader: {
  11362. log: fragmentLog,
  11363. prefix: prefixFragment
  11364. }
  11365. };
  11366. }
  11367. } // Clean up
  11368. // Crashes in iOS9 and iOS10. #18402
  11369. // gl.detachShader( program, glVertexShader );
  11370. // gl.detachShader( program, glFragmentShader );
  11371. gl.deleteShader(glVertexShader);
  11372. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  11373. let cachedUniforms;
  11374. this.getUniforms = function () {
  11375. if (cachedUniforms === undefined) {
  11376. cachedUniforms = new WebGLUniforms(gl, program);
  11377. }
  11378. return cachedUniforms;
  11379. }; // set up caching for attribute locations
  11380. let cachedAttributes;
  11381. this.getAttributes = function () {
  11382. if (cachedAttributes === undefined) {
  11383. cachedAttributes = fetchAttributeLocations(gl, program);
  11384. }
  11385. return cachedAttributes;
  11386. }; // free resource
  11387. this.destroy = function () {
  11388. bindingStates.releaseStatesOfProgram(this);
  11389. gl.deleteProgram(program);
  11390. this.program = undefined;
  11391. }; //
  11392. this.name = parameters.shaderName;
  11393. this.id = programIdCount++;
  11394. this.cacheKey = cacheKey;
  11395. this.usedTimes = 1;
  11396. this.program = program;
  11397. this.vertexShader = glVertexShader;
  11398. this.fragmentShader = glFragmentShader;
  11399. return this;
  11400. }
  11401. function WebGLPrograms(renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) {
  11402. const programs = [];
  11403. const isWebGL2 = capabilities.isWebGL2;
  11404. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11405. const floatVertexTextures = capabilities.floatVertexTextures;
  11406. const maxVertexUniforms = capabilities.maxVertexUniforms;
  11407. const vertexTextures = capabilities.vertexTextures;
  11408. let precision = capabilities.precision;
  11409. const shaderIDs = {
  11410. MeshDepthMaterial: 'depth',
  11411. MeshDistanceMaterial: 'distanceRGBA',
  11412. MeshNormalMaterial: 'normal',
  11413. MeshBasicMaterial: 'basic',
  11414. MeshLambertMaterial: 'lambert',
  11415. MeshPhongMaterial: 'phong',
  11416. MeshToonMaterial: 'toon',
  11417. MeshStandardMaterial: 'physical',
  11418. MeshPhysicalMaterial: 'physical',
  11419. MeshMatcapMaterial: 'matcap',
  11420. LineBasicMaterial: 'basic',
  11421. LineDashedMaterial: 'dashed',
  11422. PointsMaterial: 'points',
  11423. ShadowMaterial: 'shadow',
  11424. SpriteMaterial: 'sprite'
  11425. };
  11426. const parameterNames = ['precision', 'isWebGL2', 'supportsVertexTextures', 'outputEncoding', 'instancing', 'instancingColor', 'map', 'mapEncoding', 'matcap', 'matcapEncoding', 'envMap', 'envMapMode', 'envMapEncoding', 'envMapCubeUV', 'lightMap', 'lightMapEncoding', 'aoMap', 'emissiveMap', 'emissiveMapEncoding', 'bumpMap', 'normalMap', 'objectSpaceNormalMap', 'tangentSpaceNormalMap', 'clearcoat', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap', 'displacementMap', 'specularMap', 'specularIntensityMap', 'specularTintMap', 'specularTintMapEncoding', 'roughnessMap', 'metalnessMap', 'gradientMap', 'alphaMap', 'alphaTest', 'combine', 'vertexColors', 'vertexAlphas', 'vertexTangents', 'vertexUvs', 'uvsVertexOnly', 'fog', 'useFog', 'fogExp2', 'flatShading', 'sizeAttenuation', 'logarithmicDepthBuffer', 'skinning', 'maxBones', 'useVertexTexture', 'morphTargets', 'morphNormals', 'premultipliedAlpha', 'numDirLights', 'numPointLights', 'numSpotLights', 'numHemiLights', 'numRectAreaLights', 'numDirLightShadows', 'numPointLightShadows', 'numSpotLightShadows', 'shadowMapEnabled', 'shadowMapType', 'toneMapping', 'physicallyCorrectLights', 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering', 'format', 'sheen', 'transmission', 'transmissionMap', 'thicknessMap'];
  11427. function getMaxBones(object) {
  11428. const skeleton = object.skeleton;
  11429. const bones = skeleton.bones;
  11430. if (floatVertexTextures) {
  11431. return 1024;
  11432. } else {
  11433. // default for when object is not specified
  11434. // ( for example when prebuilding shader to be used with multiple objects )
  11435. //
  11436. // - leave some extra space for other uniforms
  11437. // - limit here is ANGLE's 254 max uniform vectors
  11438. // (up to 54 should be safe)
  11439. const nVertexUniforms = maxVertexUniforms;
  11440. const nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  11441. const maxBones = Math.min(nVertexMatrices, bones.length);
  11442. if (maxBones < bones.length) {
  11443. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  11444. return 0;
  11445. }
  11446. return maxBones;
  11447. }
  11448. }
  11449. function getTextureEncodingFromMap(map) {
  11450. let encoding;
  11451. if (map && map.isTexture) {
  11452. encoding = map.encoding;
  11453. } else if (map && map.isWebGLRenderTarget) {
  11454. console.warn('THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.');
  11455. encoding = map.texture.encoding;
  11456. } else {
  11457. encoding = LinearEncoding;
  11458. }
  11459. return encoding;
  11460. }
  11461. function getParameters(material, lights, shadows, scene, object) {
  11462. const fog = scene.fog;
  11463. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11464. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  11465. const shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  11466. // (not to blow over maxLights budget)
  11467. const maxBones = object.isSkinnedMesh ? getMaxBones(object) : 0;
  11468. if (material.precision !== null) {
  11469. precision = capabilities.getMaxPrecision(material.precision);
  11470. if (precision !== material.precision) {
  11471. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  11472. }
  11473. }
  11474. let vertexShader, fragmentShader;
  11475. if (shaderID) {
  11476. const shader = ShaderLib[shaderID];
  11477. vertexShader = shader.vertexShader;
  11478. fragmentShader = shader.fragmentShader;
  11479. } else {
  11480. vertexShader = material.vertexShader;
  11481. fragmentShader = material.fragmentShader;
  11482. }
  11483. const currentRenderTarget = renderer.getRenderTarget();
  11484. const useAlphaTest = material.alphaTest > 0;
  11485. const useClearcoat = material.clearcoat > 0;
  11486. const parameters = {
  11487. isWebGL2: isWebGL2,
  11488. shaderID: shaderID,
  11489. shaderName: material.type,
  11490. vertexShader: vertexShader,
  11491. fragmentShader: fragmentShader,
  11492. defines: material.defines,
  11493. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11494. glslVersion: material.glslVersion,
  11495. precision: precision,
  11496. instancing: object.isInstancedMesh === true,
  11497. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11498. supportsVertexTextures: vertexTextures,
  11499. outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
  11500. map: !!material.map,
  11501. mapEncoding: getTextureEncodingFromMap(material.map),
  11502. matcap: !!material.matcap,
  11503. matcapEncoding: getTextureEncodingFromMap(material.matcap),
  11504. envMap: !!envMap,
  11505. envMapMode: envMap && envMap.mapping,
  11506. envMapEncoding: getTextureEncodingFromMap(envMap),
  11507. envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
  11508. lightMap: !!material.lightMap,
  11509. lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
  11510. aoMap: !!material.aoMap,
  11511. emissiveMap: !!material.emissiveMap,
  11512. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
  11513. bumpMap: !!material.bumpMap,
  11514. normalMap: !!material.normalMap,
  11515. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11516. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11517. clearcoat: useClearcoat,
  11518. clearcoatMap: useClearcoat && !!material.clearcoatMap,
  11519. clearcoatRoughnessMap: useClearcoat && !!material.clearcoatRoughnessMap,
  11520. clearcoatNormalMap: useClearcoat && !!material.clearcoatNormalMap,
  11521. displacementMap: !!material.displacementMap,
  11522. roughnessMap: !!material.roughnessMap,
  11523. metalnessMap: !!material.metalnessMap,
  11524. specularMap: !!material.specularMap,
  11525. specularIntensityMap: !!material.specularIntensityMap,
  11526. specularTintMap: !!material.specularTintMap,
  11527. specularTintMapEncoding: getTextureEncodingFromMap(material.specularTintMap),
  11528. alphaMap: !!material.alphaMap,
  11529. alphaTest: useAlphaTest,
  11530. gradientMap: !!material.gradientMap,
  11531. sheen: material.sheen > 0,
  11532. transmission: material.transmission > 0,
  11533. transmissionMap: !!material.transmissionMap,
  11534. thicknessMap: !!material.thicknessMap,
  11535. combine: material.combine,
  11536. vertexTangents: !!material.normalMap && !!object.geometry && !!object.geometry.attributes.tangent,
  11537. vertexColors: material.vertexColors,
  11538. vertexAlphas: material.vertexColors === true && !!object.geometry && !!object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4,
  11539. vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatMap || !!material.clearcoatRoughnessMap || !!material.clearcoatNormalMap || !!material.displacementMap || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularTintMap,
  11540. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || material.transmission > 0 || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularTintMap) && !!material.displacementMap,
  11541. fog: !!fog,
  11542. useFog: material.fog,
  11543. fogExp2: fog && fog.isFogExp2,
  11544. flatShading: !!material.flatShading,
  11545. sizeAttenuation: material.sizeAttenuation,
  11546. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11547. skinning: object.isSkinnedMesh === true && maxBones > 0,
  11548. maxBones: maxBones,
  11549. useVertexTexture: floatVertexTextures,
  11550. morphTargets: !!object.geometry && !!object.geometry.morphAttributes.position,
  11551. morphNormals: !!object.geometry && !!object.geometry.morphAttributes.normal,
  11552. numDirLights: lights.directional.length,
  11553. numPointLights: lights.point.length,
  11554. numSpotLights: lights.spot.length,
  11555. numRectAreaLights: lights.rectArea.length,
  11556. numHemiLights: lights.hemi.length,
  11557. numDirLightShadows: lights.directionalShadowMap.length,
  11558. numPointLightShadows: lights.pointShadowMap.length,
  11559. numSpotLightShadows: lights.spotShadowMap.length,
  11560. numClippingPlanes: clipping.numPlanes,
  11561. numClipIntersection: clipping.numIntersection,
  11562. format: material.format,
  11563. dithering: material.dithering,
  11564. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11565. shadowMapType: renderer.shadowMap.type,
  11566. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11567. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11568. premultipliedAlpha: material.premultipliedAlpha,
  11569. doubleSided: material.side === DoubleSide,
  11570. flipSided: material.side === BackSide,
  11571. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
  11572. index0AttributeName: material.index0AttributeName,
  11573. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11574. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11575. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11576. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11577. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  11578. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  11579. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  11580. customProgramCacheKey: material.customProgramCacheKey()
  11581. };
  11582. return parameters;
  11583. }
  11584. function getProgramCacheKey(parameters) {
  11585. const array = [];
  11586. if (parameters.shaderID) {
  11587. array.push(parameters.shaderID);
  11588. } else {
  11589. array.push(parameters.fragmentShader);
  11590. array.push(parameters.vertexShader);
  11591. }
  11592. if (parameters.defines !== undefined) {
  11593. for (const name in parameters.defines) {
  11594. array.push(name);
  11595. array.push(parameters.defines[name]);
  11596. }
  11597. }
  11598. if (parameters.isRawShaderMaterial === false) {
  11599. for (let i = 0; i < parameterNames.length; i++) {
  11600. array.push(parameters[parameterNames[i]]);
  11601. }
  11602. array.push(renderer.outputEncoding);
  11603. array.push(renderer.gammaFactor);
  11604. }
  11605. array.push(parameters.customProgramCacheKey);
  11606. return array.join();
  11607. }
  11608. function getUniforms(material) {
  11609. const shaderID = shaderIDs[material.type];
  11610. let uniforms;
  11611. if (shaderID) {
  11612. const shader = ShaderLib[shaderID];
  11613. uniforms = UniformsUtils.clone(shader.uniforms);
  11614. } else {
  11615. uniforms = material.uniforms;
  11616. }
  11617. return uniforms;
  11618. }
  11619. function acquireProgram(parameters, cacheKey) {
  11620. let program; // Check if code has been already compiled
  11621. for (let p = 0, pl = programs.length; p < pl; p++) {
  11622. const preexistingProgram = programs[p];
  11623. if (preexistingProgram.cacheKey === cacheKey) {
  11624. program = preexistingProgram;
  11625. ++program.usedTimes;
  11626. break;
  11627. }
  11628. }
  11629. if (program === undefined) {
  11630. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  11631. programs.push(program);
  11632. }
  11633. return program;
  11634. }
  11635. function releaseProgram(program) {
  11636. if (--program.usedTimes === 0) {
  11637. // Remove from unordered set
  11638. const i = programs.indexOf(program);
  11639. programs[i] = programs[programs.length - 1];
  11640. programs.pop(); // Free WebGL resources
  11641. program.destroy();
  11642. }
  11643. }
  11644. return {
  11645. getParameters: getParameters,
  11646. getProgramCacheKey: getProgramCacheKey,
  11647. getUniforms: getUniforms,
  11648. acquireProgram: acquireProgram,
  11649. releaseProgram: releaseProgram,
  11650. // Exposed for resource monitoring & error feedback via renderer.info:
  11651. programs: programs
  11652. };
  11653. }
  11654. function WebGLProperties() {
  11655. let properties = new WeakMap();
  11656. function get(object) {
  11657. let map = properties.get(object);
  11658. if (map === undefined) {
  11659. map = {};
  11660. properties.set(object, map);
  11661. }
  11662. return map;
  11663. }
  11664. function remove(object) {
  11665. properties.delete(object);
  11666. }
  11667. function update(object, key, value) {
  11668. properties.get(object)[key] = value;
  11669. }
  11670. function dispose() {
  11671. properties = new WeakMap();
  11672. }
  11673. return {
  11674. get: get,
  11675. remove: remove,
  11676. update: update,
  11677. dispose: dispose
  11678. };
  11679. }
  11680. function painterSortStable(a, b) {
  11681. if (a.groupOrder !== b.groupOrder) {
  11682. return a.groupOrder - b.groupOrder;
  11683. } else if (a.renderOrder !== b.renderOrder) {
  11684. return a.renderOrder - b.renderOrder;
  11685. } else if (a.program !== b.program) {
  11686. return a.program.id - b.program.id;
  11687. } else if (a.material.id !== b.material.id) {
  11688. return a.material.id - b.material.id;
  11689. } else if (a.z !== b.z) {
  11690. return a.z - b.z;
  11691. } else {
  11692. return a.id - b.id;
  11693. }
  11694. }
  11695. function reversePainterSortStable(a, b) {
  11696. if (a.groupOrder !== b.groupOrder) {
  11697. return a.groupOrder - b.groupOrder;
  11698. } else if (a.renderOrder !== b.renderOrder) {
  11699. return a.renderOrder - b.renderOrder;
  11700. } else if (a.z !== b.z) {
  11701. return b.z - a.z;
  11702. } else {
  11703. return a.id - b.id;
  11704. }
  11705. }
  11706. function WebGLRenderList(properties) {
  11707. const renderItems = [];
  11708. let renderItemsIndex = 0;
  11709. const opaque = [];
  11710. const transmissive = [];
  11711. const transparent = [];
  11712. const defaultProgram = {
  11713. id: -1
  11714. };
  11715. function init() {
  11716. renderItemsIndex = 0;
  11717. opaque.length = 0;
  11718. transmissive.length = 0;
  11719. transparent.length = 0;
  11720. }
  11721. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  11722. let renderItem = renderItems[renderItemsIndex];
  11723. const materialProperties = properties.get(material);
  11724. if (renderItem === undefined) {
  11725. renderItem = {
  11726. id: object.id,
  11727. object: object,
  11728. geometry: geometry,
  11729. material: material,
  11730. program: materialProperties.program || defaultProgram,
  11731. groupOrder: groupOrder,
  11732. renderOrder: object.renderOrder,
  11733. z: z,
  11734. group: group
  11735. };
  11736. renderItems[renderItemsIndex] = renderItem;
  11737. } else {
  11738. renderItem.id = object.id;
  11739. renderItem.object = object;
  11740. renderItem.geometry = geometry;
  11741. renderItem.material = material;
  11742. renderItem.program = materialProperties.program || defaultProgram;
  11743. renderItem.groupOrder = groupOrder;
  11744. renderItem.renderOrder = object.renderOrder;
  11745. renderItem.z = z;
  11746. renderItem.group = group;
  11747. }
  11748. renderItemsIndex++;
  11749. return renderItem;
  11750. }
  11751. function push(object, geometry, material, groupOrder, z, group) {
  11752. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  11753. if (material.transmission > 0.0) {
  11754. transmissive.push(renderItem);
  11755. } else if (material.transparent === true) {
  11756. transparent.push(renderItem);
  11757. } else {
  11758. opaque.push(renderItem);
  11759. }
  11760. }
  11761. function unshift(object, geometry, material, groupOrder, z, group) {
  11762. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  11763. if (material.transmission > 0.0) {
  11764. transmissive.unshift(renderItem);
  11765. } else if (material.transparent === true) {
  11766. transparent.unshift(renderItem);
  11767. } else {
  11768. opaque.unshift(renderItem);
  11769. }
  11770. }
  11771. function sort(customOpaqueSort, customTransparentSort) {
  11772. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  11773. if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable);
  11774. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  11775. }
  11776. function finish() {
  11777. // Clear references from inactive renderItems in the list
  11778. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  11779. const renderItem = renderItems[i];
  11780. if (renderItem.id === null) break;
  11781. renderItem.id = null;
  11782. renderItem.object = null;
  11783. renderItem.geometry = null;
  11784. renderItem.material = null;
  11785. renderItem.program = null;
  11786. renderItem.group = null;
  11787. }
  11788. }
  11789. return {
  11790. opaque: opaque,
  11791. transmissive: transmissive,
  11792. transparent: transparent,
  11793. init: init,
  11794. push: push,
  11795. unshift: unshift,
  11796. finish: finish,
  11797. sort: sort
  11798. };
  11799. }
  11800. function WebGLRenderLists(properties) {
  11801. let lists = new WeakMap();
  11802. function get(scene, renderCallDepth) {
  11803. let list;
  11804. if (lists.has(scene) === false) {
  11805. list = new WebGLRenderList(properties);
  11806. lists.set(scene, [list]);
  11807. } else {
  11808. if (renderCallDepth >= lists.get(scene).length) {
  11809. list = new WebGLRenderList(properties);
  11810. lists.get(scene).push(list);
  11811. } else {
  11812. list = lists.get(scene)[renderCallDepth];
  11813. }
  11814. }
  11815. return list;
  11816. }
  11817. function dispose() {
  11818. lists = new WeakMap();
  11819. }
  11820. return {
  11821. get: get,
  11822. dispose: dispose
  11823. };
  11824. }
  11825. function UniformsCache() {
  11826. const lights = {};
  11827. return {
  11828. get: function (light) {
  11829. if (lights[light.id] !== undefined) {
  11830. return lights[light.id];
  11831. }
  11832. let uniforms;
  11833. switch (light.type) {
  11834. case 'DirectionalLight':
  11835. uniforms = {
  11836. direction: new Vector3(),
  11837. color: new Color()
  11838. };
  11839. break;
  11840. case 'SpotLight':
  11841. uniforms = {
  11842. position: new Vector3(),
  11843. direction: new Vector3(),
  11844. color: new Color(),
  11845. distance: 0,
  11846. coneCos: 0,
  11847. penumbraCos: 0,
  11848. decay: 0
  11849. };
  11850. break;
  11851. case 'PointLight':
  11852. uniforms = {
  11853. position: new Vector3(),
  11854. color: new Color(),
  11855. distance: 0,
  11856. decay: 0
  11857. };
  11858. break;
  11859. case 'HemisphereLight':
  11860. uniforms = {
  11861. direction: new Vector3(),
  11862. skyColor: new Color(),
  11863. groundColor: new Color()
  11864. };
  11865. break;
  11866. case 'RectAreaLight':
  11867. uniforms = {
  11868. color: new Color(),
  11869. position: new Vector3(),
  11870. halfWidth: new Vector3(),
  11871. halfHeight: new Vector3()
  11872. };
  11873. break;
  11874. }
  11875. lights[light.id] = uniforms;
  11876. return uniforms;
  11877. }
  11878. };
  11879. }
  11880. function ShadowUniformsCache() {
  11881. const lights = {};
  11882. return {
  11883. get: function (light) {
  11884. if (lights[light.id] !== undefined) {
  11885. return lights[light.id];
  11886. }
  11887. let uniforms;
  11888. switch (light.type) {
  11889. case 'DirectionalLight':
  11890. uniforms = {
  11891. shadowBias: 0,
  11892. shadowNormalBias: 0,
  11893. shadowRadius: 1,
  11894. shadowMapSize: new Vector2()
  11895. };
  11896. break;
  11897. case 'SpotLight':
  11898. uniforms = {
  11899. shadowBias: 0,
  11900. shadowNormalBias: 0,
  11901. shadowRadius: 1,
  11902. shadowMapSize: new Vector2()
  11903. };
  11904. break;
  11905. case 'PointLight':
  11906. uniforms = {
  11907. shadowBias: 0,
  11908. shadowNormalBias: 0,
  11909. shadowRadius: 1,
  11910. shadowMapSize: new Vector2(),
  11911. shadowCameraNear: 1,
  11912. shadowCameraFar: 1000
  11913. };
  11914. break;
  11915. // TODO (abelnation): set RectAreaLight shadow uniforms
  11916. }
  11917. lights[light.id] = uniforms;
  11918. return uniforms;
  11919. }
  11920. };
  11921. }
  11922. let nextVersion = 0;
  11923. function shadowCastingLightsFirst(lightA, lightB) {
  11924. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  11925. }
  11926. function WebGLLights(extensions, capabilities) {
  11927. const cache = new UniformsCache();
  11928. const shadowCache = ShadowUniformsCache();
  11929. const state = {
  11930. version: 0,
  11931. hash: {
  11932. directionalLength: -1,
  11933. pointLength: -1,
  11934. spotLength: -1,
  11935. rectAreaLength: -1,
  11936. hemiLength: -1,
  11937. numDirectionalShadows: -1,
  11938. numPointShadows: -1,
  11939. numSpotShadows: -1
  11940. },
  11941. ambient: [0, 0, 0],
  11942. probe: [],
  11943. directional: [],
  11944. directionalShadow: [],
  11945. directionalShadowMap: [],
  11946. directionalShadowMatrix: [],
  11947. spot: [],
  11948. spotShadow: [],
  11949. spotShadowMap: [],
  11950. spotShadowMatrix: [],
  11951. rectArea: [],
  11952. rectAreaLTC1: null,
  11953. rectAreaLTC2: null,
  11954. point: [],
  11955. pointShadow: [],
  11956. pointShadowMap: [],
  11957. pointShadowMatrix: [],
  11958. hemi: []
  11959. };
  11960. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  11961. const vector3 = new Vector3();
  11962. const matrix4 = new Matrix4();
  11963. const matrix42 = new Matrix4();
  11964. function setup(lights, physicallyCorrectLights) {
  11965. let r = 0,
  11966. g = 0,
  11967. b = 0;
  11968. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  11969. let directionalLength = 0;
  11970. let pointLength = 0;
  11971. let spotLength = 0;
  11972. let rectAreaLength = 0;
  11973. let hemiLength = 0;
  11974. let numDirectionalShadows = 0;
  11975. let numPointShadows = 0;
  11976. let numSpotShadows = 0;
  11977. lights.sort(shadowCastingLightsFirst); // artist-friendly light intensity scaling factor
  11978. const scaleFactor = physicallyCorrectLights !== true ? Math.PI : 1;
  11979. for (let i = 0, l = lights.length; i < l; i++) {
  11980. const light = lights[i];
  11981. const color = light.color;
  11982. const intensity = light.intensity;
  11983. const distance = light.distance;
  11984. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  11985. if (light.isAmbientLight) {
  11986. r += color.r * intensity * scaleFactor;
  11987. g += color.g * intensity * scaleFactor;
  11988. b += color.b * intensity * scaleFactor;
  11989. } else if (light.isLightProbe) {
  11990. for (let j = 0; j < 9; j++) {
  11991. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  11992. }
  11993. } else if (light.isDirectionalLight) {
  11994. const uniforms = cache.get(light);
  11995. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  11996. if (light.castShadow) {
  11997. const shadow = light.shadow;
  11998. const shadowUniforms = shadowCache.get(light);
  11999. shadowUniforms.shadowBias = shadow.bias;
  12000. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12001. shadowUniforms.shadowRadius = shadow.radius;
  12002. shadowUniforms.shadowMapSize = shadow.mapSize;
  12003. state.directionalShadow[directionalLength] = shadowUniforms;
  12004. state.directionalShadowMap[directionalLength] = shadowMap;
  12005. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  12006. numDirectionalShadows++;
  12007. }
  12008. state.directional[directionalLength] = uniforms;
  12009. directionalLength++;
  12010. } else if (light.isSpotLight) {
  12011. const uniforms = cache.get(light);
  12012. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12013. uniforms.color.copy(color).multiplyScalar(intensity * scaleFactor);
  12014. uniforms.distance = distance;
  12015. uniforms.coneCos = Math.cos(light.angle);
  12016. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  12017. uniforms.decay = light.decay;
  12018. if (light.castShadow) {
  12019. const shadow = light.shadow;
  12020. const shadowUniforms = shadowCache.get(light);
  12021. shadowUniforms.shadowBias = shadow.bias;
  12022. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12023. shadowUniforms.shadowRadius = shadow.radius;
  12024. shadowUniforms.shadowMapSize = shadow.mapSize;
  12025. state.spotShadow[spotLength] = shadowUniforms;
  12026. state.spotShadowMap[spotLength] = shadowMap;
  12027. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  12028. numSpotShadows++;
  12029. }
  12030. state.spot[spotLength] = uniforms;
  12031. spotLength++;
  12032. } else if (light.isRectAreaLight) {
  12033. const uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  12034. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  12035. // (b) intensity is the brightness of the light
  12036. uniforms.color.copy(color).multiplyScalar(intensity);
  12037. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12038. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12039. state.rectArea[rectAreaLength] = uniforms;
  12040. rectAreaLength++;
  12041. } else if (light.isPointLight) {
  12042. const uniforms = cache.get(light);
  12043. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  12044. uniforms.distance = light.distance;
  12045. uniforms.decay = light.decay;
  12046. if (light.castShadow) {
  12047. const shadow = light.shadow;
  12048. const shadowUniforms = shadowCache.get(light);
  12049. shadowUniforms.shadowBias = shadow.bias;
  12050. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12051. shadowUniforms.shadowRadius = shadow.radius;
  12052. shadowUniforms.shadowMapSize = shadow.mapSize;
  12053. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12054. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12055. state.pointShadow[pointLength] = shadowUniforms;
  12056. state.pointShadowMap[pointLength] = shadowMap;
  12057. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  12058. numPointShadows++;
  12059. }
  12060. state.point[pointLength] = uniforms;
  12061. pointLength++;
  12062. } else if (light.isHemisphereLight) {
  12063. const uniforms = cache.get(light);
  12064. uniforms.skyColor.copy(light.color).multiplyScalar(intensity * scaleFactor);
  12065. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity * scaleFactor);
  12066. state.hemi[hemiLength] = uniforms;
  12067. hemiLength++;
  12068. }
  12069. }
  12070. if (rectAreaLength > 0) {
  12071. if (capabilities.isWebGL2) {
  12072. // WebGL 2
  12073. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12074. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12075. } else {
  12076. // WebGL 1
  12077. if (extensions.has('OES_texture_float_linear') === true) {
  12078. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12079. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12080. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  12081. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12082. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12083. } else {
  12084. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  12085. }
  12086. }
  12087. }
  12088. state.ambient[0] = r;
  12089. state.ambient[1] = g;
  12090. state.ambient[2] = b;
  12091. const hash = state.hash;
  12092. if (hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows) {
  12093. state.directional.length = directionalLength;
  12094. state.spot.length = spotLength;
  12095. state.rectArea.length = rectAreaLength;
  12096. state.point.length = pointLength;
  12097. state.hemi.length = hemiLength;
  12098. state.directionalShadow.length = numDirectionalShadows;
  12099. state.directionalShadowMap.length = numDirectionalShadows;
  12100. state.pointShadow.length = numPointShadows;
  12101. state.pointShadowMap.length = numPointShadows;
  12102. state.spotShadow.length = numSpotShadows;
  12103. state.spotShadowMap.length = numSpotShadows;
  12104. state.directionalShadowMatrix.length = numDirectionalShadows;
  12105. state.pointShadowMatrix.length = numPointShadows;
  12106. state.spotShadowMatrix.length = numSpotShadows;
  12107. hash.directionalLength = directionalLength;
  12108. hash.pointLength = pointLength;
  12109. hash.spotLength = spotLength;
  12110. hash.rectAreaLength = rectAreaLength;
  12111. hash.hemiLength = hemiLength;
  12112. hash.numDirectionalShadows = numDirectionalShadows;
  12113. hash.numPointShadows = numPointShadows;
  12114. hash.numSpotShadows = numSpotShadows;
  12115. state.version = nextVersion++;
  12116. }
  12117. }
  12118. function setupView(lights, camera) {
  12119. let directionalLength = 0;
  12120. let pointLength = 0;
  12121. let spotLength = 0;
  12122. let rectAreaLength = 0;
  12123. let hemiLength = 0;
  12124. const viewMatrix = camera.matrixWorldInverse;
  12125. for (let i = 0, l = lights.length; i < l; i++) {
  12126. const light = lights[i];
  12127. if (light.isDirectionalLight) {
  12128. const uniforms = state.directional[directionalLength];
  12129. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12130. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12131. uniforms.direction.sub(vector3);
  12132. uniforms.direction.transformDirection(viewMatrix);
  12133. directionalLength++;
  12134. } else if (light.isSpotLight) {
  12135. const uniforms = state.spot[spotLength];
  12136. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12137. uniforms.position.applyMatrix4(viewMatrix);
  12138. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12139. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12140. uniforms.direction.sub(vector3);
  12141. uniforms.direction.transformDirection(viewMatrix);
  12142. spotLength++;
  12143. } else if (light.isRectAreaLight) {
  12144. const uniforms = state.rectArea[rectAreaLength];
  12145. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12146. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  12147. matrix42.identity();
  12148. matrix4.copy(light.matrixWorld);
  12149. matrix4.premultiply(viewMatrix);
  12150. matrix42.extractRotation(matrix4);
  12151. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12152. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12153. uniforms.halfWidth.applyMatrix4(matrix42);
  12154. uniforms.halfHeight.applyMatrix4(matrix42);
  12155. rectAreaLength++;
  12156. } else if (light.isPointLight) {
  12157. const uniforms = state.point[pointLength];
  12158. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12159. uniforms.position.applyMatrix4(viewMatrix);
  12160. pointLength++;
  12161. } else if (light.isHemisphereLight) {
  12162. const uniforms = state.hemi[hemiLength];
  12163. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12164. uniforms.direction.transformDirection(viewMatrix);
  12165. uniforms.direction.normalize();
  12166. hemiLength++;
  12167. }
  12168. }
  12169. }
  12170. return {
  12171. setup: setup,
  12172. setupView: setupView,
  12173. state: state
  12174. };
  12175. }
  12176. function WebGLRenderState(extensions, capabilities) {
  12177. const lights = new WebGLLights(extensions, capabilities);
  12178. const lightsArray = [];
  12179. const shadowsArray = [];
  12180. function init() {
  12181. lightsArray.length = 0;
  12182. shadowsArray.length = 0;
  12183. }
  12184. function pushLight(light) {
  12185. lightsArray.push(light);
  12186. }
  12187. function pushShadow(shadowLight) {
  12188. shadowsArray.push(shadowLight);
  12189. }
  12190. function setupLights(physicallyCorrectLights) {
  12191. lights.setup(lightsArray, physicallyCorrectLights);
  12192. }
  12193. function setupLightsView(camera) {
  12194. lights.setupView(lightsArray, camera);
  12195. }
  12196. const state = {
  12197. lightsArray: lightsArray,
  12198. shadowsArray: shadowsArray,
  12199. lights: lights
  12200. };
  12201. return {
  12202. init: init,
  12203. state: state,
  12204. setupLights: setupLights,
  12205. setupLightsView: setupLightsView,
  12206. pushLight: pushLight,
  12207. pushShadow: pushShadow
  12208. };
  12209. }
  12210. function WebGLRenderStates(extensions, capabilities) {
  12211. let renderStates = new WeakMap();
  12212. function get(scene, renderCallDepth = 0) {
  12213. let renderState;
  12214. if (renderStates.has(scene) === false) {
  12215. renderState = new WebGLRenderState(extensions, capabilities);
  12216. renderStates.set(scene, [renderState]);
  12217. } else {
  12218. if (renderCallDepth >= renderStates.get(scene).length) {
  12219. renderState = new WebGLRenderState(extensions, capabilities);
  12220. renderStates.get(scene).push(renderState);
  12221. } else {
  12222. renderState = renderStates.get(scene)[renderCallDepth];
  12223. }
  12224. }
  12225. return renderState;
  12226. }
  12227. function dispose() {
  12228. renderStates = new WeakMap();
  12229. }
  12230. return {
  12231. get: get,
  12232. dispose: dispose
  12233. };
  12234. }
  12235. /**
  12236. * parameters = {
  12237. *
  12238. * opacity: <float>,
  12239. *
  12240. * map: new THREE.Texture( <Image> ),
  12241. *
  12242. * alphaMap: new THREE.Texture( <Image> ),
  12243. *
  12244. * displacementMap: new THREE.Texture( <Image> ),
  12245. * displacementScale: <float>,
  12246. * displacementBias: <float>,
  12247. *
  12248. * wireframe: <boolean>,
  12249. * wireframeLinewidth: <float>
  12250. * }
  12251. */
  12252. class MeshDepthMaterial extends Material {
  12253. constructor(parameters) {
  12254. super();
  12255. this.type = 'MeshDepthMaterial';
  12256. this.depthPacking = BasicDepthPacking;
  12257. this.map = null;
  12258. this.alphaMap = null;
  12259. this.displacementMap = null;
  12260. this.displacementScale = 1;
  12261. this.displacementBias = 0;
  12262. this.wireframe = false;
  12263. this.wireframeLinewidth = 1;
  12264. this.fog = false;
  12265. this.setValues(parameters);
  12266. }
  12267. copy(source) {
  12268. super.copy(source);
  12269. this.depthPacking = source.depthPacking;
  12270. this.map = source.map;
  12271. this.alphaMap = source.alphaMap;
  12272. this.displacementMap = source.displacementMap;
  12273. this.displacementScale = source.displacementScale;
  12274. this.displacementBias = source.displacementBias;
  12275. this.wireframe = source.wireframe;
  12276. this.wireframeLinewidth = source.wireframeLinewidth;
  12277. return this;
  12278. }
  12279. }
  12280. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  12281. /**
  12282. * parameters = {
  12283. *
  12284. * referencePosition: <float>,
  12285. * nearDistance: <float>,
  12286. * farDistance: <float>,
  12287. *
  12288. * map: new THREE.Texture( <Image> ),
  12289. *
  12290. * alphaMap: new THREE.Texture( <Image> ),
  12291. *
  12292. * displacementMap: new THREE.Texture( <Image> ),
  12293. * displacementScale: <float>,
  12294. * displacementBias: <float>
  12295. *
  12296. * }
  12297. */
  12298. class MeshDistanceMaterial extends Material {
  12299. constructor(parameters) {
  12300. super();
  12301. this.type = 'MeshDistanceMaterial';
  12302. this.referencePosition = new Vector3();
  12303. this.nearDistance = 1;
  12304. this.farDistance = 1000;
  12305. this.map = null;
  12306. this.alphaMap = null;
  12307. this.displacementMap = null;
  12308. this.displacementScale = 1;
  12309. this.displacementBias = 0;
  12310. this.fog = false;
  12311. this.setValues(parameters);
  12312. }
  12313. copy(source) {
  12314. super.copy(source);
  12315. this.referencePosition.copy(source.referencePosition);
  12316. this.nearDistance = source.nearDistance;
  12317. this.farDistance = source.farDistance;
  12318. this.map = source.map;
  12319. this.alphaMap = source.alphaMap;
  12320. this.displacementMap = source.displacementMap;
  12321. this.displacementScale = source.displacementScale;
  12322. this.displacementBias = source.displacementBias;
  12323. return this;
  12324. }
  12325. }
  12326. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  12327. var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\nuniform float samples;\n#include <packing>\nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  12328. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12329. function WebGLShadowMap(_renderer, _objects, _capabilities) {
  12330. let _frustum = new Frustum();
  12331. const _shadowMapSize = new Vector2(),
  12332. _viewportSize = new Vector2(),
  12333. _viewport = new Vector4(),
  12334. _depthMaterial = new MeshDepthMaterial({
  12335. depthPacking: RGBADepthPacking
  12336. }),
  12337. _distanceMaterial = new MeshDistanceMaterial(),
  12338. _materialCache = {},
  12339. _maxTextureSize = _capabilities.maxTextureSize;
  12340. const shadowSide = {
  12341. 0: BackSide,
  12342. 1: FrontSide,
  12343. 2: DoubleSide
  12344. };
  12345. const shadowMaterialVertical = new ShaderMaterial({
  12346. uniforms: {
  12347. shadow_pass: {
  12348. value: null
  12349. },
  12350. resolution: {
  12351. value: new Vector2()
  12352. },
  12353. radius: {
  12354. value: 4.0
  12355. },
  12356. samples: {
  12357. value: 8.0
  12358. }
  12359. },
  12360. vertexShader: vsm_vert,
  12361. fragmentShader: vsm_frag
  12362. });
  12363. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12364. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12365. const fullScreenTri = new BufferGeometry();
  12366. fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  12367. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  12368. const scope = this;
  12369. this.enabled = false;
  12370. this.autoUpdate = true;
  12371. this.needsUpdate = false;
  12372. this.type = PCFShadowMap;
  12373. this.render = function (lights, scene, camera) {
  12374. if (scope.enabled === false) return;
  12375. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  12376. if (lights.length === 0) return;
  12377. const currentRenderTarget = _renderer.getRenderTarget();
  12378. const activeCubeFace = _renderer.getActiveCubeFace();
  12379. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12380. const _state = _renderer.state; // Set GL state for depth map.
  12381. _state.setBlending(NoBlending);
  12382. _state.buffers.color.setClear(1, 1, 1, 1);
  12383. _state.buffers.depth.setTest(true);
  12384. _state.setScissorTest(false); // render depth map
  12385. for (let i = 0, il = lights.length; i < il; i++) {
  12386. const light = lights[i];
  12387. const shadow = light.shadow;
  12388. if (shadow === undefined) {
  12389. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  12390. continue;
  12391. }
  12392. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  12393. _shadowMapSize.copy(shadow.mapSize);
  12394. const shadowFrameExtents = shadow.getFrameExtents();
  12395. _shadowMapSize.multiply(shadowFrameExtents);
  12396. _viewportSize.copy(shadow.mapSize);
  12397. if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) {
  12398. if (_shadowMapSize.x > _maxTextureSize) {
  12399. _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x);
  12400. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12401. shadow.mapSize.x = _viewportSize.x;
  12402. }
  12403. if (_shadowMapSize.y > _maxTextureSize) {
  12404. _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y);
  12405. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12406. shadow.mapSize.y = _viewportSize.y;
  12407. }
  12408. }
  12409. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12410. const pars = {
  12411. minFilter: LinearFilter,
  12412. magFilter: LinearFilter,
  12413. format: RGBAFormat
  12414. };
  12415. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12416. shadow.map.texture.name = light.name + '.shadowMap';
  12417. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12418. shadow.camera.updateProjectionMatrix();
  12419. }
  12420. if (shadow.map === null) {
  12421. const pars = {
  12422. minFilter: NearestFilter,
  12423. magFilter: NearestFilter,
  12424. format: RGBAFormat
  12425. };
  12426. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12427. shadow.map.texture.name = light.name + '.shadowMap';
  12428. shadow.camera.updateProjectionMatrix();
  12429. }
  12430. _renderer.setRenderTarget(shadow.map);
  12431. _renderer.clear();
  12432. const viewportCount = shadow.getViewportCount();
  12433. for (let vp = 0; vp < viewportCount; vp++) {
  12434. const viewport = shadow.getViewport(vp);
  12435. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  12436. _state.viewport(_viewport);
  12437. shadow.updateMatrices(light, vp);
  12438. _frustum = shadow.getFrustum();
  12439. renderObject(scene, camera, shadow.camera, light, this.type);
  12440. } // do blur pass for VSM
  12441. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12442. VSMPass(shadow, camera);
  12443. }
  12444. shadow.needsUpdate = false;
  12445. }
  12446. scope.needsUpdate = false;
  12447. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  12448. };
  12449. function VSMPass(shadow, camera) {
  12450. const geometry = _objects.update(fullScreenMesh); // vertical pass
  12451. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12452. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12453. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12454. shadowMaterialVertical.uniforms.samples.value = shadow.blurSamples;
  12455. _renderer.setRenderTarget(shadow.mapPass);
  12456. _renderer.clear();
  12457. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizontal pass
  12458. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12459. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12460. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12461. shadowMaterialHorizontal.uniforms.samples.value = shadow.blurSamples;
  12462. _renderer.setRenderTarget(shadow.map);
  12463. _renderer.clear();
  12464. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  12465. }
  12466. function getDepthMaterial(object, geometry, material, light, shadowCameraNear, shadowCameraFar, type) {
  12467. let result = null;
  12468. const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial;
  12469. if (customMaterial !== undefined) {
  12470. result = customMaterial;
  12471. } else {
  12472. result = light.isPointLight === true ? _distanceMaterial : _depthMaterial;
  12473. }
  12474. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0) {
  12475. // in this case we need a unique material instance reflecting the
  12476. // appropriate state
  12477. const keyA = result.uuid,
  12478. keyB = material.uuid;
  12479. let materialsForVariant = _materialCache[keyA];
  12480. if (materialsForVariant === undefined) {
  12481. materialsForVariant = {};
  12482. _materialCache[keyA] = materialsForVariant;
  12483. }
  12484. let cachedMaterial = materialsForVariant[keyB];
  12485. if (cachedMaterial === undefined) {
  12486. cachedMaterial = result.clone();
  12487. materialsForVariant[keyB] = cachedMaterial;
  12488. }
  12489. result = cachedMaterial;
  12490. }
  12491. result.visible = material.visible;
  12492. result.wireframe = material.wireframe;
  12493. if (type === VSMShadowMap) {
  12494. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  12495. } else {
  12496. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  12497. }
  12498. result.alphaMap = material.alphaMap;
  12499. result.alphaTest = material.alphaTest;
  12500. result.clipShadows = material.clipShadows;
  12501. result.clippingPlanes = material.clippingPlanes;
  12502. result.clipIntersection = material.clipIntersection;
  12503. result.displacementMap = material.displacementMap;
  12504. result.displacementScale = material.displacementScale;
  12505. result.displacementBias = material.displacementBias;
  12506. result.wireframeLinewidth = material.wireframeLinewidth;
  12507. result.linewidth = material.linewidth;
  12508. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  12509. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  12510. result.nearDistance = shadowCameraNear;
  12511. result.farDistance = shadowCameraFar;
  12512. }
  12513. return result;
  12514. }
  12515. function renderObject(object, camera, shadowCamera, light, type) {
  12516. if (object.visible === false) return;
  12517. const visible = object.layers.test(camera.layers);
  12518. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  12519. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  12520. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  12521. const geometry = _objects.update(object);
  12522. const material = object.material;
  12523. if (Array.isArray(material)) {
  12524. const groups = geometry.groups;
  12525. for (let k = 0, kl = groups.length; k < kl; k++) {
  12526. const group = groups[k];
  12527. const groupMaterial = material[group.materialIndex];
  12528. if (groupMaterial && groupMaterial.visible) {
  12529. const depthMaterial = getDepthMaterial(object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  12530. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  12531. }
  12532. }
  12533. } else if (material.visible) {
  12534. const depthMaterial = getDepthMaterial(object, geometry, material, light, shadowCamera.near, shadowCamera.far, type);
  12535. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  12536. }
  12537. }
  12538. }
  12539. const children = object.children;
  12540. for (let i = 0, l = children.length; i < l; i++) {
  12541. renderObject(children[i], camera, shadowCamera, light, type);
  12542. }
  12543. }
  12544. }
  12545. function WebGLState(gl, extensions, capabilities) {
  12546. const isWebGL2 = capabilities.isWebGL2;
  12547. function ColorBuffer() {
  12548. let locked = false;
  12549. const color = new Vector4();
  12550. let currentColorMask = null;
  12551. const currentColorClear = new Vector4(0, 0, 0, 0);
  12552. return {
  12553. setMask: function (colorMask) {
  12554. if (currentColorMask !== colorMask && !locked) {
  12555. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  12556. currentColorMask = colorMask;
  12557. }
  12558. },
  12559. setLocked: function (lock) {
  12560. locked = lock;
  12561. },
  12562. setClear: function (r, g, b, a, premultipliedAlpha) {
  12563. if (premultipliedAlpha === true) {
  12564. r *= a;
  12565. g *= a;
  12566. b *= a;
  12567. }
  12568. color.set(r, g, b, a);
  12569. if (currentColorClear.equals(color) === false) {
  12570. gl.clearColor(r, g, b, a);
  12571. currentColorClear.copy(color);
  12572. }
  12573. },
  12574. reset: function () {
  12575. locked = false;
  12576. currentColorMask = null;
  12577. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  12578. }
  12579. };
  12580. }
  12581. function DepthBuffer() {
  12582. let locked = false;
  12583. let currentDepthMask = null;
  12584. let currentDepthFunc = null;
  12585. let currentDepthClear = null;
  12586. return {
  12587. setTest: function (depthTest) {
  12588. if (depthTest) {
  12589. enable(gl.DEPTH_TEST);
  12590. } else {
  12591. disable(gl.DEPTH_TEST);
  12592. }
  12593. },
  12594. setMask: function (depthMask) {
  12595. if (currentDepthMask !== depthMask && !locked) {
  12596. gl.depthMask(depthMask);
  12597. currentDepthMask = depthMask;
  12598. }
  12599. },
  12600. setFunc: function (depthFunc) {
  12601. if (currentDepthFunc !== depthFunc) {
  12602. if (depthFunc) {
  12603. switch (depthFunc) {
  12604. case NeverDepth:
  12605. gl.depthFunc(gl.NEVER);
  12606. break;
  12607. case AlwaysDepth:
  12608. gl.depthFunc(gl.ALWAYS);
  12609. break;
  12610. case LessDepth:
  12611. gl.depthFunc(gl.LESS);
  12612. break;
  12613. case LessEqualDepth:
  12614. gl.depthFunc(gl.LEQUAL);
  12615. break;
  12616. case EqualDepth:
  12617. gl.depthFunc(gl.EQUAL);
  12618. break;
  12619. case GreaterEqualDepth:
  12620. gl.depthFunc(gl.GEQUAL);
  12621. break;
  12622. case GreaterDepth:
  12623. gl.depthFunc(gl.GREATER);
  12624. break;
  12625. case NotEqualDepth:
  12626. gl.depthFunc(gl.NOTEQUAL);
  12627. break;
  12628. default:
  12629. gl.depthFunc(gl.LEQUAL);
  12630. }
  12631. } else {
  12632. gl.depthFunc(gl.LEQUAL);
  12633. }
  12634. currentDepthFunc = depthFunc;
  12635. }
  12636. },
  12637. setLocked: function (lock) {
  12638. locked = lock;
  12639. },
  12640. setClear: function (depth) {
  12641. if (currentDepthClear !== depth) {
  12642. gl.clearDepth(depth);
  12643. currentDepthClear = depth;
  12644. }
  12645. },
  12646. reset: function () {
  12647. locked = false;
  12648. currentDepthMask = null;
  12649. currentDepthFunc = null;
  12650. currentDepthClear = null;
  12651. }
  12652. };
  12653. }
  12654. function StencilBuffer() {
  12655. let locked = false;
  12656. let currentStencilMask = null;
  12657. let currentStencilFunc = null;
  12658. let currentStencilRef = null;
  12659. let currentStencilFuncMask = null;
  12660. let currentStencilFail = null;
  12661. let currentStencilZFail = null;
  12662. let currentStencilZPass = null;
  12663. let currentStencilClear = null;
  12664. return {
  12665. setTest: function (stencilTest) {
  12666. if (!locked) {
  12667. if (stencilTest) {
  12668. enable(gl.STENCIL_TEST);
  12669. } else {
  12670. disable(gl.STENCIL_TEST);
  12671. }
  12672. }
  12673. },
  12674. setMask: function (stencilMask) {
  12675. if (currentStencilMask !== stencilMask && !locked) {
  12676. gl.stencilMask(stencilMask);
  12677. currentStencilMask = stencilMask;
  12678. }
  12679. },
  12680. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  12681. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  12682. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  12683. currentStencilFunc = stencilFunc;
  12684. currentStencilRef = stencilRef;
  12685. currentStencilFuncMask = stencilMask;
  12686. }
  12687. },
  12688. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  12689. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  12690. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  12691. currentStencilFail = stencilFail;
  12692. currentStencilZFail = stencilZFail;
  12693. currentStencilZPass = stencilZPass;
  12694. }
  12695. },
  12696. setLocked: function (lock) {
  12697. locked = lock;
  12698. },
  12699. setClear: function (stencil) {
  12700. if (currentStencilClear !== stencil) {
  12701. gl.clearStencil(stencil);
  12702. currentStencilClear = stencil;
  12703. }
  12704. },
  12705. reset: function () {
  12706. locked = false;
  12707. currentStencilMask = null;
  12708. currentStencilFunc = null;
  12709. currentStencilRef = null;
  12710. currentStencilFuncMask = null;
  12711. currentStencilFail = null;
  12712. currentStencilZFail = null;
  12713. currentStencilZPass = null;
  12714. currentStencilClear = null;
  12715. }
  12716. };
  12717. } //
  12718. const colorBuffer = new ColorBuffer();
  12719. const depthBuffer = new DepthBuffer();
  12720. const stencilBuffer = new StencilBuffer();
  12721. let enabledCapabilities = {};
  12722. let xrFramebuffer = null;
  12723. let currentBoundFramebuffers = {};
  12724. let currentProgram = null;
  12725. let currentBlendingEnabled = false;
  12726. let currentBlending = null;
  12727. let currentBlendEquation = null;
  12728. let currentBlendSrc = null;
  12729. let currentBlendDst = null;
  12730. let currentBlendEquationAlpha = null;
  12731. let currentBlendSrcAlpha = null;
  12732. let currentBlendDstAlpha = null;
  12733. let currentPremultipledAlpha = false;
  12734. let currentFlipSided = null;
  12735. let currentCullFace = null;
  12736. let currentLineWidth = null;
  12737. let currentPolygonOffsetFactor = null;
  12738. let currentPolygonOffsetUnits = null;
  12739. const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12740. let lineWidthAvailable = false;
  12741. let version = 0;
  12742. const glVersion = gl.getParameter(gl.VERSION);
  12743. if (glVersion.indexOf('WebGL') !== -1) {
  12744. version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
  12745. lineWidthAvailable = version >= 1.0;
  12746. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  12747. version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
  12748. lineWidthAvailable = version >= 2.0;
  12749. }
  12750. let currentTextureSlot = null;
  12751. let currentBoundTextures = {};
  12752. const scissorParam = gl.getParameter(gl.SCISSOR_BOX);
  12753. const viewportParam = gl.getParameter(gl.VIEWPORT);
  12754. const currentScissor = new Vector4().fromArray(scissorParam);
  12755. const currentViewport = new Vector4().fromArray(viewportParam);
  12756. function createTexture(type, target, count) {
  12757. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  12758. const texture = gl.createTexture();
  12759. gl.bindTexture(type, texture);
  12760. gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12761. gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12762. for (let i = 0; i < count; i++) {
  12763. gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
  12764. }
  12765. return texture;
  12766. }
  12767. const emptyTextures = {};
  12768. emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1);
  12769. emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); // init
  12770. colorBuffer.setClear(0, 0, 0, 1);
  12771. depthBuffer.setClear(1);
  12772. stencilBuffer.setClear(0);
  12773. enable(gl.DEPTH_TEST);
  12774. depthBuffer.setFunc(LessEqualDepth);
  12775. setFlipSided(false);
  12776. setCullFace(CullFaceBack);
  12777. enable(gl.CULL_FACE);
  12778. setBlending(NoBlending); //
  12779. function enable(id) {
  12780. if (enabledCapabilities[id] !== true) {
  12781. gl.enable(id);
  12782. enabledCapabilities[id] = true;
  12783. }
  12784. }
  12785. function disable(id) {
  12786. if (enabledCapabilities[id] !== false) {
  12787. gl.disable(id);
  12788. enabledCapabilities[id] = false;
  12789. }
  12790. }
  12791. function bindXRFramebuffer(framebuffer) {
  12792. if (framebuffer !== xrFramebuffer) {
  12793. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  12794. xrFramebuffer = framebuffer;
  12795. }
  12796. }
  12797. function bindFramebuffer(target, framebuffer) {
  12798. if (framebuffer === null && xrFramebuffer !== null) framebuffer = xrFramebuffer; // use active XR framebuffer if available
  12799. if (currentBoundFramebuffers[target] !== framebuffer) {
  12800. gl.bindFramebuffer(target, framebuffer);
  12801. currentBoundFramebuffers[target] = framebuffer;
  12802. if (isWebGL2) {
  12803. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  12804. if (target === gl.DRAW_FRAMEBUFFER) {
  12805. currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer;
  12806. }
  12807. if (target === gl.FRAMEBUFFER) {
  12808. currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer;
  12809. }
  12810. }
  12811. return true;
  12812. }
  12813. return false;
  12814. }
  12815. function useProgram(program) {
  12816. if (currentProgram !== program) {
  12817. gl.useProgram(program);
  12818. currentProgram = program;
  12819. return true;
  12820. }
  12821. return false;
  12822. }
  12823. const equationToGL = {
  12824. [AddEquation]: gl.FUNC_ADD,
  12825. [SubtractEquation]: gl.FUNC_SUBTRACT,
  12826. [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT
  12827. };
  12828. if (isWebGL2) {
  12829. equationToGL[MinEquation] = gl.MIN;
  12830. equationToGL[MaxEquation] = gl.MAX;
  12831. } else {
  12832. const extension = extensions.get('EXT_blend_minmax');
  12833. if (extension !== null) {
  12834. equationToGL[MinEquation] = extension.MIN_EXT;
  12835. equationToGL[MaxEquation] = extension.MAX_EXT;
  12836. }
  12837. }
  12838. const factorToGL = {
  12839. [ZeroFactor]: gl.ZERO,
  12840. [OneFactor]: gl.ONE,
  12841. [SrcColorFactor]: gl.SRC_COLOR,
  12842. [SrcAlphaFactor]: gl.SRC_ALPHA,
  12843. [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE,
  12844. [DstColorFactor]: gl.DST_COLOR,
  12845. [DstAlphaFactor]: gl.DST_ALPHA,
  12846. [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR,
  12847. [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA,
  12848. [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR,
  12849. [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA
  12850. };
  12851. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  12852. if (blending === NoBlending) {
  12853. if (currentBlendingEnabled === true) {
  12854. disable(gl.BLEND);
  12855. currentBlendingEnabled = false;
  12856. }
  12857. return;
  12858. }
  12859. if (currentBlendingEnabled === false) {
  12860. enable(gl.BLEND);
  12861. currentBlendingEnabled = true;
  12862. }
  12863. if (blending !== CustomBlending) {
  12864. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  12865. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  12866. gl.blendEquation(gl.FUNC_ADD);
  12867. currentBlendEquation = AddEquation;
  12868. currentBlendEquationAlpha = AddEquation;
  12869. }
  12870. if (premultipliedAlpha) {
  12871. switch (blending) {
  12872. case NormalBlending:
  12873. gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  12874. break;
  12875. case AdditiveBlending:
  12876. gl.blendFunc(gl.ONE, gl.ONE);
  12877. break;
  12878. case SubtractiveBlending:
  12879. gl.blendFuncSeparate(gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA);
  12880. break;
  12881. case MultiplyBlending:
  12882. gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA);
  12883. break;
  12884. default:
  12885. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12886. break;
  12887. }
  12888. } else {
  12889. switch (blending) {
  12890. case NormalBlending:
  12891. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  12892. break;
  12893. case AdditiveBlending:
  12894. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  12895. break;
  12896. case SubtractiveBlending:
  12897. gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_COLOR);
  12898. break;
  12899. case MultiplyBlending:
  12900. gl.blendFunc(gl.ZERO, gl.SRC_COLOR);
  12901. break;
  12902. default:
  12903. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12904. break;
  12905. }
  12906. }
  12907. currentBlendSrc = null;
  12908. currentBlendDst = null;
  12909. currentBlendSrcAlpha = null;
  12910. currentBlendDstAlpha = null;
  12911. currentBlending = blending;
  12912. currentPremultipledAlpha = premultipliedAlpha;
  12913. }
  12914. return;
  12915. } // custom blending
  12916. blendEquationAlpha = blendEquationAlpha || blendEquation;
  12917. blendSrcAlpha = blendSrcAlpha || blendSrc;
  12918. blendDstAlpha = blendDstAlpha || blendDst;
  12919. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  12920. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  12921. currentBlendEquation = blendEquation;
  12922. currentBlendEquationAlpha = blendEquationAlpha;
  12923. }
  12924. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  12925. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  12926. currentBlendSrc = blendSrc;
  12927. currentBlendDst = blendDst;
  12928. currentBlendSrcAlpha = blendSrcAlpha;
  12929. currentBlendDstAlpha = blendDstAlpha;
  12930. }
  12931. currentBlending = blending;
  12932. currentPremultipledAlpha = null;
  12933. }
  12934. function setMaterial(material, frontFaceCW) {
  12935. material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE);
  12936. let flipSided = material.side === BackSide;
  12937. if (frontFaceCW) flipSided = !flipSided;
  12938. setFlipSided(flipSided);
  12939. material.blending === NormalBlending && material.transparent === false ? setBlending(NoBlending) : setBlending(material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha);
  12940. depthBuffer.setFunc(material.depthFunc);
  12941. depthBuffer.setTest(material.depthTest);
  12942. depthBuffer.setMask(material.depthWrite);
  12943. colorBuffer.setMask(material.colorWrite);
  12944. const stencilWrite = material.stencilWrite;
  12945. stencilBuffer.setTest(stencilWrite);
  12946. if (stencilWrite) {
  12947. stencilBuffer.setMask(material.stencilWriteMask);
  12948. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  12949. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  12950. }
  12951. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  12952. material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  12953. } //
  12954. function setFlipSided(flipSided) {
  12955. if (currentFlipSided !== flipSided) {
  12956. if (flipSided) {
  12957. gl.frontFace(gl.CW);
  12958. } else {
  12959. gl.frontFace(gl.CCW);
  12960. }
  12961. currentFlipSided = flipSided;
  12962. }
  12963. }
  12964. function setCullFace(cullFace) {
  12965. if (cullFace !== CullFaceNone) {
  12966. enable(gl.CULL_FACE);
  12967. if (cullFace !== currentCullFace) {
  12968. if (cullFace === CullFaceBack) {
  12969. gl.cullFace(gl.BACK);
  12970. } else if (cullFace === CullFaceFront) {
  12971. gl.cullFace(gl.FRONT);
  12972. } else {
  12973. gl.cullFace(gl.FRONT_AND_BACK);
  12974. }
  12975. }
  12976. } else {
  12977. disable(gl.CULL_FACE);
  12978. }
  12979. currentCullFace = cullFace;
  12980. }
  12981. function setLineWidth(width) {
  12982. if (width !== currentLineWidth) {
  12983. if (lineWidthAvailable) gl.lineWidth(width);
  12984. currentLineWidth = width;
  12985. }
  12986. }
  12987. function setPolygonOffset(polygonOffset, factor, units) {
  12988. if (polygonOffset) {
  12989. enable(gl.POLYGON_OFFSET_FILL);
  12990. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  12991. gl.polygonOffset(factor, units);
  12992. currentPolygonOffsetFactor = factor;
  12993. currentPolygonOffsetUnits = units;
  12994. }
  12995. } else {
  12996. disable(gl.POLYGON_OFFSET_FILL);
  12997. }
  12998. }
  12999. function setScissorTest(scissorTest) {
  13000. if (scissorTest) {
  13001. enable(gl.SCISSOR_TEST);
  13002. } else {
  13003. disable(gl.SCISSOR_TEST);
  13004. }
  13005. } // texture
  13006. function activeTexture(webglSlot) {
  13007. if (webglSlot === undefined) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13008. if (currentTextureSlot !== webglSlot) {
  13009. gl.activeTexture(webglSlot);
  13010. currentTextureSlot = webglSlot;
  13011. }
  13012. }
  13013. function bindTexture(webglType, webglTexture) {
  13014. if (currentTextureSlot === null) {
  13015. activeTexture();
  13016. }
  13017. let boundTexture = currentBoundTextures[currentTextureSlot];
  13018. if (boundTexture === undefined) {
  13019. boundTexture = {
  13020. type: undefined,
  13021. texture: undefined
  13022. };
  13023. currentBoundTextures[currentTextureSlot] = boundTexture;
  13024. }
  13025. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  13026. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  13027. boundTexture.type = webglType;
  13028. boundTexture.texture = webglTexture;
  13029. }
  13030. }
  13031. function unbindTexture() {
  13032. const boundTexture = currentBoundTextures[currentTextureSlot];
  13033. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  13034. gl.bindTexture(boundTexture.type, null);
  13035. boundTexture.type = undefined;
  13036. boundTexture.texture = undefined;
  13037. }
  13038. }
  13039. function compressedTexImage2D() {
  13040. try {
  13041. gl.compressedTexImage2D.apply(gl, arguments);
  13042. } catch (error) {
  13043. console.error('THREE.WebGLState:', error);
  13044. }
  13045. }
  13046. function texImage2D() {
  13047. try {
  13048. gl.texImage2D.apply(gl, arguments);
  13049. } catch (error) {
  13050. console.error('THREE.WebGLState:', error);
  13051. }
  13052. }
  13053. function texImage3D() {
  13054. try {
  13055. gl.texImage3D.apply(gl, arguments);
  13056. } catch (error) {
  13057. console.error('THREE.WebGLState:', error);
  13058. }
  13059. } //
  13060. function scissor(scissor) {
  13061. if (currentScissor.equals(scissor) === false) {
  13062. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  13063. currentScissor.copy(scissor);
  13064. }
  13065. }
  13066. function viewport(viewport) {
  13067. if (currentViewport.equals(viewport) === false) {
  13068. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  13069. currentViewport.copy(viewport);
  13070. }
  13071. } //
  13072. function reset() {
  13073. // reset state
  13074. gl.disable(gl.BLEND);
  13075. gl.disable(gl.CULL_FACE);
  13076. gl.disable(gl.DEPTH_TEST);
  13077. gl.disable(gl.POLYGON_OFFSET_FILL);
  13078. gl.disable(gl.SCISSOR_TEST);
  13079. gl.disable(gl.STENCIL_TEST);
  13080. gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13081. gl.blendEquation(gl.FUNC_ADD);
  13082. gl.blendFunc(gl.ONE, gl.ZERO);
  13083. gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
  13084. gl.colorMask(true, true, true, true);
  13085. gl.clearColor(0, 0, 0, 0);
  13086. gl.depthMask(true);
  13087. gl.depthFunc(gl.LESS);
  13088. gl.clearDepth(1);
  13089. gl.stencilMask(0xffffffff);
  13090. gl.stencilFunc(gl.ALWAYS, 0, 0xffffffff);
  13091. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  13092. gl.clearStencil(0);
  13093. gl.cullFace(gl.BACK);
  13094. gl.frontFace(gl.CCW);
  13095. gl.polygonOffset(0, 0);
  13096. gl.activeTexture(gl.TEXTURE0);
  13097. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13098. if (isWebGL2 === true) {
  13099. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  13100. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  13101. }
  13102. gl.useProgram(null);
  13103. gl.lineWidth(1);
  13104. gl.scissor(0, 0, gl.canvas.width, gl.canvas.height);
  13105. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); // reset internals
  13106. enabledCapabilities = {};
  13107. currentTextureSlot = null;
  13108. currentBoundTextures = {};
  13109. xrFramebuffer = null;
  13110. currentBoundFramebuffers = {};
  13111. currentProgram = null;
  13112. currentBlendingEnabled = false;
  13113. currentBlending = null;
  13114. currentBlendEquation = null;
  13115. currentBlendSrc = null;
  13116. currentBlendDst = null;
  13117. currentBlendEquationAlpha = null;
  13118. currentBlendSrcAlpha = null;
  13119. currentBlendDstAlpha = null;
  13120. currentPremultipledAlpha = false;
  13121. currentFlipSided = null;
  13122. currentCullFace = null;
  13123. currentLineWidth = null;
  13124. currentPolygonOffsetFactor = null;
  13125. currentPolygonOffsetUnits = null;
  13126. currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height);
  13127. currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height);
  13128. colorBuffer.reset();
  13129. depthBuffer.reset();
  13130. stencilBuffer.reset();
  13131. }
  13132. return {
  13133. buffers: {
  13134. color: colorBuffer,
  13135. depth: depthBuffer,
  13136. stencil: stencilBuffer
  13137. },
  13138. enable: enable,
  13139. disable: disable,
  13140. bindFramebuffer: bindFramebuffer,
  13141. bindXRFramebuffer: bindXRFramebuffer,
  13142. useProgram: useProgram,
  13143. setBlending: setBlending,
  13144. setMaterial: setMaterial,
  13145. setFlipSided: setFlipSided,
  13146. setCullFace: setCullFace,
  13147. setLineWidth: setLineWidth,
  13148. setPolygonOffset: setPolygonOffset,
  13149. setScissorTest: setScissorTest,
  13150. activeTexture: activeTexture,
  13151. bindTexture: bindTexture,
  13152. unbindTexture: unbindTexture,
  13153. compressedTexImage2D: compressedTexImage2D,
  13154. texImage2D: texImage2D,
  13155. texImage3D: texImage3D,
  13156. scissor: scissor,
  13157. viewport: viewport,
  13158. reset: reset
  13159. };
  13160. }
  13161. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  13162. const isWebGL2 = capabilities.isWebGL2;
  13163. const maxTextures = capabilities.maxTextures;
  13164. const maxCubemapSize = capabilities.maxCubemapSize;
  13165. const maxTextureSize = capabilities.maxTextureSize;
  13166. const maxSamples = capabilities.maxSamples;
  13167. const _videoTextures = new WeakMap();
  13168. let _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13169. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13170. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13171. let useOffscreenCanvas = false;
  13172. try {
  13173. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext('2d') !== null;
  13174. } catch (err) {// Ignore any errors
  13175. }
  13176. function createCanvas(width, height) {
  13177. // Use OffscreenCanvas when available. Specially needed in web workers
  13178. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  13179. }
  13180. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  13181. let scale = 1; // handle case if texture exceeds max size
  13182. if (image.width > maxSize || image.height > maxSize) {
  13183. scale = maxSize / Math.max(image.width, image.height);
  13184. } // only perform resize if necessary
  13185. if (scale < 1 || needsPowerOfTwo === true) {
  13186. // only perform resize for certain image types
  13187. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  13188. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13189. const width = floor(scale * image.width);
  13190. const height = floor(scale * image.height);
  13191. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  13192. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  13193. canvas.width = width;
  13194. canvas.height = height;
  13195. const context = canvas.getContext('2d');
  13196. context.drawImage(image, 0, 0, width, height);
  13197. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  13198. return canvas;
  13199. } else {
  13200. if ('data' in image) {
  13201. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  13202. }
  13203. return image;
  13204. }
  13205. }
  13206. return image;
  13207. }
  13208. function isPowerOfTwo$1(image) {
  13209. return isPowerOfTwo(image.width) && isPowerOfTwo(image.height);
  13210. }
  13211. function textureNeedsPowerOfTwo(texture) {
  13212. if (isWebGL2) return false;
  13213. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13214. }
  13215. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  13216. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13217. }
  13218. function generateMipmap(target, texture, width, height, depth = 1) {
  13219. _gl.generateMipmap(target);
  13220. const textureProperties = properties.get(texture);
  13221. textureProperties.__maxMipLevel = Math.log2(Math.max(width, height, depth));
  13222. }
  13223. function getInternalFormat(internalFormatName, glFormat, glType) {
  13224. if (isWebGL2 === false) return glFormat;
  13225. if (internalFormatName !== null) {
  13226. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  13227. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  13228. }
  13229. let internalFormat = glFormat;
  13230. if (glFormat === _gl.RED) {
  13231. if (glType === _gl.FLOAT) internalFormat = _gl.R32F;
  13232. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F;
  13233. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8;
  13234. }
  13235. if (glFormat === _gl.RGB) {
  13236. if (glType === _gl.FLOAT) internalFormat = _gl.RGB32F;
  13237. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGB16F;
  13238. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGB8;
  13239. }
  13240. if (glFormat === _gl.RGBA) {
  13241. if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
  13242. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
  13243. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGBA8;
  13244. }
  13245. if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) {
  13246. extensions.get('EXT_color_buffer_float');
  13247. }
  13248. return internalFormat;
  13249. } // Fallback filters for non-power-of-2 textures
  13250. function filterFallback(f) {
  13251. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  13252. return _gl.NEAREST;
  13253. }
  13254. return _gl.LINEAR;
  13255. } //
  13256. function onTextureDispose(event) {
  13257. const texture = event.target;
  13258. texture.removeEventListener('dispose', onTextureDispose);
  13259. deallocateTexture(texture);
  13260. if (texture.isVideoTexture) {
  13261. _videoTextures.delete(texture);
  13262. }
  13263. info.memory.textures--;
  13264. }
  13265. function onRenderTargetDispose(event) {
  13266. const renderTarget = event.target;
  13267. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  13268. deallocateRenderTarget(renderTarget);
  13269. } //
  13270. function deallocateTexture(texture) {
  13271. const textureProperties = properties.get(texture);
  13272. if (textureProperties.__webglInit === undefined) return;
  13273. _gl.deleteTexture(textureProperties.__webglTexture);
  13274. properties.remove(texture);
  13275. }
  13276. function deallocateRenderTarget(renderTarget) {
  13277. const texture = renderTarget.texture;
  13278. const renderTargetProperties = properties.get(renderTarget);
  13279. const textureProperties = properties.get(texture);
  13280. if (!renderTarget) return;
  13281. if (textureProperties.__webglTexture !== undefined) {
  13282. _gl.deleteTexture(textureProperties.__webglTexture);
  13283. info.memory.textures--;
  13284. }
  13285. if (renderTarget.depthTexture) {
  13286. renderTarget.depthTexture.dispose();
  13287. }
  13288. if (renderTarget.isWebGLCubeRenderTarget) {
  13289. for (let i = 0; i < 6; i++) {
  13290. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  13291. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  13292. }
  13293. } else {
  13294. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  13295. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  13296. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  13297. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  13298. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  13299. }
  13300. if (renderTarget.isWebGLMultipleRenderTargets) {
  13301. for (let i = 0, il = texture.length; i < il; i++) {
  13302. const attachmentProperties = properties.get(texture[i]);
  13303. if (attachmentProperties.__webglTexture) {
  13304. _gl.deleteTexture(attachmentProperties.__webglTexture);
  13305. info.memory.textures--;
  13306. }
  13307. properties.remove(texture[i]);
  13308. }
  13309. }
  13310. properties.remove(texture);
  13311. properties.remove(renderTarget);
  13312. } //
  13313. let textureUnits = 0;
  13314. function resetTextureUnits() {
  13315. textureUnits = 0;
  13316. }
  13317. function allocateTextureUnit() {
  13318. const textureUnit = textureUnits;
  13319. if (textureUnit >= maxTextures) {
  13320. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  13321. }
  13322. textureUnits += 1;
  13323. return textureUnit;
  13324. } //
  13325. function setTexture2D(texture, slot) {
  13326. const textureProperties = properties.get(texture);
  13327. if (texture.isVideoTexture) updateVideoTexture(texture);
  13328. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13329. const image = texture.image;
  13330. if (image === undefined) {
  13331. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  13332. } else if (image.complete === false) {
  13333. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  13334. } else {
  13335. uploadTexture(textureProperties, texture, slot);
  13336. return;
  13337. }
  13338. }
  13339. state.activeTexture(_gl.TEXTURE0 + slot);
  13340. state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture);
  13341. }
  13342. function setTexture2DArray(texture, slot) {
  13343. const textureProperties = properties.get(texture);
  13344. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13345. uploadTexture(textureProperties, texture, slot);
  13346. return;
  13347. }
  13348. state.activeTexture(_gl.TEXTURE0 + slot);
  13349. state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture);
  13350. }
  13351. function setTexture3D(texture, slot) {
  13352. const textureProperties = properties.get(texture);
  13353. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13354. uploadTexture(textureProperties, texture, slot);
  13355. return;
  13356. }
  13357. state.activeTexture(_gl.TEXTURE0 + slot);
  13358. state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture);
  13359. }
  13360. function setTextureCube(texture, slot) {
  13361. const textureProperties = properties.get(texture);
  13362. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13363. uploadCubeTexture(textureProperties, texture, slot);
  13364. return;
  13365. }
  13366. state.activeTexture(_gl.TEXTURE0 + slot);
  13367. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13368. }
  13369. const wrappingToGL = {
  13370. [RepeatWrapping]: _gl.REPEAT,
  13371. [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE,
  13372. [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT
  13373. };
  13374. const filterToGL = {
  13375. [NearestFilter]: _gl.NEAREST,
  13376. [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST,
  13377. [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR,
  13378. [LinearFilter]: _gl.LINEAR,
  13379. [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST,
  13380. [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR
  13381. };
  13382. function setTextureParameters(textureType, texture, supportsMips) {
  13383. if (supportsMips) {
  13384. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]);
  13385. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]);
  13386. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  13387. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]);
  13388. }
  13389. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]);
  13390. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]);
  13391. } else {
  13392. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE);
  13393. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE);
  13394. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  13395. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE);
  13396. }
  13397. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  13398. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  13399. }
  13400. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter));
  13401. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter));
  13402. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13403. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  13404. }
  13405. }
  13406. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  13407. const extension = extensions.get('EXT_texture_filter_anisotropic');
  13408. if (texture.type === FloatType && extensions.has('OES_texture_float_linear') === false) return; // verify extension for WebGL 1 and WebGL 2
  13409. if (isWebGL2 === false && texture.type === HalfFloatType && extensions.has('OES_texture_half_float_linear') === false) return; // verify extension for WebGL 1 only
  13410. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  13411. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  13412. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  13413. }
  13414. }
  13415. }
  13416. function initTexture(textureProperties, texture) {
  13417. if (textureProperties.__webglInit === undefined) {
  13418. textureProperties.__webglInit = true;
  13419. texture.addEventListener('dispose', onTextureDispose);
  13420. textureProperties.__webglTexture = _gl.createTexture();
  13421. info.memory.textures++;
  13422. }
  13423. }
  13424. function uploadTexture(textureProperties, texture, slot) {
  13425. let textureType = _gl.TEXTURE_2D;
  13426. if (texture.isDataTexture2DArray) textureType = _gl.TEXTURE_2D_ARRAY;
  13427. if (texture.isDataTexture3D) textureType = _gl.TEXTURE_3D;
  13428. initTexture(textureProperties, texture);
  13429. state.activeTexture(_gl.TEXTURE0 + slot);
  13430. state.bindTexture(textureType, textureProperties.__webglTexture);
  13431. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  13432. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  13433. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  13434. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  13435. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false;
  13436. const image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  13437. const supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  13438. glFormat = utils.convert(texture.format);
  13439. let glType = utils.convert(texture.type),
  13440. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13441. setTextureParameters(textureType, texture, supportsMips);
  13442. let mipmap;
  13443. const mipmaps = texture.mipmaps;
  13444. if (texture.isDepthTexture) {
  13445. // populate depth texture with dummy data
  13446. glInternalFormat = _gl.DEPTH_COMPONENT;
  13447. if (isWebGL2) {
  13448. if (texture.type === FloatType) {
  13449. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  13450. } else if (texture.type === UnsignedIntType) {
  13451. glInternalFormat = _gl.DEPTH_COMPONENT24;
  13452. } else if (texture.type === UnsignedInt248Type) {
  13453. glInternalFormat = _gl.DEPTH24_STENCIL8;
  13454. } else {
  13455. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  13456. }
  13457. } else {
  13458. if (texture.type === FloatType) {
  13459. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  13460. }
  13461. } // validation checks for WebGL 1
  13462. if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  13463. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13464. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13465. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13466. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  13467. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  13468. texture.type = UnsignedShortType;
  13469. glType = utils.convert(texture.type);
  13470. }
  13471. }
  13472. if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  13473. // Depth stencil textures need the DEPTH_STENCIL internal format
  13474. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13475. glInternalFormat = _gl.DEPTH_STENCIL; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13476. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13477. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13478. if (texture.type !== UnsignedInt248Type) {
  13479. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  13480. texture.type = UnsignedInt248Type;
  13481. glType = utils.convert(texture.type);
  13482. }
  13483. } //
  13484. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  13485. } else if (texture.isDataTexture) {
  13486. // use manually created mipmaps if available
  13487. // if there are no manual mipmaps
  13488. // set 0 level mipmap and then use GL to generate other mipmap levels
  13489. if (mipmaps.length > 0 && supportsMips) {
  13490. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13491. mipmap = mipmaps[i];
  13492. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13493. }
  13494. texture.generateMipmaps = false;
  13495. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13496. } else {
  13497. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  13498. textureProperties.__maxMipLevel = 0;
  13499. }
  13500. } else if (texture.isCompressedTexture) {
  13501. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13502. mipmap = mipmaps[i];
  13503. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13504. if (glFormat !== null) {
  13505. state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13506. } else {
  13507. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  13508. }
  13509. } else {
  13510. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13511. }
  13512. }
  13513. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13514. } else if (texture.isDataTexture2DArray) {
  13515. state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13516. textureProperties.__maxMipLevel = 0;
  13517. } else if (texture.isDataTexture3D) {
  13518. state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13519. textureProperties.__maxMipLevel = 0;
  13520. } else {
  13521. // regular Texture (image, video, canvas)
  13522. // use manually created mipmaps if available
  13523. // if there are no manual mipmaps
  13524. // set 0 level mipmap and then use GL to generate other mipmap levels
  13525. if (mipmaps.length > 0 && supportsMips) {
  13526. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13527. mipmap = mipmaps[i];
  13528. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap);
  13529. }
  13530. texture.generateMipmaps = false;
  13531. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13532. } else {
  13533. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image);
  13534. textureProperties.__maxMipLevel = 0;
  13535. }
  13536. }
  13537. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13538. generateMipmap(textureType, texture, image.width, image.height);
  13539. }
  13540. textureProperties.__version = texture.version;
  13541. if (texture.onUpdate) texture.onUpdate(texture);
  13542. }
  13543. function uploadCubeTexture(textureProperties, texture, slot) {
  13544. if (texture.image.length !== 6) return;
  13545. initTexture(textureProperties, texture);
  13546. state.activeTexture(_gl.TEXTURE0 + slot);
  13547. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13548. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  13549. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  13550. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  13551. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  13552. const isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
  13553. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  13554. const cubeImage = [];
  13555. for (let i = 0; i < 6; i++) {
  13556. if (!isCompressed && !isDataTexture) {
  13557. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  13558. } else {
  13559. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  13560. }
  13561. }
  13562. const image = cubeImage[0],
  13563. supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  13564. glFormat = utils.convert(texture.format),
  13565. glType = utils.convert(texture.type),
  13566. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13567. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  13568. let mipmaps;
  13569. if (isCompressed) {
  13570. for (let i = 0; i < 6; i++) {
  13571. mipmaps = cubeImage[i].mipmaps;
  13572. for (let j = 0; j < mipmaps.length; j++) {
  13573. const mipmap = mipmaps[j];
  13574. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13575. if (glFormat !== null) {
  13576. state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13577. } else {
  13578. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  13579. }
  13580. } else {
  13581. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13582. }
  13583. }
  13584. }
  13585. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13586. } else {
  13587. mipmaps = texture.mipmaps;
  13588. for (let i = 0; i < 6; i++) {
  13589. if (isDataTexture) {
  13590. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  13591. for (let j = 0; j < mipmaps.length; j++) {
  13592. const mipmap = mipmaps[j];
  13593. const mipmapImage = mipmap.image[i].image;
  13594. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  13595. }
  13596. } else {
  13597. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  13598. for (let j = 0; j < mipmaps.length; j++) {
  13599. const mipmap = mipmaps[j];
  13600. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  13601. }
  13602. }
  13603. }
  13604. textureProperties.__maxMipLevel = mipmaps.length;
  13605. }
  13606. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13607. // We assume images for cube map have the same size.
  13608. generateMipmap(_gl.TEXTURE_CUBE_MAP, texture, image.width, image.height);
  13609. }
  13610. textureProperties.__version = texture.version;
  13611. if (texture.onUpdate) texture.onUpdate(texture);
  13612. } // Render targets
  13613. // Setup storage for target texture and bind it to correct framebuffer
  13614. function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) {
  13615. const glFormat = utils.convert(texture.format);
  13616. const glType = utils.convert(texture.type);
  13617. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13618. if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) {
  13619. state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null);
  13620. } else {
  13621. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  13622. }
  13623. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  13624. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0);
  13625. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  13626. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  13627. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  13628. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
  13629. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  13630. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  13631. if (isMultisample) {
  13632. const depthTexture = renderTarget.depthTexture;
  13633. if (depthTexture && depthTexture.isDepthTexture) {
  13634. if (depthTexture.type === FloatType) {
  13635. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  13636. } else if (depthTexture.type === UnsignedIntType) {
  13637. glInternalFormat = _gl.DEPTH_COMPONENT24;
  13638. }
  13639. }
  13640. const samples = getRenderTargetSamples(renderTarget);
  13641. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13642. } else {
  13643. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  13644. }
  13645. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  13646. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  13647. if (isMultisample) {
  13648. const samples = getRenderTargetSamples(renderTarget);
  13649. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  13650. } else {
  13651. _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height);
  13652. }
  13653. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  13654. } else {
  13655. // Use the first texture for MRT so far
  13656. const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[0] : renderTarget.texture;
  13657. const glFormat = utils.convert(texture.format);
  13658. const glType = utils.convert(texture.type);
  13659. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13660. if (isMultisample) {
  13661. const samples = getRenderTargetSamples(renderTarget);
  13662. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13663. } else {
  13664. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  13665. }
  13666. }
  13667. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  13668. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  13669. function setupDepthTexture(framebuffer, renderTarget) {
  13670. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  13671. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  13672. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  13673. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  13674. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  13675. } // upload an empty depth texture with framebuffer size
  13676. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  13677. renderTarget.depthTexture.image.width = renderTarget.width;
  13678. renderTarget.depthTexture.image.height = renderTarget.height;
  13679. renderTarget.depthTexture.needsUpdate = true;
  13680. }
  13681. setTexture2D(renderTarget.depthTexture, 0);
  13682. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  13683. if (renderTarget.depthTexture.format === DepthFormat) {
  13684. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  13685. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  13686. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  13687. } else {
  13688. throw new Error('Unknown depthTexture format');
  13689. }
  13690. } // Setup GL resources for a non-texture depth buffer
  13691. function setupDepthRenderbuffer(renderTarget) {
  13692. const renderTargetProperties = properties.get(renderTarget);
  13693. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  13694. if (renderTarget.depthTexture) {
  13695. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  13696. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  13697. } else {
  13698. if (isCube) {
  13699. renderTargetProperties.__webglDepthbuffer = [];
  13700. for (let i = 0; i < 6; i++) {
  13701. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]);
  13702. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  13703. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  13704. }
  13705. } else {
  13706. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  13707. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  13708. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  13709. }
  13710. }
  13711. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  13712. } // Set up GL resources for the render target
  13713. function setupRenderTarget(renderTarget) {
  13714. const texture = renderTarget.texture;
  13715. const renderTargetProperties = properties.get(renderTarget);
  13716. const textureProperties = properties.get(texture);
  13717. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  13718. if (renderTarget.isWebGLMultipleRenderTargets !== true) {
  13719. textureProperties.__webglTexture = _gl.createTexture();
  13720. textureProperties.__version = texture.version;
  13721. info.memory.textures++;
  13722. }
  13723. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  13724. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
  13725. const isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  13726. const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
  13727. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
  13728. if (isWebGL2 && texture.format === RGBFormat && (texture.type === FloatType || texture.type === HalfFloatType)) {
  13729. texture.format = RGBAFormat;
  13730. console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
  13731. } // Setup framebuffer
  13732. if (isCube) {
  13733. renderTargetProperties.__webglFramebuffer = [];
  13734. for (let i = 0; i < 6; i++) {
  13735. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  13736. }
  13737. } else {
  13738. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  13739. if (isMultipleRenderTargets) {
  13740. if (capabilities.drawBuffers) {
  13741. const textures = renderTarget.texture;
  13742. for (let i = 0, il = textures.length; i < il; i++) {
  13743. const attachmentProperties = properties.get(textures[i]);
  13744. if (attachmentProperties.__webglTexture === undefined) {
  13745. attachmentProperties.__webglTexture = _gl.createTexture();
  13746. info.memory.textures++;
  13747. }
  13748. }
  13749. } else {
  13750. console.warn('THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.');
  13751. }
  13752. } else if (isMultisample) {
  13753. if (isWebGL2) {
  13754. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  13755. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  13756. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  13757. const glFormat = utils.convert(texture.format);
  13758. const glType = utils.convert(texture.type);
  13759. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13760. const samples = getRenderTargetSamples(renderTarget);
  13761. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13762. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13763. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  13764. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  13765. if (renderTarget.depthBuffer) {
  13766. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  13767. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  13768. }
  13769. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  13770. } else {
  13771. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13772. }
  13773. }
  13774. } // Setup color buffer
  13775. if (isCube) {
  13776. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13777. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  13778. for (let i = 0; i < 6; i++) {
  13779. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i);
  13780. }
  13781. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13782. generateMipmap(_gl.TEXTURE_CUBE_MAP, texture, renderTarget.width, renderTarget.height);
  13783. }
  13784. state.unbindTexture();
  13785. } else if (isMultipleRenderTargets) {
  13786. const textures = renderTarget.texture;
  13787. for (let i = 0, il = textures.length; i < il; i++) {
  13788. const attachment = textures[i];
  13789. const attachmentProperties = properties.get(attachment);
  13790. state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture);
  13791. setTextureParameters(_gl.TEXTURE_2D, attachment, supportsMips);
  13792. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D);
  13793. if (textureNeedsGenerateMipmaps(attachment, supportsMips)) {
  13794. generateMipmap(_gl.TEXTURE_2D, attachment, renderTarget.width, renderTarget.height);
  13795. }
  13796. }
  13797. state.unbindTexture();
  13798. } else {
  13799. let glTextureType = _gl.TEXTURE_2D;
  13800. if (isRenderTarget3D) {
  13801. // Render targets containing layers, i.e: Texture 3D and 2d arrays
  13802. if (isWebGL2) {
  13803. const isTexture3D = texture.isDataTexture3D;
  13804. glTextureType = isTexture3D ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  13805. } else {
  13806. console.warn('THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.');
  13807. }
  13808. }
  13809. state.bindTexture(glTextureType, textureProperties.__webglTexture);
  13810. setTextureParameters(glTextureType, texture, supportsMips);
  13811. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType);
  13812. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13813. generateMipmap(glTextureType, texture, renderTarget.width, renderTarget.height, renderTarget.depth);
  13814. }
  13815. state.unbindTexture();
  13816. } // Setup depth and stencil buffers
  13817. if (renderTarget.depthBuffer) {
  13818. setupDepthRenderbuffer(renderTarget);
  13819. }
  13820. }
  13821. function updateRenderTargetMipmap(renderTarget) {
  13822. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
  13823. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  13824. for (let i = 0, il = textures.length; i < il; i++) {
  13825. const texture = textures[i];
  13826. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13827. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  13828. const webglTexture = properties.get(texture).__webglTexture;
  13829. state.bindTexture(target, webglTexture);
  13830. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  13831. state.unbindTexture();
  13832. }
  13833. }
  13834. }
  13835. function updateMultisampleRenderTarget(renderTarget) {
  13836. if (renderTarget.isWebGLMultisampleRenderTarget) {
  13837. if (isWebGL2) {
  13838. const width = renderTarget.width;
  13839. const height = renderTarget.height;
  13840. let mask = _gl.COLOR_BUFFER_BIT;
  13841. if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT;
  13842. if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT;
  13843. const renderTargetProperties = properties.get(renderTarget);
  13844. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13845. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  13846. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST);
  13847. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
  13848. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13849. } else {
  13850. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13851. }
  13852. }
  13853. }
  13854. function getRenderTargetSamples(renderTarget) {
  13855. return isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(maxSamples, renderTarget.samples) : 0;
  13856. }
  13857. function updateVideoTexture(texture) {
  13858. const frame = info.render.frame; // Check the last frame we updated the VideoTexture
  13859. if (_videoTextures.get(texture) !== frame) {
  13860. _videoTextures.set(texture, frame);
  13861. texture.update();
  13862. }
  13863. } // backwards compatibility
  13864. let warnedTexture2D = false;
  13865. let warnedTextureCube = false;
  13866. function safeSetTexture2D(texture, slot) {
  13867. if (texture && texture.isWebGLRenderTarget) {
  13868. if (warnedTexture2D === false) {
  13869. console.warn('THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.');
  13870. warnedTexture2D = true;
  13871. }
  13872. texture = texture.texture;
  13873. }
  13874. setTexture2D(texture, slot);
  13875. }
  13876. function safeSetTextureCube(texture, slot) {
  13877. if (texture && texture.isWebGLCubeRenderTarget) {
  13878. if (warnedTextureCube === false) {
  13879. console.warn('THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.');
  13880. warnedTextureCube = true;
  13881. }
  13882. texture = texture.texture;
  13883. }
  13884. setTextureCube(texture, slot);
  13885. } //
  13886. this.allocateTextureUnit = allocateTextureUnit;
  13887. this.resetTextureUnits = resetTextureUnits;
  13888. this.setTexture2D = setTexture2D;
  13889. this.setTexture2DArray = setTexture2DArray;
  13890. this.setTexture3D = setTexture3D;
  13891. this.setTextureCube = setTextureCube;
  13892. this.setupRenderTarget = setupRenderTarget;
  13893. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  13894. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  13895. this.safeSetTexture2D = safeSetTexture2D;
  13896. this.safeSetTextureCube = safeSetTextureCube;
  13897. }
  13898. function WebGLUtils(gl, extensions, capabilities) {
  13899. const isWebGL2 = capabilities.isWebGL2;
  13900. function convert(p) {
  13901. let extension;
  13902. if (p === UnsignedByteType) return gl.UNSIGNED_BYTE;
  13903. if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4;
  13904. if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1;
  13905. if (p === UnsignedShort565Type) return gl.UNSIGNED_SHORT_5_6_5;
  13906. if (p === ByteType) return gl.BYTE;
  13907. if (p === ShortType) return gl.SHORT;
  13908. if (p === UnsignedShortType) return gl.UNSIGNED_SHORT;
  13909. if (p === IntType) return gl.INT;
  13910. if (p === UnsignedIntType) return gl.UNSIGNED_INT;
  13911. if (p === FloatType) return gl.FLOAT;
  13912. if (p === HalfFloatType) {
  13913. if (isWebGL2) return gl.HALF_FLOAT;
  13914. extension = extensions.get('OES_texture_half_float');
  13915. if (extension !== null) {
  13916. return extension.HALF_FLOAT_OES;
  13917. } else {
  13918. return null;
  13919. }
  13920. }
  13921. if (p === AlphaFormat) return gl.ALPHA;
  13922. if (p === RGBFormat) return gl.RGB;
  13923. if (p === RGBAFormat) return gl.RGBA;
  13924. if (p === LuminanceFormat) return gl.LUMINANCE;
  13925. if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
  13926. if (p === DepthFormat) return gl.DEPTH_COMPONENT;
  13927. if (p === DepthStencilFormat) return gl.DEPTH_STENCIL;
  13928. if (p === RedFormat) return gl.RED; // WebGL2 formats.
  13929. if (p === RedIntegerFormat) return gl.RED_INTEGER;
  13930. if (p === RGFormat) return gl.RG;
  13931. if (p === RGIntegerFormat) return gl.RG_INTEGER;
  13932. if (p === RGBIntegerFormat) return gl.RGB_INTEGER;
  13933. if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER;
  13934. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  13935. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  13936. if (extension !== null) {
  13937. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13938. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13939. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13940. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13941. } else {
  13942. return null;
  13943. }
  13944. }
  13945. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  13946. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  13947. if (extension !== null) {
  13948. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13949. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13950. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13951. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13952. } else {
  13953. return null;
  13954. }
  13955. }
  13956. if (p === RGB_ETC1_Format) {
  13957. extension = extensions.get('WEBGL_compressed_texture_etc1');
  13958. if (extension !== null) {
  13959. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13960. } else {
  13961. return null;
  13962. }
  13963. }
  13964. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  13965. extension = extensions.get('WEBGL_compressed_texture_etc');
  13966. if (extension !== null) {
  13967. if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
  13968. if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  13969. }
  13970. }
  13971. if (p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format || p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format || p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format || p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format || p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format || p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format) {
  13972. extension = extensions.get('WEBGL_compressed_texture_astc');
  13973. if (extension !== null) {
  13974. // TODO Complete?
  13975. return p;
  13976. } else {
  13977. return null;
  13978. }
  13979. }
  13980. if (p === RGBA_BPTC_Format) {
  13981. extension = extensions.get('EXT_texture_compression_bptc');
  13982. if (extension !== null) {
  13983. // TODO Complete?
  13984. return p;
  13985. } else {
  13986. return null;
  13987. }
  13988. }
  13989. if (p === UnsignedInt248Type) {
  13990. if (isWebGL2) return gl.UNSIGNED_INT_24_8;
  13991. extension = extensions.get('WEBGL_depth_texture');
  13992. if (extension !== null) {
  13993. return extension.UNSIGNED_INT_24_8_WEBGL;
  13994. } else {
  13995. return null;
  13996. }
  13997. }
  13998. }
  13999. return {
  14000. convert: convert
  14001. };
  14002. }
  14003. class ArrayCamera extends PerspectiveCamera {
  14004. constructor(array = []) {
  14005. super();
  14006. this.cameras = array;
  14007. }
  14008. }
  14009. ArrayCamera.prototype.isArrayCamera = true;
  14010. class Group extends Object3D {
  14011. constructor() {
  14012. super();
  14013. this.type = 'Group';
  14014. }
  14015. }
  14016. Group.prototype.isGroup = true;
  14017. const _moveEvent = {
  14018. type: 'move'
  14019. };
  14020. class WebXRController {
  14021. constructor() {
  14022. this._targetRay = null;
  14023. this._grip = null;
  14024. this._hand = null;
  14025. }
  14026. getHandSpace() {
  14027. if (this._hand === null) {
  14028. this._hand = new Group();
  14029. this._hand.matrixAutoUpdate = false;
  14030. this._hand.visible = false;
  14031. this._hand.joints = {};
  14032. this._hand.inputState = {
  14033. pinching: false
  14034. };
  14035. }
  14036. return this._hand;
  14037. }
  14038. getTargetRaySpace() {
  14039. if (this._targetRay === null) {
  14040. this._targetRay = new Group();
  14041. this._targetRay.matrixAutoUpdate = false;
  14042. this._targetRay.visible = false;
  14043. this._targetRay.hasLinearVelocity = false;
  14044. this._targetRay.linearVelocity = new Vector3();
  14045. this._targetRay.hasAngularVelocity = false;
  14046. this._targetRay.angularVelocity = new Vector3();
  14047. }
  14048. return this._targetRay;
  14049. }
  14050. getGripSpace() {
  14051. if (this._grip === null) {
  14052. this._grip = new Group();
  14053. this._grip.matrixAutoUpdate = false;
  14054. this._grip.visible = false;
  14055. this._grip.hasLinearVelocity = false;
  14056. this._grip.linearVelocity = new Vector3();
  14057. this._grip.hasAngularVelocity = false;
  14058. this._grip.angularVelocity = new Vector3();
  14059. }
  14060. return this._grip;
  14061. }
  14062. dispatchEvent(event) {
  14063. if (this._targetRay !== null) {
  14064. this._targetRay.dispatchEvent(event);
  14065. }
  14066. if (this._grip !== null) {
  14067. this._grip.dispatchEvent(event);
  14068. }
  14069. if (this._hand !== null) {
  14070. this._hand.dispatchEvent(event);
  14071. }
  14072. return this;
  14073. }
  14074. disconnect(inputSource) {
  14075. this.dispatchEvent({
  14076. type: 'disconnected',
  14077. data: inputSource
  14078. });
  14079. if (this._targetRay !== null) {
  14080. this._targetRay.visible = false;
  14081. }
  14082. if (this._grip !== null) {
  14083. this._grip.visible = false;
  14084. }
  14085. if (this._hand !== null) {
  14086. this._hand.visible = false;
  14087. }
  14088. return this;
  14089. }
  14090. update(inputSource, frame, referenceSpace) {
  14091. let inputPose = null;
  14092. let gripPose = null;
  14093. let handPose = null;
  14094. const targetRay = this._targetRay;
  14095. const grip = this._grip;
  14096. const hand = this._hand;
  14097. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  14098. if (targetRay !== null) {
  14099. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  14100. if (inputPose !== null) {
  14101. targetRay.matrix.fromArray(inputPose.transform.matrix);
  14102. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  14103. if (inputPose.linearVelocity) {
  14104. targetRay.hasLinearVelocity = true;
  14105. targetRay.linearVelocity.copy(inputPose.linearVelocity);
  14106. } else {
  14107. targetRay.hasLinearVelocity = false;
  14108. }
  14109. if (inputPose.angularVelocity) {
  14110. targetRay.hasAngularVelocity = true;
  14111. targetRay.angularVelocity.copy(inputPose.angularVelocity);
  14112. } else {
  14113. targetRay.hasAngularVelocity = false;
  14114. }
  14115. this.dispatchEvent(_moveEvent);
  14116. }
  14117. }
  14118. if (hand && inputSource.hand) {
  14119. handPose = true;
  14120. for (const inputjoint of inputSource.hand.values()) {
  14121. // Update the joints groups with the XRJoint poses
  14122. const jointPose = frame.getJointPose(inputjoint, referenceSpace);
  14123. if (hand.joints[inputjoint.jointName] === undefined) {
  14124. // The transform of this joint will be updated with the joint pose on each frame
  14125. const joint = new Group();
  14126. joint.matrixAutoUpdate = false;
  14127. joint.visible = false;
  14128. hand.joints[inputjoint.jointName] = joint; // ??
  14129. hand.add(joint);
  14130. }
  14131. const joint = hand.joints[inputjoint.jointName];
  14132. if (jointPose !== null) {
  14133. joint.matrix.fromArray(jointPose.transform.matrix);
  14134. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  14135. joint.jointRadius = jointPose.radius;
  14136. }
  14137. joint.visible = jointPose !== null;
  14138. } // Custom events
  14139. // Check pinchz
  14140. const indexTip = hand.joints['index-finger-tip'];
  14141. const thumbTip = hand.joints['thumb-tip'];
  14142. const distance = indexTip.position.distanceTo(thumbTip.position);
  14143. const distanceToPinch = 0.02;
  14144. const threshold = 0.005;
  14145. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  14146. hand.inputState.pinching = false;
  14147. this.dispatchEvent({
  14148. type: 'pinchend',
  14149. handedness: inputSource.handedness,
  14150. target: this
  14151. });
  14152. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  14153. hand.inputState.pinching = true;
  14154. this.dispatchEvent({
  14155. type: 'pinchstart',
  14156. handedness: inputSource.handedness,
  14157. target: this
  14158. });
  14159. }
  14160. } else {
  14161. if (grip !== null && inputSource.gripSpace) {
  14162. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  14163. if (gripPose !== null) {
  14164. grip.matrix.fromArray(gripPose.transform.matrix);
  14165. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  14166. if (gripPose.linearVelocity) {
  14167. grip.hasLinearVelocity = true;
  14168. grip.linearVelocity.copy(gripPose.linearVelocity);
  14169. } else {
  14170. grip.hasLinearVelocity = false;
  14171. }
  14172. if (gripPose.angularVelocity) {
  14173. grip.hasAngularVelocity = true;
  14174. grip.angularVelocity.copy(gripPose.angularVelocity);
  14175. } else {
  14176. grip.hasAngularVelocity = false;
  14177. }
  14178. }
  14179. }
  14180. }
  14181. }
  14182. if (targetRay !== null) {
  14183. targetRay.visible = inputPose !== null;
  14184. }
  14185. if (grip !== null) {
  14186. grip.visible = gripPose !== null;
  14187. }
  14188. if (hand !== null) {
  14189. hand.visible = handPose !== null;
  14190. }
  14191. return this;
  14192. }
  14193. }
  14194. class WebXRManager extends EventDispatcher {
  14195. constructor(renderer, gl) {
  14196. super();
  14197. const scope = this;
  14198. const state = renderer.state;
  14199. let session = null;
  14200. let framebufferScaleFactor = 1.0;
  14201. let referenceSpace = null;
  14202. let referenceSpaceType = 'local-floor';
  14203. let pose = null;
  14204. let glBinding = null;
  14205. let glFramebuffer = null;
  14206. let glProjLayer = null;
  14207. let glBaseLayer = null;
  14208. let isMultisample = false;
  14209. let glMultisampledFramebuffer = null;
  14210. let glColorRenderbuffer = null;
  14211. let glDepthRenderbuffer = null;
  14212. let xrFrame = null;
  14213. let depthStyle = null;
  14214. let clearStyle = null;
  14215. const controllers = [];
  14216. const inputSourcesMap = new Map(); //
  14217. const cameraL = new PerspectiveCamera();
  14218. cameraL.layers.enable(1);
  14219. cameraL.viewport = new Vector4();
  14220. const cameraR = new PerspectiveCamera();
  14221. cameraR.layers.enable(2);
  14222. cameraR.viewport = new Vector4();
  14223. const cameras = [cameraL, cameraR];
  14224. const cameraVR = new ArrayCamera();
  14225. cameraVR.layers.enable(1);
  14226. cameraVR.layers.enable(2);
  14227. let _currentDepthNear = null;
  14228. let _currentDepthFar = null; //
  14229. this.cameraAutoUpdate = true;
  14230. this.enabled = false;
  14231. this.isPresenting = false;
  14232. this.getController = function (index) {
  14233. let controller = controllers[index];
  14234. if (controller === undefined) {
  14235. controller = new WebXRController();
  14236. controllers[index] = controller;
  14237. }
  14238. return controller.getTargetRaySpace();
  14239. };
  14240. this.getControllerGrip = function (index) {
  14241. let controller = controllers[index];
  14242. if (controller === undefined) {
  14243. controller = new WebXRController();
  14244. controllers[index] = controller;
  14245. }
  14246. return controller.getGripSpace();
  14247. };
  14248. this.getHand = function (index) {
  14249. let controller = controllers[index];
  14250. if (controller === undefined) {
  14251. controller = new WebXRController();
  14252. controllers[index] = controller;
  14253. }
  14254. return controller.getHandSpace();
  14255. }; //
  14256. function onSessionEvent(event) {
  14257. const controller = inputSourcesMap.get(event.inputSource);
  14258. if (controller) {
  14259. controller.dispatchEvent({
  14260. type: event.type,
  14261. data: event.inputSource
  14262. });
  14263. }
  14264. }
  14265. function onSessionEnd() {
  14266. inputSourcesMap.forEach(function (controller, inputSource) {
  14267. controller.disconnect(inputSource);
  14268. });
  14269. inputSourcesMap.clear();
  14270. _currentDepthNear = null;
  14271. _currentDepthFar = null; // restore framebuffer/rendering state
  14272. state.bindXRFramebuffer(null);
  14273. renderer.setRenderTarget(renderer.getRenderTarget());
  14274. if (glFramebuffer) gl.deleteFramebuffer(glFramebuffer);
  14275. if (glMultisampledFramebuffer) gl.deleteFramebuffer(glMultisampledFramebuffer);
  14276. if (glColorRenderbuffer) gl.deleteRenderbuffer(glColorRenderbuffer);
  14277. if (glDepthRenderbuffer) gl.deleteRenderbuffer(glDepthRenderbuffer);
  14278. glFramebuffer = null;
  14279. glMultisampledFramebuffer = null;
  14280. glColorRenderbuffer = null;
  14281. glDepthRenderbuffer = null;
  14282. glBaseLayer = null;
  14283. glProjLayer = null;
  14284. glBinding = null;
  14285. session = null; //
  14286. animation.stop();
  14287. scope.isPresenting = false;
  14288. scope.dispatchEvent({
  14289. type: 'sessionend'
  14290. });
  14291. }
  14292. this.setFramebufferScaleFactor = function (value) {
  14293. framebufferScaleFactor = value;
  14294. if (scope.isPresenting === true) {
  14295. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  14296. }
  14297. };
  14298. this.setReferenceSpaceType = function (value) {
  14299. referenceSpaceType = value;
  14300. if (scope.isPresenting === true) {
  14301. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  14302. }
  14303. };
  14304. this.getReferenceSpace = function () {
  14305. return referenceSpace;
  14306. };
  14307. this.getBaseLayer = function () {
  14308. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  14309. };
  14310. this.getBinding = function () {
  14311. return glBinding;
  14312. };
  14313. this.getFrame = function () {
  14314. return xrFrame;
  14315. };
  14316. this.getSession = function () {
  14317. return session;
  14318. };
  14319. this.setSession = async function (value) {
  14320. session = value;
  14321. if (session !== null) {
  14322. session.addEventListener('select', onSessionEvent);
  14323. session.addEventListener('selectstart', onSessionEvent);
  14324. session.addEventListener('selectend', onSessionEvent);
  14325. session.addEventListener('squeeze', onSessionEvent);
  14326. session.addEventListener('squeezestart', onSessionEvent);
  14327. session.addEventListener('squeezeend', onSessionEvent);
  14328. session.addEventListener('end', onSessionEnd);
  14329. session.addEventListener('inputsourceschange', onInputSourcesChange);
  14330. const attributes = gl.getContextAttributes();
  14331. if (attributes.xrCompatible !== true) {
  14332. await gl.makeXRCompatible();
  14333. }
  14334. if (session.renderState.layers === undefined) {
  14335. const layerInit = {
  14336. antialias: attributes.antialias,
  14337. alpha: attributes.alpha,
  14338. depth: attributes.depth,
  14339. stencil: attributes.stencil,
  14340. framebufferScaleFactor: framebufferScaleFactor
  14341. };
  14342. glBaseLayer = new XRWebGLLayer(session, gl, layerInit);
  14343. session.updateRenderState({
  14344. baseLayer: glBaseLayer
  14345. });
  14346. } else if (gl instanceof WebGLRenderingContext) {
  14347. // Use old style webgl layer because we can't use MSAA
  14348. // WebGL2 support.
  14349. const layerInit = {
  14350. antialias: true,
  14351. alpha: attributes.alpha,
  14352. depth: attributes.depth,
  14353. stencil: attributes.stencil,
  14354. framebufferScaleFactor: framebufferScaleFactor
  14355. };
  14356. glBaseLayer = new XRWebGLLayer(session, gl, layerInit);
  14357. session.updateRenderState({
  14358. layers: [glBaseLayer]
  14359. });
  14360. } else {
  14361. isMultisample = attributes.antialias;
  14362. let depthFormat = null;
  14363. if (attributes.depth) {
  14364. clearStyle = gl.DEPTH_BUFFER_BIT;
  14365. if (attributes.stencil) clearStyle |= gl.STENCIL_BUFFER_BIT;
  14366. depthStyle = attributes.stencil ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  14367. depthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  14368. }
  14369. const projectionlayerInit = {
  14370. colorFormat: attributes.alpha ? gl.RGBA8 : gl.RGB8,
  14371. depthFormat: depthFormat,
  14372. scaleFactor: framebufferScaleFactor
  14373. };
  14374. glBinding = new XRWebGLBinding(session, gl);
  14375. glProjLayer = glBinding.createProjectionLayer(projectionlayerInit);
  14376. glFramebuffer = gl.createFramebuffer();
  14377. session.updateRenderState({
  14378. layers: [glProjLayer]
  14379. });
  14380. if (isMultisample) {
  14381. glMultisampledFramebuffer = gl.createFramebuffer();
  14382. glColorRenderbuffer = gl.createRenderbuffer();
  14383. gl.bindRenderbuffer(gl.RENDERBUFFER, glColorRenderbuffer);
  14384. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, 4, gl.RGBA8, glProjLayer.textureWidth, glProjLayer.textureHeight);
  14385. state.bindFramebuffer(gl.FRAMEBUFFER, glMultisampledFramebuffer);
  14386. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, glColorRenderbuffer);
  14387. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14388. if (depthFormat !== null) {
  14389. glDepthRenderbuffer = gl.createRenderbuffer();
  14390. gl.bindRenderbuffer(gl.RENDERBUFFER, glDepthRenderbuffer);
  14391. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, 4, depthFormat, glProjLayer.textureWidth, glProjLayer.textureHeight);
  14392. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, glDepthRenderbuffer);
  14393. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14394. }
  14395. state.bindFramebuffer(gl.FRAMEBUFFER, null);
  14396. }
  14397. }
  14398. referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
  14399. animation.setContext(session);
  14400. animation.start();
  14401. scope.isPresenting = true;
  14402. scope.dispatchEvent({
  14403. type: 'sessionstart'
  14404. });
  14405. }
  14406. };
  14407. function onInputSourcesChange(event) {
  14408. const inputSources = session.inputSources; // Assign inputSources to available controllers
  14409. for (let i = 0; i < controllers.length; i++) {
  14410. inputSourcesMap.set(inputSources[i], controllers[i]);
  14411. } // Notify disconnected
  14412. for (let i = 0; i < event.removed.length; i++) {
  14413. const inputSource = event.removed[i];
  14414. const controller = inputSourcesMap.get(inputSource);
  14415. if (controller) {
  14416. controller.dispatchEvent({
  14417. type: 'disconnected',
  14418. data: inputSource
  14419. });
  14420. inputSourcesMap.delete(inputSource);
  14421. }
  14422. } // Notify connected
  14423. for (let i = 0; i < event.added.length; i++) {
  14424. const inputSource = event.added[i];
  14425. const controller = inputSourcesMap.get(inputSource);
  14426. if (controller) {
  14427. controller.dispatchEvent({
  14428. type: 'connected',
  14429. data: inputSource
  14430. });
  14431. }
  14432. }
  14433. } //
  14434. const cameraLPos = new Vector3();
  14435. const cameraRPos = new Vector3();
  14436. /**
  14437. * Assumes 2 cameras that are parallel and share an X-axis, and that
  14438. * the cameras' projection and world matrices have already been set.
  14439. * And that near and far planes are identical for both cameras.
  14440. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  14441. */
  14442. function setProjectionFromUnion(camera, cameraL, cameraR) {
  14443. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  14444. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  14445. const ipd = cameraLPos.distanceTo(cameraRPos);
  14446. const projL = cameraL.projectionMatrix.elements;
  14447. const projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  14448. // most likely identical top and bottom frustum extents.
  14449. // Use the left camera for these values.
  14450. const near = projL[14] / (projL[10] - 1);
  14451. const far = projL[14] / (projL[10] + 1);
  14452. const topFov = (projL[9] + 1) / projL[5];
  14453. const bottomFov = (projL[9] - 1) / projL[5];
  14454. const leftFov = (projL[8] - 1) / projL[0];
  14455. const rightFov = (projR[8] + 1) / projR[0];
  14456. const left = near * leftFov;
  14457. const right = near * rightFov; // Calculate the new camera's position offset from the
  14458. // left camera. xOffset should be roughly half `ipd`.
  14459. const zOffset = ipd / (-leftFov + rightFov);
  14460. const xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  14461. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  14462. camera.translateX(xOffset);
  14463. camera.translateZ(zOffset);
  14464. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  14465. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  14466. // the values so that the near plane's position does not change in world space,
  14467. // although must now be relative to the new union camera.
  14468. const near2 = near + zOffset;
  14469. const far2 = far + zOffset;
  14470. const left2 = left - xOffset;
  14471. const right2 = right + (ipd - xOffset);
  14472. const top2 = topFov * far / far2 * near2;
  14473. const bottom2 = bottomFov * far / far2 * near2;
  14474. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  14475. }
  14476. function updateCamera(camera, parent) {
  14477. if (parent === null) {
  14478. camera.matrixWorld.copy(camera.matrix);
  14479. } else {
  14480. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  14481. }
  14482. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  14483. }
  14484. this.updateCamera = function (camera) {
  14485. if (session === null) return;
  14486. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  14487. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  14488. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  14489. // Note that the new renderState won't apply until the next frame. See #18320
  14490. session.updateRenderState({
  14491. depthNear: cameraVR.near,
  14492. depthFar: cameraVR.far
  14493. });
  14494. _currentDepthNear = cameraVR.near;
  14495. _currentDepthFar = cameraVR.far;
  14496. }
  14497. const parent = camera.parent;
  14498. const cameras = cameraVR.cameras;
  14499. updateCamera(cameraVR, parent);
  14500. for (let i = 0; i < cameras.length; i++) {
  14501. updateCamera(cameras[i], parent);
  14502. }
  14503. cameraVR.matrixWorld.decompose(cameraVR.position, cameraVR.quaternion, cameraVR.scale); // update user camera and its children
  14504. camera.position.copy(cameraVR.position);
  14505. camera.quaternion.copy(cameraVR.quaternion);
  14506. camera.scale.copy(cameraVR.scale);
  14507. camera.matrix.copy(cameraVR.matrix);
  14508. camera.matrixWorld.copy(cameraVR.matrixWorld);
  14509. const children = camera.children;
  14510. for (let i = 0, l = children.length; i < l; i++) {
  14511. children[i].updateMatrixWorld(true);
  14512. } // update projection matrix for proper view frustum culling
  14513. if (cameras.length === 2) {
  14514. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  14515. } else {
  14516. // assume single camera setup (AR)
  14517. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  14518. }
  14519. };
  14520. this.getCamera = function () {
  14521. return cameraVR;
  14522. };
  14523. this.getFoveation = function () {
  14524. if (glProjLayer !== null) {
  14525. return glProjLayer.fixedFoveation;
  14526. }
  14527. if (glBaseLayer !== null) {
  14528. return glBaseLayer.fixedFoveation;
  14529. }
  14530. return undefined;
  14531. };
  14532. this.setFoveation = function (foveation) {
  14533. // 0 = no foveation = full resolution
  14534. // 1 = maximum foveation = the edges render at lower resolution
  14535. if (glProjLayer !== null) {
  14536. glProjLayer.fixedFoveation = foveation;
  14537. }
  14538. if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined) {
  14539. glBaseLayer.fixedFoveation = foveation;
  14540. }
  14541. }; // Animation Loop
  14542. let onAnimationFrameCallback = null;
  14543. function onAnimationFrame(time, frame) {
  14544. pose = frame.getViewerPose(referenceSpace);
  14545. xrFrame = frame;
  14546. if (pose !== null) {
  14547. const views = pose.views;
  14548. if (glBaseLayer !== null) {
  14549. state.bindXRFramebuffer(glBaseLayer.framebuffer);
  14550. }
  14551. let cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  14552. if (views.length !== cameraVR.cameras.length) {
  14553. cameraVR.cameras.length = 0;
  14554. cameraVRNeedsUpdate = true;
  14555. }
  14556. for (let i = 0; i < views.length; i++) {
  14557. const view = views[i];
  14558. let viewport = null;
  14559. if (glBaseLayer !== null) {
  14560. viewport = glBaseLayer.getViewport(view);
  14561. } else {
  14562. const glSubImage = glBinding.getViewSubImage(glProjLayer, view);
  14563. state.bindXRFramebuffer(glFramebuffer);
  14564. if (glSubImage.depthStencilTexture !== undefined) {
  14565. gl.framebufferTexture2D(gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, glSubImage.depthStencilTexture, 0);
  14566. }
  14567. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, glSubImage.colorTexture, 0);
  14568. viewport = glSubImage.viewport;
  14569. }
  14570. const camera = cameras[i];
  14571. camera.matrix.fromArray(view.transform.matrix);
  14572. camera.projectionMatrix.fromArray(view.projectionMatrix);
  14573. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  14574. if (i === 0) {
  14575. cameraVR.matrix.copy(camera.matrix);
  14576. }
  14577. if (cameraVRNeedsUpdate === true) {
  14578. cameraVR.cameras.push(camera);
  14579. }
  14580. }
  14581. if (isMultisample) {
  14582. state.bindXRFramebuffer(glMultisampledFramebuffer);
  14583. if (clearStyle !== null) gl.clear(clearStyle);
  14584. }
  14585. } //
  14586. const inputSources = session.inputSources;
  14587. for (let i = 0; i < controllers.length; i++) {
  14588. const controller = controllers[i];
  14589. const inputSource = inputSources[i];
  14590. controller.update(inputSource, frame, referenceSpace);
  14591. }
  14592. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  14593. if (isMultisample) {
  14594. const width = glProjLayer.textureWidth;
  14595. const height = glProjLayer.textureHeight;
  14596. state.bindFramebuffer(gl.READ_FRAMEBUFFER, glMultisampledFramebuffer);
  14597. state.bindFramebuffer(gl.DRAW_FRAMEBUFFER, glFramebuffer); // Invalidate the depth here to avoid flush of the depth data to main memory.
  14598. gl.invalidateFramebuffer(gl.READ_FRAMEBUFFER, [depthStyle]);
  14599. gl.invalidateFramebuffer(gl.DRAW_FRAMEBUFFER, [depthStyle]);
  14600. gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST); // Invalidate the MSAA buffer because it's not needed anymore.
  14601. gl.invalidateFramebuffer(gl.READ_FRAMEBUFFER, [gl.COLOR_ATTACHMENT0]);
  14602. state.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  14603. state.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  14604. state.bindFramebuffer(gl.FRAMEBUFFER, glMultisampledFramebuffer);
  14605. }
  14606. xrFrame = null;
  14607. }
  14608. const animation = new WebGLAnimation();
  14609. animation.setAnimationLoop(onAnimationFrame);
  14610. this.setAnimationLoop = function (callback) {
  14611. onAnimationFrameCallback = callback;
  14612. };
  14613. this.dispose = function () {};
  14614. }
  14615. }
  14616. function WebGLMaterials(properties) {
  14617. function refreshFogUniforms(uniforms, fog) {
  14618. uniforms.fogColor.value.copy(fog.color);
  14619. if (fog.isFog) {
  14620. uniforms.fogNear.value = fog.near;
  14621. uniforms.fogFar.value = fog.far;
  14622. } else if (fog.isFogExp2) {
  14623. uniforms.fogDensity.value = fog.density;
  14624. }
  14625. }
  14626. function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) {
  14627. if (material.isMeshBasicMaterial) {
  14628. refreshUniformsCommon(uniforms, material);
  14629. } else if (material.isMeshLambertMaterial) {
  14630. refreshUniformsCommon(uniforms, material);
  14631. refreshUniformsLambert(uniforms, material);
  14632. } else if (material.isMeshToonMaterial) {
  14633. refreshUniformsCommon(uniforms, material);
  14634. refreshUniformsToon(uniforms, material);
  14635. } else if (material.isMeshPhongMaterial) {
  14636. refreshUniformsCommon(uniforms, material);
  14637. refreshUniformsPhong(uniforms, material);
  14638. } else if (material.isMeshStandardMaterial) {
  14639. refreshUniformsCommon(uniforms, material);
  14640. if (material.isMeshPhysicalMaterial) {
  14641. refreshUniformsPhysical(uniforms, material, transmissionRenderTarget);
  14642. } else {
  14643. refreshUniformsStandard(uniforms, material);
  14644. }
  14645. } else if (material.isMeshMatcapMaterial) {
  14646. refreshUniformsCommon(uniforms, material);
  14647. refreshUniformsMatcap(uniforms, material);
  14648. } else if (material.isMeshDepthMaterial) {
  14649. refreshUniformsCommon(uniforms, material);
  14650. refreshUniformsDepth(uniforms, material);
  14651. } else if (material.isMeshDistanceMaterial) {
  14652. refreshUniformsCommon(uniforms, material);
  14653. refreshUniformsDistance(uniforms, material);
  14654. } else if (material.isMeshNormalMaterial) {
  14655. refreshUniformsCommon(uniforms, material);
  14656. refreshUniformsNormal(uniforms, material);
  14657. } else if (material.isLineBasicMaterial) {
  14658. refreshUniformsLine(uniforms, material);
  14659. if (material.isLineDashedMaterial) {
  14660. refreshUniformsDash(uniforms, material);
  14661. }
  14662. } else if (material.isPointsMaterial) {
  14663. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  14664. } else if (material.isSpriteMaterial) {
  14665. refreshUniformsSprites(uniforms, material);
  14666. } else if (material.isShadowMaterial) {
  14667. uniforms.color.value.copy(material.color);
  14668. uniforms.opacity.value = material.opacity;
  14669. } else if (material.isShaderMaterial) {
  14670. material.uniformsNeedUpdate = false; // #15581
  14671. }
  14672. }
  14673. function refreshUniformsCommon(uniforms, material) {
  14674. uniforms.opacity.value = material.opacity;
  14675. if (material.color) {
  14676. uniforms.diffuse.value.copy(material.color);
  14677. }
  14678. if (material.emissive) {
  14679. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  14680. }
  14681. if (material.map) {
  14682. uniforms.map.value = material.map;
  14683. }
  14684. if (material.alphaMap) {
  14685. uniforms.alphaMap.value = material.alphaMap;
  14686. }
  14687. if (material.specularMap) {
  14688. uniforms.specularMap.value = material.specularMap;
  14689. }
  14690. if (material.alphaTest > 0) {
  14691. uniforms.alphaTest.value = material.alphaTest;
  14692. }
  14693. const envMap = properties.get(material).envMap;
  14694. if (envMap) {
  14695. uniforms.envMap.value = envMap;
  14696. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1;
  14697. uniforms.reflectivity.value = material.reflectivity;
  14698. uniforms.ior.value = material.ior;
  14699. uniforms.refractionRatio.value = material.refractionRatio;
  14700. const maxMipLevel = properties.get(envMap).__maxMipLevel;
  14701. if (maxMipLevel !== undefined) {
  14702. uniforms.maxMipLevel.value = maxMipLevel;
  14703. }
  14704. }
  14705. if (material.lightMap) {
  14706. uniforms.lightMap.value = material.lightMap;
  14707. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  14708. }
  14709. if (material.aoMap) {
  14710. uniforms.aoMap.value = material.aoMap;
  14711. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  14712. } // uv repeat and offset setting priorities
  14713. // 1. color map
  14714. // 2. specular map
  14715. // 3. displacementMap map
  14716. // 4. normal map
  14717. // 5. bump map
  14718. // 6. roughnessMap map
  14719. // 7. metalnessMap map
  14720. // 8. alphaMap map
  14721. // 9. emissiveMap map
  14722. // 10. clearcoat map
  14723. // 11. clearcoat normal map
  14724. // 12. clearcoat roughnessMap map
  14725. // 13. specular intensity map
  14726. // 14. specular tint map
  14727. // 15. transmission map
  14728. // 16. thickness map
  14729. let uvScaleMap;
  14730. if (material.map) {
  14731. uvScaleMap = material.map;
  14732. } else if (material.specularMap) {
  14733. uvScaleMap = material.specularMap;
  14734. } else if (material.displacementMap) {
  14735. uvScaleMap = material.displacementMap;
  14736. } else if (material.normalMap) {
  14737. uvScaleMap = material.normalMap;
  14738. } else if (material.bumpMap) {
  14739. uvScaleMap = material.bumpMap;
  14740. } else if (material.roughnessMap) {
  14741. uvScaleMap = material.roughnessMap;
  14742. } else if (material.metalnessMap) {
  14743. uvScaleMap = material.metalnessMap;
  14744. } else if (material.alphaMap) {
  14745. uvScaleMap = material.alphaMap;
  14746. } else if (material.emissiveMap) {
  14747. uvScaleMap = material.emissiveMap;
  14748. } else if (material.clearcoatMap) {
  14749. uvScaleMap = material.clearcoatMap;
  14750. } else if (material.clearcoatNormalMap) {
  14751. uvScaleMap = material.clearcoatNormalMap;
  14752. } else if (material.clearcoatRoughnessMap) {
  14753. uvScaleMap = material.clearcoatRoughnessMap;
  14754. } else if (material.specularIntensityMap) {
  14755. uvScaleMap = material.specularIntensityMap;
  14756. } else if (material.specularTintMap) {
  14757. uvScaleMap = material.specularTintMap;
  14758. } else if (material.transmissionMap) {
  14759. uvScaleMap = material.transmissionMap;
  14760. } else if (material.thicknessMap) {
  14761. uvScaleMap = material.thicknessMap;
  14762. }
  14763. if (uvScaleMap !== undefined) {
  14764. // backwards compatibility
  14765. if (uvScaleMap.isWebGLRenderTarget) {
  14766. uvScaleMap = uvScaleMap.texture;
  14767. }
  14768. if (uvScaleMap.matrixAutoUpdate === true) {
  14769. uvScaleMap.updateMatrix();
  14770. }
  14771. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  14772. } // uv repeat and offset setting priorities for uv2
  14773. // 1. ao map
  14774. // 2. light map
  14775. let uv2ScaleMap;
  14776. if (material.aoMap) {
  14777. uv2ScaleMap = material.aoMap;
  14778. } else if (material.lightMap) {
  14779. uv2ScaleMap = material.lightMap;
  14780. }
  14781. if (uv2ScaleMap !== undefined) {
  14782. // backwards compatibility
  14783. if (uv2ScaleMap.isWebGLRenderTarget) {
  14784. uv2ScaleMap = uv2ScaleMap.texture;
  14785. }
  14786. if (uv2ScaleMap.matrixAutoUpdate === true) {
  14787. uv2ScaleMap.updateMatrix();
  14788. }
  14789. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  14790. }
  14791. }
  14792. function refreshUniformsLine(uniforms, material) {
  14793. uniforms.diffuse.value.copy(material.color);
  14794. uniforms.opacity.value = material.opacity;
  14795. }
  14796. function refreshUniformsDash(uniforms, material) {
  14797. uniforms.dashSize.value = material.dashSize;
  14798. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14799. uniforms.scale.value = material.scale;
  14800. }
  14801. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  14802. uniforms.diffuse.value.copy(material.color);
  14803. uniforms.opacity.value = material.opacity;
  14804. uniforms.size.value = material.size * pixelRatio;
  14805. uniforms.scale.value = height * 0.5;
  14806. if (material.map) {
  14807. uniforms.map.value = material.map;
  14808. }
  14809. if (material.alphaMap) {
  14810. uniforms.alphaMap.value = material.alphaMap;
  14811. }
  14812. if (material.alphaTest > 0) {
  14813. uniforms.alphaTest.value = material.alphaTest;
  14814. } // uv repeat and offset setting priorities
  14815. // 1. color map
  14816. // 2. alpha map
  14817. let uvScaleMap;
  14818. if (material.map) {
  14819. uvScaleMap = material.map;
  14820. } else if (material.alphaMap) {
  14821. uvScaleMap = material.alphaMap;
  14822. }
  14823. if (uvScaleMap !== undefined) {
  14824. if (uvScaleMap.matrixAutoUpdate === true) {
  14825. uvScaleMap.updateMatrix();
  14826. }
  14827. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  14828. }
  14829. }
  14830. function refreshUniformsSprites(uniforms, material) {
  14831. uniforms.diffuse.value.copy(material.color);
  14832. uniforms.opacity.value = material.opacity;
  14833. uniforms.rotation.value = material.rotation;
  14834. if (material.map) {
  14835. uniforms.map.value = material.map;
  14836. }
  14837. if (material.alphaMap) {
  14838. uniforms.alphaMap.value = material.alphaMap;
  14839. }
  14840. if (material.alphaTest > 0) {
  14841. uniforms.alphaTest.value = material.alphaTest;
  14842. } // uv repeat and offset setting priorities
  14843. // 1. color map
  14844. // 2. alpha map
  14845. let uvScaleMap;
  14846. if (material.map) {
  14847. uvScaleMap = material.map;
  14848. } else if (material.alphaMap) {
  14849. uvScaleMap = material.alphaMap;
  14850. }
  14851. if (uvScaleMap !== undefined) {
  14852. if (uvScaleMap.matrixAutoUpdate === true) {
  14853. uvScaleMap.updateMatrix();
  14854. }
  14855. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  14856. }
  14857. }
  14858. function refreshUniformsLambert(uniforms, material) {
  14859. if (material.emissiveMap) {
  14860. uniforms.emissiveMap.value = material.emissiveMap;
  14861. }
  14862. }
  14863. function refreshUniformsPhong(uniforms, material) {
  14864. uniforms.specular.value.copy(material.specular);
  14865. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  14866. if (material.emissiveMap) {
  14867. uniforms.emissiveMap.value = material.emissiveMap;
  14868. }
  14869. if (material.bumpMap) {
  14870. uniforms.bumpMap.value = material.bumpMap;
  14871. uniforms.bumpScale.value = material.bumpScale;
  14872. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14873. }
  14874. if (material.normalMap) {
  14875. uniforms.normalMap.value = material.normalMap;
  14876. uniforms.normalScale.value.copy(material.normalScale);
  14877. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14878. }
  14879. if (material.displacementMap) {
  14880. uniforms.displacementMap.value = material.displacementMap;
  14881. uniforms.displacementScale.value = material.displacementScale;
  14882. uniforms.displacementBias.value = material.displacementBias;
  14883. }
  14884. }
  14885. function refreshUniformsToon(uniforms, material) {
  14886. if (material.gradientMap) {
  14887. uniforms.gradientMap.value = material.gradientMap;
  14888. }
  14889. if (material.emissiveMap) {
  14890. uniforms.emissiveMap.value = material.emissiveMap;
  14891. }
  14892. if (material.bumpMap) {
  14893. uniforms.bumpMap.value = material.bumpMap;
  14894. uniforms.bumpScale.value = material.bumpScale;
  14895. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14896. }
  14897. if (material.normalMap) {
  14898. uniforms.normalMap.value = material.normalMap;
  14899. uniforms.normalScale.value.copy(material.normalScale);
  14900. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14901. }
  14902. if (material.displacementMap) {
  14903. uniforms.displacementMap.value = material.displacementMap;
  14904. uniforms.displacementScale.value = material.displacementScale;
  14905. uniforms.displacementBias.value = material.displacementBias;
  14906. }
  14907. }
  14908. function refreshUniformsStandard(uniforms, material) {
  14909. uniforms.roughness.value = material.roughness;
  14910. uniforms.metalness.value = material.metalness;
  14911. if (material.roughnessMap) {
  14912. uniforms.roughnessMap.value = material.roughnessMap;
  14913. }
  14914. if (material.metalnessMap) {
  14915. uniforms.metalnessMap.value = material.metalnessMap;
  14916. }
  14917. if (material.emissiveMap) {
  14918. uniforms.emissiveMap.value = material.emissiveMap;
  14919. }
  14920. if (material.bumpMap) {
  14921. uniforms.bumpMap.value = material.bumpMap;
  14922. uniforms.bumpScale.value = material.bumpScale;
  14923. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14924. }
  14925. if (material.normalMap) {
  14926. uniforms.normalMap.value = material.normalMap;
  14927. uniforms.normalScale.value.copy(material.normalScale);
  14928. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14929. }
  14930. if (material.displacementMap) {
  14931. uniforms.displacementMap.value = material.displacementMap;
  14932. uniforms.displacementScale.value = material.displacementScale;
  14933. uniforms.displacementBias.value = material.displacementBias;
  14934. }
  14935. const envMap = properties.get(material).envMap;
  14936. if (envMap) {
  14937. //uniforms.envMap.value = material.envMap; // part of uniforms common
  14938. uniforms.envMapIntensity.value = material.envMapIntensity;
  14939. }
  14940. }
  14941. function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) {
  14942. refreshUniformsStandard(uniforms, material);
  14943. uniforms.ior.value = material.ior; // also part of uniforms common
  14944. if (material.sheen > 0) {
  14945. uniforms.sheenTint.value.copy(material.sheenTint).multiplyScalar(material.sheen);
  14946. uniforms.sheenRoughness.value = material.sheenRoughness;
  14947. }
  14948. if (material.clearcoat > 0) {
  14949. uniforms.clearcoat.value = material.clearcoat;
  14950. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  14951. if (material.clearcoatMap) {
  14952. uniforms.clearcoatMap.value = material.clearcoatMap;
  14953. }
  14954. if (material.clearcoatRoughnessMap) {
  14955. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  14956. }
  14957. if (material.clearcoatNormalMap) {
  14958. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  14959. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  14960. if (material.side === BackSide) {
  14961. uniforms.clearcoatNormalScale.value.negate();
  14962. }
  14963. }
  14964. }
  14965. if (material.transmission > 0) {
  14966. uniforms.transmission.value = material.transmission;
  14967. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  14968. uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height);
  14969. if (material.transmissionMap) {
  14970. uniforms.transmissionMap.value = material.transmissionMap;
  14971. }
  14972. uniforms.thickness.value = material.thickness;
  14973. if (material.thicknessMap) {
  14974. uniforms.thicknessMap.value = material.thicknessMap;
  14975. }
  14976. uniforms.attenuationDistance.value = material.attenuationDistance;
  14977. uniforms.attenuationTint.value.copy(material.attenuationTint);
  14978. }
  14979. uniforms.specularIntensity.value = material.specularIntensity;
  14980. uniforms.specularTint.value.copy(material.specularTint);
  14981. if (material.specularIntensityMap) {
  14982. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  14983. }
  14984. if (material.specularTintMap) {
  14985. uniforms.specularTintMap.value = material.specularTintMap;
  14986. }
  14987. }
  14988. function refreshUniformsMatcap(uniforms, material) {
  14989. if (material.matcap) {
  14990. uniforms.matcap.value = material.matcap;
  14991. }
  14992. if (material.bumpMap) {
  14993. uniforms.bumpMap.value = material.bumpMap;
  14994. uniforms.bumpScale.value = material.bumpScale;
  14995. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14996. }
  14997. if (material.normalMap) {
  14998. uniforms.normalMap.value = material.normalMap;
  14999. uniforms.normalScale.value.copy(material.normalScale);
  15000. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15001. }
  15002. if (material.displacementMap) {
  15003. uniforms.displacementMap.value = material.displacementMap;
  15004. uniforms.displacementScale.value = material.displacementScale;
  15005. uniforms.displacementBias.value = material.displacementBias;
  15006. }
  15007. }
  15008. function refreshUniformsDepth(uniforms, material) {
  15009. if (material.displacementMap) {
  15010. uniforms.displacementMap.value = material.displacementMap;
  15011. uniforms.displacementScale.value = material.displacementScale;
  15012. uniforms.displacementBias.value = material.displacementBias;
  15013. }
  15014. }
  15015. function refreshUniformsDistance(uniforms, material) {
  15016. if (material.displacementMap) {
  15017. uniforms.displacementMap.value = material.displacementMap;
  15018. uniforms.displacementScale.value = material.displacementScale;
  15019. uniforms.displacementBias.value = material.displacementBias;
  15020. }
  15021. uniforms.referencePosition.value.copy(material.referencePosition);
  15022. uniforms.nearDistance.value = material.nearDistance;
  15023. uniforms.farDistance.value = material.farDistance;
  15024. }
  15025. function refreshUniformsNormal(uniforms, material) {
  15026. if (material.bumpMap) {
  15027. uniforms.bumpMap.value = material.bumpMap;
  15028. uniforms.bumpScale.value = material.bumpScale;
  15029. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15030. }
  15031. if (material.normalMap) {
  15032. uniforms.normalMap.value = material.normalMap;
  15033. uniforms.normalScale.value.copy(material.normalScale);
  15034. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15035. }
  15036. if (material.displacementMap) {
  15037. uniforms.displacementMap.value = material.displacementMap;
  15038. uniforms.displacementScale.value = material.displacementScale;
  15039. uniforms.displacementBias.value = material.displacementBias;
  15040. }
  15041. }
  15042. return {
  15043. refreshFogUniforms: refreshFogUniforms,
  15044. refreshMaterialUniforms: refreshMaterialUniforms
  15045. };
  15046. }
  15047. function createCanvasElement() {
  15048. const canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  15049. canvas.style.display = 'block';
  15050. return canvas;
  15051. }
  15052. function WebGLRenderer(parameters = {}) {
  15053. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  15054. _context = parameters.context !== undefined ? parameters.context : null,
  15055. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  15056. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15057. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15058. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15059. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15060. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  15061. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  15062. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  15063. let currentRenderList = null;
  15064. let currentRenderState = null; // render() can be called from within a callback triggered by another render.
  15065. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  15066. const renderListStack = [];
  15067. const renderStateStack = []; // public properties
  15068. this.domElement = _canvas; // Debug configuration container
  15069. this.debug = {
  15070. /**
  15071. * Enables error checking and reporting when shader programs are being compiled
  15072. * @type {boolean}
  15073. */
  15074. checkShaderErrors: true
  15075. }; // clearing
  15076. this.autoClear = true;
  15077. this.autoClearColor = true;
  15078. this.autoClearDepth = true;
  15079. this.autoClearStencil = true; // scene graph
  15080. this.sortObjects = true; // user-defined clipping
  15081. this.clippingPlanes = [];
  15082. this.localClippingEnabled = false; // physically based shading
  15083. this.gammaFactor = 2.0; // for backwards compatibility
  15084. this.outputEncoding = LinearEncoding; // physical lights
  15085. this.physicallyCorrectLights = false; // tone mapping
  15086. this.toneMapping = NoToneMapping;
  15087. this.toneMappingExposure = 1.0; // internal properties
  15088. const _this = this;
  15089. let _isContextLost = false; // internal state cache
  15090. let _currentActiveCubeFace = 0;
  15091. let _currentActiveMipmapLevel = 0;
  15092. let _currentRenderTarget = null;
  15093. let _currentMaterialId = -1;
  15094. let _currentCamera = null;
  15095. const _currentViewport = new Vector4();
  15096. const _currentScissor = new Vector4();
  15097. let _currentScissorTest = null; //
  15098. let _width = _canvas.width;
  15099. let _height = _canvas.height;
  15100. let _pixelRatio = 1;
  15101. let _opaqueSort = null;
  15102. let _transparentSort = null;
  15103. const _viewport = new Vector4(0, 0, _width, _height);
  15104. const _scissor = new Vector4(0, 0, _width, _height);
  15105. let _scissorTest = false; //
  15106. const _currentDrawBuffers = []; // frustum
  15107. const _frustum = new Frustum(); // clipping
  15108. let _clippingEnabled = false;
  15109. let _localClippingEnabled = false; // transmission
  15110. let _transmissionRenderTarget = null; // camera matrices cache
  15111. const _projScreenMatrix = new Matrix4();
  15112. const _vector3 = new Vector3();
  15113. const _emptyScene = {
  15114. background: null,
  15115. fog: null,
  15116. environment: null,
  15117. overrideMaterial: null,
  15118. isScene: true
  15119. };
  15120. function getTargetPixelRatio() {
  15121. return _currentRenderTarget === null ? _pixelRatio : 1;
  15122. } // initialize
  15123. let _gl = _context;
  15124. function getContext(contextNames, contextAttributes) {
  15125. for (let i = 0; i < contextNames.length; i++) {
  15126. const contextName = contextNames[i];
  15127. const context = _canvas.getContext(contextName, contextAttributes);
  15128. if (context !== null) return context;
  15129. }
  15130. return null;
  15131. }
  15132. try {
  15133. const contextAttributes = {
  15134. alpha: _alpha,
  15135. depth: _depth,
  15136. stencil: _stencil,
  15137. antialias: _antialias,
  15138. premultipliedAlpha: _premultipliedAlpha,
  15139. preserveDrawingBuffer: _preserveDrawingBuffer,
  15140. powerPreference: _powerPreference,
  15141. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  15142. }; // event listeners must be registered before WebGL context is created, see #12753
  15143. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  15144. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  15145. if (_gl === null) {
  15146. const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  15147. if (_this.isWebGL1Renderer === true) {
  15148. contextNames.shift();
  15149. }
  15150. _gl = getContext(contextNames, contextAttributes);
  15151. if (_gl === null) {
  15152. if (getContext(contextNames)) {
  15153. throw new Error('Error creating WebGL context with your selected attributes.');
  15154. } else {
  15155. throw new Error('Error creating WebGL context.');
  15156. }
  15157. }
  15158. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  15159. if (_gl.getShaderPrecisionFormat === undefined) {
  15160. _gl.getShaderPrecisionFormat = function () {
  15161. return {
  15162. 'rangeMin': 1,
  15163. 'rangeMax': 1,
  15164. 'precision': 1
  15165. };
  15166. };
  15167. }
  15168. } catch (error) {
  15169. console.error('THREE.WebGLRenderer: ' + error.message);
  15170. throw error;
  15171. }
  15172. let extensions, capabilities, state, info;
  15173. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  15174. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  15175. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  15176. let utils, bindingStates;
  15177. function initGLContext() {
  15178. extensions = new WebGLExtensions(_gl);
  15179. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  15180. extensions.init(capabilities);
  15181. utils = new WebGLUtils(_gl, extensions, capabilities);
  15182. state = new WebGLState(_gl, extensions, capabilities);
  15183. _currentDrawBuffers[0] = _gl.BACK;
  15184. info = new WebGLInfo(_gl);
  15185. properties = new WebGLProperties();
  15186. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  15187. cubemaps = new WebGLCubeMaps(_this);
  15188. cubeuvmaps = new WebGLCubeUVMaps(_this);
  15189. attributes = new WebGLAttributes(_gl, capabilities);
  15190. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  15191. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  15192. objects = new WebGLObjects(_gl, geometries, attributes, info);
  15193. morphtargets = new WebGLMorphtargets(_gl);
  15194. clipping = new WebGLClipping(properties);
  15195. programCache = new WebGLPrograms(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping);
  15196. materials = new WebGLMaterials(properties);
  15197. renderLists = new WebGLRenderLists(properties);
  15198. renderStates = new WebGLRenderStates(extensions, capabilities);
  15199. background = new WebGLBackground(_this, cubemaps, state, objects, _premultipliedAlpha);
  15200. shadowMap = new WebGLShadowMap(_this, objects, capabilities);
  15201. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  15202. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  15203. info.programs = programCache.programs;
  15204. _this.capabilities = capabilities;
  15205. _this.extensions = extensions;
  15206. _this.properties = properties;
  15207. _this.renderLists = renderLists;
  15208. _this.shadowMap = shadowMap;
  15209. _this.state = state;
  15210. _this.info = info;
  15211. }
  15212. initGLContext(); // xr
  15213. const xr = new WebXRManager(_this, _gl);
  15214. this.xr = xr; // API
  15215. this.getContext = function () {
  15216. return _gl;
  15217. };
  15218. this.getContextAttributes = function () {
  15219. return _gl.getContextAttributes();
  15220. };
  15221. this.forceContextLoss = function () {
  15222. const extension = extensions.get('WEBGL_lose_context');
  15223. if (extension) extension.loseContext();
  15224. };
  15225. this.forceContextRestore = function () {
  15226. const extension = extensions.get('WEBGL_lose_context');
  15227. if (extension) extension.restoreContext();
  15228. };
  15229. this.getPixelRatio = function () {
  15230. return _pixelRatio;
  15231. };
  15232. this.setPixelRatio = function (value) {
  15233. if (value === undefined) return;
  15234. _pixelRatio = value;
  15235. this.setSize(_width, _height, false);
  15236. };
  15237. this.getSize = function (target) {
  15238. return target.set(_width, _height);
  15239. };
  15240. this.setSize = function (width, height, updateStyle) {
  15241. if (xr.isPresenting) {
  15242. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  15243. return;
  15244. }
  15245. _width = width;
  15246. _height = height;
  15247. _canvas.width = Math.floor(width * _pixelRatio);
  15248. _canvas.height = Math.floor(height * _pixelRatio);
  15249. if (updateStyle !== false) {
  15250. _canvas.style.width = width + 'px';
  15251. _canvas.style.height = height + 'px';
  15252. }
  15253. this.setViewport(0, 0, width, height);
  15254. };
  15255. this.getDrawingBufferSize = function (target) {
  15256. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  15257. };
  15258. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  15259. _width = width;
  15260. _height = height;
  15261. _pixelRatio = pixelRatio;
  15262. _canvas.width = Math.floor(width * pixelRatio);
  15263. _canvas.height = Math.floor(height * pixelRatio);
  15264. this.setViewport(0, 0, width, height);
  15265. };
  15266. this.getCurrentViewport = function (target) {
  15267. return target.copy(_currentViewport);
  15268. };
  15269. this.getViewport = function (target) {
  15270. return target.copy(_viewport);
  15271. };
  15272. this.setViewport = function (x, y, width, height) {
  15273. if (x.isVector4) {
  15274. _viewport.set(x.x, x.y, x.z, x.w);
  15275. } else {
  15276. _viewport.set(x, y, width, height);
  15277. }
  15278. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  15279. };
  15280. this.getScissor = function (target) {
  15281. return target.copy(_scissor);
  15282. };
  15283. this.setScissor = function (x, y, width, height) {
  15284. if (x.isVector4) {
  15285. _scissor.set(x.x, x.y, x.z, x.w);
  15286. } else {
  15287. _scissor.set(x, y, width, height);
  15288. }
  15289. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  15290. };
  15291. this.getScissorTest = function () {
  15292. return _scissorTest;
  15293. };
  15294. this.setScissorTest = function (boolean) {
  15295. state.setScissorTest(_scissorTest = boolean);
  15296. };
  15297. this.setOpaqueSort = function (method) {
  15298. _opaqueSort = method;
  15299. };
  15300. this.setTransparentSort = function (method) {
  15301. _transparentSort = method;
  15302. }; // Clearing
  15303. this.getClearColor = function (target) {
  15304. return target.copy(background.getClearColor());
  15305. };
  15306. this.setClearColor = function () {
  15307. background.setClearColor.apply(background, arguments);
  15308. };
  15309. this.getClearAlpha = function () {
  15310. return background.getClearAlpha();
  15311. };
  15312. this.setClearAlpha = function () {
  15313. background.setClearAlpha.apply(background, arguments);
  15314. };
  15315. this.clear = function (color, depth, stencil) {
  15316. let bits = 0;
  15317. if (color === undefined || color) bits |= _gl.COLOR_BUFFER_BIT;
  15318. if (depth === undefined || depth) bits |= _gl.DEPTH_BUFFER_BIT;
  15319. if (stencil === undefined || stencil) bits |= _gl.STENCIL_BUFFER_BIT;
  15320. _gl.clear(bits);
  15321. };
  15322. this.clearColor = function () {
  15323. this.clear(true, false, false);
  15324. };
  15325. this.clearDepth = function () {
  15326. this.clear(false, true, false);
  15327. };
  15328. this.clearStencil = function () {
  15329. this.clear(false, false, true);
  15330. }; //
  15331. this.dispose = function () {
  15332. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  15333. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  15334. renderLists.dispose();
  15335. renderStates.dispose();
  15336. properties.dispose();
  15337. cubemaps.dispose();
  15338. cubeuvmaps.dispose();
  15339. objects.dispose();
  15340. bindingStates.dispose();
  15341. xr.dispose();
  15342. xr.removeEventListener('sessionstart', onXRSessionStart);
  15343. xr.removeEventListener('sessionend', onXRSessionEnd);
  15344. if (_transmissionRenderTarget) {
  15345. _transmissionRenderTarget.dispose();
  15346. _transmissionRenderTarget = null;
  15347. }
  15348. animation.stop();
  15349. }; // Events
  15350. function onContextLost(event) {
  15351. event.preventDefault();
  15352. console.log('THREE.WebGLRenderer: Context Lost.');
  15353. _isContextLost = true;
  15354. }
  15355. function onContextRestore() {
  15356. console.log('THREE.WebGLRenderer: Context Restored.');
  15357. _isContextLost = false;
  15358. const infoAutoReset = info.autoReset;
  15359. const shadowMapEnabled = shadowMap.enabled;
  15360. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  15361. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  15362. const shadowMapType = shadowMap.type;
  15363. initGLContext();
  15364. info.autoReset = infoAutoReset;
  15365. shadowMap.enabled = shadowMapEnabled;
  15366. shadowMap.autoUpdate = shadowMapAutoUpdate;
  15367. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  15368. shadowMap.type = shadowMapType;
  15369. }
  15370. function onMaterialDispose(event) {
  15371. const material = event.target;
  15372. material.removeEventListener('dispose', onMaterialDispose);
  15373. deallocateMaterial(material);
  15374. } // Buffer deallocation
  15375. function deallocateMaterial(material) {
  15376. releaseMaterialProgramReferences(material);
  15377. properties.remove(material);
  15378. }
  15379. function releaseMaterialProgramReferences(material) {
  15380. const programs = properties.get(material).programs;
  15381. if (programs !== undefined) {
  15382. programs.forEach(function (program) {
  15383. programCache.releaseProgram(program);
  15384. });
  15385. }
  15386. } // Buffer rendering
  15387. function renderObjectImmediate(object, program) {
  15388. object.render(function (object) {
  15389. _this.renderBufferImmediate(object, program);
  15390. });
  15391. }
  15392. this.renderBufferImmediate = function (object, program) {
  15393. bindingStates.initAttributes();
  15394. const buffers = properties.get(object);
  15395. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  15396. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  15397. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  15398. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  15399. const programAttributes = program.getAttributes();
  15400. if (object.hasPositions) {
  15401. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.position);
  15402. _gl.bufferData(_gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW);
  15403. bindingStates.enableAttribute(programAttributes.position.location);
  15404. _gl.vertexAttribPointer(programAttributes.position.location, 3, _gl.FLOAT, false, 0, 0);
  15405. }
  15406. if (object.hasNormals) {
  15407. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.normal);
  15408. _gl.bufferData(_gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW);
  15409. bindingStates.enableAttribute(programAttributes.normal.location);
  15410. _gl.vertexAttribPointer(programAttributes.normal.location, 3, _gl.FLOAT, false, 0, 0);
  15411. }
  15412. if (object.hasUvs) {
  15413. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.uv);
  15414. _gl.bufferData(_gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW);
  15415. bindingStates.enableAttribute(programAttributes.uv.location);
  15416. _gl.vertexAttribPointer(programAttributes.uv.location, 2, _gl.FLOAT, false, 0, 0);
  15417. }
  15418. if (object.hasColors) {
  15419. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.color);
  15420. _gl.bufferData(_gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW);
  15421. bindingStates.enableAttribute(programAttributes.color.location);
  15422. _gl.vertexAttribPointer(programAttributes.color.location, 3, _gl.FLOAT, false, 0, 0);
  15423. }
  15424. bindingStates.disableUnusedAttributes();
  15425. _gl.drawArrays(_gl.TRIANGLES, 0, object.count);
  15426. object.count = 0;
  15427. };
  15428. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  15429. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  15430. const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  15431. const program = setProgram(camera, scene, material, object);
  15432. state.setMaterial(material, frontFaceCW); //
  15433. let index = geometry.index;
  15434. const position = geometry.attributes.position; //
  15435. if (index === null) {
  15436. if (position === undefined || position.count === 0) return;
  15437. } else if (index.count === 0) {
  15438. return;
  15439. } //
  15440. let rangeFactor = 1;
  15441. if (material.wireframe === true) {
  15442. index = geometries.getWireframeAttribute(geometry);
  15443. rangeFactor = 2;
  15444. }
  15445. if (geometry.morphAttributes.position !== undefined || geometry.morphAttributes.normal !== undefined) {
  15446. morphtargets.update(object, geometry, material, program);
  15447. }
  15448. bindingStates.setup(object, material, program, geometry, index);
  15449. let attribute;
  15450. let renderer = bufferRenderer;
  15451. if (index !== null) {
  15452. attribute = attributes.get(index);
  15453. renderer = indexedBufferRenderer;
  15454. renderer.setIndex(attribute);
  15455. } //
  15456. const dataCount = index !== null ? index.count : position.count;
  15457. const rangeStart = geometry.drawRange.start * rangeFactor;
  15458. const rangeCount = geometry.drawRange.count * rangeFactor;
  15459. const groupStart = group !== null ? group.start * rangeFactor : 0;
  15460. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  15461. const drawStart = Math.max(rangeStart, groupStart);
  15462. const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  15463. const drawCount = Math.max(0, drawEnd - drawStart + 1);
  15464. if (drawCount === 0) return; //
  15465. if (object.isMesh) {
  15466. if (material.wireframe === true) {
  15467. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  15468. renderer.setMode(_gl.LINES);
  15469. } else {
  15470. renderer.setMode(_gl.TRIANGLES);
  15471. }
  15472. } else if (object.isLine) {
  15473. let lineWidth = material.linewidth;
  15474. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  15475. state.setLineWidth(lineWidth * getTargetPixelRatio());
  15476. if (object.isLineSegments) {
  15477. renderer.setMode(_gl.LINES);
  15478. } else if (object.isLineLoop) {
  15479. renderer.setMode(_gl.LINE_LOOP);
  15480. } else {
  15481. renderer.setMode(_gl.LINE_STRIP);
  15482. }
  15483. } else if (object.isPoints) {
  15484. renderer.setMode(_gl.POINTS);
  15485. } else if (object.isSprite) {
  15486. renderer.setMode(_gl.TRIANGLES);
  15487. }
  15488. if (object.isInstancedMesh) {
  15489. renderer.renderInstances(drawStart, drawCount, object.count);
  15490. } else if (geometry.isInstancedBufferGeometry) {
  15491. const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  15492. renderer.renderInstances(drawStart, drawCount, instanceCount);
  15493. } else {
  15494. renderer.render(drawStart, drawCount);
  15495. }
  15496. }; // Compile
  15497. this.compile = function (scene, camera) {
  15498. currentRenderState = renderStates.get(scene);
  15499. currentRenderState.init();
  15500. renderStateStack.push(currentRenderState);
  15501. scene.traverseVisible(function (object) {
  15502. if (object.isLight && object.layers.test(camera.layers)) {
  15503. currentRenderState.pushLight(object);
  15504. if (object.castShadow) {
  15505. currentRenderState.pushShadow(object);
  15506. }
  15507. }
  15508. });
  15509. currentRenderState.setupLights(_this.physicallyCorrectLights);
  15510. scene.traverse(function (object) {
  15511. const material = object.material;
  15512. if (material) {
  15513. if (Array.isArray(material)) {
  15514. for (let i = 0; i < material.length; i++) {
  15515. const material2 = material[i];
  15516. getProgram(material2, scene, object);
  15517. }
  15518. } else {
  15519. getProgram(material, scene, object);
  15520. }
  15521. }
  15522. });
  15523. renderStateStack.pop();
  15524. currentRenderState = null;
  15525. }; // Animation Loop
  15526. let onAnimationFrameCallback = null;
  15527. function onAnimationFrame(time) {
  15528. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  15529. }
  15530. function onXRSessionStart() {
  15531. animation.stop();
  15532. }
  15533. function onXRSessionEnd() {
  15534. animation.start();
  15535. }
  15536. const animation = new WebGLAnimation();
  15537. animation.setAnimationLoop(onAnimationFrame);
  15538. if (typeof window !== 'undefined') animation.setContext(window);
  15539. this.setAnimationLoop = function (callback) {
  15540. onAnimationFrameCallback = callback;
  15541. xr.setAnimationLoop(callback);
  15542. callback === null ? animation.stop() : animation.start();
  15543. };
  15544. xr.addEventListener('sessionstart', onXRSessionStart);
  15545. xr.addEventListener('sessionend', onXRSessionEnd); // Rendering
  15546. this.render = function (scene, camera) {
  15547. if (camera !== undefined && camera.isCamera !== true) {
  15548. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  15549. return;
  15550. }
  15551. if (_isContextLost === true) return; // update scene graph
  15552. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  15553. if (camera.parent === null) camera.updateMatrixWorld();
  15554. if (xr.enabled === true && xr.isPresenting === true) {
  15555. if (xr.cameraAutoUpdate === true) xr.updateCamera(camera);
  15556. camera = xr.getCamera(); // use XR camera for rendering
  15557. } //
  15558. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget);
  15559. currentRenderState = renderStates.get(scene, renderStateStack.length);
  15560. currentRenderState.init();
  15561. renderStateStack.push(currentRenderState);
  15562. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  15563. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  15564. _localClippingEnabled = this.localClippingEnabled;
  15565. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  15566. currentRenderList = renderLists.get(scene, renderListStack.length);
  15567. currentRenderList.init();
  15568. renderListStack.push(currentRenderList);
  15569. projectObject(scene, camera, 0, _this.sortObjects);
  15570. currentRenderList.finish();
  15571. if (_this.sortObjects === true) {
  15572. currentRenderList.sort(_opaqueSort, _transparentSort);
  15573. } //
  15574. if (_clippingEnabled === true) clipping.beginShadows();
  15575. const shadowsArray = currentRenderState.state.shadowsArray;
  15576. shadowMap.render(shadowsArray, scene, camera);
  15577. if (_clippingEnabled === true) clipping.endShadows(); //
  15578. if (this.info.autoReset === true) this.info.reset(); //
  15579. background.render(currentRenderList, scene); // render scene
  15580. currentRenderState.setupLights(_this.physicallyCorrectLights);
  15581. if (camera.isArrayCamera) {
  15582. const cameras = camera.cameras;
  15583. for (let i = 0, l = cameras.length; i < l; i++) {
  15584. const camera2 = cameras[i];
  15585. renderScene(currentRenderList, scene, camera2, camera2.viewport);
  15586. }
  15587. } else {
  15588. renderScene(currentRenderList, scene, camera);
  15589. } //
  15590. if (_currentRenderTarget !== null) {
  15591. // resolve multisample renderbuffers to a single-sample texture if necessary
  15592. textures.updateMultisampleRenderTarget(_currentRenderTarget); // Generate mipmap if we're using any kind of mipmap filtering
  15593. textures.updateRenderTargetMipmap(_currentRenderTarget);
  15594. } //
  15595. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); // Ensure depth buffer writing is enabled so it can be cleared on next render
  15596. state.buffers.depth.setTest(true);
  15597. state.buffers.depth.setMask(true);
  15598. state.buffers.color.setMask(true);
  15599. state.setPolygonOffset(false); // _gl.finish();
  15600. bindingStates.resetDefaultState();
  15601. _currentMaterialId = -1;
  15602. _currentCamera = null;
  15603. renderStateStack.pop();
  15604. if (renderStateStack.length > 0) {
  15605. currentRenderState = renderStateStack[renderStateStack.length - 1];
  15606. } else {
  15607. currentRenderState = null;
  15608. }
  15609. renderListStack.pop();
  15610. if (renderListStack.length > 0) {
  15611. currentRenderList = renderListStack[renderListStack.length - 1];
  15612. } else {
  15613. currentRenderList = null;
  15614. }
  15615. };
  15616. function projectObject(object, camera, groupOrder, sortObjects) {
  15617. if (object.visible === false) return;
  15618. const visible = object.layers.test(camera.layers);
  15619. if (visible) {
  15620. if (object.isGroup) {
  15621. groupOrder = object.renderOrder;
  15622. } else if (object.isLOD) {
  15623. if (object.autoUpdate === true) object.update(camera);
  15624. } else if (object.isLight) {
  15625. currentRenderState.pushLight(object);
  15626. if (object.castShadow) {
  15627. currentRenderState.pushShadow(object);
  15628. }
  15629. } else if (object.isSprite) {
  15630. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  15631. if (sortObjects) {
  15632. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15633. }
  15634. const geometry = objects.update(object);
  15635. const material = object.material;
  15636. if (material.visible) {
  15637. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  15638. }
  15639. }
  15640. } else if (object.isImmediateRenderObject) {
  15641. if (sortObjects) {
  15642. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15643. }
  15644. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  15645. } else if (object.isMesh || object.isLine || object.isPoints) {
  15646. if (object.isSkinnedMesh) {
  15647. // update skeleton only once in a frame
  15648. if (object.skeleton.frame !== info.render.frame) {
  15649. object.skeleton.update();
  15650. object.skeleton.frame = info.render.frame;
  15651. }
  15652. }
  15653. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  15654. if (sortObjects) {
  15655. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15656. }
  15657. const geometry = objects.update(object);
  15658. const material = object.material;
  15659. if (Array.isArray(material)) {
  15660. const groups = geometry.groups;
  15661. for (let i = 0, l = groups.length; i < l; i++) {
  15662. const group = groups[i];
  15663. const groupMaterial = material[group.materialIndex];
  15664. if (groupMaterial && groupMaterial.visible) {
  15665. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  15666. }
  15667. }
  15668. } else if (material.visible) {
  15669. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  15670. }
  15671. }
  15672. }
  15673. }
  15674. const children = object.children;
  15675. for (let i = 0, l = children.length; i < l; i++) {
  15676. projectObject(children[i], camera, groupOrder, sortObjects);
  15677. }
  15678. }
  15679. function renderScene(currentRenderList, scene, camera, viewport) {
  15680. const opaqueObjects = currentRenderList.opaque;
  15681. const transmissiveObjects = currentRenderList.transmissive;
  15682. const transparentObjects = currentRenderList.transparent;
  15683. currentRenderState.setupLightsView(camera);
  15684. if (transmissiveObjects.length > 0) renderTransmissionPass(opaqueObjects, scene, camera);
  15685. if (viewport) state.viewport(_currentViewport.copy(viewport));
  15686. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  15687. if (transmissiveObjects.length > 0) renderObjects(transmissiveObjects, scene, camera);
  15688. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera);
  15689. }
  15690. function renderTransmissionPass(opaqueObjects, scene, camera) {
  15691. if (_transmissionRenderTarget === null) {
  15692. const needsAntialias = _antialias === true && capabilities.isWebGL2 === true;
  15693. const renderTargetType = needsAntialias ? WebGLMultisampleRenderTarget : WebGLRenderTarget;
  15694. _transmissionRenderTarget = new renderTargetType(1024, 1024, {
  15695. generateMipmaps: true,
  15696. type: utils.convert(HalfFloatType) !== null ? HalfFloatType : UnsignedByteType,
  15697. minFilter: LinearMipmapLinearFilter,
  15698. magFilter: NearestFilter,
  15699. wrapS: ClampToEdgeWrapping,
  15700. wrapT: ClampToEdgeWrapping
  15701. });
  15702. }
  15703. const currentRenderTarget = _this.getRenderTarget();
  15704. _this.setRenderTarget(_transmissionRenderTarget);
  15705. _this.clear(); // Turn off the features which can affect the frag color for opaque objects pass.
  15706. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  15707. const currentToneMapping = _this.toneMapping;
  15708. _this.toneMapping = NoToneMapping;
  15709. renderObjects(opaqueObjects, scene, camera);
  15710. _this.toneMapping = currentToneMapping;
  15711. textures.updateMultisampleRenderTarget(_transmissionRenderTarget);
  15712. textures.updateRenderTargetMipmap(_transmissionRenderTarget);
  15713. _this.setRenderTarget(currentRenderTarget);
  15714. }
  15715. function renderObjects(renderList, scene, camera) {
  15716. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  15717. for (let i = 0, l = renderList.length; i < l; i++) {
  15718. const renderItem = renderList[i];
  15719. const object = renderItem.object;
  15720. const geometry = renderItem.geometry;
  15721. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  15722. const group = renderItem.group;
  15723. if (object.layers.test(camera.layers)) {
  15724. renderObject(object, scene, camera, geometry, material, group);
  15725. }
  15726. }
  15727. }
  15728. function renderObject(object, scene, camera, geometry, material, group) {
  15729. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  15730. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  15731. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  15732. if (object.isImmediateRenderObject) {
  15733. const program = setProgram(camera, scene, material, object);
  15734. state.setMaterial(material);
  15735. bindingStates.reset();
  15736. renderObjectImmediate(object, program);
  15737. } else {
  15738. if (material.transparent === true && material.side === DoubleSide) {
  15739. material.side = BackSide;
  15740. material.needsUpdate = true;
  15741. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  15742. material.side = FrontSide;
  15743. material.needsUpdate = true;
  15744. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  15745. material.side = DoubleSide;
  15746. } else {
  15747. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  15748. }
  15749. }
  15750. object.onAfterRender(_this, scene, camera, geometry, material, group);
  15751. }
  15752. function getProgram(material, scene, object) {
  15753. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15754. const materialProperties = properties.get(material);
  15755. const lights = currentRenderState.state.lights;
  15756. const shadowsArray = currentRenderState.state.shadowsArray;
  15757. const lightsStateVersion = lights.state.version;
  15758. const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  15759. const programCacheKey = programCache.getProgramCacheKey(parameters);
  15760. let programs = materialProperties.programs; // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  15761. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  15762. materialProperties.fog = scene.fog;
  15763. materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment);
  15764. if (programs === undefined) {
  15765. // new material
  15766. material.addEventListener('dispose', onMaterialDispose);
  15767. programs = new Map();
  15768. materialProperties.programs = programs;
  15769. }
  15770. let program = programs.get(programCacheKey);
  15771. if (program !== undefined) {
  15772. // early out if program and light state is identical
  15773. if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) {
  15774. updateCommonMaterialProperties(material, parameters);
  15775. return program;
  15776. }
  15777. } else {
  15778. parameters.uniforms = programCache.getUniforms(material);
  15779. material.onBuild(parameters, _this);
  15780. material.onBeforeCompile(parameters, _this);
  15781. program = programCache.acquireProgram(parameters, programCacheKey);
  15782. programs.set(programCacheKey, program);
  15783. materialProperties.uniforms = parameters.uniforms;
  15784. }
  15785. const uniforms = materialProperties.uniforms;
  15786. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  15787. uniforms.clippingPlanes = clipping.uniform;
  15788. }
  15789. updateCommonMaterialProperties(material, parameters); // store the light setup it was created for
  15790. materialProperties.needsLights = materialNeedsLights(material);
  15791. materialProperties.lightsStateVersion = lightsStateVersion;
  15792. if (materialProperties.needsLights) {
  15793. // wire up the material to this renderer's lighting state
  15794. uniforms.ambientLightColor.value = lights.state.ambient;
  15795. uniforms.lightProbe.value = lights.state.probe;
  15796. uniforms.directionalLights.value = lights.state.directional;
  15797. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  15798. uniforms.spotLights.value = lights.state.spot;
  15799. uniforms.spotLightShadows.value = lights.state.spotShadow;
  15800. uniforms.rectAreaLights.value = lights.state.rectArea;
  15801. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  15802. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  15803. uniforms.pointLights.value = lights.state.point;
  15804. uniforms.pointLightShadows.value = lights.state.pointShadow;
  15805. uniforms.hemisphereLights.value = lights.state.hemi;
  15806. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  15807. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  15808. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  15809. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  15810. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  15811. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  15812. }
  15813. const progUniforms = program.getUniforms();
  15814. const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  15815. materialProperties.currentProgram = program;
  15816. materialProperties.uniformsList = uniformsList;
  15817. return program;
  15818. }
  15819. function updateCommonMaterialProperties(material, parameters) {
  15820. const materialProperties = properties.get(material);
  15821. materialProperties.outputEncoding = parameters.outputEncoding;
  15822. materialProperties.instancing = parameters.instancing;
  15823. materialProperties.skinning = parameters.skinning;
  15824. materialProperties.morphTargets = parameters.morphTargets;
  15825. materialProperties.morphNormals = parameters.morphNormals;
  15826. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  15827. materialProperties.numIntersection = parameters.numClipIntersection;
  15828. materialProperties.vertexAlphas = parameters.vertexAlphas;
  15829. materialProperties.vertexTangents = parameters.vertexTangents;
  15830. }
  15831. function setProgram(camera, scene, material, object) {
  15832. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15833. textures.resetTextureUnits();
  15834. const fog = scene.fog;
  15835. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  15836. const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  15837. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  15838. const vertexAlphas = material.vertexColors === true && !!object.geometry && !!object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4;
  15839. const vertexTangents = !!object.geometry && !!object.geometry.attributes.tangent;
  15840. const morphTargets = !!object.geometry && !!object.geometry.morphAttributes.position;
  15841. const morphNormals = !!object.geometry && !!object.geometry.morphAttributes.normal;
  15842. const materialProperties = properties.get(material);
  15843. const lights = currentRenderState.state.lights;
  15844. if (_clippingEnabled === true) {
  15845. if (_localClippingEnabled === true || camera !== _currentCamera) {
  15846. const useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  15847. // object instead of the material, once it becomes feasible
  15848. // (#8465, #8379)
  15849. clipping.setState(material, camera, useCache);
  15850. }
  15851. } //
  15852. let needsProgramChange = false;
  15853. if (material.version === materialProperties.__version) {
  15854. if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  15855. needsProgramChange = true;
  15856. } else if (materialProperties.outputEncoding !== encoding) {
  15857. needsProgramChange = true;
  15858. } else if (object.isInstancedMesh && materialProperties.instancing === false) {
  15859. needsProgramChange = true;
  15860. } else if (!object.isInstancedMesh && materialProperties.instancing === true) {
  15861. needsProgramChange = true;
  15862. } else if (object.isSkinnedMesh && materialProperties.skinning === false) {
  15863. needsProgramChange = true;
  15864. } else if (!object.isSkinnedMesh && materialProperties.skinning === true) {
  15865. needsProgramChange = true;
  15866. } else if (materialProperties.envMap !== envMap) {
  15867. needsProgramChange = true;
  15868. } else if (material.fog && materialProperties.fog !== fog) {
  15869. needsProgramChange = true;
  15870. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  15871. needsProgramChange = true;
  15872. } else if (materialProperties.vertexAlphas !== vertexAlphas) {
  15873. needsProgramChange = true;
  15874. } else if (materialProperties.vertexTangents !== vertexTangents) {
  15875. needsProgramChange = true;
  15876. } else if (materialProperties.morphTargets !== morphTargets) {
  15877. needsProgramChange = true;
  15878. } else if (materialProperties.morphNormals !== morphNormals) {
  15879. needsProgramChange = true;
  15880. }
  15881. } else {
  15882. needsProgramChange = true;
  15883. materialProperties.__version = material.version;
  15884. } //
  15885. let program = materialProperties.currentProgram;
  15886. if (needsProgramChange === true) {
  15887. program = getProgram(material, scene, object);
  15888. }
  15889. let refreshProgram = false;
  15890. let refreshMaterial = false;
  15891. let refreshLights = false;
  15892. const p_uniforms = program.getUniforms(),
  15893. m_uniforms = materialProperties.uniforms;
  15894. if (state.useProgram(program.program)) {
  15895. refreshProgram = true;
  15896. refreshMaterial = true;
  15897. refreshLights = true;
  15898. }
  15899. if (material.id !== _currentMaterialId) {
  15900. _currentMaterialId = material.id;
  15901. refreshMaterial = true;
  15902. }
  15903. if (refreshProgram || _currentCamera !== camera) {
  15904. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  15905. if (capabilities.logarithmicDepthBuffer) {
  15906. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  15907. }
  15908. if (_currentCamera !== camera) {
  15909. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  15910. // now, in case this material supports lights - or later, when
  15911. // the next material that does gets activated:
  15912. refreshMaterial = true; // set to true on material change
  15913. refreshLights = true; // remains set until update done
  15914. } // load material specific uniforms
  15915. // (shader material also gets them for the sake of genericity)
  15916. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  15917. const uCamPos = p_uniforms.map.cameraPosition;
  15918. if (uCamPos !== undefined) {
  15919. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  15920. }
  15921. }
  15922. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  15923. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  15924. }
  15925. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || object.isSkinnedMesh) {
  15926. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  15927. }
  15928. } // skinning uniforms must be set even if material didn't change
  15929. // auto-setting of texture unit for bone texture must go before other textures
  15930. // otherwise textures used for skinning can take over texture units reserved for other material textures
  15931. if (object.isSkinnedMesh) {
  15932. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  15933. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  15934. const skeleton = object.skeleton;
  15935. if (skeleton) {
  15936. if (capabilities.floatVertexTextures) {
  15937. if (skeleton.boneTexture === null) skeleton.computeBoneTexture();
  15938. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  15939. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  15940. } else {
  15941. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  15942. }
  15943. }
  15944. }
  15945. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  15946. materialProperties.receiveShadow = object.receiveShadow;
  15947. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  15948. }
  15949. if (refreshMaterial) {
  15950. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  15951. if (materialProperties.needsLights) {
  15952. // the current material requires lighting info
  15953. // note: all lighting uniforms are always set correctly
  15954. // they simply reference the renderer's state for their
  15955. // values
  15956. //
  15957. // use the current material's .needsUpdate flags to set
  15958. // the GL state when required
  15959. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  15960. } // refresh uniforms common to several materials
  15961. if (fog && material.fog) {
  15962. materials.refreshFogUniforms(m_uniforms, fog);
  15963. }
  15964. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget);
  15965. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15966. }
  15967. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  15968. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15969. material.uniformsNeedUpdate = false;
  15970. }
  15971. if (material.isSpriteMaterial) {
  15972. p_uniforms.setValue(_gl, 'center', object.center);
  15973. } // common matrices
  15974. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  15975. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  15976. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  15977. return program;
  15978. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15979. function markUniformsLightsNeedsUpdate(uniforms, value) {
  15980. uniforms.ambientLightColor.needsUpdate = value;
  15981. uniforms.lightProbe.needsUpdate = value;
  15982. uniforms.directionalLights.needsUpdate = value;
  15983. uniforms.directionalLightShadows.needsUpdate = value;
  15984. uniforms.pointLights.needsUpdate = value;
  15985. uniforms.pointLightShadows.needsUpdate = value;
  15986. uniforms.spotLights.needsUpdate = value;
  15987. uniforms.spotLightShadows.needsUpdate = value;
  15988. uniforms.rectAreaLights.needsUpdate = value;
  15989. uniforms.hemisphereLights.needsUpdate = value;
  15990. }
  15991. function materialNeedsLights(material) {
  15992. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  15993. }
  15994. this.getActiveCubeFace = function () {
  15995. return _currentActiveCubeFace;
  15996. };
  15997. this.getActiveMipmapLevel = function () {
  15998. return _currentActiveMipmapLevel;
  15999. };
  16000. this.getRenderTarget = function () {
  16001. return _currentRenderTarget;
  16002. };
  16003. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  16004. _currentRenderTarget = renderTarget;
  16005. _currentActiveCubeFace = activeCubeFace;
  16006. _currentActiveMipmapLevel = activeMipmapLevel;
  16007. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  16008. textures.setupRenderTarget(renderTarget);
  16009. }
  16010. let framebuffer = null;
  16011. let isCube = false;
  16012. let isRenderTarget3D = false;
  16013. if (renderTarget) {
  16014. const texture = renderTarget.texture;
  16015. if (texture.isDataTexture3D || texture.isDataTexture2DArray) {
  16016. isRenderTarget3D = true;
  16017. }
  16018. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  16019. if (renderTarget.isWebGLCubeRenderTarget) {
  16020. framebuffer = __webglFramebuffer[activeCubeFace];
  16021. isCube = true;
  16022. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  16023. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  16024. } else {
  16025. framebuffer = __webglFramebuffer;
  16026. }
  16027. _currentViewport.copy(renderTarget.viewport);
  16028. _currentScissor.copy(renderTarget.scissor);
  16029. _currentScissorTest = renderTarget.scissorTest;
  16030. } else {
  16031. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  16032. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  16033. _currentScissorTest = _scissorTest;
  16034. }
  16035. const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16036. if (framebufferBound && capabilities.drawBuffers) {
  16037. let needsUpdate = false;
  16038. if (renderTarget) {
  16039. if (renderTarget.isWebGLMultipleRenderTargets) {
  16040. const textures = renderTarget.texture;
  16041. if (_currentDrawBuffers.length !== textures.length || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  16042. for (let i = 0, il = textures.length; i < il; i++) {
  16043. _currentDrawBuffers[i] = _gl.COLOR_ATTACHMENT0 + i;
  16044. }
  16045. _currentDrawBuffers.length = textures.length;
  16046. needsUpdate = true;
  16047. }
  16048. } else {
  16049. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  16050. _currentDrawBuffers[0] = _gl.COLOR_ATTACHMENT0;
  16051. _currentDrawBuffers.length = 1;
  16052. needsUpdate = true;
  16053. }
  16054. }
  16055. } else {
  16056. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.BACK) {
  16057. _currentDrawBuffers[0] = _gl.BACK;
  16058. _currentDrawBuffers.length = 1;
  16059. needsUpdate = true;
  16060. }
  16061. }
  16062. if (needsUpdate) {
  16063. if (capabilities.isWebGL2) {
  16064. _gl.drawBuffers(_currentDrawBuffers);
  16065. } else {
  16066. extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(_currentDrawBuffers);
  16067. }
  16068. }
  16069. }
  16070. state.viewport(_currentViewport);
  16071. state.scissor(_currentScissor);
  16072. state.setScissorTest(_currentScissorTest);
  16073. if (isCube) {
  16074. const textureProperties = properties.get(renderTarget.texture);
  16075. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  16076. } else if (isRenderTarget3D) {
  16077. const textureProperties = properties.get(renderTarget.texture);
  16078. const layer = activeCubeFace || 0;
  16079. _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer);
  16080. }
  16081. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  16082. };
  16083. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  16084. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  16085. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  16086. return;
  16087. }
  16088. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  16089. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  16090. framebuffer = framebuffer[activeCubeFaceIndex];
  16091. }
  16092. if (framebuffer) {
  16093. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16094. try {
  16095. const texture = renderTarget.texture;
  16096. const textureFormat = texture.format;
  16097. const textureType = texture.type;
  16098. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) {
  16099. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  16100. return;
  16101. }
  16102. const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
  16103. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513)
  16104. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  16105. !halfFloatSupportedByExt) {
  16106. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  16107. return;
  16108. }
  16109. if (_gl.checkFramebufferStatus(_gl.FRAMEBUFFER) === _gl.FRAMEBUFFER_COMPLETE) {
  16110. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16111. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  16112. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  16113. }
  16114. } else {
  16115. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  16116. }
  16117. } finally {
  16118. // restore framebuffer of current render target if necessary
  16119. const framebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
  16120. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16121. }
  16122. }
  16123. };
  16124. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  16125. const levelScale = Math.pow(2, -level);
  16126. const width = Math.floor(texture.image.width * levelScale);
  16127. const height = Math.floor(texture.image.height * levelScale);
  16128. let glFormat = utils.convert(texture.format);
  16129. if (capabilities.isWebGL2) {
  16130. // Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=1120100
  16131. // Not needed in Chrome 93+
  16132. if (glFormat === _gl.RGB) glFormat = _gl.RGB8;
  16133. if (glFormat === _gl.RGBA) glFormat = _gl.RGBA8;
  16134. }
  16135. textures.setTexture2D(texture, 0);
  16136. _gl.copyTexImage2D(_gl.TEXTURE_2D, level, glFormat, position.x, position.y, width, height, 0);
  16137. state.unbindTexture();
  16138. };
  16139. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  16140. const width = srcTexture.image.width;
  16141. const height = srcTexture.image.height;
  16142. const glFormat = utils.convert(dstTexture.format);
  16143. const glType = utils.convert(dstTexture.type);
  16144. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  16145. // parameters, make sure they are correct for the dstTexture
  16146. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  16147. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  16148. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  16149. if (srcTexture.isDataTexture) {
  16150. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  16151. } else {
  16152. if (srcTexture.isCompressedTexture) {
  16153. _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  16154. } else {
  16155. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image);
  16156. }
  16157. } // Generate mipmaps only when copying level 0
  16158. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D);
  16159. state.unbindTexture();
  16160. };
  16161. this.copyTextureToTexture3D = function (sourceBox, position, srcTexture, dstTexture, level = 0) {
  16162. if (_this.isWebGL1Renderer) {
  16163. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.');
  16164. return;
  16165. }
  16166. const width = sourceBox.max.x - sourceBox.min.x + 1;
  16167. const height = sourceBox.max.y - sourceBox.min.y + 1;
  16168. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  16169. const glFormat = utils.convert(dstTexture.format);
  16170. const glType = utils.convert(dstTexture.type);
  16171. let glTarget;
  16172. if (dstTexture.isDataTexture3D) {
  16173. textures.setTexture3D(dstTexture, 0);
  16174. glTarget = _gl.TEXTURE_3D;
  16175. } else if (dstTexture.isDataTexture2DArray) {
  16176. textures.setTexture2DArray(dstTexture, 0);
  16177. glTarget = _gl.TEXTURE_2D_ARRAY;
  16178. } else {
  16179. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.');
  16180. return;
  16181. }
  16182. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  16183. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  16184. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  16185. const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH);
  16186. const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT);
  16187. const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS);
  16188. const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS);
  16189. const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES);
  16190. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[0] : srcTexture.image;
  16191. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width);
  16192. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height);
  16193. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x);
  16194. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y);
  16195. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z);
  16196. if (srcTexture.isDataTexture || srcTexture.isDataTexture3D) {
  16197. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data);
  16198. } else {
  16199. if (srcTexture.isCompressedTexture) {
  16200. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.');
  16201. _gl.compressedTexSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data);
  16202. } else {
  16203. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image);
  16204. }
  16205. }
  16206. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen);
  16207. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight);
  16208. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels);
  16209. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows);
  16210. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages); // Generate mipmaps only when copying level 0
  16211. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget);
  16212. state.unbindTexture();
  16213. };
  16214. this.initTexture = function (texture) {
  16215. textures.setTexture2D(texture, 0);
  16216. state.unbindTexture();
  16217. };
  16218. this.resetState = function () {
  16219. _currentActiveCubeFace = 0;
  16220. _currentActiveMipmapLevel = 0;
  16221. _currentRenderTarget = null;
  16222. state.reset();
  16223. bindingStates.reset();
  16224. };
  16225. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  16226. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  16227. detail: this
  16228. })); // eslint-disable-line no-undef
  16229. }
  16230. }
  16231. class WebGL1Renderer extends WebGLRenderer {}
  16232. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  16233. class FogExp2 {
  16234. constructor(color, density = 0.00025) {
  16235. this.name = '';
  16236. this.color = new Color(color);
  16237. this.density = density;
  16238. }
  16239. clone() {
  16240. return new FogExp2(this.color, this.density);
  16241. }
  16242. toJSON() {
  16243. return {
  16244. type: 'FogExp2',
  16245. color: this.color.getHex(),
  16246. density: this.density
  16247. };
  16248. }
  16249. }
  16250. FogExp2.prototype.isFogExp2 = true;
  16251. class Fog {
  16252. constructor(color, near = 1, far = 1000) {
  16253. this.name = '';
  16254. this.color = new Color(color);
  16255. this.near = near;
  16256. this.far = far;
  16257. }
  16258. clone() {
  16259. return new Fog(this.color, this.near, this.far);
  16260. }
  16261. toJSON() {
  16262. return {
  16263. type: 'Fog',
  16264. color: this.color.getHex(),
  16265. near: this.near,
  16266. far: this.far
  16267. };
  16268. }
  16269. }
  16270. Fog.prototype.isFog = true;
  16271. class Scene extends Object3D {
  16272. constructor() {
  16273. super();
  16274. this.type = 'Scene';
  16275. this.background = null;
  16276. this.environment = null;
  16277. this.fog = null;
  16278. this.overrideMaterial = null;
  16279. this.autoUpdate = true; // checked by the renderer
  16280. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  16281. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  16282. detail: this
  16283. })); // eslint-disable-line no-undef
  16284. }
  16285. }
  16286. copy(source, recursive) {
  16287. super.copy(source, recursive);
  16288. if (source.background !== null) this.background = source.background.clone();
  16289. if (source.environment !== null) this.environment = source.environment.clone();
  16290. if (source.fog !== null) this.fog = source.fog.clone();
  16291. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  16292. this.autoUpdate = source.autoUpdate;
  16293. this.matrixAutoUpdate = source.matrixAutoUpdate;
  16294. return this;
  16295. }
  16296. toJSON(meta) {
  16297. const data = super.toJSON(meta);
  16298. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  16299. return data;
  16300. }
  16301. }
  16302. Scene.prototype.isScene = true;
  16303. class InterleavedBuffer {
  16304. constructor(array, stride) {
  16305. this.array = array;
  16306. this.stride = stride;
  16307. this.count = array !== undefined ? array.length / stride : 0;
  16308. this.usage = StaticDrawUsage;
  16309. this.updateRange = {
  16310. offset: 0,
  16311. count: -1
  16312. };
  16313. this.version = 0;
  16314. this.uuid = generateUUID();
  16315. }
  16316. onUploadCallback() {}
  16317. set needsUpdate(value) {
  16318. if (value === true) this.version++;
  16319. }
  16320. setUsage(value) {
  16321. this.usage = value;
  16322. return this;
  16323. }
  16324. copy(source) {
  16325. this.array = new source.array.constructor(source.array);
  16326. this.count = source.count;
  16327. this.stride = source.stride;
  16328. this.usage = source.usage;
  16329. return this;
  16330. }
  16331. copyAt(index1, attribute, index2) {
  16332. index1 *= this.stride;
  16333. index2 *= attribute.stride;
  16334. for (let i = 0, l = this.stride; i < l; i++) {
  16335. this.array[index1 + i] = attribute.array[index2 + i];
  16336. }
  16337. return this;
  16338. }
  16339. set(value, offset = 0) {
  16340. this.array.set(value, offset);
  16341. return this;
  16342. }
  16343. clone(data) {
  16344. if (data.arrayBuffers === undefined) {
  16345. data.arrayBuffers = {};
  16346. }
  16347. if (this.array.buffer._uuid === undefined) {
  16348. this.array.buffer._uuid = generateUUID();
  16349. }
  16350. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  16351. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  16352. }
  16353. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  16354. const ib = new this.constructor(array, this.stride);
  16355. ib.setUsage(this.usage);
  16356. return ib;
  16357. }
  16358. onUpload(callback) {
  16359. this.onUploadCallback = callback;
  16360. return this;
  16361. }
  16362. toJSON(data) {
  16363. if (data.arrayBuffers === undefined) {
  16364. data.arrayBuffers = {};
  16365. } // generate UUID for array buffer if necessary
  16366. if (this.array.buffer._uuid === undefined) {
  16367. this.array.buffer._uuid = generateUUID();
  16368. }
  16369. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  16370. data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
  16371. } //
  16372. return {
  16373. uuid: this.uuid,
  16374. buffer: this.array.buffer._uuid,
  16375. type: this.array.constructor.name,
  16376. stride: this.stride
  16377. };
  16378. }
  16379. }
  16380. InterleavedBuffer.prototype.isInterleavedBuffer = true;
  16381. const _vector$6 = /*@__PURE__*/new Vector3();
  16382. class InterleavedBufferAttribute {
  16383. constructor(interleavedBuffer, itemSize, offset, normalized = false) {
  16384. this.name = '';
  16385. this.data = interleavedBuffer;
  16386. this.itemSize = itemSize;
  16387. this.offset = offset;
  16388. this.normalized = normalized === true;
  16389. }
  16390. get count() {
  16391. return this.data.count;
  16392. }
  16393. get array() {
  16394. return this.data.array;
  16395. }
  16396. set needsUpdate(value) {
  16397. this.data.needsUpdate = value;
  16398. }
  16399. applyMatrix4(m) {
  16400. for (let i = 0, l = this.data.count; i < l; i++) {
  16401. _vector$6.x = this.getX(i);
  16402. _vector$6.y = this.getY(i);
  16403. _vector$6.z = this.getZ(i);
  16404. _vector$6.applyMatrix4(m);
  16405. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16406. }
  16407. return this;
  16408. }
  16409. applyNormalMatrix(m) {
  16410. for (let i = 0, l = this.count; i < l; i++) {
  16411. _vector$6.x = this.getX(i);
  16412. _vector$6.y = this.getY(i);
  16413. _vector$6.z = this.getZ(i);
  16414. _vector$6.applyNormalMatrix(m);
  16415. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16416. }
  16417. return this;
  16418. }
  16419. transformDirection(m) {
  16420. for (let i = 0, l = this.count; i < l; i++) {
  16421. _vector$6.x = this.getX(i);
  16422. _vector$6.y = this.getY(i);
  16423. _vector$6.z = this.getZ(i);
  16424. _vector$6.transformDirection(m);
  16425. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16426. }
  16427. return this;
  16428. }
  16429. setX(index, x) {
  16430. this.data.array[index * this.data.stride + this.offset] = x;
  16431. return this;
  16432. }
  16433. setY(index, y) {
  16434. this.data.array[index * this.data.stride + this.offset + 1] = y;
  16435. return this;
  16436. }
  16437. setZ(index, z) {
  16438. this.data.array[index * this.data.stride + this.offset + 2] = z;
  16439. return this;
  16440. }
  16441. setW(index, w) {
  16442. this.data.array[index * this.data.stride + this.offset + 3] = w;
  16443. return this;
  16444. }
  16445. getX(index) {
  16446. return this.data.array[index * this.data.stride + this.offset];
  16447. }
  16448. getY(index) {
  16449. return this.data.array[index * this.data.stride + this.offset + 1];
  16450. }
  16451. getZ(index) {
  16452. return this.data.array[index * this.data.stride + this.offset + 2];
  16453. }
  16454. getW(index) {
  16455. return this.data.array[index * this.data.stride + this.offset + 3];
  16456. }
  16457. setXY(index, x, y) {
  16458. index = index * this.data.stride + this.offset;
  16459. this.data.array[index + 0] = x;
  16460. this.data.array[index + 1] = y;
  16461. return this;
  16462. }
  16463. setXYZ(index, x, y, z) {
  16464. index = index * this.data.stride + this.offset;
  16465. this.data.array[index + 0] = x;
  16466. this.data.array[index + 1] = y;
  16467. this.data.array[index + 2] = z;
  16468. return this;
  16469. }
  16470. setXYZW(index, x, y, z, w) {
  16471. index = index * this.data.stride + this.offset;
  16472. this.data.array[index + 0] = x;
  16473. this.data.array[index + 1] = y;
  16474. this.data.array[index + 2] = z;
  16475. this.data.array[index + 3] = w;
  16476. return this;
  16477. }
  16478. clone(data) {
  16479. if (data === undefined) {
  16480. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');
  16481. const array = [];
  16482. for (let i = 0; i < this.count; i++) {
  16483. const index = i * this.data.stride + this.offset;
  16484. for (let j = 0; j < this.itemSize; j++) {
  16485. array.push(this.data.array[index + j]);
  16486. }
  16487. }
  16488. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  16489. } else {
  16490. if (data.interleavedBuffers === undefined) {
  16491. data.interleavedBuffers = {};
  16492. }
  16493. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  16494. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  16495. }
  16496. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  16497. }
  16498. }
  16499. toJSON(data) {
  16500. if (data === undefined) {
  16501. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');
  16502. const array = [];
  16503. for (let i = 0; i < this.count; i++) {
  16504. const index = i * this.data.stride + this.offset;
  16505. for (let j = 0; j < this.itemSize; j++) {
  16506. array.push(this.data.array[index + j]);
  16507. }
  16508. } // deinterleave data and save it as an ordinary buffer attribute for now
  16509. return {
  16510. itemSize: this.itemSize,
  16511. type: this.array.constructor.name,
  16512. array: array,
  16513. normalized: this.normalized
  16514. };
  16515. } else {
  16516. // save as true interlaved attribtue
  16517. if (data.interleavedBuffers === undefined) {
  16518. data.interleavedBuffers = {};
  16519. }
  16520. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  16521. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  16522. }
  16523. return {
  16524. isInterleavedBufferAttribute: true,
  16525. itemSize: this.itemSize,
  16526. data: this.data.uuid,
  16527. offset: this.offset,
  16528. normalized: this.normalized
  16529. };
  16530. }
  16531. }
  16532. }
  16533. InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
  16534. /**
  16535. * parameters = {
  16536. * color: <hex>,
  16537. * map: new THREE.Texture( <Image> ),
  16538. * alphaMap: new THREE.Texture( <Image> ),
  16539. * rotation: <float>,
  16540. * sizeAttenuation: <bool>
  16541. * }
  16542. */
  16543. class SpriteMaterial extends Material {
  16544. constructor(parameters) {
  16545. super();
  16546. this.type = 'SpriteMaterial';
  16547. this.color = new Color(0xffffff);
  16548. this.map = null;
  16549. this.alphaMap = null;
  16550. this.rotation = 0;
  16551. this.sizeAttenuation = true;
  16552. this.transparent = true;
  16553. this.setValues(parameters);
  16554. }
  16555. copy(source) {
  16556. super.copy(source);
  16557. this.color.copy(source.color);
  16558. this.map = source.map;
  16559. this.alphaMap = source.alphaMap;
  16560. this.rotation = source.rotation;
  16561. this.sizeAttenuation = source.sizeAttenuation;
  16562. return this;
  16563. }
  16564. }
  16565. SpriteMaterial.prototype.isSpriteMaterial = true;
  16566. let _geometry;
  16567. const _intersectPoint = /*@__PURE__*/new Vector3();
  16568. const _worldScale = /*@__PURE__*/new Vector3();
  16569. const _mvPosition = /*@__PURE__*/new Vector3();
  16570. const _alignedPosition = /*@__PURE__*/new Vector2();
  16571. const _rotatedPosition = /*@__PURE__*/new Vector2();
  16572. const _viewWorldMatrix = /*@__PURE__*/new Matrix4();
  16573. const _vA = /*@__PURE__*/new Vector3();
  16574. const _vB = /*@__PURE__*/new Vector3();
  16575. const _vC = /*@__PURE__*/new Vector3();
  16576. const _uvA = /*@__PURE__*/new Vector2();
  16577. const _uvB = /*@__PURE__*/new Vector2();
  16578. const _uvC = /*@__PURE__*/new Vector2();
  16579. class Sprite extends Object3D {
  16580. constructor(material) {
  16581. super();
  16582. this.type = 'Sprite';
  16583. if (_geometry === undefined) {
  16584. _geometry = new BufferGeometry();
  16585. const float32Array = new Float32Array([-0.5, -0.5, 0, 0, 0, 0.5, -0.5, 0, 1, 0, 0.5, 0.5, 0, 1, 1, -0.5, 0.5, 0, 0, 1]);
  16586. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  16587. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  16588. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  16589. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  16590. }
  16591. this.geometry = _geometry;
  16592. this.material = material !== undefined ? material : new SpriteMaterial();
  16593. this.center = new Vector2(0.5, 0.5);
  16594. }
  16595. raycast(raycaster, intersects) {
  16596. if (raycaster.camera === null) {
  16597. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  16598. }
  16599. _worldScale.setFromMatrixScale(this.matrixWorld);
  16600. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  16601. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  16602. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  16603. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  16604. _worldScale.multiplyScalar(-_mvPosition.z);
  16605. }
  16606. const rotation = this.material.rotation;
  16607. let sin, cos;
  16608. if (rotation !== 0) {
  16609. cos = Math.cos(rotation);
  16610. sin = Math.sin(rotation);
  16611. }
  16612. const center = this.center;
  16613. transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16614. transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16615. transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16616. _uvA.set(0, 0);
  16617. _uvB.set(1, 0);
  16618. _uvC.set(1, 1); // check first triangle
  16619. let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
  16620. if (intersect === null) {
  16621. // check second triangle
  16622. transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16623. _uvB.set(0, 1);
  16624. intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
  16625. if (intersect === null) {
  16626. return;
  16627. }
  16628. }
  16629. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  16630. if (distance < raycaster.near || distance > raycaster.far) return;
  16631. intersects.push({
  16632. distance: distance,
  16633. point: _intersectPoint.clone(),
  16634. uv: Triangle.getUV(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()),
  16635. face: null,
  16636. object: this
  16637. });
  16638. }
  16639. copy(source) {
  16640. super.copy(source);
  16641. if (source.center !== undefined) this.center.copy(source.center);
  16642. this.material = source.material;
  16643. return this;
  16644. }
  16645. }
  16646. Sprite.prototype.isSprite = true;
  16647. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  16648. // compute position in camera space
  16649. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  16650. if (sin !== undefined) {
  16651. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  16652. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  16653. } else {
  16654. _rotatedPosition.copy(_alignedPosition);
  16655. }
  16656. vertexPosition.copy(mvPosition);
  16657. vertexPosition.x += _rotatedPosition.x;
  16658. vertexPosition.y += _rotatedPosition.y; // transform to world space
  16659. vertexPosition.applyMatrix4(_viewWorldMatrix);
  16660. }
  16661. const _v1$2 = /*@__PURE__*/new Vector3();
  16662. const _v2$1 = /*@__PURE__*/new Vector3();
  16663. class LOD extends Object3D {
  16664. constructor() {
  16665. super();
  16666. this._currentLevel = 0;
  16667. this.type = 'LOD';
  16668. Object.defineProperties(this, {
  16669. levels: {
  16670. enumerable: true,
  16671. value: []
  16672. },
  16673. isLOD: {
  16674. value: true
  16675. }
  16676. });
  16677. this.autoUpdate = true;
  16678. }
  16679. copy(source) {
  16680. super.copy(source, false);
  16681. const levels = source.levels;
  16682. for (let i = 0, l = levels.length; i < l; i++) {
  16683. const level = levels[i];
  16684. this.addLevel(level.object.clone(), level.distance);
  16685. }
  16686. this.autoUpdate = source.autoUpdate;
  16687. return this;
  16688. }
  16689. addLevel(object, distance = 0) {
  16690. distance = Math.abs(distance);
  16691. const levels = this.levels;
  16692. let l;
  16693. for (l = 0; l < levels.length; l++) {
  16694. if (distance < levels[l].distance) {
  16695. break;
  16696. }
  16697. }
  16698. levels.splice(l, 0, {
  16699. distance: distance,
  16700. object: object
  16701. });
  16702. this.add(object);
  16703. return this;
  16704. }
  16705. getCurrentLevel() {
  16706. return this._currentLevel;
  16707. }
  16708. getObjectForDistance(distance) {
  16709. const levels = this.levels;
  16710. if (levels.length > 0) {
  16711. let i, l;
  16712. for (i = 1, l = levels.length; i < l; i++) {
  16713. if (distance < levels[i].distance) {
  16714. break;
  16715. }
  16716. }
  16717. return levels[i - 1].object;
  16718. }
  16719. return null;
  16720. }
  16721. raycast(raycaster, intersects) {
  16722. const levels = this.levels;
  16723. if (levels.length > 0) {
  16724. _v1$2.setFromMatrixPosition(this.matrixWorld);
  16725. const distance = raycaster.ray.origin.distanceTo(_v1$2);
  16726. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  16727. }
  16728. }
  16729. update(camera) {
  16730. const levels = this.levels;
  16731. if (levels.length > 1) {
  16732. _v1$2.setFromMatrixPosition(camera.matrixWorld);
  16733. _v2$1.setFromMatrixPosition(this.matrixWorld);
  16734. const distance = _v1$2.distanceTo(_v2$1) / camera.zoom;
  16735. levels[0].object.visible = true;
  16736. let i, l;
  16737. for (i = 1, l = levels.length; i < l; i++) {
  16738. if (distance >= levels[i].distance) {
  16739. levels[i - 1].object.visible = false;
  16740. levels[i].object.visible = true;
  16741. } else {
  16742. break;
  16743. }
  16744. }
  16745. this._currentLevel = i - 1;
  16746. for (; i < l; i++) {
  16747. levels[i].object.visible = false;
  16748. }
  16749. }
  16750. }
  16751. toJSON(meta) {
  16752. const data = super.toJSON(meta);
  16753. if (this.autoUpdate === false) data.object.autoUpdate = false;
  16754. data.object.levels = [];
  16755. const levels = this.levels;
  16756. for (let i = 0, l = levels.length; i < l; i++) {
  16757. const level = levels[i];
  16758. data.object.levels.push({
  16759. object: level.object.uuid,
  16760. distance: level.distance
  16761. });
  16762. }
  16763. return data;
  16764. }
  16765. }
  16766. const _basePosition = /*@__PURE__*/new Vector3();
  16767. const _skinIndex = /*@__PURE__*/new Vector4();
  16768. const _skinWeight = /*@__PURE__*/new Vector4();
  16769. const _vector$5 = /*@__PURE__*/new Vector3();
  16770. const _matrix = /*@__PURE__*/new Matrix4();
  16771. class SkinnedMesh extends Mesh {
  16772. constructor(geometry, material) {
  16773. super(geometry, material);
  16774. this.type = 'SkinnedMesh';
  16775. this.bindMode = 'attached';
  16776. this.bindMatrix = new Matrix4();
  16777. this.bindMatrixInverse = new Matrix4();
  16778. }
  16779. copy(source) {
  16780. super.copy(source);
  16781. this.bindMode = source.bindMode;
  16782. this.bindMatrix.copy(source.bindMatrix);
  16783. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  16784. this.skeleton = source.skeleton;
  16785. return this;
  16786. }
  16787. bind(skeleton, bindMatrix) {
  16788. this.skeleton = skeleton;
  16789. if (bindMatrix === undefined) {
  16790. this.updateMatrixWorld(true);
  16791. this.skeleton.calculateInverses();
  16792. bindMatrix = this.matrixWorld;
  16793. }
  16794. this.bindMatrix.copy(bindMatrix);
  16795. this.bindMatrixInverse.copy(bindMatrix).invert();
  16796. }
  16797. pose() {
  16798. this.skeleton.pose();
  16799. }
  16800. normalizeSkinWeights() {
  16801. const vector = new Vector4();
  16802. const skinWeight = this.geometry.attributes.skinWeight;
  16803. for (let i = 0, l = skinWeight.count; i < l; i++) {
  16804. vector.x = skinWeight.getX(i);
  16805. vector.y = skinWeight.getY(i);
  16806. vector.z = skinWeight.getZ(i);
  16807. vector.w = skinWeight.getW(i);
  16808. const scale = 1.0 / vector.manhattanLength();
  16809. if (scale !== Infinity) {
  16810. vector.multiplyScalar(scale);
  16811. } else {
  16812. vector.set(1, 0, 0, 0); // do something reasonable
  16813. }
  16814. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  16815. }
  16816. }
  16817. updateMatrixWorld(force) {
  16818. super.updateMatrixWorld(force);
  16819. if (this.bindMode === 'attached') {
  16820. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  16821. } else if (this.bindMode === 'detached') {
  16822. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  16823. } else {
  16824. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  16825. }
  16826. }
  16827. boneTransform(index, target) {
  16828. const skeleton = this.skeleton;
  16829. const geometry = this.geometry;
  16830. _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  16831. _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  16832. _basePosition.fromBufferAttribute(geometry.attributes.position, index).applyMatrix4(this.bindMatrix);
  16833. target.set(0, 0, 0);
  16834. for (let i = 0; i < 4; i++) {
  16835. const weight = _skinWeight.getComponent(i);
  16836. if (weight !== 0) {
  16837. const boneIndex = _skinIndex.getComponent(i);
  16838. _matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  16839. target.addScaledVector(_vector$5.copy(_basePosition).applyMatrix4(_matrix), weight);
  16840. }
  16841. }
  16842. return target.applyMatrix4(this.bindMatrixInverse);
  16843. }
  16844. }
  16845. SkinnedMesh.prototype.isSkinnedMesh = true;
  16846. class Bone extends Object3D {
  16847. constructor() {
  16848. super();
  16849. this.type = 'Bone';
  16850. }
  16851. }
  16852. Bone.prototype.isBone = true;
  16853. class DataTexture extends Texture {
  16854. constructor(data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding) {
  16855. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  16856. this.image = {
  16857. data: data,
  16858. width: width,
  16859. height: height
  16860. };
  16861. this.magFilter = magFilter;
  16862. this.minFilter = minFilter;
  16863. this.generateMipmaps = false;
  16864. this.flipY = false;
  16865. this.unpackAlignment = 1;
  16866. this.needsUpdate = true;
  16867. }
  16868. }
  16869. DataTexture.prototype.isDataTexture = true;
  16870. const _offsetMatrix = /*@__PURE__*/new Matrix4();
  16871. const _identityMatrix = /*@__PURE__*/new Matrix4();
  16872. class Skeleton {
  16873. constructor(bones = [], boneInverses = []) {
  16874. this.uuid = generateUUID();
  16875. this.bones = bones.slice(0);
  16876. this.boneInverses = boneInverses;
  16877. this.boneMatrices = null;
  16878. this.boneTexture = null;
  16879. this.boneTextureSize = 0;
  16880. this.frame = -1;
  16881. this.init();
  16882. }
  16883. init() {
  16884. const bones = this.bones;
  16885. const boneInverses = this.boneInverses;
  16886. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  16887. if (boneInverses.length === 0) {
  16888. this.calculateInverses();
  16889. } else {
  16890. // handle special case
  16891. if (bones.length !== boneInverses.length) {
  16892. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  16893. this.boneInverses = [];
  16894. for (let i = 0, il = this.bones.length; i < il; i++) {
  16895. this.boneInverses.push(new Matrix4());
  16896. }
  16897. }
  16898. }
  16899. }
  16900. calculateInverses() {
  16901. this.boneInverses.length = 0;
  16902. for (let i = 0, il = this.bones.length; i < il; i++) {
  16903. const inverse = new Matrix4();
  16904. if (this.bones[i]) {
  16905. inverse.copy(this.bones[i].matrixWorld).invert();
  16906. }
  16907. this.boneInverses.push(inverse);
  16908. }
  16909. }
  16910. pose() {
  16911. // recover the bind-time world matrices
  16912. for (let i = 0, il = this.bones.length; i < il; i++) {
  16913. const bone = this.bones[i];
  16914. if (bone) {
  16915. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  16916. }
  16917. } // compute the local matrices, positions, rotations and scales
  16918. for (let i = 0, il = this.bones.length; i < il; i++) {
  16919. const bone = this.bones[i];
  16920. if (bone) {
  16921. if (bone.parent && bone.parent.isBone) {
  16922. bone.matrix.copy(bone.parent.matrixWorld).invert();
  16923. bone.matrix.multiply(bone.matrixWorld);
  16924. } else {
  16925. bone.matrix.copy(bone.matrixWorld);
  16926. }
  16927. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  16928. }
  16929. }
  16930. }
  16931. update() {
  16932. const bones = this.bones;
  16933. const boneInverses = this.boneInverses;
  16934. const boneMatrices = this.boneMatrices;
  16935. const boneTexture = this.boneTexture; // flatten bone matrices to array
  16936. for (let i = 0, il = bones.length; i < il; i++) {
  16937. // compute the offset between the current and the original transform
  16938. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  16939. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  16940. _offsetMatrix.toArray(boneMatrices, i * 16);
  16941. }
  16942. if (boneTexture !== null) {
  16943. boneTexture.needsUpdate = true;
  16944. }
  16945. }
  16946. clone() {
  16947. return new Skeleton(this.bones, this.boneInverses);
  16948. }
  16949. computeBoneTexture() {
  16950. // layout (1 matrix = 4 pixels)
  16951. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  16952. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  16953. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  16954. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  16955. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  16956. let size = Math.sqrt(this.bones.length * 4); // 4 pixels needed for 1 matrix
  16957. size = ceilPowerOfTwo(size);
  16958. size = Math.max(size, 4);
  16959. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  16960. boneMatrices.set(this.boneMatrices); // copy current values
  16961. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  16962. this.boneMatrices = boneMatrices;
  16963. this.boneTexture = boneTexture;
  16964. this.boneTextureSize = size;
  16965. return this;
  16966. }
  16967. getBoneByName(name) {
  16968. for (let i = 0, il = this.bones.length; i < il; i++) {
  16969. const bone = this.bones[i];
  16970. if (bone.name === name) {
  16971. return bone;
  16972. }
  16973. }
  16974. return undefined;
  16975. }
  16976. dispose() {
  16977. if (this.boneTexture !== null) {
  16978. this.boneTexture.dispose();
  16979. this.boneTexture = null;
  16980. }
  16981. }
  16982. fromJSON(json, bones) {
  16983. this.uuid = json.uuid;
  16984. for (let i = 0, l = json.bones.length; i < l; i++) {
  16985. const uuid = json.bones[i];
  16986. let bone = bones[uuid];
  16987. if (bone === undefined) {
  16988. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  16989. bone = new Bone();
  16990. }
  16991. this.bones.push(bone);
  16992. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  16993. }
  16994. this.init();
  16995. return this;
  16996. }
  16997. toJSON() {
  16998. const data = {
  16999. metadata: {
  17000. version: 4.5,
  17001. type: 'Skeleton',
  17002. generator: 'Skeleton.toJSON'
  17003. },
  17004. bones: [],
  17005. boneInverses: []
  17006. };
  17007. data.uuid = this.uuid;
  17008. const bones = this.bones;
  17009. const boneInverses = this.boneInverses;
  17010. for (let i = 0, l = bones.length; i < l; i++) {
  17011. const bone = bones[i];
  17012. data.bones.push(bone.uuid);
  17013. const boneInverse = boneInverses[i];
  17014. data.boneInverses.push(boneInverse.toArray());
  17015. }
  17016. return data;
  17017. }
  17018. }
  17019. class InstancedBufferAttribute extends BufferAttribute {
  17020. constructor(array, itemSize, normalized, meshPerAttribute = 1) {
  17021. if (typeof normalized === 'number') {
  17022. meshPerAttribute = normalized;
  17023. normalized = false;
  17024. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  17025. }
  17026. super(array, itemSize, normalized);
  17027. this.meshPerAttribute = meshPerAttribute;
  17028. }
  17029. copy(source) {
  17030. super.copy(source);
  17031. this.meshPerAttribute = source.meshPerAttribute;
  17032. return this;
  17033. }
  17034. toJSON() {
  17035. const data = super.toJSON();
  17036. data.meshPerAttribute = this.meshPerAttribute;
  17037. data.isInstancedBufferAttribute = true;
  17038. return data;
  17039. }
  17040. }
  17041. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  17042. const _instanceLocalMatrix = /*@__PURE__*/new Matrix4();
  17043. const _instanceWorldMatrix = /*@__PURE__*/new Matrix4();
  17044. const _instanceIntersects = [];
  17045. const _mesh = /*@__PURE__*/new Mesh();
  17046. class InstancedMesh extends Mesh {
  17047. constructor(geometry, material, count) {
  17048. super(geometry, material);
  17049. this.instanceMatrix = new InstancedBufferAttribute(new Float32Array(count * 16), 16);
  17050. this.instanceColor = null;
  17051. this.count = count;
  17052. this.frustumCulled = false;
  17053. }
  17054. copy(source) {
  17055. super.copy(source);
  17056. this.instanceMatrix.copy(source.instanceMatrix);
  17057. if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
  17058. this.count = source.count;
  17059. return this;
  17060. }
  17061. getColorAt(index, color) {
  17062. color.fromArray(this.instanceColor.array, index * 3);
  17063. }
  17064. getMatrixAt(index, matrix) {
  17065. matrix.fromArray(this.instanceMatrix.array, index * 16);
  17066. }
  17067. raycast(raycaster, intersects) {
  17068. const matrixWorld = this.matrixWorld;
  17069. const raycastTimes = this.count;
  17070. _mesh.geometry = this.geometry;
  17071. _mesh.material = this.material;
  17072. if (_mesh.material === undefined) return;
  17073. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  17074. // calculate the world matrix for each instance
  17075. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  17076. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  17077. _mesh.matrixWorld = _instanceWorldMatrix;
  17078. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  17079. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  17080. const intersect = _instanceIntersects[i];
  17081. intersect.instanceId = instanceId;
  17082. intersect.object = this;
  17083. intersects.push(intersect);
  17084. }
  17085. _instanceIntersects.length = 0;
  17086. }
  17087. }
  17088. setColorAt(index, color) {
  17089. if (this.instanceColor === null) {
  17090. this.instanceColor = new InstancedBufferAttribute(new Float32Array(this.instanceMatrix.count * 3), 3);
  17091. }
  17092. color.toArray(this.instanceColor.array, index * 3);
  17093. }
  17094. setMatrixAt(index, matrix) {
  17095. matrix.toArray(this.instanceMatrix.array, index * 16);
  17096. }
  17097. updateMorphTargets() {}
  17098. dispose() {
  17099. this.dispatchEvent({
  17100. type: 'dispose'
  17101. });
  17102. }
  17103. }
  17104. InstancedMesh.prototype.isInstancedMesh = true;
  17105. /**
  17106. * parameters = {
  17107. * color: <hex>,
  17108. * opacity: <float>,
  17109. *
  17110. * linewidth: <float>,
  17111. * linecap: "round",
  17112. * linejoin: "round"
  17113. * }
  17114. */
  17115. class LineBasicMaterial extends Material {
  17116. constructor(parameters) {
  17117. super();
  17118. this.type = 'LineBasicMaterial';
  17119. this.color = new Color(0xffffff);
  17120. this.linewidth = 1;
  17121. this.linecap = 'round';
  17122. this.linejoin = 'round';
  17123. this.setValues(parameters);
  17124. }
  17125. copy(source) {
  17126. super.copy(source);
  17127. this.color.copy(source.color);
  17128. this.linewidth = source.linewidth;
  17129. this.linecap = source.linecap;
  17130. this.linejoin = source.linejoin;
  17131. return this;
  17132. }
  17133. }
  17134. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  17135. const _start$1 = /*@__PURE__*/new Vector3();
  17136. const _end$1 = /*@__PURE__*/new Vector3();
  17137. const _inverseMatrix$1 = /*@__PURE__*/new Matrix4();
  17138. const _ray$1 = /*@__PURE__*/new Ray();
  17139. const _sphere$1 = /*@__PURE__*/new Sphere();
  17140. class Line extends Object3D {
  17141. constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) {
  17142. super();
  17143. this.type = 'Line';
  17144. this.geometry = geometry;
  17145. this.material = material;
  17146. this.updateMorphTargets();
  17147. }
  17148. copy(source) {
  17149. super.copy(source);
  17150. this.material = source.material;
  17151. this.geometry = source.geometry;
  17152. return this;
  17153. }
  17154. computeLineDistances() {
  17155. const geometry = this.geometry;
  17156. if (geometry.isBufferGeometry) {
  17157. // we assume non-indexed geometry
  17158. if (geometry.index === null) {
  17159. const positionAttribute = geometry.attributes.position;
  17160. const lineDistances = [0];
  17161. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  17162. _start$1.fromBufferAttribute(positionAttribute, i - 1);
  17163. _end$1.fromBufferAttribute(positionAttribute, i);
  17164. lineDistances[i] = lineDistances[i - 1];
  17165. lineDistances[i] += _start$1.distanceTo(_end$1);
  17166. }
  17167. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17168. } else {
  17169. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17170. }
  17171. } else if (geometry.isGeometry) {
  17172. console.error('THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17173. }
  17174. return this;
  17175. }
  17176. raycast(raycaster, intersects) {
  17177. const geometry = this.geometry;
  17178. const matrixWorld = this.matrixWorld;
  17179. const threshold = raycaster.params.Line.threshold;
  17180. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  17181. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17182. _sphere$1.copy(geometry.boundingSphere);
  17183. _sphere$1.applyMatrix4(matrixWorld);
  17184. _sphere$1.radius += threshold;
  17185. if (raycaster.ray.intersectsSphere(_sphere$1) === false) return; //
  17186. _inverseMatrix$1.copy(matrixWorld).invert();
  17187. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  17188. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17189. const localThresholdSq = localThreshold * localThreshold;
  17190. const vStart = new Vector3();
  17191. const vEnd = new Vector3();
  17192. const interSegment = new Vector3();
  17193. const interRay = new Vector3();
  17194. const step = this.isLineSegments ? 2 : 1;
  17195. if (geometry.isBufferGeometry) {
  17196. const index = geometry.index;
  17197. const attributes = geometry.attributes;
  17198. const positionAttribute = attributes.position;
  17199. if (index !== null) {
  17200. const start = Math.max(0, drawRange.start);
  17201. const end = Math.min(index.count, drawRange.start + drawRange.count);
  17202. for (let i = start, l = end - 1; i < l; i += step) {
  17203. const a = index.getX(i);
  17204. const b = index.getX(i + 1);
  17205. vStart.fromBufferAttribute(positionAttribute, a);
  17206. vEnd.fromBufferAttribute(positionAttribute, b);
  17207. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17208. if (distSq > localThresholdSq) continue;
  17209. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17210. const distance = raycaster.ray.origin.distanceTo(interRay);
  17211. if (distance < raycaster.near || distance > raycaster.far) continue;
  17212. intersects.push({
  17213. distance: distance,
  17214. // What do we want? intersection point on the ray or on the segment??
  17215. // point: raycaster.ray.at( distance ),
  17216. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17217. index: i,
  17218. face: null,
  17219. faceIndex: null,
  17220. object: this
  17221. });
  17222. }
  17223. } else {
  17224. const start = Math.max(0, drawRange.start);
  17225. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  17226. for (let i = start, l = end - 1; i < l; i += step) {
  17227. vStart.fromBufferAttribute(positionAttribute, i);
  17228. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  17229. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17230. if (distSq > localThresholdSq) continue;
  17231. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17232. const distance = raycaster.ray.origin.distanceTo(interRay);
  17233. if (distance < raycaster.near || distance > raycaster.far) continue;
  17234. intersects.push({
  17235. distance: distance,
  17236. // What do we want? intersection point on the ray or on the segment??
  17237. // point: raycaster.ray.at( distance ),
  17238. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17239. index: i,
  17240. face: null,
  17241. faceIndex: null,
  17242. object: this
  17243. });
  17244. }
  17245. }
  17246. } else if (geometry.isGeometry) {
  17247. console.error('THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17248. }
  17249. }
  17250. updateMorphTargets() {
  17251. const geometry = this.geometry;
  17252. if (geometry.isBufferGeometry) {
  17253. const morphAttributes = geometry.morphAttributes;
  17254. const keys = Object.keys(morphAttributes);
  17255. if (keys.length > 0) {
  17256. const morphAttribute = morphAttributes[keys[0]];
  17257. if (morphAttribute !== undefined) {
  17258. this.morphTargetInfluences = [];
  17259. this.morphTargetDictionary = {};
  17260. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  17261. const name = morphAttribute[m].name || String(m);
  17262. this.morphTargetInfluences.push(0);
  17263. this.morphTargetDictionary[name] = m;
  17264. }
  17265. }
  17266. }
  17267. } else {
  17268. const morphTargets = geometry.morphTargets;
  17269. if (morphTargets !== undefined && morphTargets.length > 0) {
  17270. console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17271. }
  17272. }
  17273. }
  17274. }
  17275. Line.prototype.isLine = true;
  17276. const _start = /*@__PURE__*/new Vector3();
  17277. const _end = /*@__PURE__*/new Vector3();
  17278. class LineSegments extends Line {
  17279. constructor(geometry, material) {
  17280. super(geometry, material);
  17281. this.type = 'LineSegments';
  17282. }
  17283. computeLineDistances() {
  17284. const geometry = this.geometry;
  17285. if (geometry.isBufferGeometry) {
  17286. // we assume non-indexed geometry
  17287. if (geometry.index === null) {
  17288. const positionAttribute = geometry.attributes.position;
  17289. const lineDistances = [];
  17290. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  17291. _start.fromBufferAttribute(positionAttribute, i);
  17292. _end.fromBufferAttribute(positionAttribute, i + 1);
  17293. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  17294. lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end);
  17295. }
  17296. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17297. } else {
  17298. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17299. }
  17300. } else if (geometry.isGeometry) {
  17301. console.error('THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17302. }
  17303. return this;
  17304. }
  17305. }
  17306. LineSegments.prototype.isLineSegments = true;
  17307. class LineLoop extends Line {
  17308. constructor(geometry, material) {
  17309. super(geometry, material);
  17310. this.type = 'LineLoop';
  17311. }
  17312. }
  17313. LineLoop.prototype.isLineLoop = true;
  17314. /**
  17315. * parameters = {
  17316. * color: <hex>,
  17317. * opacity: <float>,
  17318. * map: new THREE.Texture( <Image> ),
  17319. * alphaMap: new THREE.Texture( <Image> ),
  17320. *
  17321. * size: <float>,
  17322. * sizeAttenuation: <bool>
  17323. *
  17324. * }
  17325. */
  17326. class PointsMaterial extends Material {
  17327. constructor(parameters) {
  17328. super();
  17329. this.type = 'PointsMaterial';
  17330. this.color = new Color(0xffffff);
  17331. this.map = null;
  17332. this.alphaMap = null;
  17333. this.size = 1;
  17334. this.sizeAttenuation = true;
  17335. this.setValues(parameters);
  17336. }
  17337. copy(source) {
  17338. super.copy(source);
  17339. this.color.copy(source.color);
  17340. this.map = source.map;
  17341. this.alphaMap = source.alphaMap;
  17342. this.size = source.size;
  17343. this.sizeAttenuation = source.sizeAttenuation;
  17344. return this;
  17345. }
  17346. }
  17347. PointsMaterial.prototype.isPointsMaterial = true;
  17348. const _inverseMatrix = /*@__PURE__*/new Matrix4();
  17349. const _ray = /*@__PURE__*/new Ray();
  17350. const _sphere = /*@__PURE__*/new Sphere();
  17351. const _position$2 = /*@__PURE__*/new Vector3();
  17352. class Points extends Object3D {
  17353. constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) {
  17354. super();
  17355. this.type = 'Points';
  17356. this.geometry = geometry;
  17357. this.material = material;
  17358. this.updateMorphTargets();
  17359. }
  17360. copy(source) {
  17361. super.copy(source);
  17362. this.material = source.material;
  17363. this.geometry = source.geometry;
  17364. return this;
  17365. }
  17366. raycast(raycaster, intersects) {
  17367. const geometry = this.geometry;
  17368. const matrixWorld = this.matrixWorld;
  17369. const threshold = raycaster.params.Points.threshold;
  17370. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  17371. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17372. _sphere.copy(geometry.boundingSphere);
  17373. _sphere.applyMatrix4(matrixWorld);
  17374. _sphere.radius += threshold;
  17375. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  17376. _inverseMatrix.copy(matrixWorld).invert();
  17377. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);
  17378. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17379. const localThresholdSq = localThreshold * localThreshold;
  17380. if (geometry.isBufferGeometry) {
  17381. const index = geometry.index;
  17382. const attributes = geometry.attributes;
  17383. const positionAttribute = attributes.position;
  17384. if (index !== null) {
  17385. const start = Math.max(0, drawRange.start);
  17386. const end = Math.min(index.count, drawRange.start + drawRange.count);
  17387. for (let i = start, il = end; i < il; i++) {
  17388. const a = index.getX(i);
  17389. _position$2.fromBufferAttribute(positionAttribute, a);
  17390. testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17391. }
  17392. } else {
  17393. const start = Math.max(0, drawRange.start);
  17394. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  17395. for (let i = start, l = end; i < l; i++) {
  17396. _position$2.fromBufferAttribute(positionAttribute, i);
  17397. testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17398. }
  17399. }
  17400. } else {
  17401. console.error('THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17402. }
  17403. }
  17404. updateMorphTargets() {
  17405. const geometry = this.geometry;
  17406. if (geometry.isBufferGeometry) {
  17407. const morphAttributes = geometry.morphAttributes;
  17408. const keys = Object.keys(morphAttributes);
  17409. if (keys.length > 0) {
  17410. const morphAttribute = morphAttributes[keys[0]];
  17411. if (morphAttribute !== undefined) {
  17412. this.morphTargetInfluences = [];
  17413. this.morphTargetDictionary = {};
  17414. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  17415. const name = morphAttribute[m].name || String(m);
  17416. this.morphTargetInfluences.push(0);
  17417. this.morphTargetDictionary[name] = m;
  17418. }
  17419. }
  17420. }
  17421. } else {
  17422. const morphTargets = geometry.morphTargets;
  17423. if (morphTargets !== undefined && morphTargets.length > 0) {
  17424. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17425. }
  17426. }
  17427. }
  17428. }
  17429. Points.prototype.isPoints = true;
  17430. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  17431. const rayPointDistanceSq = _ray.distanceSqToPoint(point);
  17432. if (rayPointDistanceSq < localThresholdSq) {
  17433. const intersectPoint = new Vector3();
  17434. _ray.closestPointToPoint(point, intersectPoint);
  17435. intersectPoint.applyMatrix4(matrixWorld);
  17436. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  17437. if (distance < raycaster.near || distance > raycaster.far) return;
  17438. intersects.push({
  17439. distance: distance,
  17440. distanceToRay: Math.sqrt(rayPointDistanceSq),
  17441. point: intersectPoint,
  17442. index: index,
  17443. face: null,
  17444. object: object
  17445. });
  17446. }
  17447. }
  17448. class VideoTexture extends Texture {
  17449. constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17450. super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17451. this.format = format !== undefined ? format : RGBFormat;
  17452. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  17453. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  17454. this.generateMipmaps = false;
  17455. const scope = this;
  17456. function updateVideo() {
  17457. scope.needsUpdate = true;
  17458. video.requestVideoFrameCallback(updateVideo);
  17459. }
  17460. if ('requestVideoFrameCallback' in video) {
  17461. video.requestVideoFrameCallback(updateVideo);
  17462. }
  17463. }
  17464. clone() {
  17465. return new this.constructor(this.image).copy(this);
  17466. }
  17467. update() {
  17468. const video = this.image;
  17469. const hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  17470. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  17471. this.needsUpdate = true;
  17472. }
  17473. }
  17474. }
  17475. VideoTexture.prototype.isVideoTexture = true;
  17476. class CompressedTexture extends Texture {
  17477. constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  17478. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  17479. this.image = {
  17480. width: width,
  17481. height: height
  17482. };
  17483. this.mipmaps = mipmaps; // no flipping for cube textures
  17484. // (also flipping doesn't work for compressed textures )
  17485. this.flipY = false; // can't generate mipmaps for compressed textures
  17486. // mips must be embedded in DDS files
  17487. this.generateMipmaps = false;
  17488. }
  17489. }
  17490. CompressedTexture.prototype.isCompressedTexture = true;
  17491. class CanvasTexture extends Texture {
  17492. constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17493. super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17494. this.needsUpdate = true;
  17495. }
  17496. }
  17497. CanvasTexture.prototype.isCanvasTexture = true;
  17498. class DepthTexture extends Texture {
  17499. constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  17500. format = format !== undefined ? format : DepthFormat;
  17501. if (format !== DepthFormat && format !== DepthStencilFormat) {
  17502. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  17503. }
  17504. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  17505. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  17506. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17507. this.image = {
  17508. width: width,
  17509. height: height
  17510. };
  17511. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  17512. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  17513. this.flipY = false;
  17514. this.generateMipmaps = false;
  17515. }
  17516. }
  17517. DepthTexture.prototype.isDepthTexture = true;
  17518. class CircleGeometry extends BufferGeometry {
  17519. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  17520. super();
  17521. this.type = 'CircleGeometry';
  17522. this.parameters = {
  17523. radius: radius,
  17524. segments: segments,
  17525. thetaStart: thetaStart,
  17526. thetaLength: thetaLength
  17527. };
  17528. segments = Math.max(3, segments); // buffers
  17529. const indices = [];
  17530. const vertices = [];
  17531. const normals = [];
  17532. const uvs = []; // helper variables
  17533. const vertex = new Vector3();
  17534. const uv = new Vector2(); // center point
  17535. vertices.push(0, 0, 0);
  17536. normals.push(0, 0, 1);
  17537. uvs.push(0.5, 0.5);
  17538. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  17539. const segment = thetaStart + s / segments * thetaLength; // vertex
  17540. vertex.x = radius * Math.cos(segment);
  17541. vertex.y = radius * Math.sin(segment);
  17542. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17543. normals.push(0, 0, 1); // uvs
  17544. uv.x = (vertices[i] / radius + 1) / 2;
  17545. uv.y = (vertices[i + 1] / radius + 1) / 2;
  17546. uvs.push(uv.x, uv.y);
  17547. } // indices
  17548. for (let i = 1; i <= segments; i++) {
  17549. indices.push(i, i + 1, 0);
  17550. } // build geometry
  17551. this.setIndex(indices);
  17552. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17553. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17554. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17555. }
  17556. static fromJSON(data) {
  17557. return new CircleGeometry(data.radius, data.segments, data.thetaStart, data.thetaLength);
  17558. }
  17559. }
  17560. class CylinderGeometry extends BufferGeometry {
  17561. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  17562. super();
  17563. this.type = 'CylinderGeometry';
  17564. this.parameters = {
  17565. radiusTop: radiusTop,
  17566. radiusBottom: radiusBottom,
  17567. height: height,
  17568. radialSegments: radialSegments,
  17569. heightSegments: heightSegments,
  17570. openEnded: openEnded,
  17571. thetaStart: thetaStart,
  17572. thetaLength: thetaLength
  17573. };
  17574. const scope = this;
  17575. radialSegments = Math.floor(radialSegments);
  17576. heightSegments = Math.floor(heightSegments); // buffers
  17577. const indices = [];
  17578. const vertices = [];
  17579. const normals = [];
  17580. const uvs = []; // helper variables
  17581. let index = 0;
  17582. const indexArray = [];
  17583. const halfHeight = height / 2;
  17584. let groupStart = 0; // generate geometry
  17585. generateTorso();
  17586. if (openEnded === false) {
  17587. if (radiusTop > 0) generateCap(true);
  17588. if (radiusBottom > 0) generateCap(false);
  17589. } // build geometry
  17590. this.setIndex(indices);
  17591. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17592. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17593. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17594. function generateTorso() {
  17595. const normal = new Vector3();
  17596. const vertex = new Vector3();
  17597. let groupCount = 0; // this will be used to calculate the normal
  17598. const slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  17599. for (let y = 0; y <= heightSegments; y++) {
  17600. const indexRow = [];
  17601. const v = y / heightSegments; // calculate the radius of the current row
  17602. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  17603. for (let x = 0; x <= radialSegments; x++) {
  17604. const u = x / radialSegments;
  17605. const theta = u * thetaLength + thetaStart;
  17606. const sinTheta = Math.sin(theta);
  17607. const cosTheta = Math.cos(theta); // vertex
  17608. vertex.x = radius * sinTheta;
  17609. vertex.y = -v * height + halfHeight;
  17610. vertex.z = radius * cosTheta;
  17611. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17612. normal.set(sinTheta, slope, cosTheta).normalize();
  17613. normals.push(normal.x, normal.y, normal.z); // uv
  17614. uvs.push(u, 1 - v); // save index of vertex in respective row
  17615. indexRow.push(index++);
  17616. } // now save vertices of the row in our index array
  17617. indexArray.push(indexRow);
  17618. } // generate indices
  17619. for (let x = 0; x < radialSegments; x++) {
  17620. for (let y = 0; y < heightSegments; y++) {
  17621. // we use the index array to access the correct indices
  17622. const a = indexArray[y][x];
  17623. const b = indexArray[y + 1][x];
  17624. const c = indexArray[y + 1][x + 1];
  17625. const d = indexArray[y][x + 1]; // faces
  17626. indices.push(a, b, d);
  17627. indices.push(b, c, d); // update group counter
  17628. groupCount += 6;
  17629. }
  17630. } // add a group to the geometry. this will ensure multi material support
  17631. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  17632. groupStart += groupCount;
  17633. }
  17634. function generateCap(top) {
  17635. // save the index of the first center vertex
  17636. const centerIndexStart = index;
  17637. const uv = new Vector2();
  17638. const vertex = new Vector3();
  17639. let groupCount = 0;
  17640. const radius = top === true ? radiusTop : radiusBottom;
  17641. const sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  17642. // because the geometry needs one set of uvs per face,
  17643. // we must generate a center vertex per face/segment
  17644. for (let x = 1; x <= radialSegments; x++) {
  17645. // vertex
  17646. vertices.push(0, halfHeight * sign, 0); // normal
  17647. normals.push(0, sign, 0); // uv
  17648. uvs.push(0.5, 0.5); // increase index
  17649. index++;
  17650. } // save the index of the last center vertex
  17651. const centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  17652. for (let x = 0; x <= radialSegments; x++) {
  17653. const u = x / radialSegments;
  17654. const theta = u * thetaLength + thetaStart;
  17655. const cosTheta = Math.cos(theta);
  17656. const sinTheta = Math.sin(theta); // vertex
  17657. vertex.x = radius * sinTheta;
  17658. vertex.y = halfHeight * sign;
  17659. vertex.z = radius * cosTheta;
  17660. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17661. normals.push(0, sign, 0); // uv
  17662. uv.x = cosTheta * 0.5 + 0.5;
  17663. uv.y = sinTheta * 0.5 * sign + 0.5;
  17664. uvs.push(uv.x, uv.y); // increase index
  17665. index++;
  17666. } // generate indices
  17667. for (let x = 0; x < radialSegments; x++) {
  17668. const c = centerIndexStart + x;
  17669. const i = centerIndexEnd + x;
  17670. if (top === true) {
  17671. // face top
  17672. indices.push(i, i + 1, c);
  17673. } else {
  17674. // face bottom
  17675. indices.push(i + 1, i, c);
  17676. }
  17677. groupCount += 3;
  17678. } // add a group to the geometry. this will ensure multi material support
  17679. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  17680. groupStart += groupCount;
  17681. }
  17682. }
  17683. static fromJSON(data) {
  17684. return new CylinderGeometry(data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  17685. }
  17686. }
  17687. class ConeGeometry extends CylinderGeometry {
  17688. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  17689. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  17690. this.type = 'ConeGeometry';
  17691. this.parameters = {
  17692. radius: radius,
  17693. height: height,
  17694. radialSegments: radialSegments,
  17695. heightSegments: heightSegments,
  17696. openEnded: openEnded,
  17697. thetaStart: thetaStart,
  17698. thetaLength: thetaLength
  17699. };
  17700. }
  17701. static fromJSON(data) {
  17702. return new ConeGeometry(data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  17703. }
  17704. }
  17705. class PolyhedronGeometry extends BufferGeometry {
  17706. constructor(vertices, indices, radius = 1, detail = 0) {
  17707. super();
  17708. this.type = 'PolyhedronGeometry';
  17709. this.parameters = {
  17710. vertices: vertices,
  17711. indices: indices,
  17712. radius: radius,
  17713. detail: detail
  17714. }; // default buffer data
  17715. const vertexBuffer = [];
  17716. const uvBuffer = []; // the subdivision creates the vertex buffer data
  17717. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  17718. applyRadius(radius); // finally, create the uv data
  17719. generateUVs(); // build non-indexed geometry
  17720. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  17721. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  17722. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  17723. if (detail === 0) {
  17724. this.computeVertexNormals(); // flat normals
  17725. } else {
  17726. this.normalizeNormals(); // smooth normals
  17727. } // helper functions
  17728. function subdivide(detail) {
  17729. const a = new Vector3();
  17730. const b = new Vector3();
  17731. const c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  17732. for (let i = 0; i < indices.length; i += 3) {
  17733. // get the vertices of the face
  17734. getVertexByIndex(indices[i + 0], a);
  17735. getVertexByIndex(indices[i + 1], b);
  17736. getVertexByIndex(indices[i + 2], c); // perform subdivision
  17737. subdivideFace(a, b, c, detail);
  17738. }
  17739. }
  17740. function subdivideFace(a, b, c, detail) {
  17741. const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  17742. const v = []; // construct all of the vertices for this subdivision
  17743. for (let i = 0; i <= cols; i++) {
  17744. v[i] = [];
  17745. const aj = a.clone().lerp(c, i / cols);
  17746. const bj = b.clone().lerp(c, i / cols);
  17747. const rows = cols - i;
  17748. for (let j = 0; j <= rows; j++) {
  17749. if (j === 0 && i === cols) {
  17750. v[i][j] = aj;
  17751. } else {
  17752. v[i][j] = aj.clone().lerp(bj, j / rows);
  17753. }
  17754. }
  17755. } // construct all of the faces
  17756. for (let i = 0; i < cols; i++) {
  17757. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  17758. const k = Math.floor(j / 2);
  17759. if (j % 2 === 0) {
  17760. pushVertex(v[i][k + 1]);
  17761. pushVertex(v[i + 1][k]);
  17762. pushVertex(v[i][k]);
  17763. } else {
  17764. pushVertex(v[i][k + 1]);
  17765. pushVertex(v[i + 1][k + 1]);
  17766. pushVertex(v[i + 1][k]);
  17767. }
  17768. }
  17769. }
  17770. }
  17771. function applyRadius(radius) {
  17772. const vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  17773. for (let i = 0; i < vertexBuffer.length; i += 3) {
  17774. vertex.x = vertexBuffer[i + 0];
  17775. vertex.y = vertexBuffer[i + 1];
  17776. vertex.z = vertexBuffer[i + 2];
  17777. vertex.normalize().multiplyScalar(radius);
  17778. vertexBuffer[i + 0] = vertex.x;
  17779. vertexBuffer[i + 1] = vertex.y;
  17780. vertexBuffer[i + 2] = vertex.z;
  17781. }
  17782. }
  17783. function generateUVs() {
  17784. const vertex = new Vector3();
  17785. for (let i = 0; i < vertexBuffer.length; i += 3) {
  17786. vertex.x = vertexBuffer[i + 0];
  17787. vertex.y = vertexBuffer[i + 1];
  17788. vertex.z = vertexBuffer[i + 2];
  17789. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  17790. const v = inclination(vertex) / Math.PI + 0.5;
  17791. uvBuffer.push(u, 1 - v);
  17792. }
  17793. correctUVs();
  17794. correctSeam();
  17795. }
  17796. function correctSeam() {
  17797. // handle case when face straddles the seam, see #3269
  17798. for (let i = 0; i < uvBuffer.length; i += 6) {
  17799. // uv data of a single face
  17800. const x0 = uvBuffer[i + 0];
  17801. const x1 = uvBuffer[i + 2];
  17802. const x2 = uvBuffer[i + 4];
  17803. const max = Math.max(x0, x1, x2);
  17804. const min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  17805. if (max > 0.9 && min < 0.1) {
  17806. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  17807. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  17808. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  17809. }
  17810. }
  17811. }
  17812. function pushVertex(vertex) {
  17813. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  17814. }
  17815. function getVertexByIndex(index, vertex) {
  17816. const stride = index * 3;
  17817. vertex.x = vertices[stride + 0];
  17818. vertex.y = vertices[stride + 1];
  17819. vertex.z = vertices[stride + 2];
  17820. }
  17821. function correctUVs() {
  17822. const a = new Vector3();
  17823. const b = new Vector3();
  17824. const c = new Vector3();
  17825. const centroid = new Vector3();
  17826. const uvA = new Vector2();
  17827. const uvB = new Vector2();
  17828. const uvC = new Vector2();
  17829. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  17830. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  17831. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  17832. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  17833. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  17834. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  17835. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  17836. centroid.copy(a).add(b).add(c).divideScalar(3);
  17837. const azi = azimuth(centroid);
  17838. correctUV(uvA, j + 0, a, azi);
  17839. correctUV(uvB, j + 2, b, azi);
  17840. correctUV(uvC, j + 4, c, azi);
  17841. }
  17842. }
  17843. function correctUV(uv, stride, vector, azimuth) {
  17844. if (azimuth < 0 && uv.x === 1) {
  17845. uvBuffer[stride] = uv.x - 1;
  17846. }
  17847. if (vector.x === 0 && vector.z === 0) {
  17848. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  17849. }
  17850. } // Angle around the Y axis, counter-clockwise when looking from above.
  17851. function azimuth(vector) {
  17852. return Math.atan2(vector.z, -vector.x);
  17853. } // Angle above the XZ plane.
  17854. function inclination(vector) {
  17855. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  17856. }
  17857. }
  17858. static fromJSON(data) {
  17859. return new PolyhedronGeometry(data.vertices, data.indices, data.radius, data.details);
  17860. }
  17861. }
  17862. class DodecahedronGeometry extends PolyhedronGeometry {
  17863. constructor(radius = 1, detail = 0) {
  17864. const t = (1 + Math.sqrt(5)) / 2;
  17865. const r = 1 / t;
  17866. const vertices = [// (±1, ±1, ±1)
  17867. -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, 1, // (0, ±1/φ, ±φ)
  17868. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  17869. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  17870. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  17871. const indices = [3, 11, 7, 3, 7, 15, 3, 15, 13, 7, 19, 17, 7, 17, 6, 7, 6, 15, 17, 4, 8, 17, 8, 10, 17, 10, 6, 8, 0, 16, 8, 16, 2, 8, 2, 10, 0, 12, 1, 0, 1, 18, 0, 18, 16, 6, 10, 2, 6, 2, 13, 6, 13, 15, 2, 16, 18, 2, 18, 3, 2, 3, 13, 18, 1, 9, 18, 9, 11, 18, 11, 3, 4, 14, 12, 4, 12, 0, 4, 0, 8, 11, 9, 5, 11, 5, 19, 11, 19, 7, 19, 5, 14, 19, 14, 4, 19, 4, 17, 1, 12, 14, 1, 14, 5, 1, 5, 9];
  17872. super(vertices, indices, radius, detail);
  17873. this.type = 'DodecahedronGeometry';
  17874. this.parameters = {
  17875. radius: radius,
  17876. detail: detail
  17877. };
  17878. }
  17879. static fromJSON(data) {
  17880. return new DodecahedronGeometry(data.radius, data.detail);
  17881. }
  17882. }
  17883. const _v0 = new Vector3();
  17884. const _v1$1 = new Vector3();
  17885. const _normal = new Vector3();
  17886. const _triangle = new Triangle();
  17887. class EdgesGeometry extends BufferGeometry {
  17888. constructor(geometry, thresholdAngle) {
  17889. super();
  17890. this.type = 'EdgesGeometry';
  17891. this.parameters = {
  17892. thresholdAngle: thresholdAngle
  17893. };
  17894. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1;
  17895. if (geometry.isGeometry === true) {
  17896. console.error('THREE.EdgesGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17897. return;
  17898. }
  17899. const precisionPoints = 4;
  17900. const precision = Math.pow(10, precisionPoints);
  17901. const thresholdDot = Math.cos(DEG2RAD * thresholdAngle);
  17902. const indexAttr = geometry.getIndex();
  17903. const positionAttr = geometry.getAttribute('position');
  17904. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  17905. const indexArr = [0, 0, 0];
  17906. const vertKeys = ['a', 'b', 'c'];
  17907. const hashes = new Array(3);
  17908. const edgeData = {};
  17909. const vertices = [];
  17910. for (let i = 0; i < indexCount; i += 3) {
  17911. if (indexAttr) {
  17912. indexArr[0] = indexAttr.getX(i);
  17913. indexArr[1] = indexAttr.getX(i + 1);
  17914. indexArr[2] = indexAttr.getX(i + 2);
  17915. } else {
  17916. indexArr[0] = i;
  17917. indexArr[1] = i + 1;
  17918. indexArr[2] = i + 2;
  17919. }
  17920. const {
  17921. a,
  17922. b,
  17923. c
  17924. } = _triangle;
  17925. a.fromBufferAttribute(positionAttr, indexArr[0]);
  17926. b.fromBufferAttribute(positionAttr, indexArr[1]);
  17927. c.fromBufferAttribute(positionAttr, indexArr[2]);
  17928. _triangle.getNormal(_normal); // create hashes for the edge from the vertices
  17929. hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`;
  17930. hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`;
  17931. hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; // skip degenerate triangles
  17932. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  17933. continue;
  17934. } // iterate over every edge
  17935. for (let j = 0; j < 3; j++) {
  17936. // get the first and next vertex making up the edge
  17937. const jNext = (j + 1) % 3;
  17938. const vecHash0 = hashes[j];
  17939. const vecHash1 = hashes[jNext];
  17940. const v0 = _triangle[vertKeys[j]];
  17941. const v1 = _triangle[vertKeys[jNext]];
  17942. const hash = `${vecHash0}_${vecHash1}`;
  17943. const reverseHash = `${vecHash1}_${vecHash0}`;
  17944. if (reverseHash in edgeData && edgeData[reverseHash]) {
  17945. // if we found a sibling edge add it into the vertex array if
  17946. // it meets the angle threshold and delete the edge from the map.
  17947. if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  17948. vertices.push(v0.x, v0.y, v0.z);
  17949. vertices.push(v1.x, v1.y, v1.z);
  17950. }
  17951. edgeData[reverseHash] = null;
  17952. } else if (!(hash in edgeData)) {
  17953. // if we've already got an edge here then skip adding a new one
  17954. edgeData[hash] = {
  17955. index0: indexArr[j],
  17956. index1: indexArr[jNext],
  17957. normal: _normal.clone()
  17958. };
  17959. }
  17960. }
  17961. } // iterate over all remaining, unmatched edges and add them to the vertex array
  17962. for (const key in edgeData) {
  17963. if (edgeData[key]) {
  17964. const {
  17965. index0,
  17966. index1
  17967. } = edgeData[key];
  17968. _v0.fromBufferAttribute(positionAttr, index0);
  17969. _v1$1.fromBufferAttribute(positionAttr, index1);
  17970. vertices.push(_v0.x, _v0.y, _v0.z);
  17971. vertices.push(_v1$1.x, _v1$1.y, _v1$1.z);
  17972. }
  17973. }
  17974. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17975. }
  17976. }
  17977. /**
  17978. * Extensible curve object.
  17979. *
  17980. * Some common of curve methods:
  17981. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  17982. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  17983. * .getPoints(), .getSpacedPoints()
  17984. * .getLength()
  17985. * .updateArcLengths()
  17986. *
  17987. * This following curves inherit from THREE.Curve:
  17988. *
  17989. * -- 2D curves --
  17990. * THREE.ArcCurve
  17991. * THREE.CubicBezierCurve
  17992. * THREE.EllipseCurve
  17993. * THREE.LineCurve
  17994. * THREE.QuadraticBezierCurve
  17995. * THREE.SplineCurve
  17996. *
  17997. * -- 3D curves --
  17998. * THREE.CatmullRomCurve3
  17999. * THREE.CubicBezierCurve3
  18000. * THREE.LineCurve3
  18001. * THREE.QuadraticBezierCurve3
  18002. *
  18003. * A series of curves can be represented as a THREE.CurvePath.
  18004. *
  18005. **/
  18006. class Curve {
  18007. constructor() {
  18008. this.type = 'Curve';
  18009. this.arcLengthDivisions = 200;
  18010. } // Virtual base class method to overwrite and implement in subclasses
  18011. // - t [0 .. 1]
  18012. getPoint() {
  18013. console.warn('THREE.Curve: .getPoint() not implemented.');
  18014. return null;
  18015. } // Get point at relative position in curve according to arc length
  18016. // - u [0 .. 1]
  18017. getPointAt(u, optionalTarget) {
  18018. const t = this.getUtoTmapping(u);
  18019. return this.getPoint(t, optionalTarget);
  18020. } // Get sequence of points using getPoint( t )
  18021. getPoints(divisions = 5) {
  18022. const points = [];
  18023. for (let d = 0; d <= divisions; d++) {
  18024. points.push(this.getPoint(d / divisions));
  18025. }
  18026. return points;
  18027. } // Get sequence of points using getPointAt( u )
  18028. getSpacedPoints(divisions = 5) {
  18029. const points = [];
  18030. for (let d = 0; d <= divisions; d++) {
  18031. points.push(this.getPointAt(d / divisions));
  18032. }
  18033. return points;
  18034. } // Get total curve arc length
  18035. getLength() {
  18036. const lengths = this.getLengths();
  18037. return lengths[lengths.length - 1];
  18038. } // Get list of cumulative segment lengths
  18039. getLengths(divisions = this.arcLengthDivisions) {
  18040. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  18041. return this.cacheArcLengths;
  18042. }
  18043. this.needsUpdate = false;
  18044. const cache = [];
  18045. let current,
  18046. last = this.getPoint(0);
  18047. let sum = 0;
  18048. cache.push(0);
  18049. for (let p = 1; p <= divisions; p++) {
  18050. current = this.getPoint(p / divisions);
  18051. sum += current.distanceTo(last);
  18052. cache.push(sum);
  18053. last = current;
  18054. }
  18055. this.cacheArcLengths = cache;
  18056. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18057. }
  18058. updateArcLengths() {
  18059. this.needsUpdate = true;
  18060. this.getLengths();
  18061. } // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18062. getUtoTmapping(u, distance) {
  18063. const arcLengths = this.getLengths();
  18064. let i = 0;
  18065. const il = arcLengths.length;
  18066. let targetArcLength; // The targeted u distance value to get
  18067. if (distance) {
  18068. targetArcLength = distance;
  18069. } else {
  18070. targetArcLength = u * arcLengths[il - 1];
  18071. } // binary search for the index with largest value smaller than target u distance
  18072. let low = 0,
  18073. high = il - 1,
  18074. comparison;
  18075. while (low <= high) {
  18076. 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
  18077. comparison = arcLengths[i] - targetArcLength;
  18078. if (comparison < 0) {
  18079. low = i + 1;
  18080. } else if (comparison > 0) {
  18081. high = i - 1;
  18082. } else {
  18083. high = i;
  18084. break; // DONE
  18085. }
  18086. }
  18087. i = high;
  18088. if (arcLengths[i] === targetArcLength) {
  18089. return i / (il - 1);
  18090. } // we could get finer grain at lengths, or use simple interpolation between two points
  18091. const lengthBefore = arcLengths[i];
  18092. const lengthAfter = arcLengths[i + 1];
  18093. const segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  18094. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  18095. const t = (i + segmentFraction) / (il - 1);
  18096. return t;
  18097. } // Returns a unit vector tangent at t
  18098. // In case any sub curve does not implement its tangent derivation,
  18099. // 2 points a small delta apart will be used to find its gradient
  18100. // which seems to give a reasonable approximation
  18101. getTangent(t, optionalTarget) {
  18102. const delta = 0.0001;
  18103. let t1 = t - delta;
  18104. let t2 = t + delta; // Capping in case of danger
  18105. if (t1 < 0) t1 = 0;
  18106. if (t2 > 1) t2 = 1;
  18107. const pt1 = this.getPoint(t1);
  18108. const pt2 = this.getPoint(t2);
  18109. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  18110. tangent.copy(pt2).sub(pt1).normalize();
  18111. return tangent;
  18112. }
  18113. getTangentAt(u, optionalTarget) {
  18114. const t = this.getUtoTmapping(u);
  18115. return this.getTangent(t, optionalTarget);
  18116. }
  18117. computeFrenetFrames(segments, closed) {
  18118. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18119. const normal = new Vector3();
  18120. const tangents = [];
  18121. const normals = [];
  18122. const binormals = [];
  18123. const vec = new Vector3();
  18124. const mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  18125. for (let i = 0; i <= segments; i++) {
  18126. const u = i / segments;
  18127. tangents[i] = this.getTangentAt(u, new Vector3());
  18128. tangents[i].normalize();
  18129. } // select an initial normal vector perpendicular to the first tangent vector,
  18130. // and in the direction of the minimum tangent xyz component
  18131. normals[0] = new Vector3();
  18132. binormals[0] = new Vector3();
  18133. let min = Number.MAX_VALUE;
  18134. const tx = Math.abs(tangents[0].x);
  18135. const ty = Math.abs(tangents[0].y);
  18136. const tz = Math.abs(tangents[0].z);
  18137. if (tx <= min) {
  18138. min = tx;
  18139. normal.set(1, 0, 0);
  18140. }
  18141. if (ty <= min) {
  18142. min = ty;
  18143. normal.set(0, 1, 0);
  18144. }
  18145. if (tz <= min) {
  18146. normal.set(0, 0, 1);
  18147. }
  18148. vec.crossVectors(tangents[0], normal).normalize();
  18149. normals[0].crossVectors(tangents[0], vec);
  18150. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18151. for (let i = 1; i <= segments; i++) {
  18152. normals[i] = normals[i - 1].clone();
  18153. binormals[i] = binormals[i - 1].clone();
  18154. vec.crossVectors(tangents[i - 1], tangents[i]);
  18155. if (vec.length() > Number.EPSILON) {
  18156. vec.normalize();
  18157. const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  18158. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  18159. }
  18160. binormals[i].crossVectors(tangents[i], normals[i]);
  18161. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18162. if (closed === true) {
  18163. let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1));
  18164. theta /= segments;
  18165. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  18166. theta = -theta;
  18167. }
  18168. for (let i = 1; i <= segments; i++) {
  18169. // twist a little...
  18170. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  18171. binormals[i].crossVectors(tangents[i], normals[i]);
  18172. }
  18173. }
  18174. return {
  18175. tangents: tangents,
  18176. normals: normals,
  18177. binormals: binormals
  18178. };
  18179. }
  18180. clone() {
  18181. return new this.constructor().copy(this);
  18182. }
  18183. copy(source) {
  18184. this.arcLengthDivisions = source.arcLengthDivisions;
  18185. return this;
  18186. }
  18187. toJSON() {
  18188. const data = {
  18189. metadata: {
  18190. version: 4.5,
  18191. type: 'Curve',
  18192. generator: 'Curve.toJSON'
  18193. }
  18194. };
  18195. data.arcLengthDivisions = this.arcLengthDivisions;
  18196. data.type = this.type;
  18197. return data;
  18198. }
  18199. fromJSON(json) {
  18200. this.arcLengthDivisions = json.arcLengthDivisions;
  18201. return this;
  18202. }
  18203. }
  18204. class EllipseCurve extends Curve {
  18205. constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) {
  18206. super();
  18207. this.type = 'EllipseCurve';
  18208. this.aX = aX;
  18209. this.aY = aY;
  18210. this.xRadius = xRadius;
  18211. this.yRadius = yRadius;
  18212. this.aStartAngle = aStartAngle;
  18213. this.aEndAngle = aEndAngle;
  18214. this.aClockwise = aClockwise;
  18215. this.aRotation = aRotation;
  18216. }
  18217. getPoint(t, optionalTarget) {
  18218. const point = optionalTarget || new Vector2();
  18219. const twoPi = Math.PI * 2;
  18220. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18221. const samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  18222. while (deltaAngle < 0) deltaAngle += twoPi;
  18223. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  18224. if (deltaAngle < Number.EPSILON) {
  18225. if (samePoints) {
  18226. deltaAngle = 0;
  18227. } else {
  18228. deltaAngle = twoPi;
  18229. }
  18230. }
  18231. if (this.aClockwise === true && !samePoints) {
  18232. if (deltaAngle === twoPi) {
  18233. deltaAngle = -twoPi;
  18234. } else {
  18235. deltaAngle = deltaAngle - twoPi;
  18236. }
  18237. }
  18238. const angle = this.aStartAngle + t * deltaAngle;
  18239. let x = this.aX + this.xRadius * Math.cos(angle);
  18240. let y = this.aY + this.yRadius * Math.sin(angle);
  18241. if (this.aRotation !== 0) {
  18242. const cos = Math.cos(this.aRotation);
  18243. const sin = Math.sin(this.aRotation);
  18244. const tx = x - this.aX;
  18245. const ty = y - this.aY; // Rotate the point about the center of the ellipse.
  18246. x = tx * cos - ty * sin + this.aX;
  18247. y = tx * sin + ty * cos + this.aY;
  18248. }
  18249. return point.set(x, y);
  18250. }
  18251. copy(source) {
  18252. super.copy(source);
  18253. this.aX = source.aX;
  18254. this.aY = source.aY;
  18255. this.xRadius = source.xRadius;
  18256. this.yRadius = source.yRadius;
  18257. this.aStartAngle = source.aStartAngle;
  18258. this.aEndAngle = source.aEndAngle;
  18259. this.aClockwise = source.aClockwise;
  18260. this.aRotation = source.aRotation;
  18261. return this;
  18262. }
  18263. toJSON() {
  18264. const data = super.toJSON();
  18265. data.aX = this.aX;
  18266. data.aY = this.aY;
  18267. data.xRadius = this.xRadius;
  18268. data.yRadius = this.yRadius;
  18269. data.aStartAngle = this.aStartAngle;
  18270. data.aEndAngle = this.aEndAngle;
  18271. data.aClockwise = this.aClockwise;
  18272. data.aRotation = this.aRotation;
  18273. return data;
  18274. }
  18275. fromJSON(json) {
  18276. super.fromJSON(json);
  18277. this.aX = json.aX;
  18278. this.aY = json.aY;
  18279. this.xRadius = json.xRadius;
  18280. this.yRadius = json.yRadius;
  18281. this.aStartAngle = json.aStartAngle;
  18282. this.aEndAngle = json.aEndAngle;
  18283. this.aClockwise = json.aClockwise;
  18284. this.aRotation = json.aRotation;
  18285. return this;
  18286. }
  18287. }
  18288. EllipseCurve.prototype.isEllipseCurve = true;
  18289. class ArcCurve extends EllipseCurve {
  18290. constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  18291. super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  18292. this.type = 'ArcCurve';
  18293. }
  18294. }
  18295. ArcCurve.prototype.isArcCurve = true;
  18296. /**
  18297. * Centripetal CatmullRom Curve - which is useful for avoiding
  18298. * cusps and self-intersections in non-uniform catmull rom curves.
  18299. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18300. *
  18301. * curve.type accepts centripetal(default), chordal and catmullrom
  18302. * curve.tension is used for catmullrom which defaults to 0.5
  18303. */
  18304. /*
  18305. Based on an optimized c++ solution in
  18306. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  18307. - http://ideone.com/NoEbVM
  18308. This CubicPoly class could be used for reusing some variables and calculations,
  18309. but for three.js curve use, it could be possible inlined and flatten into a single function call
  18310. which can be placed in CurveUtils.
  18311. */
  18312. function CubicPoly() {
  18313. let c0 = 0,
  18314. c1 = 0,
  18315. c2 = 0,
  18316. c3 = 0;
  18317. /*
  18318. * Compute coefficients for a cubic polynomial
  18319. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  18320. * such that
  18321. * p(0) = x0, p(1) = x1
  18322. * and
  18323. * p'(0) = t0, p'(1) = t1.
  18324. */
  18325. function init(x0, x1, t0, t1) {
  18326. c0 = x0;
  18327. c1 = t0;
  18328. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  18329. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  18330. }
  18331. return {
  18332. initCatmullRom: function (x0, x1, x2, x3, tension) {
  18333. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  18334. },
  18335. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  18336. // compute tangents when parameterized in [t1,t2]
  18337. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  18338. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  18339. t1 *= dt1;
  18340. t2 *= dt1;
  18341. init(x1, x2, t1, t2);
  18342. },
  18343. calc: function (t) {
  18344. const t2 = t * t;
  18345. const t3 = t2 * t;
  18346. return c0 + c1 * t + c2 * t2 + c3 * t3;
  18347. }
  18348. };
  18349. } //
  18350. const tmp = new Vector3();
  18351. const px = new CubicPoly(),
  18352. py = new CubicPoly(),
  18353. pz = new CubicPoly();
  18354. class CatmullRomCurve3 extends Curve {
  18355. constructor(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  18356. super();
  18357. this.type = 'CatmullRomCurve3';
  18358. this.points = points;
  18359. this.closed = closed;
  18360. this.curveType = curveType;
  18361. this.tension = tension;
  18362. }
  18363. getPoint(t, optionalTarget = new Vector3()) {
  18364. const point = optionalTarget;
  18365. const points = this.points;
  18366. const l = points.length;
  18367. const p = (l - (this.closed ? 0 : 1)) * t;
  18368. let intPoint = Math.floor(p);
  18369. let weight = p - intPoint;
  18370. if (this.closed) {
  18371. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  18372. } else if (weight === 0 && intPoint === l - 1) {
  18373. intPoint = l - 2;
  18374. weight = 1;
  18375. }
  18376. let p0, p3; // 4 points (p1 & p2 defined below)
  18377. if (this.closed || intPoint > 0) {
  18378. p0 = points[(intPoint - 1) % l];
  18379. } else {
  18380. // extrapolate first point
  18381. tmp.subVectors(points[0], points[1]).add(points[0]);
  18382. p0 = tmp;
  18383. }
  18384. const p1 = points[intPoint % l];
  18385. const p2 = points[(intPoint + 1) % l];
  18386. if (this.closed || intPoint + 2 < l) {
  18387. p3 = points[(intPoint + 2) % l];
  18388. } else {
  18389. // extrapolate last point
  18390. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  18391. p3 = tmp;
  18392. }
  18393. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  18394. // init Centripetal / Chordal Catmull-Rom
  18395. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  18396. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  18397. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  18398. let dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  18399. if (dt1 < 1e-4) dt1 = 1.0;
  18400. if (dt0 < 1e-4) dt0 = dt1;
  18401. if (dt2 < 1e-4) dt2 = dt1;
  18402. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  18403. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  18404. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  18405. } else if (this.curveType === 'catmullrom') {
  18406. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  18407. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  18408. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  18409. }
  18410. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  18411. return point;
  18412. }
  18413. copy(source) {
  18414. super.copy(source);
  18415. this.points = [];
  18416. for (let i = 0, l = source.points.length; i < l; i++) {
  18417. const point = source.points[i];
  18418. this.points.push(point.clone());
  18419. }
  18420. this.closed = source.closed;
  18421. this.curveType = source.curveType;
  18422. this.tension = source.tension;
  18423. return this;
  18424. }
  18425. toJSON() {
  18426. const data = super.toJSON();
  18427. data.points = [];
  18428. for (let i = 0, l = this.points.length; i < l; i++) {
  18429. const point = this.points[i];
  18430. data.points.push(point.toArray());
  18431. }
  18432. data.closed = this.closed;
  18433. data.curveType = this.curveType;
  18434. data.tension = this.tension;
  18435. return data;
  18436. }
  18437. fromJSON(json) {
  18438. super.fromJSON(json);
  18439. this.points = [];
  18440. for (let i = 0, l = json.points.length; i < l; i++) {
  18441. const point = json.points[i];
  18442. this.points.push(new Vector3().fromArray(point));
  18443. }
  18444. this.closed = json.closed;
  18445. this.curveType = json.curveType;
  18446. this.tension = json.tension;
  18447. return this;
  18448. }
  18449. }
  18450. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  18451. /**
  18452. * Bezier Curves formulas obtained from
  18453. * http://en.wikipedia.org/wiki/Bézier_curve
  18454. */
  18455. function CatmullRom(t, p0, p1, p2, p3) {
  18456. const v0 = (p2 - p0) * 0.5;
  18457. const v1 = (p3 - p1) * 0.5;
  18458. const t2 = t * t;
  18459. const t3 = t * t2;
  18460. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  18461. } //
  18462. function QuadraticBezierP0(t, p) {
  18463. const k = 1 - t;
  18464. return k * k * p;
  18465. }
  18466. function QuadraticBezierP1(t, p) {
  18467. return 2 * (1 - t) * t * p;
  18468. }
  18469. function QuadraticBezierP2(t, p) {
  18470. return t * t * p;
  18471. }
  18472. function QuadraticBezier(t, p0, p1, p2) {
  18473. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  18474. } //
  18475. function CubicBezierP0(t, p) {
  18476. const k = 1 - t;
  18477. return k * k * k * p;
  18478. }
  18479. function CubicBezierP1(t, p) {
  18480. const k = 1 - t;
  18481. return 3 * k * k * t * p;
  18482. }
  18483. function CubicBezierP2(t, p) {
  18484. return 3 * (1 - t) * t * t * p;
  18485. }
  18486. function CubicBezierP3(t, p) {
  18487. return t * t * t * p;
  18488. }
  18489. function CubicBezier(t, p0, p1, p2, p3) {
  18490. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  18491. }
  18492. class CubicBezierCurve extends Curve {
  18493. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  18494. super();
  18495. this.type = 'CubicBezierCurve';
  18496. this.v0 = v0;
  18497. this.v1 = v1;
  18498. this.v2 = v2;
  18499. this.v3 = v3;
  18500. }
  18501. getPoint(t, optionalTarget = new Vector2()) {
  18502. const point = optionalTarget;
  18503. const v0 = this.v0,
  18504. v1 = this.v1,
  18505. v2 = this.v2,
  18506. v3 = this.v3;
  18507. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  18508. return point;
  18509. }
  18510. copy(source) {
  18511. super.copy(source);
  18512. this.v0.copy(source.v0);
  18513. this.v1.copy(source.v1);
  18514. this.v2.copy(source.v2);
  18515. this.v3.copy(source.v3);
  18516. return this;
  18517. }
  18518. toJSON() {
  18519. const data = super.toJSON();
  18520. data.v0 = this.v0.toArray();
  18521. data.v1 = this.v1.toArray();
  18522. data.v2 = this.v2.toArray();
  18523. data.v3 = this.v3.toArray();
  18524. return data;
  18525. }
  18526. fromJSON(json) {
  18527. super.fromJSON(json);
  18528. this.v0.fromArray(json.v0);
  18529. this.v1.fromArray(json.v1);
  18530. this.v2.fromArray(json.v2);
  18531. this.v3.fromArray(json.v3);
  18532. return this;
  18533. }
  18534. }
  18535. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  18536. class CubicBezierCurve3 extends Curve {
  18537. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  18538. super();
  18539. this.type = 'CubicBezierCurve3';
  18540. this.v0 = v0;
  18541. this.v1 = v1;
  18542. this.v2 = v2;
  18543. this.v3 = v3;
  18544. }
  18545. getPoint(t, optionalTarget = new Vector3()) {
  18546. const point = optionalTarget;
  18547. const v0 = this.v0,
  18548. v1 = this.v1,
  18549. v2 = this.v2,
  18550. v3 = this.v3;
  18551. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y), CubicBezier(t, v0.z, v1.z, v2.z, v3.z));
  18552. return point;
  18553. }
  18554. copy(source) {
  18555. super.copy(source);
  18556. this.v0.copy(source.v0);
  18557. this.v1.copy(source.v1);
  18558. this.v2.copy(source.v2);
  18559. this.v3.copy(source.v3);
  18560. return this;
  18561. }
  18562. toJSON() {
  18563. const data = super.toJSON();
  18564. data.v0 = this.v0.toArray();
  18565. data.v1 = this.v1.toArray();
  18566. data.v2 = this.v2.toArray();
  18567. data.v3 = this.v3.toArray();
  18568. return data;
  18569. }
  18570. fromJSON(json) {
  18571. super.fromJSON(json);
  18572. this.v0.fromArray(json.v0);
  18573. this.v1.fromArray(json.v1);
  18574. this.v2.fromArray(json.v2);
  18575. this.v3.fromArray(json.v3);
  18576. return this;
  18577. }
  18578. }
  18579. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  18580. class LineCurve extends Curve {
  18581. constructor(v1 = new Vector2(), v2 = new Vector2()) {
  18582. super();
  18583. this.type = 'LineCurve';
  18584. this.v1 = v1;
  18585. this.v2 = v2;
  18586. }
  18587. getPoint(t, optionalTarget = new Vector2()) {
  18588. const point = optionalTarget;
  18589. if (t === 1) {
  18590. point.copy(this.v2);
  18591. } else {
  18592. point.copy(this.v2).sub(this.v1);
  18593. point.multiplyScalar(t).add(this.v1);
  18594. }
  18595. return point;
  18596. } // Line curve is linear, so we can overwrite default getPointAt
  18597. getPointAt(u, optionalTarget) {
  18598. return this.getPoint(u, optionalTarget);
  18599. }
  18600. getTangent(t, optionalTarget) {
  18601. const tangent = optionalTarget || new Vector2();
  18602. tangent.copy(this.v2).sub(this.v1).normalize();
  18603. return tangent;
  18604. }
  18605. copy(source) {
  18606. super.copy(source);
  18607. this.v1.copy(source.v1);
  18608. this.v2.copy(source.v2);
  18609. return this;
  18610. }
  18611. toJSON() {
  18612. const data = super.toJSON();
  18613. data.v1 = this.v1.toArray();
  18614. data.v2 = this.v2.toArray();
  18615. return data;
  18616. }
  18617. fromJSON(json) {
  18618. super.fromJSON(json);
  18619. this.v1.fromArray(json.v1);
  18620. this.v2.fromArray(json.v2);
  18621. return this;
  18622. }
  18623. }
  18624. LineCurve.prototype.isLineCurve = true;
  18625. class LineCurve3 extends Curve {
  18626. constructor(v1 = new Vector3(), v2 = new Vector3()) {
  18627. super();
  18628. this.type = 'LineCurve3';
  18629. this.isLineCurve3 = true;
  18630. this.v1 = v1;
  18631. this.v2 = v2;
  18632. }
  18633. getPoint(t, optionalTarget = new Vector3()) {
  18634. const point = optionalTarget;
  18635. if (t === 1) {
  18636. point.copy(this.v2);
  18637. } else {
  18638. point.copy(this.v2).sub(this.v1);
  18639. point.multiplyScalar(t).add(this.v1);
  18640. }
  18641. return point;
  18642. } // Line curve is linear, so we can overwrite default getPointAt
  18643. getPointAt(u, optionalTarget) {
  18644. return this.getPoint(u, optionalTarget);
  18645. }
  18646. copy(source) {
  18647. super.copy(source);
  18648. this.v1.copy(source.v1);
  18649. this.v2.copy(source.v2);
  18650. return this;
  18651. }
  18652. toJSON() {
  18653. const data = super.toJSON();
  18654. data.v1 = this.v1.toArray();
  18655. data.v2 = this.v2.toArray();
  18656. return data;
  18657. }
  18658. fromJSON(json) {
  18659. super.fromJSON(json);
  18660. this.v1.fromArray(json.v1);
  18661. this.v2.fromArray(json.v2);
  18662. return this;
  18663. }
  18664. }
  18665. class QuadraticBezierCurve extends Curve {
  18666. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  18667. super();
  18668. this.type = 'QuadraticBezierCurve';
  18669. this.v0 = v0;
  18670. this.v1 = v1;
  18671. this.v2 = v2;
  18672. }
  18673. getPoint(t, optionalTarget = new Vector2()) {
  18674. const point = optionalTarget;
  18675. const v0 = this.v0,
  18676. v1 = this.v1,
  18677. v2 = this.v2;
  18678. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  18679. return point;
  18680. }
  18681. copy(source) {
  18682. super.copy(source);
  18683. this.v0.copy(source.v0);
  18684. this.v1.copy(source.v1);
  18685. this.v2.copy(source.v2);
  18686. return this;
  18687. }
  18688. toJSON() {
  18689. const data = super.toJSON();
  18690. data.v0 = this.v0.toArray();
  18691. data.v1 = this.v1.toArray();
  18692. data.v2 = this.v2.toArray();
  18693. return data;
  18694. }
  18695. fromJSON(json) {
  18696. super.fromJSON(json);
  18697. this.v0.fromArray(json.v0);
  18698. this.v1.fromArray(json.v1);
  18699. this.v2.fromArray(json.v2);
  18700. return this;
  18701. }
  18702. }
  18703. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  18704. class QuadraticBezierCurve3 extends Curve {
  18705. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  18706. super();
  18707. this.type = 'QuadraticBezierCurve3';
  18708. this.v0 = v0;
  18709. this.v1 = v1;
  18710. this.v2 = v2;
  18711. }
  18712. getPoint(t, optionalTarget = new Vector3()) {
  18713. const point = optionalTarget;
  18714. const v0 = this.v0,
  18715. v1 = this.v1,
  18716. v2 = this.v2;
  18717. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y), QuadraticBezier(t, v0.z, v1.z, v2.z));
  18718. return point;
  18719. }
  18720. copy(source) {
  18721. super.copy(source);
  18722. this.v0.copy(source.v0);
  18723. this.v1.copy(source.v1);
  18724. this.v2.copy(source.v2);
  18725. return this;
  18726. }
  18727. toJSON() {
  18728. const data = super.toJSON();
  18729. data.v0 = this.v0.toArray();
  18730. data.v1 = this.v1.toArray();
  18731. data.v2 = this.v2.toArray();
  18732. return data;
  18733. }
  18734. fromJSON(json) {
  18735. super.fromJSON(json);
  18736. this.v0.fromArray(json.v0);
  18737. this.v1.fromArray(json.v1);
  18738. this.v2.fromArray(json.v2);
  18739. return this;
  18740. }
  18741. }
  18742. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  18743. class SplineCurve extends Curve {
  18744. constructor(points = []) {
  18745. super();
  18746. this.type = 'SplineCurve';
  18747. this.points = points;
  18748. }
  18749. getPoint(t, optionalTarget = new Vector2()) {
  18750. const point = optionalTarget;
  18751. const points = this.points;
  18752. const p = (points.length - 1) * t;
  18753. const intPoint = Math.floor(p);
  18754. const weight = p - intPoint;
  18755. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  18756. const p1 = points[intPoint];
  18757. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  18758. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  18759. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  18760. return point;
  18761. }
  18762. copy(source) {
  18763. super.copy(source);
  18764. this.points = [];
  18765. for (let i = 0, l = source.points.length; i < l; i++) {
  18766. const point = source.points[i];
  18767. this.points.push(point.clone());
  18768. }
  18769. return this;
  18770. }
  18771. toJSON() {
  18772. const data = super.toJSON();
  18773. data.points = [];
  18774. for (let i = 0, l = this.points.length; i < l; i++) {
  18775. const point = this.points[i];
  18776. data.points.push(point.toArray());
  18777. }
  18778. return data;
  18779. }
  18780. fromJSON(json) {
  18781. super.fromJSON(json);
  18782. this.points = [];
  18783. for (let i = 0, l = json.points.length; i < l; i++) {
  18784. const point = json.points[i];
  18785. this.points.push(new Vector2().fromArray(point));
  18786. }
  18787. return this;
  18788. }
  18789. }
  18790. SplineCurve.prototype.isSplineCurve = true;
  18791. var Curves = /*#__PURE__*/Object.freeze({
  18792. __proto__: null,
  18793. ArcCurve: ArcCurve,
  18794. CatmullRomCurve3: CatmullRomCurve3,
  18795. CubicBezierCurve: CubicBezierCurve,
  18796. CubicBezierCurve3: CubicBezierCurve3,
  18797. EllipseCurve: EllipseCurve,
  18798. LineCurve: LineCurve,
  18799. LineCurve3: LineCurve3,
  18800. QuadraticBezierCurve: QuadraticBezierCurve,
  18801. QuadraticBezierCurve3: QuadraticBezierCurve3,
  18802. SplineCurve: SplineCurve
  18803. });
  18804. /**
  18805. * Port from https://github.com/mapbox/earcut (v2.2.2)
  18806. */
  18807. const Earcut = {
  18808. triangulate: function (data, holeIndices, dim = 2) {
  18809. const hasHoles = holeIndices && holeIndices.length;
  18810. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  18811. let outerNode = linkedList(data, 0, outerLen, dim, true);
  18812. const triangles = [];
  18813. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  18814. let minX, minY, maxX, maxY, x, y, invSize;
  18815. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  18816. if (data.length > 80 * dim) {
  18817. minX = maxX = data[0];
  18818. minY = maxY = data[1];
  18819. for (let i = dim; i < outerLen; i += dim) {
  18820. x = data[i];
  18821. y = data[i + 1];
  18822. if (x < minX) minX = x;
  18823. if (y < minY) minY = y;
  18824. if (x > maxX) maxX = x;
  18825. if (y > maxY) maxY = y;
  18826. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  18827. invSize = Math.max(maxX - minX, maxY - minY);
  18828. invSize = invSize !== 0 ? 1 / invSize : 0;
  18829. }
  18830. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  18831. return triangles;
  18832. }
  18833. }; // create a circular doubly linked list from polygon points in the specified winding order
  18834. function linkedList(data, start, end, dim, clockwise) {
  18835. let i, last;
  18836. if (clockwise === signedArea(data, start, end, dim) > 0) {
  18837. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  18838. } else {
  18839. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  18840. }
  18841. if (last && equals(last, last.next)) {
  18842. removeNode(last);
  18843. last = last.next;
  18844. }
  18845. return last;
  18846. } // eliminate colinear or duplicate points
  18847. function filterPoints(start, end) {
  18848. if (!start) return start;
  18849. if (!end) end = start;
  18850. let p = start,
  18851. again;
  18852. do {
  18853. again = false;
  18854. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  18855. removeNode(p);
  18856. p = end = p.prev;
  18857. if (p === p.next) break;
  18858. again = true;
  18859. } else {
  18860. p = p.next;
  18861. }
  18862. } while (again || p !== end);
  18863. return end;
  18864. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  18865. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  18866. if (!ear) return; // interlink polygon nodes in z-order
  18867. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  18868. let stop = ear,
  18869. prev,
  18870. next; // iterate through ears, slicing them one by one
  18871. while (ear.prev !== ear.next) {
  18872. prev = ear.prev;
  18873. next = ear.next;
  18874. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  18875. // cut off the triangle
  18876. triangles.push(prev.i / dim);
  18877. triangles.push(ear.i / dim);
  18878. triangles.push(next.i / dim);
  18879. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  18880. ear = next.next;
  18881. stop = next.next;
  18882. continue;
  18883. }
  18884. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  18885. if (ear === stop) {
  18886. // try filtering points and slicing again
  18887. if (!pass) {
  18888. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  18889. } else if (pass === 1) {
  18890. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  18891. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  18892. } else if (pass === 2) {
  18893. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  18894. }
  18895. break;
  18896. }
  18897. }
  18898. } // check whether a polygon node forms a valid ear with adjacent nodes
  18899. function isEar(ear) {
  18900. const a = ear.prev,
  18901. b = ear,
  18902. c = ear.next;
  18903. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18904. // now make sure we don't have other points inside the potential ear
  18905. let p = ear.next.next;
  18906. while (p !== ear.prev) {
  18907. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  18908. p = p.next;
  18909. }
  18910. return true;
  18911. }
  18912. function isEarHashed(ear, minX, minY, invSize) {
  18913. const a = ear.prev,
  18914. b = ear,
  18915. c = ear.next;
  18916. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18917. // triangle bbox; min & max are calculated like this for speed
  18918. const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  18919. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  18920. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  18921. maxTY = a.y > b.y ? a.y > c.y ? a.y : c.y : b.y > c.y ? b.y : c.y; // z-order range for the current triangle bbox;
  18922. const minZ = zOrder(minTX, minTY, minX, minY, invSize),
  18923. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  18924. let p = ear.prevZ,
  18925. n = ear.nextZ; // look for points inside the triangle in both directions
  18926. while (p && p.z >= minZ && n && n.z <= maxZ) {
  18927. if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  18928. p = p.prevZ;
  18929. if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  18930. n = n.nextZ;
  18931. } // look for remaining points in decreasing z-order
  18932. while (p && p.z >= minZ) {
  18933. if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  18934. p = p.prevZ;
  18935. } // look for remaining points in increasing z-order
  18936. while (n && n.z <= maxZ) {
  18937. if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  18938. n = n.nextZ;
  18939. }
  18940. return true;
  18941. } // go through all polygon nodes and cure small local self-intersections
  18942. function cureLocalIntersections(start, triangles, dim) {
  18943. let p = start;
  18944. do {
  18945. const a = p.prev,
  18946. b = p.next.next;
  18947. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  18948. triangles.push(a.i / dim);
  18949. triangles.push(p.i / dim);
  18950. triangles.push(b.i / dim); // remove two nodes involved
  18951. removeNode(p);
  18952. removeNode(p.next);
  18953. p = start = b;
  18954. }
  18955. p = p.next;
  18956. } while (p !== start);
  18957. return filterPoints(p);
  18958. } // try splitting polygon into two and triangulate them independently
  18959. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  18960. // look for a valid diagonal that divides the polygon into two
  18961. let a = start;
  18962. do {
  18963. let b = a.next.next;
  18964. while (b !== a.prev) {
  18965. if (a.i !== b.i && isValidDiagonal(a, b)) {
  18966. // split the polygon in two by the diagonal
  18967. let c = splitPolygon(a, b); // filter colinear points around the cuts
  18968. a = filterPoints(a, a.next);
  18969. c = filterPoints(c, c.next); // run earcut on each half
  18970. earcutLinked(a, triangles, dim, minX, minY, invSize);
  18971. earcutLinked(c, triangles, dim, minX, minY, invSize);
  18972. return;
  18973. }
  18974. b = b.next;
  18975. }
  18976. a = a.next;
  18977. } while (a !== start);
  18978. } // link every hole into the outer loop, producing a single-ring polygon without holes
  18979. function eliminateHoles(data, holeIndices, outerNode, dim) {
  18980. const queue = [];
  18981. let i, len, start, end, list;
  18982. for (i = 0, len = holeIndices.length; i < len; i++) {
  18983. start = holeIndices[i] * dim;
  18984. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  18985. list = linkedList(data, start, end, dim, false);
  18986. if (list === list.next) list.steiner = true;
  18987. queue.push(getLeftmost(list));
  18988. }
  18989. queue.sort(compareX); // process holes from left to right
  18990. for (i = 0; i < queue.length; i++) {
  18991. eliminateHole(queue[i], outerNode);
  18992. outerNode = filterPoints(outerNode, outerNode.next);
  18993. }
  18994. return outerNode;
  18995. }
  18996. function compareX(a, b) {
  18997. return a.x - b.x;
  18998. } // find a bridge between vertices that connects hole with an outer ring and and link it
  18999. function eliminateHole(hole, outerNode) {
  19000. outerNode = findHoleBridge(hole, outerNode);
  19001. if (outerNode) {
  19002. const b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  19003. filterPoints(outerNode, outerNode.next);
  19004. filterPoints(b, b.next);
  19005. }
  19006. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  19007. function findHoleBridge(hole, outerNode) {
  19008. let p = outerNode;
  19009. const hx = hole.x;
  19010. const hy = hole.y;
  19011. let qx = -Infinity,
  19012. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  19013. // segment's endpoint with lesser x will be potential connection point
  19014. do {
  19015. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  19016. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  19017. if (x <= hx && x > qx) {
  19018. qx = x;
  19019. if (x === hx) {
  19020. if (hy === p.y) return p;
  19021. if (hy === p.next.y) return p.next;
  19022. }
  19023. m = p.x < p.next.x ? p : p.next;
  19024. }
  19025. }
  19026. p = p.next;
  19027. } while (p !== outerNode);
  19028. if (!m) return null;
  19029. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  19030. // look for points inside the triangle of hole point, segment intersection and endpoint;
  19031. // if there are no points found, we have a valid connection;
  19032. // otherwise choose the point of the minimum angle with the ray as connection point
  19033. const stop = m,
  19034. mx = m.x,
  19035. my = m.y;
  19036. let tanMin = Infinity,
  19037. tan;
  19038. p = m;
  19039. do {
  19040. if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  19041. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  19042. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  19043. m = p;
  19044. tanMin = tan;
  19045. }
  19046. }
  19047. p = p.next;
  19048. } while (p !== stop);
  19049. return m;
  19050. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  19051. function sectorContainsSector(m, p) {
  19052. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  19053. } // interlink polygon nodes in z-order
  19054. function indexCurve(start, minX, minY, invSize) {
  19055. let p = start;
  19056. do {
  19057. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  19058. p.prevZ = p.prev;
  19059. p.nextZ = p.next;
  19060. p = p.next;
  19061. } while (p !== start);
  19062. p.prevZ.nextZ = null;
  19063. p.prevZ = null;
  19064. sortLinked(p);
  19065. } // Simon Tatham's linked list merge sort algorithm
  19066. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  19067. function sortLinked(list) {
  19068. let i,
  19069. p,
  19070. q,
  19071. e,
  19072. tail,
  19073. numMerges,
  19074. pSize,
  19075. qSize,
  19076. inSize = 1;
  19077. do {
  19078. p = list;
  19079. list = null;
  19080. tail = null;
  19081. numMerges = 0;
  19082. while (p) {
  19083. numMerges++;
  19084. q = p;
  19085. pSize = 0;
  19086. for (i = 0; i < inSize; i++) {
  19087. pSize++;
  19088. q = q.nextZ;
  19089. if (!q) break;
  19090. }
  19091. qSize = inSize;
  19092. while (pSize > 0 || qSize > 0 && q) {
  19093. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  19094. e = p;
  19095. p = p.nextZ;
  19096. pSize--;
  19097. } else {
  19098. e = q;
  19099. q = q.nextZ;
  19100. qSize--;
  19101. }
  19102. if (tail) tail.nextZ = e;else list = e;
  19103. e.prevZ = tail;
  19104. tail = e;
  19105. }
  19106. p = q;
  19107. }
  19108. tail.nextZ = null;
  19109. inSize *= 2;
  19110. } while (numMerges > 1);
  19111. return list;
  19112. } // z-order of a point given coords and inverse of the longer side of data bbox
  19113. function zOrder(x, y, minX, minY, invSize) {
  19114. // coords are transformed into non-negative 15-bit integer range
  19115. x = 32767 * (x - minX) * invSize;
  19116. y = 32767 * (y - minY) * invSize;
  19117. x = (x | x << 8) & 0x00FF00FF;
  19118. x = (x | x << 4) & 0x0F0F0F0F;
  19119. x = (x | x << 2) & 0x33333333;
  19120. x = (x | x << 1) & 0x55555555;
  19121. y = (y | y << 8) & 0x00FF00FF;
  19122. y = (y | y << 4) & 0x0F0F0F0F;
  19123. y = (y | y << 2) & 0x33333333;
  19124. y = (y | y << 1) & 0x55555555;
  19125. return x | y << 1;
  19126. } // find the leftmost node of a polygon ring
  19127. function getLeftmost(start) {
  19128. let p = start,
  19129. leftmost = start;
  19130. do {
  19131. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  19132. p = p.next;
  19133. } while (p !== start);
  19134. return leftmost;
  19135. } // check if a point lies within a convex triangle
  19136. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  19137. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  19138. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  19139. function isValidDiagonal(a, b) {
  19140. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  19141. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  19142. } // signed area of a triangle
  19143. function area(p, q, r) {
  19144. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  19145. } // check if two points are equal
  19146. function equals(p1, p2) {
  19147. return p1.x === p2.x && p1.y === p2.y;
  19148. } // check if two segments intersect
  19149. function intersects(p1, q1, p2, q2) {
  19150. const o1 = sign(area(p1, q1, p2));
  19151. const o2 = sign(area(p1, q1, q2));
  19152. const o3 = sign(area(p2, q2, p1));
  19153. const o4 = sign(area(p2, q2, q1));
  19154. if (o1 !== o2 && o3 !== o4) return true; // general case
  19155. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  19156. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  19157. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  19158. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  19159. return false;
  19160. } // for collinear points p, q, r, check if point q lies on segment pr
  19161. function onSegment(p, q, r) {
  19162. 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);
  19163. }
  19164. function sign(num) {
  19165. return num > 0 ? 1 : num < 0 ? -1 : 0;
  19166. } // check if a polygon diagonal intersects any polygon segments
  19167. function intersectsPolygon(a, b) {
  19168. let p = a;
  19169. do {
  19170. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) return true;
  19171. p = p.next;
  19172. } while (p !== a);
  19173. return false;
  19174. } // check if a polygon diagonal is locally inside the polygon
  19175. function locallyInside(a, b) {
  19176. return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  19177. } // check if the middle point of a polygon diagonal is inside the polygon
  19178. function middleInside(a, b) {
  19179. let p = a,
  19180. inside = false;
  19181. const px = (a.x + b.x) / 2,
  19182. py = (a.y + b.y) / 2;
  19183. do {
  19184. if (p.y > py !== p.next.y > py && p.next.y !== p.y && px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x) inside = !inside;
  19185. p = p.next;
  19186. } while (p !== a);
  19187. return inside;
  19188. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  19189. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  19190. function splitPolygon(a, b) {
  19191. const a2 = new Node(a.i, a.x, a.y),
  19192. b2 = new Node(b.i, b.x, b.y),
  19193. an = a.next,
  19194. bp = b.prev;
  19195. a.next = b;
  19196. b.prev = a;
  19197. a2.next = an;
  19198. an.prev = a2;
  19199. b2.next = a2;
  19200. a2.prev = b2;
  19201. bp.next = b2;
  19202. b2.prev = bp;
  19203. return b2;
  19204. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  19205. function insertNode(i, x, y, last) {
  19206. const p = new Node(i, x, y);
  19207. if (!last) {
  19208. p.prev = p;
  19209. p.next = p;
  19210. } else {
  19211. p.next = last.next;
  19212. p.prev = last;
  19213. last.next.prev = p;
  19214. last.next = p;
  19215. }
  19216. return p;
  19217. }
  19218. function removeNode(p) {
  19219. p.next.prev = p.prev;
  19220. p.prev.next = p.next;
  19221. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  19222. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  19223. }
  19224. function Node(i, x, y) {
  19225. // vertex index in coordinates array
  19226. this.i = i; // vertex coordinates
  19227. this.x = x;
  19228. this.y = y; // previous and next vertex nodes in a polygon ring
  19229. this.prev = null;
  19230. this.next = null; // z-order curve value
  19231. this.z = null; // previous and next nodes in z-order
  19232. this.prevZ = null;
  19233. this.nextZ = null; // indicates whether this is a steiner point
  19234. this.steiner = false;
  19235. }
  19236. function signedArea(data, start, end, dim) {
  19237. let sum = 0;
  19238. for (let i = start, j = end - dim; i < end; i += dim) {
  19239. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  19240. j = i;
  19241. }
  19242. return sum;
  19243. }
  19244. class ShapeUtils {
  19245. // calculate area of the contour polygon
  19246. static area(contour) {
  19247. const n = contour.length;
  19248. let a = 0.0;
  19249. for (let p = n - 1, q = 0; q < n; p = q++) {
  19250. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  19251. }
  19252. return a * 0.5;
  19253. }
  19254. static isClockWise(pts) {
  19255. return ShapeUtils.area(pts) < 0;
  19256. }
  19257. static triangulateShape(contour, holes) {
  19258. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  19259. const holeIndices = []; // array of hole indices
  19260. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  19261. removeDupEndPts(contour);
  19262. addContour(vertices, contour); //
  19263. let holeIndex = contour.length;
  19264. holes.forEach(removeDupEndPts);
  19265. for (let i = 0; i < holes.length; i++) {
  19266. holeIndices.push(holeIndex);
  19267. holeIndex += holes[i].length;
  19268. addContour(vertices, holes[i]);
  19269. } //
  19270. const triangles = Earcut.triangulate(vertices, holeIndices); //
  19271. for (let i = 0; i < triangles.length; i += 3) {
  19272. faces.push(triangles.slice(i, i + 3));
  19273. }
  19274. return faces;
  19275. }
  19276. }
  19277. function removeDupEndPts(points) {
  19278. const l = points.length;
  19279. if (l > 2 && points[l - 1].equals(points[0])) {
  19280. points.pop();
  19281. }
  19282. }
  19283. function addContour(vertices, contour) {
  19284. for (let i = 0; i < contour.length; i++) {
  19285. vertices.push(contour[i].x);
  19286. vertices.push(contour[i].y);
  19287. }
  19288. }
  19289. /**
  19290. * Creates extruded geometry from a path shape.
  19291. *
  19292. * parameters = {
  19293. *
  19294. * curveSegments: <int>, // number of points on the curves
  19295. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19296. * depth: <float>, // Depth to extrude the shape
  19297. *
  19298. * bevelEnabled: <bool>, // turn on bevel
  19299. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19300. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  19301. * bevelOffset: <float>, // how far from shape outline does bevel start
  19302. * bevelSegments: <int>, // number of bevel layers
  19303. *
  19304. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19305. *
  19306. * UVGenerator: <Object> // object that provides UV generator functions
  19307. *
  19308. * }
  19309. */
  19310. class ExtrudeGeometry extends BufferGeometry {
  19311. constructor(shapes, options) {
  19312. super();
  19313. this.type = 'ExtrudeGeometry';
  19314. this.parameters = {
  19315. shapes: shapes,
  19316. options: options
  19317. };
  19318. shapes = Array.isArray(shapes) ? shapes : [shapes];
  19319. const scope = this;
  19320. const verticesArray = [];
  19321. const uvArray = [];
  19322. for (let i = 0, l = shapes.length; i < l; i++) {
  19323. const shape = shapes[i];
  19324. addShape(shape);
  19325. } // build geometry
  19326. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  19327. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  19328. this.computeVertexNormals(); // functions
  19329. function addShape(shape) {
  19330. const placeholder = []; // options
  19331. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19332. const steps = options.steps !== undefined ? options.steps : 1;
  19333. let depth = options.depth !== undefined ? options.depth : 100;
  19334. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  19335. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  19336. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  19337. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  19338. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19339. const extrudePath = options.extrudePath;
  19340. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  19341. if (options.amount !== undefined) {
  19342. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  19343. depth = options.amount;
  19344. } //
  19345. let extrudePts,
  19346. extrudeByPath = false;
  19347. let splineTube, binormal, normal, position2;
  19348. if (extrudePath) {
  19349. extrudePts = extrudePath.getSpacedPoints(steps);
  19350. extrudeByPath = true;
  19351. bevelEnabled = false; // bevels not supported for path extrusion
  19352. // SETUP TNB variables
  19353. // TODO1 - have a .isClosed in spline?
  19354. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19355. binormal = new Vector3();
  19356. normal = new Vector3();
  19357. position2 = new Vector3();
  19358. } // Safeguards if bevels are not enabled
  19359. if (!bevelEnabled) {
  19360. bevelSegments = 0;
  19361. bevelThickness = 0;
  19362. bevelSize = 0;
  19363. bevelOffset = 0;
  19364. } // Variables initialization
  19365. const shapePoints = shape.extractPoints(curveSegments);
  19366. let vertices = shapePoints.shape;
  19367. const holes = shapePoints.holes;
  19368. const reverse = !ShapeUtils.isClockWise(vertices);
  19369. if (reverse) {
  19370. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19371. for (let h = 0, hl = holes.length; h < hl; h++) {
  19372. const ahole = holes[h];
  19373. if (ShapeUtils.isClockWise(ahole)) {
  19374. holes[h] = ahole.reverse();
  19375. }
  19376. }
  19377. }
  19378. const faces = ShapeUtils.triangulateShape(vertices, holes);
  19379. /* Vertices */
  19380. const contour = vertices; // vertices has all points but contour has only points of circumference
  19381. for (let h = 0, hl = holes.length; h < hl; h++) {
  19382. const ahole = holes[h];
  19383. vertices = vertices.concat(ahole);
  19384. }
  19385. function scalePt2(pt, vec, size) {
  19386. if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
  19387. return vec.clone().multiplyScalar(size).add(pt);
  19388. }
  19389. const vlen = vertices.length,
  19390. flen = faces.length; // Find directions for point movement
  19391. function getBevelVec(inPt, inPrev, inNext) {
  19392. // computes for inPt the corresponding point inPt' on a new contour
  19393. // shifted by 1 unit (length of normalized vector) to the left
  19394. // if we walk along contour clockwise, this new contour is outside the old one
  19395. //
  19396. // inPt' is the intersection of the two lines parallel to the two
  19397. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19398. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  19399. // good reading for geometry algorithms (here: line-line intersection)
  19400. // http://geomalgorithms.com/a05-_intersect-1.html
  19401. const v_prev_x = inPt.x - inPrev.x,
  19402. v_prev_y = inPt.y - inPrev.y;
  19403. const v_next_x = inNext.x - inPt.x,
  19404. v_next_y = inNext.y - inPt.y;
  19405. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  19406. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  19407. if (Math.abs(collinear0) > Number.EPSILON) {
  19408. // not collinear
  19409. // length of vectors for normalizing
  19410. const v_prev_len = Math.sqrt(v_prev_lensq);
  19411. const v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y); // shift adjacent points by unit vectors to the left
  19412. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  19413. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  19414. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  19415. const ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  19416. const sf = ((ptNextShift_x - ptPrevShift_x) * v_next_y - (ptNextShift_y - ptPrevShift_y) * v_next_x) / (v_prev_x * v_next_y - v_prev_y * v_next_x); // vector from inPt to intersection point
  19417. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  19418. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  19419. // but prevent crazy spikes
  19420. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  19421. if (v_trans_lensq <= 2) {
  19422. return new Vector2(v_trans_x, v_trans_y);
  19423. } else {
  19424. shrink_by = Math.sqrt(v_trans_lensq / 2);
  19425. }
  19426. } else {
  19427. // handle special case of collinear edges
  19428. let direction_eq = false; // assumes: opposite
  19429. if (v_prev_x > Number.EPSILON) {
  19430. if (v_next_x > Number.EPSILON) {
  19431. direction_eq = true;
  19432. }
  19433. } else {
  19434. if (v_prev_x < -Number.EPSILON) {
  19435. if (v_next_x < -Number.EPSILON) {
  19436. direction_eq = true;
  19437. }
  19438. } else {
  19439. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  19440. direction_eq = true;
  19441. }
  19442. }
  19443. }
  19444. if (direction_eq) {
  19445. // console.log("Warning: lines are a straight sequence");
  19446. v_trans_x = -v_prev_y;
  19447. v_trans_y = v_prev_x;
  19448. shrink_by = Math.sqrt(v_prev_lensq);
  19449. } else {
  19450. // console.log("Warning: lines are a straight spike");
  19451. v_trans_x = v_prev_x;
  19452. v_trans_y = v_prev_y;
  19453. shrink_by = Math.sqrt(v_prev_lensq / 2);
  19454. }
  19455. }
  19456. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  19457. }
  19458. const contourMovements = [];
  19459. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  19460. if (j === il) j = 0;
  19461. if (k === il) k = 0; // (j)---(i)---(k)
  19462. // console.log('i,j,k', i, j , k)
  19463. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  19464. }
  19465. const holesMovements = [];
  19466. let oneHoleMovements,
  19467. verticesMovements = contourMovements.concat();
  19468. for (let h = 0, hl = holes.length; h < hl; h++) {
  19469. const ahole = holes[h];
  19470. oneHoleMovements = [];
  19471. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  19472. if (j === il) j = 0;
  19473. if (k === il) k = 0; // (j)---(i)---(k)
  19474. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  19475. }
  19476. holesMovements.push(oneHoleMovements);
  19477. verticesMovements = verticesMovements.concat(oneHoleMovements);
  19478. } // Loop bevelSegments, 1 for the front, 1 for the back
  19479. for (let b = 0; b < bevelSegments; b++) {
  19480. //for ( b = bevelSegments; b > 0; b -- ) {
  19481. const t = b / bevelSegments;
  19482. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  19483. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  19484. for (let i = 0, il = contour.length; i < il; i++) {
  19485. const vert = scalePt2(contour[i], contourMovements[i], bs);
  19486. v(vert.x, vert.y, -z);
  19487. } // expand holes
  19488. for (let h = 0, hl = holes.length; h < hl; h++) {
  19489. const ahole = holes[h];
  19490. oneHoleMovements = holesMovements[h];
  19491. for (let i = 0, il = ahole.length; i < il; i++) {
  19492. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  19493. v(vert.x, vert.y, -z);
  19494. }
  19495. }
  19496. }
  19497. const bs = bevelSize + bevelOffset; // Back facing vertices
  19498. for (let i = 0; i < vlen; i++) {
  19499. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  19500. if (!extrudeByPath) {
  19501. v(vert.x, vert.y, 0);
  19502. } else {
  19503. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19504. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  19505. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  19506. position2.copy(extrudePts[0]).add(normal).add(binormal);
  19507. v(position2.x, position2.y, position2.z);
  19508. }
  19509. } // Add stepped vertices...
  19510. // Including front facing vertices
  19511. for (let s = 1; s <= steps; s++) {
  19512. for (let i = 0; i < vlen; i++) {
  19513. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  19514. if (!extrudeByPath) {
  19515. v(vert.x, vert.y, depth / steps * s);
  19516. } else {
  19517. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19518. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  19519. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  19520. position2.copy(extrudePts[s]).add(normal).add(binormal);
  19521. v(position2.x, position2.y, position2.z);
  19522. }
  19523. }
  19524. } // Add bevel segments planes
  19525. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19526. for (let b = bevelSegments - 1; b >= 0; b--) {
  19527. const t = b / bevelSegments;
  19528. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  19529. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  19530. for (let i = 0, il = contour.length; i < il; i++) {
  19531. const vert = scalePt2(contour[i], contourMovements[i], bs);
  19532. v(vert.x, vert.y, depth + z);
  19533. } // expand holes
  19534. for (let h = 0, hl = holes.length; h < hl; h++) {
  19535. const ahole = holes[h];
  19536. oneHoleMovements = holesMovements[h];
  19537. for (let i = 0, il = ahole.length; i < il; i++) {
  19538. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  19539. if (!extrudeByPath) {
  19540. v(vert.x, vert.y, depth + z);
  19541. } else {
  19542. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  19543. }
  19544. }
  19545. }
  19546. }
  19547. /* Faces */
  19548. // Top and bottom faces
  19549. buildLidFaces(); // Sides faces
  19550. buildSideFaces(); ///// Internal functions
  19551. function buildLidFaces() {
  19552. const start = verticesArray.length / 3;
  19553. if (bevelEnabled) {
  19554. let layer = 0; // steps + 1
  19555. let offset = vlen * layer; // Bottom faces
  19556. for (let i = 0; i < flen; i++) {
  19557. const face = faces[i];
  19558. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  19559. }
  19560. layer = steps + bevelSegments * 2;
  19561. offset = vlen * layer; // Top faces
  19562. for (let i = 0; i < flen; i++) {
  19563. const face = faces[i];
  19564. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  19565. }
  19566. } else {
  19567. // Bottom faces
  19568. for (let i = 0; i < flen; i++) {
  19569. const face = faces[i];
  19570. f3(face[2], face[1], face[0]);
  19571. } // Top faces
  19572. for (let i = 0; i < flen; i++) {
  19573. const face = faces[i];
  19574. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  19575. }
  19576. }
  19577. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  19578. } // Create faces for the z-sides of the shape
  19579. function buildSideFaces() {
  19580. const start = verticesArray.length / 3;
  19581. let layeroffset = 0;
  19582. sidewalls(contour, layeroffset);
  19583. layeroffset += contour.length;
  19584. for (let h = 0, hl = holes.length; h < hl; h++) {
  19585. const ahole = holes[h];
  19586. sidewalls(ahole, layeroffset); //, true
  19587. layeroffset += ahole.length;
  19588. }
  19589. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  19590. }
  19591. function sidewalls(contour, layeroffset) {
  19592. let i = contour.length;
  19593. while (--i >= 0) {
  19594. const j = i;
  19595. let k = i - 1;
  19596. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  19597. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  19598. const slen1 = vlen * s;
  19599. const slen2 = vlen * (s + 1);
  19600. const a = layeroffset + j + slen1,
  19601. b = layeroffset + k + slen1,
  19602. c = layeroffset + k + slen2,
  19603. d = layeroffset + j + slen2;
  19604. f4(a, b, c, d);
  19605. }
  19606. }
  19607. }
  19608. function v(x, y, z) {
  19609. placeholder.push(x);
  19610. placeholder.push(y);
  19611. placeholder.push(z);
  19612. }
  19613. function f3(a, b, c) {
  19614. addVertex(a);
  19615. addVertex(b);
  19616. addVertex(c);
  19617. const nextIndex = verticesArray.length / 3;
  19618. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  19619. addUV(uvs[0]);
  19620. addUV(uvs[1]);
  19621. addUV(uvs[2]);
  19622. }
  19623. function f4(a, b, c, d) {
  19624. addVertex(a);
  19625. addVertex(b);
  19626. addVertex(d);
  19627. addVertex(b);
  19628. addVertex(c);
  19629. addVertex(d);
  19630. const nextIndex = verticesArray.length / 3;
  19631. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  19632. addUV(uvs[0]);
  19633. addUV(uvs[1]);
  19634. addUV(uvs[3]);
  19635. addUV(uvs[1]);
  19636. addUV(uvs[2]);
  19637. addUV(uvs[3]);
  19638. }
  19639. function addVertex(index) {
  19640. verticesArray.push(placeholder[index * 3 + 0]);
  19641. verticesArray.push(placeholder[index * 3 + 1]);
  19642. verticesArray.push(placeholder[index * 3 + 2]);
  19643. }
  19644. function addUV(vector2) {
  19645. uvArray.push(vector2.x);
  19646. uvArray.push(vector2.y);
  19647. }
  19648. }
  19649. }
  19650. toJSON() {
  19651. const data = super.toJSON();
  19652. const shapes = this.parameters.shapes;
  19653. const options = this.parameters.options;
  19654. return toJSON$1(shapes, options, data);
  19655. }
  19656. static fromJSON(data, shapes) {
  19657. const geometryShapes = [];
  19658. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  19659. const shape = shapes[data.shapes[j]];
  19660. geometryShapes.push(shape);
  19661. }
  19662. const extrudePath = data.options.extrudePath;
  19663. if (extrudePath !== undefined) {
  19664. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  19665. }
  19666. return new ExtrudeGeometry(geometryShapes, data.options);
  19667. }
  19668. }
  19669. const WorldUVGenerator = {
  19670. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  19671. const a_x = vertices[indexA * 3];
  19672. const a_y = vertices[indexA * 3 + 1];
  19673. const b_x = vertices[indexB * 3];
  19674. const b_y = vertices[indexB * 3 + 1];
  19675. const c_x = vertices[indexC * 3];
  19676. const c_y = vertices[indexC * 3 + 1];
  19677. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  19678. },
  19679. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  19680. const a_x = vertices[indexA * 3];
  19681. const a_y = vertices[indexA * 3 + 1];
  19682. const a_z = vertices[indexA * 3 + 2];
  19683. const b_x = vertices[indexB * 3];
  19684. const b_y = vertices[indexB * 3 + 1];
  19685. const b_z = vertices[indexB * 3 + 2];
  19686. const c_x = vertices[indexC * 3];
  19687. const c_y = vertices[indexC * 3 + 1];
  19688. const c_z = vertices[indexC * 3 + 2];
  19689. const d_x = vertices[indexD * 3];
  19690. const d_y = vertices[indexD * 3 + 1];
  19691. const d_z = vertices[indexD * 3 + 2];
  19692. if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) {
  19693. return [new Vector2(a_x, 1 - a_z), new Vector2(b_x, 1 - b_z), new Vector2(c_x, 1 - c_z), new Vector2(d_x, 1 - d_z)];
  19694. } else {
  19695. return [new Vector2(a_y, 1 - a_z), new Vector2(b_y, 1 - b_z), new Vector2(c_y, 1 - c_z), new Vector2(d_y, 1 - d_z)];
  19696. }
  19697. }
  19698. };
  19699. function toJSON$1(shapes, options, data) {
  19700. data.shapes = [];
  19701. if (Array.isArray(shapes)) {
  19702. for (let i = 0, l = shapes.length; i < l; i++) {
  19703. const shape = shapes[i];
  19704. data.shapes.push(shape.uuid);
  19705. }
  19706. } else {
  19707. data.shapes.push(shapes.uuid);
  19708. }
  19709. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  19710. return data;
  19711. }
  19712. class IcosahedronGeometry extends PolyhedronGeometry {
  19713. constructor(radius = 1, detail = 0) {
  19714. const t = (1 + Math.sqrt(5)) / 2;
  19715. const vertices = [-1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, 0, -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, t, 0, -1, t, 0, 1, -t, 0, -1, -t, 0, 1];
  19716. const indices = [0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1];
  19717. super(vertices, indices, radius, detail);
  19718. this.type = 'IcosahedronGeometry';
  19719. this.parameters = {
  19720. radius: radius,
  19721. detail: detail
  19722. };
  19723. }
  19724. static fromJSON(data) {
  19725. return new IcosahedronGeometry(data.radius, data.detail);
  19726. }
  19727. }
  19728. class LatheGeometry extends BufferGeometry {
  19729. constructor(points, segments = 12, phiStart = 0, phiLength = Math.PI * 2) {
  19730. super();
  19731. this.type = 'LatheGeometry';
  19732. this.parameters = {
  19733. points: points,
  19734. segments: segments,
  19735. phiStart: phiStart,
  19736. phiLength: phiLength
  19737. };
  19738. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  19739. phiLength = clamp(phiLength, 0, Math.PI * 2); // buffers
  19740. const indices = [];
  19741. const vertices = [];
  19742. const uvs = []; // helper variables
  19743. const inverseSegments = 1.0 / segments;
  19744. const vertex = new Vector3();
  19745. const uv = new Vector2(); // generate vertices and uvs
  19746. for (let i = 0; i <= segments; i++) {
  19747. const phi = phiStart + i * inverseSegments * phiLength;
  19748. const sin = Math.sin(phi);
  19749. const cos = Math.cos(phi);
  19750. for (let j = 0; j <= points.length - 1; j++) {
  19751. // vertex
  19752. vertex.x = points[j].x * sin;
  19753. vertex.y = points[j].y;
  19754. vertex.z = points[j].x * cos;
  19755. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  19756. uv.x = i / segments;
  19757. uv.y = j / (points.length - 1);
  19758. uvs.push(uv.x, uv.y);
  19759. }
  19760. } // indices
  19761. for (let i = 0; i < segments; i++) {
  19762. for (let j = 0; j < points.length - 1; j++) {
  19763. const base = j + i * points.length;
  19764. const a = base;
  19765. const b = base + points.length;
  19766. const c = base + points.length + 1;
  19767. const d = base + 1; // faces
  19768. indices.push(a, b, d);
  19769. indices.push(b, c, d);
  19770. }
  19771. } // build geometry
  19772. this.setIndex(indices);
  19773. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19774. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  19775. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  19776. // because the corresponding vertices are identical (but still have different UVs).
  19777. if (phiLength === Math.PI * 2) {
  19778. const normals = this.attributes.normal.array;
  19779. const n1 = new Vector3();
  19780. const n2 = new Vector3();
  19781. const n = new Vector3(); // this is the buffer offset for the last line of vertices
  19782. const base = segments * points.length * 3;
  19783. for (let i = 0, j = 0; i < points.length; i++, j += 3) {
  19784. // select the normal of the vertex in the first line
  19785. n1.x = normals[j + 0];
  19786. n1.y = normals[j + 1];
  19787. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  19788. n2.x = normals[base + j + 0];
  19789. n2.y = normals[base + j + 1];
  19790. n2.z = normals[base + j + 2]; // average normals
  19791. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  19792. normals[j + 0] = normals[base + j + 0] = n.x;
  19793. normals[j + 1] = normals[base + j + 1] = n.y;
  19794. normals[j + 2] = normals[base + j + 2] = n.z;
  19795. }
  19796. }
  19797. }
  19798. static fromJSON(data) {
  19799. return new LatheGeometry(data.points, data.segments, data.phiStart, data.phiLength);
  19800. }
  19801. }
  19802. class OctahedronGeometry extends PolyhedronGeometry {
  19803. constructor(radius = 1, detail = 0) {
  19804. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  19805. const indices = [0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2];
  19806. super(vertices, indices, radius, detail);
  19807. this.type = 'OctahedronGeometry';
  19808. this.parameters = {
  19809. radius: radius,
  19810. detail: detail
  19811. };
  19812. }
  19813. static fromJSON(data) {
  19814. return new OctahedronGeometry(data.radius, data.detail);
  19815. }
  19816. }
  19817. /**
  19818. * Parametric Surfaces Geometry
  19819. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  19820. */
  19821. class ParametricGeometry extends BufferGeometry {
  19822. constructor(func, slices, stacks) {
  19823. super();
  19824. this.type = 'ParametricGeometry';
  19825. this.parameters = {
  19826. func: func,
  19827. slices: slices,
  19828. stacks: stacks
  19829. }; // buffers
  19830. const indices = [];
  19831. const vertices = [];
  19832. const normals = [];
  19833. const uvs = [];
  19834. const EPS = 0.00001;
  19835. const normal = new Vector3();
  19836. const p0 = new Vector3(),
  19837. p1 = new Vector3();
  19838. const pu = new Vector3(),
  19839. pv = new Vector3();
  19840. if (func.length < 3) {
  19841. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  19842. } // generate vertices, normals and uvs
  19843. const sliceCount = slices + 1;
  19844. for (let i = 0; i <= stacks; i++) {
  19845. const v = i / stacks;
  19846. for (let j = 0; j <= slices; j++) {
  19847. const u = j / slices; // vertex
  19848. func(u, v, p0);
  19849. vertices.push(p0.x, p0.y, p0.z); // normal
  19850. // approximate tangent vectors via finite differences
  19851. if (u - EPS >= 0) {
  19852. func(u - EPS, v, p1);
  19853. pu.subVectors(p0, p1);
  19854. } else {
  19855. func(u + EPS, v, p1);
  19856. pu.subVectors(p1, p0);
  19857. }
  19858. if (v - EPS >= 0) {
  19859. func(u, v - EPS, p1);
  19860. pv.subVectors(p0, p1);
  19861. } else {
  19862. func(u, v + EPS, p1);
  19863. pv.subVectors(p1, p0);
  19864. } // cross product of tangent vectors returns surface normal
  19865. normal.crossVectors(pu, pv).normalize();
  19866. normals.push(normal.x, normal.y, normal.z); // uv
  19867. uvs.push(u, v);
  19868. }
  19869. } // generate indices
  19870. for (let i = 0; i < stacks; i++) {
  19871. for (let j = 0; j < slices; j++) {
  19872. const a = i * sliceCount + j;
  19873. const b = i * sliceCount + j + 1;
  19874. const c = (i + 1) * sliceCount + j + 1;
  19875. const d = (i + 1) * sliceCount + j; // faces one and two
  19876. indices.push(a, b, d);
  19877. indices.push(b, c, d);
  19878. }
  19879. } // build geometry
  19880. this.setIndex(indices);
  19881. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19882. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19883. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19884. }
  19885. }
  19886. class RingGeometry extends BufferGeometry {
  19887. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  19888. super();
  19889. this.type = 'RingGeometry';
  19890. this.parameters = {
  19891. innerRadius: innerRadius,
  19892. outerRadius: outerRadius,
  19893. thetaSegments: thetaSegments,
  19894. phiSegments: phiSegments,
  19895. thetaStart: thetaStart,
  19896. thetaLength: thetaLength
  19897. };
  19898. thetaSegments = Math.max(3, thetaSegments);
  19899. phiSegments = Math.max(1, phiSegments); // buffers
  19900. const indices = [];
  19901. const vertices = [];
  19902. const normals = [];
  19903. const uvs = []; // some helper variables
  19904. let radius = innerRadius;
  19905. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  19906. const vertex = new Vector3();
  19907. const uv = new Vector2(); // generate vertices, normals and uvs
  19908. for (let j = 0; j <= phiSegments; j++) {
  19909. for (let i = 0; i <= thetaSegments; i++) {
  19910. // values are generate from the inside of the ring to the outside
  19911. const segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  19912. vertex.x = radius * Math.cos(segment);
  19913. vertex.y = radius * Math.sin(segment);
  19914. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19915. normals.push(0, 0, 1); // uv
  19916. uv.x = (vertex.x / outerRadius + 1) / 2;
  19917. uv.y = (vertex.y / outerRadius + 1) / 2;
  19918. uvs.push(uv.x, uv.y);
  19919. } // increase the radius for next row of vertices
  19920. radius += radiusStep;
  19921. } // indices
  19922. for (let j = 0; j < phiSegments; j++) {
  19923. const thetaSegmentLevel = j * (thetaSegments + 1);
  19924. for (let i = 0; i < thetaSegments; i++) {
  19925. const segment = i + thetaSegmentLevel;
  19926. const a = segment;
  19927. const b = segment + thetaSegments + 1;
  19928. const c = segment + thetaSegments + 2;
  19929. const d = segment + 1; // faces
  19930. indices.push(a, b, d);
  19931. indices.push(b, c, d);
  19932. }
  19933. } // build geometry
  19934. this.setIndex(indices);
  19935. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19936. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19937. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19938. }
  19939. static fromJSON(data) {
  19940. return new RingGeometry(data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  19941. }
  19942. }
  19943. class ShapeGeometry extends BufferGeometry {
  19944. constructor(shapes, curveSegments = 12) {
  19945. super();
  19946. this.type = 'ShapeGeometry';
  19947. this.parameters = {
  19948. shapes: shapes,
  19949. curveSegments: curveSegments
  19950. }; // buffers
  19951. const indices = [];
  19952. const vertices = [];
  19953. const normals = [];
  19954. const uvs = []; // helper variables
  19955. let groupStart = 0;
  19956. let groupCount = 0; // allow single and array values for "shapes" parameter
  19957. if (Array.isArray(shapes) === false) {
  19958. addShape(shapes);
  19959. } else {
  19960. for (let i = 0; i < shapes.length; i++) {
  19961. addShape(shapes[i]);
  19962. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  19963. groupStart += groupCount;
  19964. groupCount = 0;
  19965. }
  19966. } // build geometry
  19967. this.setIndex(indices);
  19968. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19969. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19970. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  19971. function addShape(shape) {
  19972. const indexOffset = vertices.length / 3;
  19973. const points = shape.extractPoints(curveSegments);
  19974. let shapeVertices = points.shape;
  19975. const shapeHoles = points.holes; // check direction of vertices
  19976. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  19977. shapeVertices = shapeVertices.reverse();
  19978. }
  19979. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  19980. const shapeHole = shapeHoles[i];
  19981. if (ShapeUtils.isClockWise(shapeHole) === true) {
  19982. shapeHoles[i] = shapeHole.reverse();
  19983. }
  19984. }
  19985. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  19986. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  19987. const shapeHole = shapeHoles[i];
  19988. shapeVertices = shapeVertices.concat(shapeHole);
  19989. } // vertices, normals, uvs
  19990. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  19991. const vertex = shapeVertices[i];
  19992. vertices.push(vertex.x, vertex.y, 0);
  19993. normals.push(0, 0, 1);
  19994. uvs.push(vertex.x, vertex.y); // world uvs
  19995. } // incides
  19996. for (let i = 0, l = faces.length; i < l; i++) {
  19997. const face = faces[i];
  19998. const a = face[0] + indexOffset;
  19999. const b = face[1] + indexOffset;
  20000. const c = face[2] + indexOffset;
  20001. indices.push(a, b, c);
  20002. groupCount += 3;
  20003. }
  20004. }
  20005. }
  20006. toJSON() {
  20007. const data = super.toJSON();
  20008. const shapes = this.parameters.shapes;
  20009. return toJSON(shapes, data);
  20010. }
  20011. static fromJSON(data, shapes) {
  20012. const geometryShapes = [];
  20013. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  20014. const shape = shapes[data.shapes[j]];
  20015. geometryShapes.push(shape);
  20016. }
  20017. return new ShapeGeometry(geometryShapes, data.curveSegments);
  20018. }
  20019. }
  20020. function toJSON(shapes, data) {
  20021. data.shapes = [];
  20022. if (Array.isArray(shapes)) {
  20023. for (let i = 0, l = shapes.length; i < l; i++) {
  20024. const shape = shapes[i];
  20025. data.shapes.push(shape.uuid);
  20026. }
  20027. } else {
  20028. data.shapes.push(shapes.uuid);
  20029. }
  20030. return data;
  20031. }
  20032. class SphereGeometry extends BufferGeometry {
  20033. constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  20034. super();
  20035. this.type = 'SphereGeometry';
  20036. this.parameters = {
  20037. radius: radius,
  20038. widthSegments: widthSegments,
  20039. heightSegments: heightSegments,
  20040. phiStart: phiStart,
  20041. phiLength: phiLength,
  20042. thetaStart: thetaStart,
  20043. thetaLength: thetaLength
  20044. };
  20045. widthSegments = Math.max(3, Math.floor(widthSegments));
  20046. heightSegments = Math.max(2, Math.floor(heightSegments));
  20047. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  20048. let index = 0;
  20049. const grid = [];
  20050. const vertex = new Vector3();
  20051. const normal = new Vector3(); // buffers
  20052. const indices = [];
  20053. const vertices = [];
  20054. const normals = [];
  20055. const uvs = []; // generate vertices, normals and uvs
  20056. for (let iy = 0; iy <= heightSegments; iy++) {
  20057. const verticesRow = [];
  20058. const v = iy / heightSegments; // special case for the poles
  20059. let uOffset = 0;
  20060. if (iy == 0 && thetaStart == 0) {
  20061. uOffset = 0.5 / widthSegments;
  20062. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  20063. uOffset = -0.5 / widthSegments;
  20064. }
  20065. for (let ix = 0; ix <= widthSegments; ix++) {
  20066. const u = ix / widthSegments; // vertex
  20067. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  20068. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  20069. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  20070. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20071. normal.copy(vertex).normalize();
  20072. normals.push(normal.x, normal.y, normal.z); // uv
  20073. uvs.push(u + uOffset, 1 - v);
  20074. verticesRow.push(index++);
  20075. }
  20076. grid.push(verticesRow);
  20077. } // indices
  20078. for (let iy = 0; iy < heightSegments; iy++) {
  20079. for (let ix = 0; ix < widthSegments; ix++) {
  20080. const a = grid[iy][ix + 1];
  20081. const b = grid[iy][ix];
  20082. const c = grid[iy + 1][ix];
  20083. const d = grid[iy + 1][ix + 1];
  20084. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  20085. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  20086. }
  20087. } // build geometry
  20088. this.setIndex(indices);
  20089. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20090. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20091. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20092. }
  20093. static fromJSON(data) {
  20094. return new SphereGeometry(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  20095. }
  20096. }
  20097. class TetrahedronGeometry extends PolyhedronGeometry {
  20098. constructor(radius = 1, detail = 0) {
  20099. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  20100. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  20101. super(vertices, indices, radius, detail);
  20102. this.type = 'TetrahedronGeometry';
  20103. this.parameters = {
  20104. radius: radius,
  20105. detail: detail
  20106. };
  20107. }
  20108. static fromJSON(data) {
  20109. return new TetrahedronGeometry(data.radius, data.detail);
  20110. }
  20111. }
  20112. /**
  20113. * Text = 3D Text
  20114. *
  20115. * parameters = {
  20116. * font: <THREE.Font>, // font
  20117. *
  20118. * size: <float>, // size of the text
  20119. * height: <float>, // thickness to extrude text
  20120. * curveSegments: <int>, // number of points on the curves
  20121. *
  20122. * bevelEnabled: <bool>, // turn on bevel
  20123. * bevelThickness: <float>, // how deep into text bevel goes
  20124. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  20125. * bevelOffset: <float> // how far from text outline does bevel start
  20126. * }
  20127. */
  20128. class TextGeometry extends ExtrudeGeometry {
  20129. constructor(text, parameters = {}) {
  20130. const font = parameters.font;
  20131. if (!(font && font.isFont)) {
  20132. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  20133. return new BufferGeometry();
  20134. }
  20135. const shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  20136. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  20137. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  20138. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  20139. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  20140. super(shapes, parameters);
  20141. this.type = 'TextGeometry';
  20142. }
  20143. }
  20144. class TorusGeometry extends BufferGeometry {
  20145. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  20146. super();
  20147. this.type = 'TorusGeometry';
  20148. this.parameters = {
  20149. radius: radius,
  20150. tube: tube,
  20151. radialSegments: radialSegments,
  20152. tubularSegments: tubularSegments,
  20153. arc: arc
  20154. };
  20155. radialSegments = Math.floor(radialSegments);
  20156. tubularSegments = Math.floor(tubularSegments); // buffers
  20157. const indices = [];
  20158. const vertices = [];
  20159. const normals = [];
  20160. const uvs = []; // helper variables
  20161. const center = new Vector3();
  20162. const vertex = new Vector3();
  20163. const normal = new Vector3(); // generate vertices, normals and uvs
  20164. for (let j = 0; j <= radialSegments; j++) {
  20165. for (let i = 0; i <= tubularSegments; i++) {
  20166. const u = i / tubularSegments * arc;
  20167. const v = j / radialSegments * Math.PI * 2; // vertex
  20168. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  20169. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  20170. vertex.z = tube * Math.sin(v);
  20171. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20172. center.x = radius * Math.cos(u);
  20173. center.y = radius * Math.sin(u);
  20174. normal.subVectors(vertex, center).normalize();
  20175. normals.push(normal.x, normal.y, normal.z); // uv
  20176. uvs.push(i / tubularSegments);
  20177. uvs.push(j / radialSegments);
  20178. }
  20179. } // generate indices
  20180. for (let j = 1; j <= radialSegments; j++) {
  20181. for (let i = 1; i <= tubularSegments; i++) {
  20182. // indices
  20183. const a = (tubularSegments + 1) * j + i - 1;
  20184. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  20185. const c = (tubularSegments + 1) * (j - 1) + i;
  20186. const d = (tubularSegments + 1) * j + i; // faces
  20187. indices.push(a, b, d);
  20188. indices.push(b, c, d);
  20189. }
  20190. } // build geometry
  20191. this.setIndex(indices);
  20192. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20193. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20194. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20195. }
  20196. static fromJSON(data) {
  20197. return new TorusGeometry(data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  20198. }
  20199. }
  20200. class TorusKnotGeometry extends BufferGeometry {
  20201. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  20202. super();
  20203. this.type = 'TorusKnotGeometry';
  20204. this.parameters = {
  20205. radius: radius,
  20206. tube: tube,
  20207. tubularSegments: tubularSegments,
  20208. radialSegments: radialSegments,
  20209. p: p,
  20210. q: q
  20211. };
  20212. tubularSegments = Math.floor(tubularSegments);
  20213. radialSegments = Math.floor(radialSegments); // buffers
  20214. const indices = [];
  20215. const vertices = [];
  20216. const normals = [];
  20217. const uvs = []; // helper variables
  20218. const vertex = new Vector3();
  20219. const normal = new Vector3();
  20220. const P1 = new Vector3();
  20221. const P2 = new Vector3();
  20222. const B = new Vector3();
  20223. const T = new Vector3();
  20224. const N = new Vector3(); // generate vertices, normals and uvs
  20225. for (let i = 0; i <= tubularSegments; ++i) {
  20226. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  20227. const u = i / tubularSegments * p * Math.PI * 2; // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  20228. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  20229. calculatePositionOnCurve(u, p, q, radius, P1);
  20230. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  20231. T.subVectors(P2, P1);
  20232. N.addVectors(P2, P1);
  20233. B.crossVectors(T, N);
  20234. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  20235. B.normalize();
  20236. N.normalize();
  20237. for (let j = 0; j <= radialSegments; ++j) {
  20238. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  20239. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  20240. const v = j / radialSegments * Math.PI * 2;
  20241. const cx = -tube * Math.cos(v);
  20242. const cy = tube * Math.sin(v); // now calculate the final vertex position.
  20243. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  20244. vertex.x = P1.x + (cx * N.x + cy * B.x);
  20245. vertex.y = P1.y + (cx * N.y + cy * B.y);
  20246. vertex.z = P1.z + (cx * N.z + cy * B.z);
  20247. vertices.push(vertex.x, vertex.y, vertex.z); // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  20248. normal.subVectors(vertex, P1).normalize();
  20249. normals.push(normal.x, normal.y, normal.z); // uv
  20250. uvs.push(i / tubularSegments);
  20251. uvs.push(j / radialSegments);
  20252. }
  20253. } // generate indices
  20254. for (let j = 1; j <= tubularSegments; j++) {
  20255. for (let i = 1; i <= radialSegments; i++) {
  20256. // indices
  20257. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  20258. const b = (radialSegments + 1) * j + (i - 1);
  20259. const c = (radialSegments + 1) * j + i;
  20260. const d = (radialSegments + 1) * (j - 1) + i; // faces
  20261. indices.push(a, b, d);
  20262. indices.push(b, c, d);
  20263. }
  20264. } // build geometry
  20265. this.setIndex(indices);
  20266. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20267. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20268. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  20269. function calculatePositionOnCurve(u, p, q, radius, position) {
  20270. const cu = Math.cos(u);
  20271. const su = Math.sin(u);
  20272. const quOverP = q / p * u;
  20273. const cs = Math.cos(quOverP);
  20274. position.x = radius * (2 + cs) * 0.5 * cu;
  20275. position.y = radius * (2 + cs) * su * 0.5;
  20276. position.z = radius * Math.sin(quOverP) * 0.5;
  20277. }
  20278. }
  20279. static fromJSON(data) {
  20280. return new TorusKnotGeometry(data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  20281. }
  20282. }
  20283. class TubeGeometry extends BufferGeometry {
  20284. constructor(path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) {
  20285. super();
  20286. this.type = 'TubeGeometry';
  20287. this.parameters = {
  20288. path: path,
  20289. tubularSegments: tubularSegments,
  20290. radius: radius,
  20291. radialSegments: radialSegments,
  20292. closed: closed
  20293. };
  20294. const frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  20295. this.tangents = frames.tangents;
  20296. this.normals = frames.normals;
  20297. this.binormals = frames.binormals; // helper variables
  20298. const vertex = new Vector3();
  20299. const normal = new Vector3();
  20300. const uv = new Vector2();
  20301. let P = new Vector3(); // buffer
  20302. const vertices = [];
  20303. const normals = [];
  20304. const uvs = [];
  20305. const indices = []; // create buffer data
  20306. generateBufferData(); // build geometry
  20307. this.setIndex(indices);
  20308. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20309. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20310. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  20311. function generateBufferData() {
  20312. for (let i = 0; i < tubularSegments; i++) {
  20313. generateSegment(i);
  20314. } // if the geometry is not closed, generate the last row of vertices and normals
  20315. // at the regular position on the given path
  20316. //
  20317. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  20318. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  20319. // this makes it easy compute correct values for closed geometries
  20320. generateUVs(); // finally create faces
  20321. generateIndices();
  20322. }
  20323. function generateSegment(i) {
  20324. // we use getPointAt to sample evenly distributed points from the given path
  20325. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  20326. const N = frames.normals[i];
  20327. const B = frames.binormals[i]; // generate normals and vertices for the current segment
  20328. for (let j = 0; j <= radialSegments; j++) {
  20329. const v = j / radialSegments * Math.PI * 2;
  20330. const sin = Math.sin(v);
  20331. const cos = -Math.cos(v); // normal
  20332. normal.x = cos * N.x + sin * B.x;
  20333. normal.y = cos * N.y + sin * B.y;
  20334. normal.z = cos * N.z + sin * B.z;
  20335. normal.normalize();
  20336. normals.push(normal.x, normal.y, normal.z); // vertex
  20337. vertex.x = P.x + radius * normal.x;
  20338. vertex.y = P.y + radius * normal.y;
  20339. vertex.z = P.z + radius * normal.z;
  20340. vertices.push(vertex.x, vertex.y, vertex.z);
  20341. }
  20342. }
  20343. function generateIndices() {
  20344. for (let j = 1; j <= tubularSegments; j++) {
  20345. for (let i = 1; i <= radialSegments; i++) {
  20346. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  20347. const b = (radialSegments + 1) * j + (i - 1);
  20348. const c = (radialSegments + 1) * j + i;
  20349. const d = (radialSegments + 1) * (j - 1) + i; // faces
  20350. indices.push(a, b, d);
  20351. indices.push(b, c, d);
  20352. }
  20353. }
  20354. }
  20355. function generateUVs() {
  20356. for (let i = 0; i <= tubularSegments; i++) {
  20357. for (let j = 0; j <= radialSegments; j++) {
  20358. uv.x = i / tubularSegments;
  20359. uv.y = j / radialSegments;
  20360. uvs.push(uv.x, uv.y);
  20361. }
  20362. }
  20363. }
  20364. }
  20365. toJSON() {
  20366. const data = super.toJSON();
  20367. data.path = this.parameters.path.toJSON();
  20368. return data;
  20369. }
  20370. static fromJSON(data) {
  20371. // This only works for built-in curves (e.g. CatmullRomCurve3).
  20372. // User defined curves or instances of CurvePath will not be deserialized.
  20373. return new TubeGeometry(new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  20374. }
  20375. }
  20376. class WireframeGeometry extends BufferGeometry {
  20377. constructor(geometry) {
  20378. super();
  20379. this.type = 'WireframeGeometry';
  20380. if (geometry.isGeometry === true) {
  20381. console.error('THREE.WireframeGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  20382. return;
  20383. } // buffer
  20384. const vertices = [];
  20385. const edges = new Set(); // helper variables
  20386. const start = new Vector3();
  20387. const end = new Vector3();
  20388. if (geometry.index !== null) {
  20389. // indexed BufferGeometry
  20390. const position = geometry.attributes.position;
  20391. const indices = geometry.index;
  20392. let groups = geometry.groups;
  20393. if (groups.length === 0) {
  20394. groups = [{
  20395. start: 0,
  20396. count: indices.count,
  20397. materialIndex: 0
  20398. }];
  20399. } // create a data structure that contains all eges without duplicates
  20400. for (let o = 0, ol = groups.length; o < ol; ++o) {
  20401. const group = groups[o];
  20402. const groupStart = group.start;
  20403. const groupCount = group.count;
  20404. for (let i = groupStart, l = groupStart + groupCount; i < l; i += 3) {
  20405. for (let j = 0; j < 3; j++) {
  20406. const index1 = indices.getX(i + j);
  20407. const index2 = indices.getX(i + (j + 1) % 3);
  20408. start.fromBufferAttribute(position, index1);
  20409. end.fromBufferAttribute(position, index2);
  20410. if (isUniqueEdge(start, end, edges) === true) {
  20411. vertices.push(start.x, start.y, start.z);
  20412. vertices.push(end.x, end.y, end.z);
  20413. }
  20414. }
  20415. }
  20416. }
  20417. } else {
  20418. // non-indexed BufferGeometry
  20419. const position = geometry.attributes.position;
  20420. for (let i = 0, l = position.count / 3; i < l; i++) {
  20421. for (let j = 0; j < 3; j++) {
  20422. // three edges per triangle, an edge is represented as (index1, index2)
  20423. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  20424. const index1 = 3 * i + j;
  20425. const index2 = 3 * i + (j + 1) % 3;
  20426. start.fromBufferAttribute(position, index1);
  20427. end.fromBufferAttribute(position, index2);
  20428. if (isUniqueEdge(start, end, edges) === true) {
  20429. vertices.push(start.x, start.y, start.z);
  20430. vertices.push(end.x, end.y, end.z);
  20431. }
  20432. }
  20433. }
  20434. } // build geometry
  20435. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20436. }
  20437. }
  20438. function isUniqueEdge(start, end, edges) {
  20439. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  20440. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  20441. if (edges.has(hash1) === true || edges.has(hash2) === true) {
  20442. return false;
  20443. } else {
  20444. edges.add(hash1, hash2);
  20445. return true;
  20446. }
  20447. }
  20448. var Geometries = /*#__PURE__*/Object.freeze({
  20449. __proto__: null,
  20450. BoxGeometry: BoxGeometry,
  20451. BoxBufferGeometry: BoxGeometry,
  20452. CircleGeometry: CircleGeometry,
  20453. CircleBufferGeometry: CircleGeometry,
  20454. ConeGeometry: ConeGeometry,
  20455. ConeBufferGeometry: ConeGeometry,
  20456. CylinderGeometry: CylinderGeometry,
  20457. CylinderBufferGeometry: CylinderGeometry,
  20458. DodecahedronGeometry: DodecahedronGeometry,
  20459. DodecahedronBufferGeometry: DodecahedronGeometry,
  20460. EdgesGeometry: EdgesGeometry,
  20461. ExtrudeGeometry: ExtrudeGeometry,
  20462. ExtrudeBufferGeometry: ExtrudeGeometry,
  20463. IcosahedronGeometry: IcosahedronGeometry,
  20464. IcosahedronBufferGeometry: IcosahedronGeometry,
  20465. LatheGeometry: LatheGeometry,
  20466. LatheBufferGeometry: LatheGeometry,
  20467. OctahedronGeometry: OctahedronGeometry,
  20468. OctahedronBufferGeometry: OctahedronGeometry,
  20469. ParametricGeometry: ParametricGeometry,
  20470. ParametricBufferGeometry: ParametricGeometry,
  20471. PlaneGeometry: PlaneGeometry,
  20472. PlaneBufferGeometry: PlaneGeometry,
  20473. PolyhedronGeometry: PolyhedronGeometry,
  20474. PolyhedronBufferGeometry: PolyhedronGeometry,
  20475. RingGeometry: RingGeometry,
  20476. RingBufferGeometry: RingGeometry,
  20477. ShapeGeometry: ShapeGeometry,
  20478. ShapeBufferGeometry: ShapeGeometry,
  20479. SphereGeometry: SphereGeometry,
  20480. SphereBufferGeometry: SphereGeometry,
  20481. TetrahedronGeometry: TetrahedronGeometry,
  20482. TetrahedronBufferGeometry: TetrahedronGeometry,
  20483. TextGeometry: TextGeometry,
  20484. TextBufferGeometry: TextGeometry,
  20485. TorusGeometry: TorusGeometry,
  20486. TorusBufferGeometry: TorusGeometry,
  20487. TorusKnotGeometry: TorusKnotGeometry,
  20488. TorusKnotBufferGeometry: TorusKnotGeometry,
  20489. TubeGeometry: TubeGeometry,
  20490. TubeBufferGeometry: TubeGeometry,
  20491. WireframeGeometry: WireframeGeometry
  20492. });
  20493. /**
  20494. * parameters = {
  20495. * color: <THREE.Color>
  20496. * }
  20497. */
  20498. class ShadowMaterial extends Material {
  20499. constructor(parameters) {
  20500. super();
  20501. this.type = 'ShadowMaterial';
  20502. this.color = new Color(0x000000);
  20503. this.transparent = true;
  20504. this.setValues(parameters);
  20505. }
  20506. copy(source) {
  20507. super.copy(source);
  20508. this.color.copy(source.color);
  20509. return this;
  20510. }
  20511. }
  20512. ShadowMaterial.prototype.isShadowMaterial = true;
  20513. /**
  20514. * parameters = {
  20515. * color: <hex>,
  20516. * roughness: <float>,
  20517. * metalness: <float>,
  20518. * opacity: <float>,
  20519. *
  20520. * map: new THREE.Texture( <Image> ),
  20521. *
  20522. * lightMap: new THREE.Texture( <Image> ),
  20523. * lightMapIntensity: <float>
  20524. *
  20525. * aoMap: new THREE.Texture( <Image> ),
  20526. * aoMapIntensity: <float>
  20527. *
  20528. * emissive: <hex>,
  20529. * emissiveIntensity: <float>
  20530. * emissiveMap: new THREE.Texture( <Image> ),
  20531. *
  20532. * bumpMap: new THREE.Texture( <Image> ),
  20533. * bumpScale: <float>,
  20534. *
  20535. * normalMap: new THREE.Texture( <Image> ),
  20536. * normalMapType: THREE.TangentSpaceNormalMap,
  20537. * normalScale: <Vector2>,
  20538. *
  20539. * displacementMap: new THREE.Texture( <Image> ),
  20540. * displacementScale: <float>,
  20541. * displacementBias: <float>,
  20542. *
  20543. * roughnessMap: new THREE.Texture( <Image> ),
  20544. *
  20545. * metalnessMap: new THREE.Texture( <Image> ),
  20546. *
  20547. * alphaMap: new THREE.Texture( <Image> ),
  20548. *
  20549. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20550. * envMapIntensity: <float>
  20551. *
  20552. * refractionRatio: <float>,
  20553. *
  20554. * wireframe: <boolean>,
  20555. * wireframeLinewidth: <float>,
  20556. *
  20557. * flatShading: <bool>
  20558. * }
  20559. */
  20560. class MeshStandardMaterial extends Material {
  20561. constructor(parameters) {
  20562. super();
  20563. this.defines = {
  20564. 'STANDARD': ''
  20565. };
  20566. this.type = 'MeshStandardMaterial';
  20567. this.color = new Color(0xffffff); // diffuse
  20568. this.roughness = 1.0;
  20569. this.metalness = 0.0;
  20570. this.map = null;
  20571. this.lightMap = null;
  20572. this.lightMapIntensity = 1.0;
  20573. this.aoMap = null;
  20574. this.aoMapIntensity = 1.0;
  20575. this.emissive = new Color(0x000000);
  20576. this.emissiveIntensity = 1.0;
  20577. this.emissiveMap = null;
  20578. this.bumpMap = null;
  20579. this.bumpScale = 1;
  20580. this.normalMap = null;
  20581. this.normalMapType = TangentSpaceNormalMap;
  20582. this.normalScale = new Vector2(1, 1);
  20583. this.displacementMap = null;
  20584. this.displacementScale = 1;
  20585. this.displacementBias = 0;
  20586. this.roughnessMap = null;
  20587. this.metalnessMap = null;
  20588. this.alphaMap = null;
  20589. this.envMap = null;
  20590. this.envMapIntensity = 1.0;
  20591. this.refractionRatio = 0.98;
  20592. this.wireframe = false;
  20593. this.wireframeLinewidth = 1;
  20594. this.wireframeLinecap = 'round';
  20595. this.wireframeLinejoin = 'round';
  20596. this.flatShading = false;
  20597. this.setValues(parameters);
  20598. }
  20599. copy(source) {
  20600. super.copy(source);
  20601. this.defines = {
  20602. 'STANDARD': ''
  20603. };
  20604. this.color.copy(source.color);
  20605. this.roughness = source.roughness;
  20606. this.metalness = source.metalness;
  20607. this.map = source.map;
  20608. this.lightMap = source.lightMap;
  20609. this.lightMapIntensity = source.lightMapIntensity;
  20610. this.aoMap = source.aoMap;
  20611. this.aoMapIntensity = source.aoMapIntensity;
  20612. this.emissive.copy(source.emissive);
  20613. this.emissiveMap = source.emissiveMap;
  20614. this.emissiveIntensity = source.emissiveIntensity;
  20615. this.bumpMap = source.bumpMap;
  20616. this.bumpScale = source.bumpScale;
  20617. this.normalMap = source.normalMap;
  20618. this.normalMapType = source.normalMapType;
  20619. this.normalScale.copy(source.normalScale);
  20620. this.displacementMap = source.displacementMap;
  20621. this.displacementScale = source.displacementScale;
  20622. this.displacementBias = source.displacementBias;
  20623. this.roughnessMap = source.roughnessMap;
  20624. this.metalnessMap = source.metalnessMap;
  20625. this.alphaMap = source.alphaMap;
  20626. this.envMap = source.envMap;
  20627. this.envMapIntensity = source.envMapIntensity;
  20628. this.refractionRatio = source.refractionRatio;
  20629. this.wireframe = source.wireframe;
  20630. this.wireframeLinewidth = source.wireframeLinewidth;
  20631. this.wireframeLinecap = source.wireframeLinecap;
  20632. this.wireframeLinejoin = source.wireframeLinejoin;
  20633. this.flatShading = source.flatShading;
  20634. return this;
  20635. }
  20636. }
  20637. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  20638. /**
  20639. * parameters = {
  20640. * clearcoat: <float>,
  20641. * clearcoatMap: new THREE.Texture( <Image> ),
  20642. * clearcoatRoughness: <float>,
  20643. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  20644. * clearcoatNormalScale: <Vector2>,
  20645. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  20646. *
  20647. * ior: <float>,
  20648. * reflectivity: <float>,
  20649. *
  20650. * sheen: <float>,
  20651. * sheenTint: <Color>,
  20652. * sheenRoughness: <float>,
  20653. *
  20654. * transmission: <float>,
  20655. * transmissionMap: new THREE.Texture( <Image> ),
  20656. *
  20657. * thickness: <float>,
  20658. * thicknessMap: new THREE.Texture( <Image> ),
  20659. * attenuationDistance: <float>,
  20660. * attenuationTint: <Color>,
  20661. *
  20662. * specularIntensity: <float>,
  20663. * specularIntensityhMap: new THREE.Texture( <Image> ),
  20664. * specularTint: <Color>,
  20665. * specularTintMap: new THREE.Texture( <Image> )
  20666. * }
  20667. */
  20668. class MeshPhysicalMaterial extends MeshStandardMaterial {
  20669. constructor(parameters) {
  20670. super();
  20671. this.defines = {
  20672. 'STANDARD': '',
  20673. 'PHYSICAL': ''
  20674. };
  20675. this.type = 'MeshPhysicalMaterial';
  20676. this.clearcoatMap = null;
  20677. this.clearcoatRoughness = 0.0;
  20678. this.clearcoatRoughnessMap = null;
  20679. this.clearcoatNormalScale = new Vector2(1, 1);
  20680. this.clearcoatNormalMap = null;
  20681. this.ior = 1.5;
  20682. Object.defineProperty(this, 'reflectivity', {
  20683. get: function () {
  20684. return clamp(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1);
  20685. },
  20686. set: function (reflectivity) {
  20687. this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity);
  20688. }
  20689. });
  20690. this.sheenTint = new Color(0x000000);
  20691. this.sheenRoughness = 1.0;
  20692. this.transmissionMap = null;
  20693. this.thickness = 0.01;
  20694. this.thicknessMap = null;
  20695. this.attenuationDistance = 0.0;
  20696. this.attenuationTint = new Color(1, 1, 1);
  20697. this.specularIntensity = 1.0;
  20698. this.specularIntensityMap = null;
  20699. this.specularTint = new Color(1, 1, 1);
  20700. this.specularTintMap = null;
  20701. this._sheen = 0.0;
  20702. this._clearcoat = 0;
  20703. this._transmission = 0;
  20704. this.setValues(parameters);
  20705. }
  20706. get sheen() {
  20707. return this._sheen;
  20708. }
  20709. set sheen(value) {
  20710. if (this._sheen > 0 !== value > 0) {
  20711. this.version++;
  20712. }
  20713. this._sheen = value;
  20714. }
  20715. get clearcoat() {
  20716. return this._clearcoat;
  20717. }
  20718. set clearcoat(value) {
  20719. if (this._clearcoat > 0 !== value > 0) {
  20720. this.version++;
  20721. }
  20722. this._clearcoat = value;
  20723. }
  20724. get transmission() {
  20725. return this._transmission;
  20726. }
  20727. set transmission(value) {
  20728. if (this._transmission > 0 !== value > 0) {
  20729. this.version++;
  20730. }
  20731. this._transmission = value;
  20732. }
  20733. copy(source) {
  20734. super.copy(source);
  20735. this.defines = {
  20736. 'STANDARD': '',
  20737. 'PHYSICAL': ''
  20738. };
  20739. this.clearcoat = source.clearcoat;
  20740. this.clearcoatMap = source.clearcoatMap;
  20741. this.clearcoatRoughness = source.clearcoatRoughness;
  20742. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  20743. this.clearcoatNormalMap = source.clearcoatNormalMap;
  20744. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  20745. this.ior = source.ior;
  20746. this.sheen = source.sheen;
  20747. this.sheenTint.copy(source.sheenTint);
  20748. this.sheenRoughness = source.sheenRoughness;
  20749. this.transmission = source.transmission;
  20750. this.transmissionMap = source.transmissionMap;
  20751. this.thickness = source.thickness;
  20752. this.thicknessMap = source.thicknessMap;
  20753. this.attenuationDistance = source.attenuationDistance;
  20754. this.attenuationTint.copy(source.attenuationTint);
  20755. this.specularIntensity = source.specularIntensity;
  20756. this.specularIntensityMap = source.specularIntensityMap;
  20757. this.specularTint.copy(source.specularTint);
  20758. this.specularTintMap = source.specularTintMap;
  20759. return this;
  20760. }
  20761. }
  20762. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  20763. /**
  20764. * parameters = {
  20765. * color: <hex>,
  20766. * specular: <hex>,
  20767. * shininess: <float>,
  20768. * opacity: <float>,
  20769. *
  20770. * map: new THREE.Texture( <Image> ),
  20771. *
  20772. * lightMap: new THREE.Texture( <Image> ),
  20773. * lightMapIntensity: <float>
  20774. *
  20775. * aoMap: new THREE.Texture( <Image> ),
  20776. * aoMapIntensity: <float>
  20777. *
  20778. * emissive: <hex>,
  20779. * emissiveIntensity: <float>
  20780. * emissiveMap: new THREE.Texture( <Image> ),
  20781. *
  20782. * bumpMap: new THREE.Texture( <Image> ),
  20783. * bumpScale: <float>,
  20784. *
  20785. * normalMap: new THREE.Texture( <Image> ),
  20786. * normalMapType: THREE.TangentSpaceNormalMap,
  20787. * normalScale: <Vector2>,
  20788. *
  20789. * displacementMap: new THREE.Texture( <Image> ),
  20790. * displacementScale: <float>,
  20791. * displacementBias: <float>,
  20792. *
  20793. * specularMap: new THREE.Texture( <Image> ),
  20794. *
  20795. * alphaMap: new THREE.Texture( <Image> ),
  20796. *
  20797. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20798. * combine: THREE.MultiplyOperation,
  20799. * reflectivity: <float>,
  20800. * refractionRatio: <float>,
  20801. *
  20802. * wireframe: <boolean>,
  20803. * wireframeLinewidth: <float>,
  20804. *
  20805. * flatShading: <bool>
  20806. * }
  20807. */
  20808. class MeshPhongMaterial extends Material {
  20809. constructor(parameters) {
  20810. super();
  20811. this.type = 'MeshPhongMaterial';
  20812. this.color = new Color(0xffffff); // diffuse
  20813. this.specular = new Color(0x111111);
  20814. this.shininess = 30;
  20815. this.map = null;
  20816. this.lightMap = null;
  20817. this.lightMapIntensity = 1.0;
  20818. this.aoMap = null;
  20819. this.aoMapIntensity = 1.0;
  20820. this.emissive = new Color(0x000000);
  20821. this.emissiveIntensity = 1.0;
  20822. this.emissiveMap = null;
  20823. this.bumpMap = null;
  20824. this.bumpScale = 1;
  20825. this.normalMap = null;
  20826. this.normalMapType = TangentSpaceNormalMap;
  20827. this.normalScale = new Vector2(1, 1);
  20828. this.displacementMap = null;
  20829. this.displacementScale = 1;
  20830. this.displacementBias = 0;
  20831. this.specularMap = null;
  20832. this.alphaMap = null;
  20833. this.envMap = null;
  20834. this.combine = MultiplyOperation;
  20835. this.reflectivity = 1;
  20836. this.refractionRatio = 0.98;
  20837. this.wireframe = false;
  20838. this.wireframeLinewidth = 1;
  20839. this.wireframeLinecap = 'round';
  20840. this.wireframeLinejoin = 'round';
  20841. this.flatShading = false;
  20842. this.setValues(parameters);
  20843. }
  20844. copy(source) {
  20845. super.copy(source);
  20846. this.color.copy(source.color);
  20847. this.specular.copy(source.specular);
  20848. this.shininess = source.shininess;
  20849. this.map = source.map;
  20850. this.lightMap = source.lightMap;
  20851. this.lightMapIntensity = source.lightMapIntensity;
  20852. this.aoMap = source.aoMap;
  20853. this.aoMapIntensity = source.aoMapIntensity;
  20854. this.emissive.copy(source.emissive);
  20855. this.emissiveMap = source.emissiveMap;
  20856. this.emissiveIntensity = source.emissiveIntensity;
  20857. this.bumpMap = source.bumpMap;
  20858. this.bumpScale = source.bumpScale;
  20859. this.normalMap = source.normalMap;
  20860. this.normalMapType = source.normalMapType;
  20861. this.normalScale.copy(source.normalScale);
  20862. this.displacementMap = source.displacementMap;
  20863. this.displacementScale = source.displacementScale;
  20864. this.displacementBias = source.displacementBias;
  20865. this.specularMap = source.specularMap;
  20866. this.alphaMap = source.alphaMap;
  20867. this.envMap = source.envMap;
  20868. this.combine = source.combine;
  20869. this.reflectivity = source.reflectivity;
  20870. this.refractionRatio = source.refractionRatio;
  20871. this.wireframe = source.wireframe;
  20872. this.wireframeLinewidth = source.wireframeLinewidth;
  20873. this.wireframeLinecap = source.wireframeLinecap;
  20874. this.wireframeLinejoin = source.wireframeLinejoin;
  20875. this.flatShading = source.flatShading;
  20876. return this;
  20877. }
  20878. }
  20879. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  20880. /**
  20881. * parameters = {
  20882. * color: <hex>,
  20883. *
  20884. * map: new THREE.Texture( <Image> ),
  20885. * gradientMap: new THREE.Texture( <Image> ),
  20886. *
  20887. * lightMap: new THREE.Texture( <Image> ),
  20888. * lightMapIntensity: <float>
  20889. *
  20890. * aoMap: new THREE.Texture( <Image> ),
  20891. * aoMapIntensity: <float>
  20892. *
  20893. * emissive: <hex>,
  20894. * emissiveIntensity: <float>
  20895. * emissiveMap: new THREE.Texture( <Image> ),
  20896. *
  20897. * bumpMap: new THREE.Texture( <Image> ),
  20898. * bumpScale: <float>,
  20899. *
  20900. * normalMap: new THREE.Texture( <Image> ),
  20901. * normalMapType: THREE.TangentSpaceNormalMap,
  20902. * normalScale: <Vector2>,
  20903. *
  20904. * displacementMap: new THREE.Texture( <Image> ),
  20905. * displacementScale: <float>,
  20906. * displacementBias: <float>,
  20907. *
  20908. * alphaMap: new THREE.Texture( <Image> ),
  20909. *
  20910. * wireframe: <boolean>,
  20911. * wireframeLinewidth: <float>,
  20912. *
  20913. * }
  20914. */
  20915. class MeshToonMaterial extends Material {
  20916. constructor(parameters) {
  20917. super();
  20918. this.defines = {
  20919. 'TOON': ''
  20920. };
  20921. this.type = 'MeshToonMaterial';
  20922. this.color = new Color(0xffffff);
  20923. this.map = null;
  20924. this.gradientMap = null;
  20925. this.lightMap = null;
  20926. this.lightMapIntensity = 1.0;
  20927. this.aoMap = null;
  20928. this.aoMapIntensity = 1.0;
  20929. this.emissive = new Color(0x000000);
  20930. this.emissiveIntensity = 1.0;
  20931. this.emissiveMap = null;
  20932. this.bumpMap = null;
  20933. this.bumpScale = 1;
  20934. this.normalMap = null;
  20935. this.normalMapType = TangentSpaceNormalMap;
  20936. this.normalScale = new Vector2(1, 1);
  20937. this.displacementMap = null;
  20938. this.displacementScale = 1;
  20939. this.displacementBias = 0;
  20940. this.alphaMap = null;
  20941. this.wireframe = false;
  20942. this.wireframeLinewidth = 1;
  20943. this.wireframeLinecap = 'round';
  20944. this.wireframeLinejoin = 'round';
  20945. this.setValues(parameters);
  20946. }
  20947. copy(source) {
  20948. super.copy(source);
  20949. this.color.copy(source.color);
  20950. this.map = source.map;
  20951. this.gradientMap = source.gradientMap;
  20952. this.lightMap = source.lightMap;
  20953. this.lightMapIntensity = source.lightMapIntensity;
  20954. this.aoMap = source.aoMap;
  20955. this.aoMapIntensity = source.aoMapIntensity;
  20956. this.emissive.copy(source.emissive);
  20957. this.emissiveMap = source.emissiveMap;
  20958. this.emissiveIntensity = source.emissiveIntensity;
  20959. this.bumpMap = source.bumpMap;
  20960. this.bumpScale = source.bumpScale;
  20961. this.normalMap = source.normalMap;
  20962. this.normalMapType = source.normalMapType;
  20963. this.normalScale.copy(source.normalScale);
  20964. this.displacementMap = source.displacementMap;
  20965. this.displacementScale = source.displacementScale;
  20966. this.displacementBias = source.displacementBias;
  20967. this.alphaMap = source.alphaMap;
  20968. this.wireframe = source.wireframe;
  20969. this.wireframeLinewidth = source.wireframeLinewidth;
  20970. this.wireframeLinecap = source.wireframeLinecap;
  20971. this.wireframeLinejoin = source.wireframeLinejoin;
  20972. return this;
  20973. }
  20974. }
  20975. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  20976. /**
  20977. * parameters = {
  20978. * opacity: <float>,
  20979. *
  20980. * bumpMap: new THREE.Texture( <Image> ),
  20981. * bumpScale: <float>,
  20982. *
  20983. * normalMap: new THREE.Texture( <Image> ),
  20984. * normalMapType: THREE.TangentSpaceNormalMap,
  20985. * normalScale: <Vector2>,
  20986. *
  20987. * displacementMap: new THREE.Texture( <Image> ),
  20988. * displacementScale: <float>,
  20989. * displacementBias: <float>,
  20990. *
  20991. * wireframe: <boolean>,
  20992. * wireframeLinewidth: <float>
  20993. *
  20994. * flatShading: <bool>
  20995. * }
  20996. */
  20997. class MeshNormalMaterial extends Material {
  20998. constructor(parameters) {
  20999. super();
  21000. this.type = 'MeshNormalMaterial';
  21001. this.bumpMap = null;
  21002. this.bumpScale = 1;
  21003. this.normalMap = null;
  21004. this.normalMapType = TangentSpaceNormalMap;
  21005. this.normalScale = new Vector2(1, 1);
  21006. this.displacementMap = null;
  21007. this.displacementScale = 1;
  21008. this.displacementBias = 0;
  21009. this.wireframe = false;
  21010. this.wireframeLinewidth = 1;
  21011. this.fog = false;
  21012. this.flatShading = false;
  21013. this.setValues(parameters);
  21014. }
  21015. copy(source) {
  21016. super.copy(source);
  21017. this.bumpMap = source.bumpMap;
  21018. this.bumpScale = source.bumpScale;
  21019. this.normalMap = source.normalMap;
  21020. this.normalMapType = source.normalMapType;
  21021. this.normalScale.copy(source.normalScale);
  21022. this.displacementMap = source.displacementMap;
  21023. this.displacementScale = source.displacementScale;
  21024. this.displacementBias = source.displacementBias;
  21025. this.wireframe = source.wireframe;
  21026. this.wireframeLinewidth = source.wireframeLinewidth;
  21027. this.flatShading = source.flatShading;
  21028. return this;
  21029. }
  21030. }
  21031. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  21032. /**
  21033. * parameters = {
  21034. * color: <hex>,
  21035. * opacity: <float>,
  21036. *
  21037. * map: new THREE.Texture( <Image> ),
  21038. *
  21039. * lightMap: new THREE.Texture( <Image> ),
  21040. * lightMapIntensity: <float>
  21041. *
  21042. * aoMap: new THREE.Texture( <Image> ),
  21043. * aoMapIntensity: <float>
  21044. *
  21045. * emissive: <hex>,
  21046. * emissiveIntensity: <float>
  21047. * emissiveMap: new THREE.Texture( <Image> ),
  21048. *
  21049. * specularMap: new THREE.Texture( <Image> ),
  21050. *
  21051. * alphaMap: new THREE.Texture( <Image> ),
  21052. *
  21053. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21054. * combine: THREE.Multiply,
  21055. * reflectivity: <float>,
  21056. * refractionRatio: <float>,
  21057. *
  21058. * wireframe: <boolean>,
  21059. * wireframeLinewidth: <float>,
  21060. *
  21061. * }
  21062. */
  21063. class MeshLambertMaterial extends Material {
  21064. constructor(parameters) {
  21065. super();
  21066. this.type = 'MeshLambertMaterial';
  21067. this.color = new Color(0xffffff); // diffuse
  21068. this.map = null;
  21069. this.lightMap = null;
  21070. this.lightMapIntensity = 1.0;
  21071. this.aoMap = null;
  21072. this.aoMapIntensity = 1.0;
  21073. this.emissive = new Color(0x000000);
  21074. this.emissiveIntensity = 1.0;
  21075. this.emissiveMap = null;
  21076. this.specularMap = null;
  21077. this.alphaMap = null;
  21078. this.envMap = null;
  21079. this.combine = MultiplyOperation;
  21080. this.reflectivity = 1;
  21081. this.refractionRatio = 0.98;
  21082. this.wireframe = false;
  21083. this.wireframeLinewidth = 1;
  21084. this.wireframeLinecap = 'round';
  21085. this.wireframeLinejoin = 'round';
  21086. this.setValues(parameters);
  21087. }
  21088. copy(source) {
  21089. super.copy(source);
  21090. this.color.copy(source.color);
  21091. this.map = source.map;
  21092. this.lightMap = source.lightMap;
  21093. this.lightMapIntensity = source.lightMapIntensity;
  21094. this.aoMap = source.aoMap;
  21095. this.aoMapIntensity = source.aoMapIntensity;
  21096. this.emissive.copy(source.emissive);
  21097. this.emissiveMap = source.emissiveMap;
  21098. this.emissiveIntensity = source.emissiveIntensity;
  21099. this.specularMap = source.specularMap;
  21100. this.alphaMap = source.alphaMap;
  21101. this.envMap = source.envMap;
  21102. this.combine = source.combine;
  21103. this.reflectivity = source.reflectivity;
  21104. this.refractionRatio = source.refractionRatio;
  21105. this.wireframe = source.wireframe;
  21106. this.wireframeLinewidth = source.wireframeLinewidth;
  21107. this.wireframeLinecap = source.wireframeLinecap;
  21108. this.wireframeLinejoin = source.wireframeLinejoin;
  21109. return this;
  21110. }
  21111. }
  21112. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  21113. /**
  21114. * parameters = {
  21115. * color: <hex>,
  21116. * opacity: <float>,
  21117. *
  21118. * matcap: new THREE.Texture( <Image> ),
  21119. *
  21120. * map: new THREE.Texture( <Image> ),
  21121. *
  21122. * bumpMap: new THREE.Texture( <Image> ),
  21123. * bumpScale: <float>,
  21124. *
  21125. * normalMap: new THREE.Texture( <Image> ),
  21126. * normalMapType: THREE.TangentSpaceNormalMap,
  21127. * normalScale: <Vector2>,
  21128. *
  21129. * displacementMap: new THREE.Texture( <Image> ),
  21130. * displacementScale: <float>,
  21131. * displacementBias: <float>,
  21132. *
  21133. * alphaMap: new THREE.Texture( <Image> ),
  21134. *
  21135. * flatShading: <bool>
  21136. * }
  21137. */
  21138. class MeshMatcapMaterial extends Material {
  21139. constructor(parameters) {
  21140. super();
  21141. this.defines = {
  21142. 'MATCAP': ''
  21143. };
  21144. this.type = 'MeshMatcapMaterial';
  21145. this.color = new Color(0xffffff); // diffuse
  21146. this.matcap = null;
  21147. this.map = null;
  21148. this.bumpMap = null;
  21149. this.bumpScale = 1;
  21150. this.normalMap = null;
  21151. this.normalMapType = TangentSpaceNormalMap;
  21152. this.normalScale = new Vector2(1, 1);
  21153. this.displacementMap = null;
  21154. this.displacementScale = 1;
  21155. this.displacementBias = 0;
  21156. this.alphaMap = null;
  21157. this.flatShading = false;
  21158. this.setValues(parameters);
  21159. }
  21160. copy(source) {
  21161. super.copy(source);
  21162. this.defines = {
  21163. 'MATCAP': ''
  21164. };
  21165. this.color.copy(source.color);
  21166. this.matcap = source.matcap;
  21167. this.map = source.map;
  21168. this.bumpMap = source.bumpMap;
  21169. this.bumpScale = source.bumpScale;
  21170. this.normalMap = source.normalMap;
  21171. this.normalMapType = source.normalMapType;
  21172. this.normalScale.copy(source.normalScale);
  21173. this.displacementMap = source.displacementMap;
  21174. this.displacementScale = source.displacementScale;
  21175. this.displacementBias = source.displacementBias;
  21176. this.alphaMap = source.alphaMap;
  21177. this.flatShading = source.flatShading;
  21178. return this;
  21179. }
  21180. }
  21181. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  21182. /**
  21183. * parameters = {
  21184. * color: <hex>,
  21185. * opacity: <float>,
  21186. *
  21187. * linewidth: <float>,
  21188. *
  21189. * scale: <float>,
  21190. * dashSize: <float>,
  21191. * gapSize: <float>
  21192. * }
  21193. */
  21194. class LineDashedMaterial extends LineBasicMaterial {
  21195. constructor(parameters) {
  21196. super();
  21197. this.type = 'LineDashedMaterial';
  21198. this.scale = 1;
  21199. this.dashSize = 3;
  21200. this.gapSize = 1;
  21201. this.setValues(parameters);
  21202. }
  21203. copy(source) {
  21204. super.copy(source);
  21205. this.scale = source.scale;
  21206. this.dashSize = source.dashSize;
  21207. this.gapSize = source.gapSize;
  21208. return this;
  21209. }
  21210. }
  21211. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  21212. var Materials = /*#__PURE__*/Object.freeze({
  21213. __proto__: null,
  21214. ShadowMaterial: ShadowMaterial,
  21215. SpriteMaterial: SpriteMaterial,
  21216. RawShaderMaterial: RawShaderMaterial,
  21217. ShaderMaterial: ShaderMaterial,
  21218. PointsMaterial: PointsMaterial,
  21219. MeshPhysicalMaterial: MeshPhysicalMaterial,
  21220. MeshStandardMaterial: MeshStandardMaterial,
  21221. MeshPhongMaterial: MeshPhongMaterial,
  21222. MeshToonMaterial: MeshToonMaterial,
  21223. MeshNormalMaterial: MeshNormalMaterial,
  21224. MeshLambertMaterial: MeshLambertMaterial,
  21225. MeshDepthMaterial: MeshDepthMaterial,
  21226. MeshDistanceMaterial: MeshDistanceMaterial,
  21227. MeshBasicMaterial: MeshBasicMaterial,
  21228. MeshMatcapMaterial: MeshMatcapMaterial,
  21229. LineDashedMaterial: LineDashedMaterial,
  21230. LineBasicMaterial: LineBasicMaterial,
  21231. Material: Material
  21232. });
  21233. const AnimationUtils = {
  21234. // same as Array.prototype.slice, but also works on typed arrays
  21235. arraySlice: function (array, from, to) {
  21236. if (AnimationUtils.isTypedArray(array)) {
  21237. // in ios9 array.subarray(from, undefined) will return empty array
  21238. // but array.subarray(from) or array.subarray(from, len) is correct
  21239. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  21240. }
  21241. return array.slice(from, to);
  21242. },
  21243. // converts an array to a specific type
  21244. convertArray: function (array, type, forceClone) {
  21245. if (!array || // let 'undefined' and 'null' pass
  21246. !forceClone && array.constructor === type) return array;
  21247. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  21248. return new type(array); // create typed array
  21249. }
  21250. return Array.prototype.slice.call(array); // create Array
  21251. },
  21252. isTypedArray: function (object) {
  21253. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  21254. },
  21255. // returns an array by which times and values can be sorted
  21256. getKeyframeOrder: function (times) {
  21257. function compareTime(i, j) {
  21258. return times[i] - times[j];
  21259. }
  21260. const n = times.length;
  21261. const result = new Array(n);
  21262. for (let i = 0; i !== n; ++i) result[i] = i;
  21263. result.sort(compareTime);
  21264. return result;
  21265. },
  21266. // uses the array previously returned by 'getKeyframeOrder' to sort data
  21267. sortedArray: function (values, stride, order) {
  21268. const nValues = values.length;
  21269. const result = new values.constructor(nValues);
  21270. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  21271. const srcOffset = order[i] * stride;
  21272. for (let j = 0; j !== stride; ++j) {
  21273. result[dstOffset++] = values[srcOffset + j];
  21274. }
  21275. }
  21276. return result;
  21277. },
  21278. // function for parsing AOS keyframe formats
  21279. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  21280. let i = 1,
  21281. key = jsonKeys[0];
  21282. while (key !== undefined && key[valuePropertyName] === undefined) {
  21283. key = jsonKeys[i++];
  21284. }
  21285. if (key === undefined) return; // no data
  21286. let value = key[valuePropertyName];
  21287. if (value === undefined) return; // no data
  21288. if (Array.isArray(value)) {
  21289. do {
  21290. value = key[valuePropertyName];
  21291. if (value !== undefined) {
  21292. times.push(key.time);
  21293. values.push.apply(values, value); // push all elements
  21294. }
  21295. key = jsonKeys[i++];
  21296. } while (key !== undefined);
  21297. } else if (value.toArray !== undefined) {
  21298. // ...assume THREE.Math-ish
  21299. do {
  21300. value = key[valuePropertyName];
  21301. if (value !== undefined) {
  21302. times.push(key.time);
  21303. value.toArray(values, values.length);
  21304. }
  21305. key = jsonKeys[i++];
  21306. } while (key !== undefined);
  21307. } else {
  21308. // otherwise push as-is
  21309. do {
  21310. value = key[valuePropertyName];
  21311. if (value !== undefined) {
  21312. times.push(key.time);
  21313. values.push(value);
  21314. }
  21315. key = jsonKeys[i++];
  21316. } while (key !== undefined);
  21317. }
  21318. },
  21319. subclip: function (sourceClip, name, startFrame, endFrame, fps = 30) {
  21320. const clip = sourceClip.clone();
  21321. clip.name = name;
  21322. const tracks = [];
  21323. for (let i = 0; i < clip.tracks.length; ++i) {
  21324. const track = clip.tracks[i];
  21325. const valueSize = track.getValueSize();
  21326. const times = [];
  21327. const values = [];
  21328. for (let j = 0; j < track.times.length; ++j) {
  21329. const frame = track.times[j] * fps;
  21330. if (frame < startFrame || frame >= endFrame) continue;
  21331. times.push(track.times[j]);
  21332. for (let k = 0; k < valueSize; ++k) {
  21333. values.push(track.values[j * valueSize + k]);
  21334. }
  21335. }
  21336. if (times.length === 0) continue;
  21337. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  21338. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  21339. tracks.push(track);
  21340. }
  21341. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  21342. let minStartTime = Infinity;
  21343. for (let i = 0; i < clip.tracks.length; ++i) {
  21344. if (minStartTime > clip.tracks[i].times[0]) {
  21345. minStartTime = clip.tracks[i].times[0];
  21346. }
  21347. } // shift all tracks such that clip begins at t=0
  21348. for (let i = 0; i < clip.tracks.length; ++i) {
  21349. clip.tracks[i].shift(-1 * minStartTime);
  21350. }
  21351. clip.resetDuration();
  21352. return clip;
  21353. },
  21354. makeClipAdditive: function (targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  21355. if (fps <= 0) fps = 30;
  21356. const numTracks = referenceClip.tracks.length;
  21357. const referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  21358. for (let i = 0; i < numTracks; ++i) {
  21359. const referenceTrack = referenceClip.tracks[i];
  21360. const referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  21361. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue; // Find the track in the target clip whose name and type matches the reference track
  21362. const targetTrack = targetClip.tracks.find(function (track) {
  21363. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  21364. });
  21365. if (targetTrack === undefined) continue;
  21366. let referenceOffset = 0;
  21367. const referenceValueSize = referenceTrack.getValueSize();
  21368. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  21369. referenceOffset = referenceValueSize / 3;
  21370. }
  21371. let targetOffset = 0;
  21372. const targetValueSize = targetTrack.getValueSize();
  21373. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  21374. targetOffset = targetValueSize / 3;
  21375. }
  21376. const lastIndex = referenceTrack.times.length - 1;
  21377. let referenceValue; // Find the value to subtract out of the track
  21378. if (referenceTime <= referenceTrack.times[0]) {
  21379. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  21380. const startIndex = referenceOffset;
  21381. const endIndex = referenceValueSize - referenceOffset;
  21382. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  21383. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  21384. // Reference frame is after the last keyframe, so just use the last keyframe
  21385. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  21386. const endIndex = startIndex + referenceValueSize - referenceOffset;
  21387. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  21388. } else {
  21389. // Interpolate to the reference value
  21390. const interpolant = referenceTrack.createInterpolant();
  21391. const startIndex = referenceOffset;
  21392. const endIndex = referenceValueSize - referenceOffset;
  21393. interpolant.evaluate(referenceTime);
  21394. referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  21395. } // Conjugate the quaternion
  21396. if (referenceTrackType === 'quaternion') {
  21397. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  21398. referenceQuat.toArray(referenceValue);
  21399. } // Subtract the reference value from all of the track values
  21400. const numTimes = targetTrack.times.length;
  21401. for (let j = 0; j < numTimes; ++j) {
  21402. const valueStart = j * targetValueSize + targetOffset;
  21403. if (referenceTrackType === 'quaternion') {
  21404. // Multiply the conjugate for quaternion track types
  21405. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  21406. } else {
  21407. const valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  21408. for (let k = 0; k < valueEnd; ++k) {
  21409. targetTrack.values[valueStart + k] -= referenceValue[k];
  21410. }
  21411. }
  21412. }
  21413. }
  21414. targetClip.blendMode = AdditiveAnimationBlendMode;
  21415. return targetClip;
  21416. }
  21417. };
  21418. /**
  21419. * Abstract base class of interpolants over parametric samples.
  21420. *
  21421. * The parameter domain is one dimensional, typically the time or a path
  21422. * along a curve defined by the data.
  21423. *
  21424. * The sample values can have any dimensionality and derived classes may
  21425. * apply special interpretations to the data.
  21426. *
  21427. * This class provides the interval seek in a Template Method, deferring
  21428. * the actual interpolation to derived classes.
  21429. *
  21430. * Time complexity is O(1) for linear access crossing at most two points
  21431. * and O(log N) for random access, where N is the number of positions.
  21432. *
  21433. * References:
  21434. *
  21435. * http://www.oodesign.com/template-method-pattern.html
  21436. *
  21437. */
  21438. class Interpolant {
  21439. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21440. this.parameterPositions = parameterPositions;
  21441. this._cachedIndex = 0;
  21442. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  21443. this.sampleValues = sampleValues;
  21444. this.valueSize = sampleSize;
  21445. this.settings = null;
  21446. this.DefaultSettings_ = {};
  21447. }
  21448. evaluate(t) {
  21449. const pp = this.parameterPositions;
  21450. let i1 = this._cachedIndex,
  21451. t1 = pp[i1],
  21452. t0 = pp[i1 - 1];
  21453. validate_interval: {
  21454. seek: {
  21455. let right;
  21456. linear_scan: {
  21457. //- See http://jsperf.com/comparison-to-undefined/3
  21458. //- slower code:
  21459. //-
  21460. //- if ( t >= t1 || t1 === undefined ) {
  21461. forward_scan: if (!(t < t1)) {
  21462. for (let giveUpAt = i1 + 2;;) {
  21463. if (t1 === undefined) {
  21464. if (t < t0) break forward_scan; // after end
  21465. i1 = pp.length;
  21466. this._cachedIndex = i1;
  21467. return this.afterEnd_(i1 - 1, t, t0);
  21468. }
  21469. if (i1 === giveUpAt) break; // this loop
  21470. t0 = t1;
  21471. t1 = pp[++i1];
  21472. if (t < t1) {
  21473. // we have arrived at the sought interval
  21474. break seek;
  21475. }
  21476. } // prepare binary search on the right side of the index
  21477. right = pp.length;
  21478. break linear_scan;
  21479. } //- slower code:
  21480. //- if ( t < t0 || t0 === undefined ) {
  21481. if (!(t >= t0)) {
  21482. // looping?
  21483. const t1global = pp[1];
  21484. if (t < t1global) {
  21485. i1 = 2; // + 1, using the scan for the details
  21486. t0 = t1global;
  21487. } // linear reverse scan
  21488. for (let giveUpAt = i1 - 2;;) {
  21489. if (t0 === undefined) {
  21490. // before start
  21491. this._cachedIndex = 0;
  21492. return this.beforeStart_(0, t, t1);
  21493. }
  21494. if (i1 === giveUpAt) break; // this loop
  21495. t1 = t0;
  21496. t0 = pp[--i1 - 1];
  21497. if (t >= t0) {
  21498. // we have arrived at the sought interval
  21499. break seek;
  21500. }
  21501. } // prepare binary search on the left side of the index
  21502. right = i1;
  21503. i1 = 0;
  21504. break linear_scan;
  21505. } // the interval is valid
  21506. break validate_interval;
  21507. } // linear scan
  21508. // binary search
  21509. while (i1 < right) {
  21510. const mid = i1 + right >>> 1;
  21511. if (t < pp[mid]) {
  21512. right = mid;
  21513. } else {
  21514. i1 = mid + 1;
  21515. }
  21516. }
  21517. t1 = pp[i1];
  21518. t0 = pp[i1 - 1]; // check boundary cases, again
  21519. if (t0 === undefined) {
  21520. this._cachedIndex = 0;
  21521. return this.beforeStart_(0, t, t1);
  21522. }
  21523. if (t1 === undefined) {
  21524. i1 = pp.length;
  21525. this._cachedIndex = i1;
  21526. return this.afterEnd_(i1 - 1, t0, t);
  21527. }
  21528. } // seek
  21529. this._cachedIndex = i1;
  21530. this.intervalChanged_(i1, t0, t1);
  21531. } // validate_interval
  21532. return this.interpolate_(i1, t0, t, t1);
  21533. }
  21534. getSettings_() {
  21535. return this.settings || this.DefaultSettings_;
  21536. }
  21537. copySampleValue_(index) {
  21538. // copies a sample value to the result buffer
  21539. const result = this.resultBuffer,
  21540. values = this.sampleValues,
  21541. stride = this.valueSize,
  21542. offset = index * stride;
  21543. for (let i = 0; i !== stride; ++i) {
  21544. result[i] = values[offset + i];
  21545. }
  21546. return result;
  21547. } // Template methods for derived classes:
  21548. interpolate_() {
  21549. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  21550. }
  21551. intervalChanged_() {// empty
  21552. }
  21553. } // ALIAS DEFINITIONS
  21554. Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
  21555. Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
  21556. /**
  21557. * Fast and simple cubic spline interpolant.
  21558. *
  21559. * It was derived from a Hermitian construction setting the first derivative
  21560. * at each sample position to the linear slope between neighboring positions
  21561. * over their parameter interval.
  21562. */
  21563. class CubicInterpolant extends Interpolant {
  21564. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21565. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  21566. this._weightPrev = -0;
  21567. this._offsetPrev = -0;
  21568. this._weightNext = -0;
  21569. this._offsetNext = -0;
  21570. this.DefaultSettings_ = {
  21571. endingStart: ZeroCurvatureEnding,
  21572. endingEnd: ZeroCurvatureEnding
  21573. };
  21574. }
  21575. intervalChanged_(i1, t0, t1) {
  21576. const pp = this.parameterPositions;
  21577. let iPrev = i1 - 2,
  21578. iNext = i1 + 1,
  21579. tPrev = pp[iPrev],
  21580. tNext = pp[iNext];
  21581. if (tPrev === undefined) {
  21582. switch (this.getSettings_().endingStart) {
  21583. case ZeroSlopeEnding:
  21584. // f'(t0) = 0
  21585. iPrev = i1;
  21586. tPrev = 2 * t0 - t1;
  21587. break;
  21588. case WrapAroundEnding:
  21589. // use the other end of the curve
  21590. iPrev = pp.length - 2;
  21591. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  21592. break;
  21593. default:
  21594. // ZeroCurvatureEnding
  21595. // f''(t0) = 0 a.k.a. Natural Spline
  21596. iPrev = i1;
  21597. tPrev = t1;
  21598. }
  21599. }
  21600. if (tNext === undefined) {
  21601. switch (this.getSettings_().endingEnd) {
  21602. case ZeroSlopeEnding:
  21603. // f'(tN) = 0
  21604. iNext = i1;
  21605. tNext = 2 * t1 - t0;
  21606. break;
  21607. case WrapAroundEnding:
  21608. // use the other end of the curve
  21609. iNext = 1;
  21610. tNext = t1 + pp[1] - pp[0];
  21611. break;
  21612. default:
  21613. // ZeroCurvatureEnding
  21614. // f''(tN) = 0, a.k.a. Natural Spline
  21615. iNext = i1 - 1;
  21616. tNext = t0;
  21617. }
  21618. }
  21619. const halfDt = (t1 - t0) * 0.5,
  21620. stride = this.valueSize;
  21621. this._weightPrev = halfDt / (t0 - tPrev);
  21622. this._weightNext = halfDt / (tNext - t1);
  21623. this._offsetPrev = iPrev * stride;
  21624. this._offsetNext = iNext * stride;
  21625. }
  21626. interpolate_(i1, t0, t, t1) {
  21627. const result = this.resultBuffer,
  21628. values = this.sampleValues,
  21629. stride = this.valueSize,
  21630. o1 = i1 * stride,
  21631. o0 = o1 - stride,
  21632. oP = this._offsetPrev,
  21633. oN = this._offsetNext,
  21634. wP = this._weightPrev,
  21635. wN = this._weightNext,
  21636. p = (t - t0) / (t1 - t0),
  21637. pp = p * p,
  21638. ppp = pp * p; // evaluate polynomials
  21639. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  21640. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  21641. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  21642. const sN = wN * ppp - wN * pp; // combine data linearly
  21643. for (let i = 0; i !== stride; ++i) {
  21644. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  21645. }
  21646. return result;
  21647. }
  21648. }
  21649. class LinearInterpolant extends Interpolant {
  21650. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21651. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  21652. }
  21653. interpolate_(i1, t0, t, t1) {
  21654. const result = this.resultBuffer,
  21655. values = this.sampleValues,
  21656. stride = this.valueSize,
  21657. offset1 = i1 * stride,
  21658. offset0 = offset1 - stride,
  21659. weight1 = (t - t0) / (t1 - t0),
  21660. weight0 = 1 - weight1;
  21661. for (let i = 0; i !== stride; ++i) {
  21662. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  21663. }
  21664. return result;
  21665. }
  21666. }
  21667. /**
  21668. *
  21669. * Interpolant that evaluates to the sample value at the position preceeding
  21670. * the parameter.
  21671. */
  21672. class DiscreteInterpolant extends Interpolant {
  21673. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21674. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  21675. }
  21676. interpolate_(i1
  21677. /*, t0, t, t1 */
  21678. ) {
  21679. return this.copySampleValue_(i1 - 1);
  21680. }
  21681. }
  21682. class KeyframeTrack {
  21683. constructor(name, times, values, interpolation) {
  21684. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  21685. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  21686. this.name = name;
  21687. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  21688. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  21689. this.setInterpolation(interpolation || this.DefaultInterpolation);
  21690. } // Serialization (in static context, because of constructor invocation
  21691. // and automatic invocation of .toJSON):
  21692. static toJSON(track) {
  21693. const trackType = track.constructor;
  21694. let json; // derived classes can define a static toJSON method
  21695. if (trackType.toJSON !== this.toJSON) {
  21696. json = trackType.toJSON(track);
  21697. } else {
  21698. // by default, we assume the data can be serialized as-is
  21699. json = {
  21700. 'name': track.name,
  21701. 'times': AnimationUtils.convertArray(track.times, Array),
  21702. 'values': AnimationUtils.convertArray(track.values, Array)
  21703. };
  21704. const interpolation = track.getInterpolation();
  21705. if (interpolation !== track.DefaultInterpolation) {
  21706. json.interpolation = interpolation;
  21707. }
  21708. }
  21709. json.type = track.ValueTypeName; // mandatory
  21710. return json;
  21711. }
  21712. InterpolantFactoryMethodDiscrete(result) {
  21713. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  21714. }
  21715. InterpolantFactoryMethodLinear(result) {
  21716. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21717. }
  21718. InterpolantFactoryMethodSmooth(result) {
  21719. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  21720. }
  21721. setInterpolation(interpolation) {
  21722. let factoryMethod;
  21723. switch (interpolation) {
  21724. case InterpolateDiscrete:
  21725. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  21726. break;
  21727. case InterpolateLinear:
  21728. factoryMethod = this.InterpolantFactoryMethodLinear;
  21729. break;
  21730. case InterpolateSmooth:
  21731. factoryMethod = this.InterpolantFactoryMethodSmooth;
  21732. break;
  21733. }
  21734. if (factoryMethod === undefined) {
  21735. const message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
  21736. if (this.createInterpolant === undefined) {
  21737. // fall back to default, unless the default itself is messed up
  21738. if (interpolation !== this.DefaultInterpolation) {
  21739. this.setInterpolation(this.DefaultInterpolation);
  21740. } else {
  21741. throw new Error(message); // fatal, in this case
  21742. }
  21743. }
  21744. console.warn('THREE.KeyframeTrack:', message);
  21745. return this;
  21746. }
  21747. this.createInterpolant = factoryMethod;
  21748. return this;
  21749. }
  21750. getInterpolation() {
  21751. switch (this.createInterpolant) {
  21752. case this.InterpolantFactoryMethodDiscrete:
  21753. return InterpolateDiscrete;
  21754. case this.InterpolantFactoryMethodLinear:
  21755. return InterpolateLinear;
  21756. case this.InterpolantFactoryMethodSmooth:
  21757. return InterpolateSmooth;
  21758. }
  21759. }
  21760. getValueSize() {
  21761. return this.values.length / this.times.length;
  21762. } // move all keyframes either forwards or backwards in time
  21763. shift(timeOffset) {
  21764. if (timeOffset !== 0.0) {
  21765. const times = this.times;
  21766. for (let i = 0, n = times.length; i !== n; ++i) {
  21767. times[i] += timeOffset;
  21768. }
  21769. }
  21770. return this;
  21771. } // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  21772. scale(timeScale) {
  21773. if (timeScale !== 1.0) {
  21774. const times = this.times;
  21775. for (let i = 0, n = times.length; i !== n; ++i) {
  21776. times[i] *= timeScale;
  21777. }
  21778. }
  21779. return this;
  21780. } // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  21781. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  21782. trim(startTime, endTime) {
  21783. const times = this.times,
  21784. nKeys = times.length;
  21785. let from = 0,
  21786. to = nKeys - 1;
  21787. while (from !== nKeys && times[from] < startTime) {
  21788. ++from;
  21789. }
  21790. while (to !== -1 && times[to] > endTime) {
  21791. --to;
  21792. }
  21793. ++to; // inclusive -> exclusive bound
  21794. if (from !== 0 || to !== nKeys) {
  21795. // empty tracks are forbidden, so keep at least one keyframe
  21796. if (from >= to) {
  21797. to = Math.max(to, 1);
  21798. from = to - 1;
  21799. }
  21800. const stride = this.getValueSize();
  21801. this.times = AnimationUtils.arraySlice(times, from, to);
  21802. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  21803. }
  21804. return this;
  21805. } // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  21806. validate() {
  21807. let valid = true;
  21808. const valueSize = this.getValueSize();
  21809. if (valueSize - Math.floor(valueSize) !== 0) {
  21810. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  21811. valid = false;
  21812. }
  21813. const times = this.times,
  21814. values = this.values,
  21815. nKeys = times.length;
  21816. if (nKeys === 0) {
  21817. console.error('THREE.KeyframeTrack: Track is empty.', this);
  21818. valid = false;
  21819. }
  21820. let prevTime = null;
  21821. for (let i = 0; i !== nKeys; i++) {
  21822. const currTime = times[i];
  21823. if (typeof currTime === 'number' && isNaN(currTime)) {
  21824. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  21825. valid = false;
  21826. break;
  21827. }
  21828. if (prevTime !== null && prevTime > currTime) {
  21829. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  21830. valid = false;
  21831. break;
  21832. }
  21833. prevTime = currTime;
  21834. }
  21835. if (values !== undefined) {
  21836. if (AnimationUtils.isTypedArray(values)) {
  21837. for (let i = 0, n = values.length; i !== n; ++i) {
  21838. const value = values[i];
  21839. if (isNaN(value)) {
  21840. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  21841. valid = false;
  21842. break;
  21843. }
  21844. }
  21845. }
  21846. }
  21847. return valid;
  21848. } // removes equivalent sequential keys as common in morph target sequences
  21849. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  21850. optimize() {
  21851. // times or values may be shared with other tracks, so overwriting is unsafe
  21852. const times = AnimationUtils.arraySlice(this.times),
  21853. values = AnimationUtils.arraySlice(this.values),
  21854. stride = this.getValueSize(),
  21855. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  21856. lastIndex = times.length - 1;
  21857. let writeIndex = 1;
  21858. for (let i = 1; i < lastIndex; ++i) {
  21859. let keep = false;
  21860. const time = times[i];
  21861. const timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  21862. if (time !== timeNext && (i !== 1 || time !== times[0])) {
  21863. if (!smoothInterpolation) {
  21864. // remove unnecessary keyframes same as their neighbors
  21865. const offset = i * stride,
  21866. offsetP = offset - stride,
  21867. offsetN = offset + stride;
  21868. for (let j = 0; j !== stride; ++j) {
  21869. const value = values[offset + j];
  21870. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  21871. keep = true;
  21872. break;
  21873. }
  21874. }
  21875. } else {
  21876. keep = true;
  21877. }
  21878. } // in-place compaction
  21879. if (keep) {
  21880. if (i !== writeIndex) {
  21881. times[writeIndex] = times[i];
  21882. const readOffset = i * stride,
  21883. writeOffset = writeIndex * stride;
  21884. for (let j = 0; j !== stride; ++j) {
  21885. values[writeOffset + j] = values[readOffset + j];
  21886. }
  21887. }
  21888. ++writeIndex;
  21889. }
  21890. } // flush last keyframe (compaction looks ahead)
  21891. if (lastIndex > 0) {
  21892. times[writeIndex] = times[lastIndex];
  21893. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  21894. values[writeOffset + j] = values[readOffset + j];
  21895. }
  21896. ++writeIndex;
  21897. }
  21898. if (writeIndex !== times.length) {
  21899. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  21900. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  21901. } else {
  21902. this.times = times;
  21903. this.values = values;
  21904. }
  21905. return this;
  21906. }
  21907. clone() {
  21908. const times = AnimationUtils.arraySlice(this.times, 0);
  21909. const values = AnimationUtils.arraySlice(this.values, 0);
  21910. const TypedKeyframeTrack = this.constructor;
  21911. const track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  21912. track.createInterpolant = this.createInterpolant;
  21913. return track;
  21914. }
  21915. }
  21916. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  21917. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  21918. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  21919. /**
  21920. * A Track of Boolean keyframe values.
  21921. */
  21922. class BooleanKeyframeTrack extends KeyframeTrack {}
  21923. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  21924. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  21925. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  21926. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  21927. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; // Note: Actually this track could have a optimized / compressed
  21928. /**
  21929. * A Track of keyframe values that represent color.
  21930. */
  21931. class ColorKeyframeTrack extends KeyframeTrack {}
  21932. ColorKeyframeTrack.prototype.ValueTypeName = 'color'; // ValueBufferType is inherited
  21933. /**
  21934. * A Track of numeric keyframe values.
  21935. */
  21936. class NumberKeyframeTrack extends KeyframeTrack {}
  21937. NumberKeyframeTrack.prototype.ValueTypeName = 'number'; // ValueBufferType is inherited
  21938. /**
  21939. * Spherical linear unit quaternion interpolant.
  21940. */
  21941. class QuaternionLinearInterpolant extends Interpolant {
  21942. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21943. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  21944. }
  21945. interpolate_(i1, t0, t, t1) {
  21946. const result = this.resultBuffer,
  21947. values = this.sampleValues,
  21948. stride = this.valueSize,
  21949. alpha = (t - t0) / (t1 - t0);
  21950. let offset = i1 * stride;
  21951. for (let end = offset + stride; offset !== end; offset += 4) {
  21952. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  21953. }
  21954. return result;
  21955. }
  21956. }
  21957. /**
  21958. * A Track of quaternion keyframe values.
  21959. */
  21960. class QuaternionKeyframeTrack extends KeyframeTrack {
  21961. InterpolantFactoryMethodLinear(result) {
  21962. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21963. }
  21964. }
  21965. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; // ValueBufferType is inherited
  21966. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  21967. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  21968. /**
  21969. * A Track that interpolates Strings
  21970. */
  21971. class StringKeyframeTrack extends KeyframeTrack {}
  21972. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  21973. StringKeyframeTrack.prototype.ValueBufferType = Array;
  21974. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  21975. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  21976. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  21977. /**
  21978. * A Track of vectored keyframe values.
  21979. */
  21980. class VectorKeyframeTrack extends KeyframeTrack {}
  21981. VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; // ValueBufferType is inherited
  21982. class AnimationClip {
  21983. constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) {
  21984. this.name = name;
  21985. this.tracks = tracks;
  21986. this.duration = duration;
  21987. this.blendMode = blendMode;
  21988. this.uuid = generateUUID(); // this means it should figure out its duration by scanning the tracks
  21989. if (this.duration < 0) {
  21990. this.resetDuration();
  21991. }
  21992. }
  21993. static parse(json) {
  21994. const tracks = [],
  21995. jsonTracks = json.tracks,
  21996. frameTime = 1.0 / (json.fps || 1.0);
  21997. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  21998. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  21999. }
  22000. const clip = new this(json.name, json.duration, tracks, json.blendMode);
  22001. clip.uuid = json.uuid;
  22002. return clip;
  22003. }
  22004. static toJSON(clip) {
  22005. const tracks = [],
  22006. clipTracks = clip.tracks;
  22007. const json = {
  22008. 'name': clip.name,
  22009. 'duration': clip.duration,
  22010. 'tracks': tracks,
  22011. 'uuid': clip.uuid,
  22012. 'blendMode': clip.blendMode
  22013. };
  22014. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  22015. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  22016. }
  22017. return json;
  22018. }
  22019. static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  22020. const numMorphTargets = morphTargetSequence.length;
  22021. const tracks = [];
  22022. for (let i = 0; i < numMorphTargets; i++) {
  22023. let times = [];
  22024. let values = [];
  22025. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  22026. values.push(0, 1, 0);
  22027. const order = AnimationUtils.getKeyframeOrder(times);
  22028. times = AnimationUtils.sortedArray(times, 1, order);
  22029. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  22030. // last frame as well for perfect loop.
  22031. if (!noLoop && times[0] === 0) {
  22032. times.push(numMorphTargets);
  22033. values.push(values[0]);
  22034. }
  22035. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  22036. }
  22037. return new this(name, -1, tracks);
  22038. }
  22039. static findByName(objectOrClipArray, name) {
  22040. let clipArray = objectOrClipArray;
  22041. if (!Array.isArray(objectOrClipArray)) {
  22042. const o = objectOrClipArray;
  22043. clipArray = o.geometry && o.geometry.animations || o.animations;
  22044. }
  22045. for (let i = 0; i < clipArray.length; i++) {
  22046. if (clipArray[i].name === name) {
  22047. return clipArray[i];
  22048. }
  22049. }
  22050. return null;
  22051. }
  22052. static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  22053. const animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  22054. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22055. const pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  22056. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22057. for (let i = 0, il = morphTargets.length; i < il; i++) {
  22058. const morphTarget = morphTargets[i];
  22059. const parts = morphTarget.name.match(pattern);
  22060. if (parts && parts.length > 1) {
  22061. const name = parts[1];
  22062. let animationMorphTargets = animationToMorphTargets[name];
  22063. if (!animationMorphTargets) {
  22064. animationToMorphTargets[name] = animationMorphTargets = [];
  22065. }
  22066. animationMorphTargets.push(morphTarget);
  22067. }
  22068. }
  22069. const clips = [];
  22070. for (const name in animationToMorphTargets) {
  22071. clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  22072. }
  22073. return clips;
  22074. } // parse the animation.hierarchy format
  22075. static parseAnimation(animation, bones) {
  22076. if (!animation) {
  22077. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  22078. return null;
  22079. }
  22080. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  22081. // only return track if there are actually keys.
  22082. if (animationKeys.length !== 0) {
  22083. const times = [];
  22084. const values = [];
  22085. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  22086. if (times.length !== 0) {
  22087. destTracks.push(new trackType(trackName, times, values));
  22088. }
  22089. }
  22090. };
  22091. const tracks = [];
  22092. const clipName = animation.name || 'default';
  22093. const fps = animation.fps || 30;
  22094. const blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  22095. let duration = animation.length || -1;
  22096. const hierarchyTracks = animation.hierarchy || [];
  22097. for (let h = 0; h < hierarchyTracks.length; h++) {
  22098. const animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  22099. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  22100. if (animationKeys[0].morphTargets) {
  22101. // figure out all morph targets used in this track
  22102. const morphTargetNames = {};
  22103. let k;
  22104. for (k = 0; k < animationKeys.length; k++) {
  22105. if (animationKeys[k].morphTargets) {
  22106. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  22107. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  22108. }
  22109. }
  22110. } // create a track for each morph target with all zero
  22111. // morphTargetInfluences except for the keys in which
  22112. // the morphTarget is named.
  22113. for (const morphTargetName in morphTargetNames) {
  22114. const times = [];
  22115. const values = [];
  22116. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  22117. const animationKey = animationKeys[k];
  22118. times.push(animationKey.time);
  22119. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  22120. }
  22121. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  22122. }
  22123. duration = morphTargetNames.length * (fps || 1.0);
  22124. } else {
  22125. // ...assume skeletal animation
  22126. const boneName = '.bones[' + bones[h].name + ']';
  22127. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  22128. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  22129. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  22130. }
  22131. }
  22132. if (tracks.length === 0) {
  22133. return null;
  22134. }
  22135. const clip = new this(clipName, duration, tracks, blendMode);
  22136. return clip;
  22137. }
  22138. resetDuration() {
  22139. const tracks = this.tracks;
  22140. let duration = 0;
  22141. for (let i = 0, n = tracks.length; i !== n; ++i) {
  22142. const track = this.tracks[i];
  22143. duration = Math.max(duration, track.times[track.times.length - 1]);
  22144. }
  22145. this.duration = duration;
  22146. return this;
  22147. }
  22148. trim() {
  22149. for (let i = 0; i < this.tracks.length; i++) {
  22150. this.tracks[i].trim(0, this.duration);
  22151. }
  22152. return this;
  22153. }
  22154. validate() {
  22155. let valid = true;
  22156. for (let i = 0; i < this.tracks.length; i++) {
  22157. valid = valid && this.tracks[i].validate();
  22158. }
  22159. return valid;
  22160. }
  22161. optimize() {
  22162. for (let i = 0; i < this.tracks.length; i++) {
  22163. this.tracks[i].optimize();
  22164. }
  22165. return this;
  22166. }
  22167. clone() {
  22168. const tracks = [];
  22169. for (let i = 0; i < this.tracks.length; i++) {
  22170. tracks.push(this.tracks[i].clone());
  22171. }
  22172. return new this.constructor(this.name, this.duration, tracks, this.blendMode);
  22173. }
  22174. toJSON() {
  22175. return this.constructor.toJSON(this);
  22176. }
  22177. }
  22178. function getTrackTypeForValueTypeName(typeName) {
  22179. switch (typeName.toLowerCase()) {
  22180. case 'scalar':
  22181. case 'double':
  22182. case 'float':
  22183. case 'number':
  22184. case 'integer':
  22185. return NumberKeyframeTrack;
  22186. case 'vector':
  22187. case 'vector2':
  22188. case 'vector3':
  22189. case 'vector4':
  22190. return VectorKeyframeTrack;
  22191. case 'color':
  22192. return ColorKeyframeTrack;
  22193. case 'quaternion':
  22194. return QuaternionKeyframeTrack;
  22195. case 'bool':
  22196. case 'boolean':
  22197. return BooleanKeyframeTrack;
  22198. case 'string':
  22199. return StringKeyframeTrack;
  22200. }
  22201. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  22202. }
  22203. function parseKeyframeTrack(json) {
  22204. if (json.type === undefined) {
  22205. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  22206. }
  22207. const trackType = getTrackTypeForValueTypeName(json.type);
  22208. if (json.times === undefined) {
  22209. const times = [],
  22210. values = [];
  22211. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  22212. json.times = times;
  22213. json.values = values;
  22214. } // derived classes can define a static parse method
  22215. if (trackType.parse !== undefined) {
  22216. return trackType.parse(json);
  22217. } else {
  22218. // by default, we assume a constructor compatible with the base
  22219. return new trackType(json.name, json.times, json.values, json.interpolation);
  22220. }
  22221. }
  22222. const Cache = {
  22223. enabled: false,
  22224. files: {},
  22225. add: function (key, file) {
  22226. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  22227. this.files[key] = file;
  22228. },
  22229. get: function (key) {
  22230. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  22231. return this.files[key];
  22232. },
  22233. remove: function (key) {
  22234. delete this.files[key];
  22235. },
  22236. clear: function () {
  22237. this.files = {};
  22238. }
  22239. };
  22240. class LoadingManager {
  22241. constructor(onLoad, onProgress, onError) {
  22242. const scope = this;
  22243. let isLoading = false;
  22244. let itemsLoaded = 0;
  22245. let itemsTotal = 0;
  22246. let urlModifier = undefined;
  22247. const handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  22248. // in the constructor
  22249. this.onStart = undefined;
  22250. this.onLoad = onLoad;
  22251. this.onProgress = onProgress;
  22252. this.onError = onError;
  22253. this.itemStart = function (url) {
  22254. itemsTotal++;
  22255. if (isLoading === false) {
  22256. if (scope.onStart !== undefined) {
  22257. scope.onStart(url, itemsLoaded, itemsTotal);
  22258. }
  22259. }
  22260. isLoading = true;
  22261. };
  22262. this.itemEnd = function (url) {
  22263. itemsLoaded++;
  22264. if (scope.onProgress !== undefined) {
  22265. scope.onProgress(url, itemsLoaded, itemsTotal);
  22266. }
  22267. if (itemsLoaded === itemsTotal) {
  22268. isLoading = false;
  22269. if (scope.onLoad !== undefined) {
  22270. scope.onLoad();
  22271. }
  22272. }
  22273. };
  22274. this.itemError = function (url) {
  22275. if (scope.onError !== undefined) {
  22276. scope.onError(url);
  22277. }
  22278. };
  22279. this.resolveURL = function (url) {
  22280. if (urlModifier) {
  22281. return urlModifier(url);
  22282. }
  22283. return url;
  22284. };
  22285. this.setURLModifier = function (transform) {
  22286. urlModifier = transform;
  22287. return this;
  22288. };
  22289. this.addHandler = function (regex, loader) {
  22290. handlers.push(regex, loader);
  22291. return this;
  22292. };
  22293. this.removeHandler = function (regex) {
  22294. const index = handlers.indexOf(regex);
  22295. if (index !== -1) {
  22296. handlers.splice(index, 2);
  22297. }
  22298. return this;
  22299. };
  22300. this.getHandler = function (file) {
  22301. for (let i = 0, l = handlers.length; i < l; i += 2) {
  22302. const regex = handlers[i];
  22303. const loader = handlers[i + 1];
  22304. if (regex.global) regex.lastIndex = 0; // see #17920
  22305. if (regex.test(file)) {
  22306. return loader;
  22307. }
  22308. }
  22309. return null;
  22310. };
  22311. }
  22312. }
  22313. const DefaultLoadingManager = new LoadingManager();
  22314. class Loader {
  22315. constructor(manager) {
  22316. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  22317. this.crossOrigin = 'anonymous';
  22318. this.withCredentials = false;
  22319. this.path = '';
  22320. this.resourcePath = '';
  22321. this.requestHeader = {};
  22322. }
  22323. load() {}
  22324. loadAsync(url, onProgress) {
  22325. const scope = this;
  22326. return new Promise(function (resolve, reject) {
  22327. scope.load(url, resolve, onProgress, reject);
  22328. });
  22329. }
  22330. parse() {}
  22331. setCrossOrigin(crossOrigin) {
  22332. this.crossOrigin = crossOrigin;
  22333. return this;
  22334. }
  22335. setWithCredentials(value) {
  22336. this.withCredentials = value;
  22337. return this;
  22338. }
  22339. setPath(path) {
  22340. this.path = path;
  22341. return this;
  22342. }
  22343. setResourcePath(resourcePath) {
  22344. this.resourcePath = resourcePath;
  22345. return this;
  22346. }
  22347. setRequestHeader(requestHeader) {
  22348. this.requestHeader = requestHeader;
  22349. return this;
  22350. }
  22351. }
  22352. const loading = {};
  22353. class FileLoader extends Loader {
  22354. constructor(manager) {
  22355. super(manager);
  22356. }
  22357. load(url, onLoad, onProgress, onError) {
  22358. if (url === undefined) url = '';
  22359. if (this.path !== undefined) url = this.path + url;
  22360. url = this.manager.resolveURL(url);
  22361. const scope = this;
  22362. const cached = Cache.get(url);
  22363. if (cached !== undefined) {
  22364. scope.manager.itemStart(url);
  22365. setTimeout(function () {
  22366. if (onLoad) onLoad(cached);
  22367. scope.manager.itemEnd(url);
  22368. }, 0);
  22369. return cached;
  22370. } // Check if request is duplicate
  22371. if (loading[url] !== undefined) {
  22372. loading[url].push({
  22373. onLoad: onLoad,
  22374. onProgress: onProgress,
  22375. onError: onError
  22376. });
  22377. return;
  22378. } // Check for data: URI
  22379. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  22380. const dataUriRegexResult = url.match(dataUriRegex);
  22381. let request; // Safari can not handle Data URIs through XMLHttpRequest so process manually
  22382. if (dataUriRegexResult) {
  22383. const mimeType = dataUriRegexResult[1];
  22384. const isBase64 = !!dataUriRegexResult[2];
  22385. let data = dataUriRegexResult[3];
  22386. data = decodeURIComponent(data);
  22387. if (isBase64) data = atob(data);
  22388. try {
  22389. let response;
  22390. const responseType = (this.responseType || '').toLowerCase();
  22391. switch (responseType) {
  22392. case 'arraybuffer':
  22393. case 'blob':
  22394. const view = new Uint8Array(data.length);
  22395. for (let i = 0; i < data.length; i++) {
  22396. view[i] = data.charCodeAt(i);
  22397. }
  22398. if (responseType === 'blob') {
  22399. response = new Blob([view.buffer], {
  22400. type: mimeType
  22401. });
  22402. } else {
  22403. response = view.buffer;
  22404. }
  22405. break;
  22406. case 'document':
  22407. const parser = new DOMParser();
  22408. response = parser.parseFromString(data, mimeType);
  22409. break;
  22410. case 'json':
  22411. response = JSON.parse(data);
  22412. break;
  22413. default:
  22414. // 'text' or other
  22415. response = data;
  22416. break;
  22417. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22418. setTimeout(function () {
  22419. if (onLoad) onLoad(response);
  22420. scope.manager.itemEnd(url);
  22421. }, 0);
  22422. } catch (error) {
  22423. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22424. setTimeout(function () {
  22425. if (onError) onError(error);
  22426. scope.manager.itemError(url);
  22427. scope.manager.itemEnd(url);
  22428. }, 0);
  22429. }
  22430. } else {
  22431. // Initialise array for duplicate requests
  22432. loading[url] = [];
  22433. loading[url].push({
  22434. onLoad: onLoad,
  22435. onProgress: onProgress,
  22436. onError: onError
  22437. });
  22438. request = new XMLHttpRequest();
  22439. request.open('GET', url, true);
  22440. request.addEventListener('load', function (event) {
  22441. const response = this.response;
  22442. const callbacks = loading[url];
  22443. delete loading[url];
  22444. if (this.status === 200 || this.status === 0) {
  22445. // Some browsers return HTTP Status 0 when using non-http protocol
  22446. // e.g. 'file://' or 'data://'. Handle as success.
  22447. if (this.status === 0) console.warn('THREE.FileLoader: HTTP Status 0 received.'); // Add to cache only on HTTP success, so that we do not cache
  22448. // error response bodies as proper responses to requests.
  22449. Cache.add(url, response);
  22450. for (let i = 0, il = callbacks.length; i < il; i++) {
  22451. const callback = callbacks[i];
  22452. if (callback.onLoad) callback.onLoad(response);
  22453. }
  22454. scope.manager.itemEnd(url);
  22455. } else {
  22456. for (let i = 0, il = callbacks.length; i < il; i++) {
  22457. const callback = callbacks[i];
  22458. if (callback.onError) callback.onError(event);
  22459. }
  22460. scope.manager.itemError(url);
  22461. scope.manager.itemEnd(url);
  22462. }
  22463. }, false);
  22464. request.addEventListener('progress', function (event) {
  22465. const callbacks = loading[url];
  22466. for (let i = 0, il = callbacks.length; i < il; i++) {
  22467. const callback = callbacks[i];
  22468. if (callback.onProgress) callback.onProgress(event);
  22469. }
  22470. }, false);
  22471. request.addEventListener('error', function (event) {
  22472. const callbacks = loading[url];
  22473. delete loading[url];
  22474. for (let i = 0, il = callbacks.length; i < il; i++) {
  22475. const callback = callbacks[i];
  22476. if (callback.onError) callback.onError(event);
  22477. }
  22478. scope.manager.itemError(url);
  22479. scope.manager.itemEnd(url);
  22480. }, false);
  22481. request.addEventListener('abort', function (event) {
  22482. const callbacks = loading[url];
  22483. delete loading[url];
  22484. for (let i = 0, il = callbacks.length; i < il; i++) {
  22485. const callback = callbacks[i];
  22486. if (callback.onError) callback.onError(event);
  22487. }
  22488. scope.manager.itemError(url);
  22489. scope.manager.itemEnd(url);
  22490. }, false);
  22491. if (this.responseType !== undefined) request.responseType = this.responseType;
  22492. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  22493. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  22494. for (const header in this.requestHeader) {
  22495. request.setRequestHeader(header, this.requestHeader[header]);
  22496. }
  22497. request.send(null);
  22498. }
  22499. scope.manager.itemStart(url);
  22500. return request;
  22501. }
  22502. setResponseType(value) {
  22503. this.responseType = value;
  22504. return this;
  22505. }
  22506. setMimeType(value) {
  22507. this.mimeType = value;
  22508. return this;
  22509. }
  22510. }
  22511. class AnimationLoader extends Loader {
  22512. constructor(manager) {
  22513. super(manager);
  22514. }
  22515. load(url, onLoad, onProgress, onError) {
  22516. const scope = this;
  22517. const loader = new FileLoader(this.manager);
  22518. loader.setPath(this.path);
  22519. loader.setRequestHeader(this.requestHeader);
  22520. loader.setWithCredentials(this.withCredentials);
  22521. loader.load(url, function (text) {
  22522. try {
  22523. onLoad(scope.parse(JSON.parse(text)));
  22524. } catch (e) {
  22525. if (onError) {
  22526. onError(e);
  22527. } else {
  22528. console.error(e);
  22529. }
  22530. scope.manager.itemError(url);
  22531. }
  22532. }, onProgress, onError);
  22533. }
  22534. parse(json) {
  22535. const animations = [];
  22536. for (let i = 0; i < json.length; i++) {
  22537. const clip = AnimationClip.parse(json[i]);
  22538. animations.push(clip);
  22539. }
  22540. return animations;
  22541. }
  22542. }
  22543. /**
  22544. * Abstract Base class to block based textures loader (dds, pvr, ...)
  22545. *
  22546. * Sub classes have to implement the parse() method which will be used in load().
  22547. */
  22548. class CompressedTextureLoader extends Loader {
  22549. constructor(manager) {
  22550. super(manager);
  22551. }
  22552. load(url, onLoad, onProgress, onError) {
  22553. const scope = this;
  22554. const images = [];
  22555. const texture = new CompressedTexture();
  22556. const loader = new FileLoader(this.manager);
  22557. loader.setPath(this.path);
  22558. loader.setResponseType('arraybuffer');
  22559. loader.setRequestHeader(this.requestHeader);
  22560. loader.setWithCredentials(scope.withCredentials);
  22561. let loaded = 0;
  22562. function loadTexture(i) {
  22563. loader.load(url[i], function (buffer) {
  22564. const texDatas = scope.parse(buffer, true);
  22565. images[i] = {
  22566. width: texDatas.width,
  22567. height: texDatas.height,
  22568. format: texDatas.format,
  22569. mipmaps: texDatas.mipmaps
  22570. };
  22571. loaded += 1;
  22572. if (loaded === 6) {
  22573. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  22574. texture.image = images;
  22575. texture.format = texDatas.format;
  22576. texture.needsUpdate = true;
  22577. if (onLoad) onLoad(texture);
  22578. }
  22579. }, onProgress, onError);
  22580. }
  22581. if (Array.isArray(url)) {
  22582. for (let i = 0, il = url.length; i < il; ++i) {
  22583. loadTexture(i);
  22584. }
  22585. } else {
  22586. // compressed cubemap texture stored in a single DDS file
  22587. loader.load(url, function (buffer) {
  22588. const texDatas = scope.parse(buffer, true);
  22589. if (texDatas.isCubemap) {
  22590. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  22591. for (let f = 0; f < faces; f++) {
  22592. images[f] = {
  22593. mipmaps: []
  22594. };
  22595. for (let i = 0; i < texDatas.mipmapCount; i++) {
  22596. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  22597. images[f].format = texDatas.format;
  22598. images[f].width = texDatas.width;
  22599. images[f].height = texDatas.height;
  22600. }
  22601. }
  22602. texture.image = images;
  22603. } else {
  22604. texture.image.width = texDatas.width;
  22605. texture.image.height = texDatas.height;
  22606. texture.mipmaps = texDatas.mipmaps;
  22607. }
  22608. if (texDatas.mipmapCount === 1) {
  22609. texture.minFilter = LinearFilter;
  22610. }
  22611. texture.format = texDatas.format;
  22612. texture.needsUpdate = true;
  22613. if (onLoad) onLoad(texture);
  22614. }, onProgress, onError);
  22615. }
  22616. return texture;
  22617. }
  22618. }
  22619. class ImageLoader extends Loader {
  22620. constructor(manager) {
  22621. super(manager);
  22622. }
  22623. load(url, onLoad, onProgress, onError) {
  22624. if (this.path !== undefined) url = this.path + url;
  22625. url = this.manager.resolveURL(url);
  22626. const scope = this;
  22627. const cached = Cache.get(url);
  22628. if (cached !== undefined) {
  22629. scope.manager.itemStart(url);
  22630. setTimeout(function () {
  22631. if (onLoad) onLoad(cached);
  22632. scope.manager.itemEnd(url);
  22633. }, 0);
  22634. return cached;
  22635. }
  22636. const image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  22637. function onImageLoad() {
  22638. image.removeEventListener('load', onImageLoad, false);
  22639. image.removeEventListener('error', onImageError, false);
  22640. Cache.add(url, this);
  22641. if (onLoad) onLoad(this);
  22642. scope.manager.itemEnd(url);
  22643. }
  22644. function onImageError(event) {
  22645. image.removeEventListener('load', onImageLoad, false);
  22646. image.removeEventListener('error', onImageError, false);
  22647. if (onError) onError(event);
  22648. scope.manager.itemError(url);
  22649. scope.manager.itemEnd(url);
  22650. }
  22651. image.addEventListener('load', onImageLoad, false);
  22652. image.addEventListener('error', onImageError, false);
  22653. if (url.substr(0, 5) !== 'data:') {
  22654. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  22655. }
  22656. scope.manager.itemStart(url);
  22657. image.src = url;
  22658. return image;
  22659. }
  22660. }
  22661. class CubeTextureLoader extends Loader {
  22662. constructor(manager) {
  22663. super(manager);
  22664. }
  22665. load(urls, onLoad, onProgress, onError) {
  22666. const texture = new CubeTexture();
  22667. const loader = new ImageLoader(this.manager);
  22668. loader.setCrossOrigin(this.crossOrigin);
  22669. loader.setPath(this.path);
  22670. let loaded = 0;
  22671. function loadTexture(i) {
  22672. loader.load(urls[i], function (image) {
  22673. texture.images[i] = image;
  22674. loaded++;
  22675. if (loaded === 6) {
  22676. texture.needsUpdate = true;
  22677. if (onLoad) onLoad(texture);
  22678. }
  22679. }, undefined, onError);
  22680. }
  22681. for (let i = 0; i < urls.length; ++i) {
  22682. loadTexture(i);
  22683. }
  22684. return texture;
  22685. }
  22686. }
  22687. /**
  22688. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  22689. *
  22690. * Sub classes have to implement the parse() method which will be used in load().
  22691. */
  22692. class DataTextureLoader extends Loader {
  22693. constructor(manager) {
  22694. super(manager);
  22695. }
  22696. load(url, onLoad, onProgress, onError) {
  22697. const scope = this;
  22698. const texture = new DataTexture();
  22699. const loader = new FileLoader(this.manager);
  22700. loader.setResponseType('arraybuffer');
  22701. loader.setRequestHeader(this.requestHeader);
  22702. loader.setPath(this.path);
  22703. loader.setWithCredentials(scope.withCredentials);
  22704. loader.load(url, function (buffer) {
  22705. const texData = scope.parse(buffer);
  22706. if (!texData) return;
  22707. if (texData.image !== undefined) {
  22708. texture.image = texData.image;
  22709. } else if (texData.data !== undefined) {
  22710. texture.image.width = texData.width;
  22711. texture.image.height = texData.height;
  22712. texture.image.data = texData.data;
  22713. }
  22714. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  22715. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  22716. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  22717. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  22718. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  22719. if (texData.encoding !== undefined) {
  22720. texture.encoding = texData.encoding;
  22721. }
  22722. if (texData.flipY !== undefined) {
  22723. texture.flipY = texData.flipY;
  22724. }
  22725. if (texData.format !== undefined) {
  22726. texture.format = texData.format;
  22727. }
  22728. if (texData.type !== undefined) {
  22729. texture.type = texData.type;
  22730. }
  22731. if (texData.mipmaps !== undefined) {
  22732. texture.mipmaps = texData.mipmaps;
  22733. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  22734. }
  22735. if (texData.mipmapCount === 1) {
  22736. texture.minFilter = LinearFilter;
  22737. }
  22738. if (texData.generateMipmaps !== undefined) {
  22739. texture.generateMipmaps = texData.generateMipmaps;
  22740. }
  22741. texture.needsUpdate = true;
  22742. if (onLoad) onLoad(texture, texData);
  22743. }, onProgress, onError);
  22744. return texture;
  22745. }
  22746. }
  22747. class TextureLoader extends Loader {
  22748. constructor(manager) {
  22749. super(manager);
  22750. }
  22751. load(url, onLoad, onProgress, onError) {
  22752. const texture = new Texture();
  22753. const loader = new ImageLoader(this.manager);
  22754. loader.setCrossOrigin(this.crossOrigin);
  22755. loader.setPath(this.path);
  22756. loader.load(url, function (image) {
  22757. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  22758. const isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  22759. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  22760. texture.needsUpdate = true;
  22761. if (onLoad !== undefined) {
  22762. onLoad(texture);
  22763. }
  22764. }, onProgress, onError);
  22765. return texture;
  22766. }
  22767. }
  22768. /**************************************************************
  22769. * Curved Path - a curve path is simply a array of connected
  22770. * curves, but retains the api of a curve
  22771. **************************************************************/
  22772. class CurvePath extends Curve {
  22773. constructor() {
  22774. super();
  22775. this.type = 'CurvePath';
  22776. this.curves = [];
  22777. this.autoClose = false; // Automatically closes the path
  22778. }
  22779. add(curve) {
  22780. this.curves.push(curve);
  22781. }
  22782. closePath() {
  22783. // Add a line curve if start and end of lines are not connected
  22784. const startPoint = this.curves[0].getPoint(0);
  22785. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  22786. if (!startPoint.equals(endPoint)) {
  22787. this.curves.push(new LineCurve(endPoint, startPoint));
  22788. }
  22789. } // To get accurate point with reference to
  22790. // entire path distance at time t,
  22791. // following has to be done:
  22792. // 1. Length of each sub path have to be known
  22793. // 2. Locate and identify type of curve
  22794. // 3. Get t for the curve
  22795. // 4. Return curve.getPointAt(t')
  22796. getPoint(t) {
  22797. const d = t * this.getLength();
  22798. const curveLengths = this.getCurveLengths();
  22799. let i = 0; // To think about boundaries points.
  22800. while (i < curveLengths.length) {
  22801. if (curveLengths[i] >= d) {
  22802. const diff = curveLengths[i] - d;
  22803. const curve = this.curves[i];
  22804. const segmentLength = curve.getLength();
  22805. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  22806. return curve.getPointAt(u);
  22807. }
  22808. i++;
  22809. }
  22810. return null; // loop where sum != 0, sum > d , sum+1 <d
  22811. } // We cannot use the default THREE.Curve getPoint() with getLength() because in
  22812. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  22813. // getPoint() depends on getLength
  22814. getLength() {
  22815. const lens = this.getCurveLengths();
  22816. return lens[lens.length - 1];
  22817. } // cacheLengths must be recalculated.
  22818. updateArcLengths() {
  22819. this.needsUpdate = true;
  22820. this.cacheLengths = null;
  22821. this.getCurveLengths();
  22822. } // Compute lengths and cache them
  22823. // We cannot overwrite getLengths() because UtoT mapping uses it.
  22824. getCurveLengths() {
  22825. // We use cache values if curves and cache array are same length
  22826. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  22827. return this.cacheLengths;
  22828. } // Get length of sub-curve
  22829. // Push sums into cached array
  22830. const lengths = [];
  22831. let sums = 0;
  22832. for (let i = 0, l = this.curves.length; i < l; i++) {
  22833. sums += this.curves[i].getLength();
  22834. lengths.push(sums);
  22835. }
  22836. this.cacheLengths = lengths;
  22837. return lengths;
  22838. }
  22839. getSpacedPoints(divisions = 40) {
  22840. const points = [];
  22841. for (let i = 0; i <= divisions; i++) {
  22842. points.push(this.getPoint(i / divisions));
  22843. }
  22844. if (this.autoClose) {
  22845. points.push(points[0]);
  22846. }
  22847. return points;
  22848. }
  22849. getPoints(divisions = 12) {
  22850. const points = [];
  22851. let last;
  22852. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  22853. const curve = curves[i];
  22854. const resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  22855. const pts = curve.getPoints(resolution);
  22856. for (let j = 0; j < pts.length; j++) {
  22857. const point = pts[j];
  22858. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  22859. points.push(point);
  22860. last = point;
  22861. }
  22862. }
  22863. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  22864. points.push(points[0]);
  22865. }
  22866. return points;
  22867. }
  22868. copy(source) {
  22869. super.copy(source);
  22870. this.curves = [];
  22871. for (let i = 0, l = source.curves.length; i < l; i++) {
  22872. const curve = source.curves[i];
  22873. this.curves.push(curve.clone());
  22874. }
  22875. this.autoClose = source.autoClose;
  22876. return this;
  22877. }
  22878. toJSON() {
  22879. const data = super.toJSON();
  22880. data.autoClose = this.autoClose;
  22881. data.curves = [];
  22882. for (let i = 0, l = this.curves.length; i < l; i++) {
  22883. const curve = this.curves[i];
  22884. data.curves.push(curve.toJSON());
  22885. }
  22886. return data;
  22887. }
  22888. fromJSON(json) {
  22889. super.fromJSON(json);
  22890. this.autoClose = json.autoClose;
  22891. this.curves = [];
  22892. for (let i = 0, l = json.curves.length; i < l; i++) {
  22893. const curve = json.curves[i];
  22894. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  22895. }
  22896. return this;
  22897. }
  22898. }
  22899. class Path extends CurvePath {
  22900. constructor(points) {
  22901. super();
  22902. this.type = 'Path';
  22903. this.currentPoint = new Vector2();
  22904. if (points) {
  22905. this.setFromPoints(points);
  22906. }
  22907. }
  22908. setFromPoints(points) {
  22909. this.moveTo(points[0].x, points[0].y);
  22910. for (let i = 1, l = points.length; i < l; i++) {
  22911. this.lineTo(points[i].x, points[i].y);
  22912. }
  22913. return this;
  22914. }
  22915. moveTo(x, y) {
  22916. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  22917. return this;
  22918. }
  22919. lineTo(x, y) {
  22920. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  22921. this.curves.push(curve);
  22922. this.currentPoint.set(x, y);
  22923. return this;
  22924. }
  22925. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  22926. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  22927. this.curves.push(curve);
  22928. this.currentPoint.set(aX, aY);
  22929. return this;
  22930. }
  22931. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  22932. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  22933. this.curves.push(curve);
  22934. this.currentPoint.set(aX, aY);
  22935. return this;
  22936. }
  22937. splineThru(pts
  22938. /*Array of Vector*/
  22939. ) {
  22940. const npts = [this.currentPoint.clone()].concat(pts);
  22941. const curve = new SplineCurve(npts);
  22942. this.curves.push(curve);
  22943. this.currentPoint.copy(pts[pts.length - 1]);
  22944. return this;
  22945. }
  22946. arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  22947. const x0 = this.currentPoint.x;
  22948. const y0 = this.currentPoint.y;
  22949. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  22950. return this;
  22951. }
  22952. absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  22953. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  22954. return this;
  22955. }
  22956. ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  22957. const x0 = this.currentPoint.x;
  22958. const y0 = this.currentPoint.y;
  22959. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  22960. return this;
  22961. }
  22962. absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  22963. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  22964. if (this.curves.length > 0) {
  22965. // if a previous curve is present, attempt to join
  22966. const firstPoint = curve.getPoint(0);
  22967. if (!firstPoint.equals(this.currentPoint)) {
  22968. this.lineTo(firstPoint.x, firstPoint.y);
  22969. }
  22970. }
  22971. this.curves.push(curve);
  22972. const lastPoint = curve.getPoint(1);
  22973. this.currentPoint.copy(lastPoint);
  22974. return this;
  22975. }
  22976. copy(source) {
  22977. super.copy(source);
  22978. this.currentPoint.copy(source.currentPoint);
  22979. return this;
  22980. }
  22981. toJSON() {
  22982. const data = super.toJSON();
  22983. data.currentPoint = this.currentPoint.toArray();
  22984. return data;
  22985. }
  22986. fromJSON(json) {
  22987. super.fromJSON(json);
  22988. this.currentPoint.fromArray(json.currentPoint);
  22989. return this;
  22990. }
  22991. }
  22992. class Shape extends Path {
  22993. constructor(points) {
  22994. super(points);
  22995. this.uuid = generateUUID();
  22996. this.type = 'Shape';
  22997. this.holes = [];
  22998. }
  22999. getPointsHoles(divisions) {
  23000. const holesPts = [];
  23001. for (let i = 0, l = this.holes.length; i < l; i++) {
  23002. holesPts[i] = this.holes[i].getPoints(divisions);
  23003. }
  23004. return holesPts;
  23005. } // get points of shape and holes (keypoints based on segments parameter)
  23006. extractPoints(divisions) {
  23007. return {
  23008. shape: this.getPoints(divisions),
  23009. holes: this.getPointsHoles(divisions)
  23010. };
  23011. }
  23012. copy(source) {
  23013. super.copy(source);
  23014. this.holes = [];
  23015. for (let i = 0, l = source.holes.length; i < l; i++) {
  23016. const hole = source.holes[i];
  23017. this.holes.push(hole.clone());
  23018. }
  23019. return this;
  23020. }
  23021. toJSON() {
  23022. const data = super.toJSON();
  23023. data.uuid = this.uuid;
  23024. data.holes = [];
  23025. for (let i = 0, l = this.holes.length; i < l; i++) {
  23026. const hole = this.holes[i];
  23027. data.holes.push(hole.toJSON());
  23028. }
  23029. return data;
  23030. }
  23031. fromJSON(json) {
  23032. super.fromJSON(json);
  23033. this.uuid = json.uuid;
  23034. this.holes = [];
  23035. for (let i = 0, l = json.holes.length; i < l; i++) {
  23036. const hole = json.holes[i];
  23037. this.holes.push(new Path().fromJSON(hole));
  23038. }
  23039. return this;
  23040. }
  23041. }
  23042. class Light extends Object3D {
  23043. constructor(color, intensity = 1) {
  23044. super();
  23045. this.type = 'Light';
  23046. this.color = new Color(color);
  23047. this.intensity = intensity;
  23048. }
  23049. dispose() {// Empty here in base class; some subclasses override.
  23050. }
  23051. copy(source) {
  23052. super.copy(source);
  23053. this.color.copy(source.color);
  23054. this.intensity = source.intensity;
  23055. return this;
  23056. }
  23057. toJSON(meta) {
  23058. const data = super.toJSON(meta);
  23059. data.object.color = this.color.getHex();
  23060. data.object.intensity = this.intensity;
  23061. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  23062. if (this.distance !== undefined) data.object.distance = this.distance;
  23063. if (this.angle !== undefined) data.object.angle = this.angle;
  23064. if (this.decay !== undefined) data.object.decay = this.decay;
  23065. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  23066. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  23067. return data;
  23068. }
  23069. }
  23070. Light.prototype.isLight = true;
  23071. class HemisphereLight extends Light {
  23072. constructor(skyColor, groundColor, intensity) {
  23073. super(skyColor, intensity);
  23074. this.type = 'HemisphereLight';
  23075. this.position.copy(Object3D.DefaultUp);
  23076. this.updateMatrix();
  23077. this.groundColor = new Color(groundColor);
  23078. }
  23079. copy(source) {
  23080. Light.prototype.copy.call(this, source);
  23081. this.groundColor.copy(source.groundColor);
  23082. return this;
  23083. }
  23084. }
  23085. HemisphereLight.prototype.isHemisphereLight = true;
  23086. const _projScreenMatrix$1 = /*@__PURE__*/new Matrix4();
  23087. const _lightPositionWorld$1 = /*@__PURE__*/new Vector3();
  23088. const _lookTarget$1 = /*@__PURE__*/new Vector3();
  23089. class LightShadow {
  23090. constructor(camera) {
  23091. this.camera = camera;
  23092. this.bias = 0;
  23093. this.normalBias = 0;
  23094. this.radius = 1;
  23095. this.blurSamples = 8;
  23096. this.mapSize = new Vector2(512, 512);
  23097. this.map = null;
  23098. this.mapPass = null;
  23099. this.matrix = new Matrix4();
  23100. this.autoUpdate = true;
  23101. this.needsUpdate = false;
  23102. this._frustum = new Frustum();
  23103. this._frameExtents = new Vector2(1, 1);
  23104. this._viewportCount = 1;
  23105. this._viewports = [new Vector4(0, 0, 1, 1)];
  23106. }
  23107. getViewportCount() {
  23108. return this._viewportCount;
  23109. }
  23110. getFrustum() {
  23111. return this._frustum;
  23112. }
  23113. updateMatrices(light) {
  23114. const shadowCamera = this.camera;
  23115. const shadowMatrix = this.matrix;
  23116. _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld);
  23117. shadowCamera.position.copy(_lightPositionWorld$1);
  23118. _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld);
  23119. shadowCamera.lookAt(_lookTarget$1);
  23120. shadowCamera.updateMatrixWorld();
  23121. _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  23122. this._frustum.setFromProjectionMatrix(_projScreenMatrix$1);
  23123. shadowMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0);
  23124. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  23125. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  23126. }
  23127. getViewport(viewportIndex) {
  23128. return this._viewports[viewportIndex];
  23129. }
  23130. getFrameExtents() {
  23131. return this._frameExtents;
  23132. }
  23133. dispose() {
  23134. if (this.map) {
  23135. this.map.dispose();
  23136. }
  23137. if (this.mapPass) {
  23138. this.mapPass.dispose();
  23139. }
  23140. }
  23141. copy(source) {
  23142. this.camera = source.camera.clone();
  23143. this.bias = source.bias;
  23144. this.radius = source.radius;
  23145. this.mapSize.copy(source.mapSize);
  23146. return this;
  23147. }
  23148. clone() {
  23149. return new this.constructor().copy(this);
  23150. }
  23151. toJSON() {
  23152. const object = {};
  23153. if (this.bias !== 0) object.bias = this.bias;
  23154. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  23155. if (this.radius !== 1) object.radius = this.radius;
  23156. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  23157. object.camera = this.camera.toJSON(false).object;
  23158. delete object.camera.matrix;
  23159. return object;
  23160. }
  23161. }
  23162. class SpotLightShadow extends LightShadow {
  23163. constructor() {
  23164. super(new PerspectiveCamera(50, 1, 0.5, 500));
  23165. this.focus = 1;
  23166. }
  23167. updateMatrices(light) {
  23168. const camera = this.camera;
  23169. const fov = RAD2DEG * 2 * light.angle * this.focus;
  23170. const aspect = this.mapSize.width / this.mapSize.height;
  23171. const far = light.distance || camera.far;
  23172. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  23173. camera.fov = fov;
  23174. camera.aspect = aspect;
  23175. camera.far = far;
  23176. camera.updateProjectionMatrix();
  23177. }
  23178. super.updateMatrices(light);
  23179. }
  23180. copy(source) {
  23181. super.copy(source);
  23182. this.focus = source.focus;
  23183. return this;
  23184. }
  23185. }
  23186. SpotLightShadow.prototype.isSpotLightShadow = true;
  23187. class SpotLight extends Light {
  23188. constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1) {
  23189. super(color, intensity);
  23190. this.type = 'SpotLight';
  23191. this.position.copy(Object3D.DefaultUp);
  23192. this.updateMatrix();
  23193. this.target = new Object3D();
  23194. this.distance = distance;
  23195. this.angle = angle;
  23196. this.penumbra = penumbra;
  23197. this.decay = decay; // for physically correct lights, should be 2.
  23198. this.shadow = new SpotLightShadow();
  23199. }
  23200. get power() {
  23201. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23202. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  23203. return this.intensity * Math.PI;
  23204. }
  23205. set power(power) {
  23206. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23207. this.intensity = power / Math.PI;
  23208. }
  23209. dispose() {
  23210. this.shadow.dispose();
  23211. }
  23212. copy(source) {
  23213. super.copy(source);
  23214. this.distance = source.distance;
  23215. this.angle = source.angle;
  23216. this.penumbra = source.penumbra;
  23217. this.decay = source.decay;
  23218. this.target = source.target.clone();
  23219. this.shadow = source.shadow.clone();
  23220. return this;
  23221. }
  23222. }
  23223. SpotLight.prototype.isSpotLight = true;
  23224. const _projScreenMatrix = /*@__PURE__*/new Matrix4();
  23225. const _lightPositionWorld = /*@__PURE__*/new Vector3();
  23226. const _lookTarget = /*@__PURE__*/new Vector3();
  23227. class PointLightShadow extends LightShadow {
  23228. constructor() {
  23229. super(new PerspectiveCamera(90, 1, 0.5, 500));
  23230. this._frameExtents = new Vector2(4, 2);
  23231. this._viewportCount = 6;
  23232. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  23233. // following orientation:
  23234. //
  23235. // xzXZ
  23236. // y Y
  23237. //
  23238. // X - Positive x direction
  23239. // x - Negative x direction
  23240. // Y - Positive y direction
  23241. // y - Negative y direction
  23242. // Z - Positive z direction
  23243. // z - Negative z direction
  23244. // positive X
  23245. new Vector4(2, 1, 1, 1), // negative X
  23246. new Vector4(0, 1, 1, 1), // positive Z
  23247. new Vector4(3, 1, 1, 1), // negative Z
  23248. new Vector4(1, 1, 1, 1), // positive Y
  23249. new Vector4(3, 0, 1, 1), // negative Y
  23250. new Vector4(1, 0, 1, 1)];
  23251. this._cubeDirections = [new Vector3(1, 0, 0), new Vector3(-1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1), new Vector3(0, 1, 0), new Vector3(0, -1, 0)];
  23252. this._cubeUps = [new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1)];
  23253. }
  23254. updateMatrices(light, viewportIndex = 0) {
  23255. const camera = this.camera;
  23256. const shadowMatrix = this.matrix;
  23257. const far = light.distance || camera.far;
  23258. if (far !== camera.far) {
  23259. camera.far = far;
  23260. camera.updateProjectionMatrix();
  23261. }
  23262. _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23263. camera.position.copy(_lightPositionWorld);
  23264. _lookTarget.copy(camera.position);
  23265. _lookTarget.add(this._cubeDirections[viewportIndex]);
  23266. camera.up.copy(this._cubeUps[viewportIndex]);
  23267. camera.lookAt(_lookTarget);
  23268. camera.updateMatrixWorld();
  23269. shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
  23270. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  23271. this._frustum.setFromProjectionMatrix(_projScreenMatrix);
  23272. }
  23273. }
  23274. PointLightShadow.prototype.isPointLightShadow = true;
  23275. class PointLight extends Light {
  23276. constructor(color, intensity, distance = 0, decay = 1) {
  23277. super(color, intensity);
  23278. this.type = 'PointLight';
  23279. this.distance = distance;
  23280. this.decay = decay; // for physically correct lights, should be 2.
  23281. this.shadow = new PointLightShadow();
  23282. }
  23283. get power() {
  23284. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23285. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  23286. return this.intensity * 4 * Math.PI;
  23287. }
  23288. set power(power) {
  23289. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23290. this.intensity = power / (4 * Math.PI);
  23291. }
  23292. dispose() {
  23293. this.shadow.dispose();
  23294. }
  23295. copy(source) {
  23296. super.copy(source);
  23297. this.distance = source.distance;
  23298. this.decay = source.decay;
  23299. this.shadow = source.shadow.clone();
  23300. return this;
  23301. }
  23302. }
  23303. PointLight.prototype.isPointLight = true;
  23304. class DirectionalLightShadow extends LightShadow {
  23305. constructor() {
  23306. super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  23307. }
  23308. }
  23309. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  23310. class DirectionalLight extends Light {
  23311. constructor(color, intensity) {
  23312. super(color, intensity);
  23313. this.type = 'DirectionalLight';
  23314. this.position.copy(Object3D.DefaultUp);
  23315. this.updateMatrix();
  23316. this.target = new Object3D();
  23317. this.shadow = new DirectionalLightShadow();
  23318. }
  23319. dispose() {
  23320. this.shadow.dispose();
  23321. }
  23322. copy(source) {
  23323. super.copy(source);
  23324. this.target = source.target.clone();
  23325. this.shadow = source.shadow.clone();
  23326. return this;
  23327. }
  23328. }
  23329. DirectionalLight.prototype.isDirectionalLight = true;
  23330. class AmbientLight extends Light {
  23331. constructor(color, intensity) {
  23332. super(color, intensity);
  23333. this.type = 'AmbientLight';
  23334. }
  23335. }
  23336. AmbientLight.prototype.isAmbientLight = true;
  23337. class RectAreaLight extends Light {
  23338. constructor(color, intensity, width = 10, height = 10) {
  23339. super(color, intensity);
  23340. this.type = 'RectAreaLight';
  23341. this.width = width;
  23342. this.height = height;
  23343. }
  23344. get power() {
  23345. // compute the light's luminous power (in lumens) from its intensity (in nits)
  23346. return this.intensity * this.width * this.height * Math.PI;
  23347. }
  23348. set power(power) {
  23349. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  23350. this.intensity = power / (this.width * this.height * Math.PI);
  23351. }
  23352. copy(source) {
  23353. super.copy(source);
  23354. this.width = source.width;
  23355. this.height = source.height;
  23356. return this;
  23357. }
  23358. toJSON(meta) {
  23359. const data = super.toJSON(meta);
  23360. data.object.width = this.width;
  23361. data.object.height = this.height;
  23362. return data;
  23363. }
  23364. }
  23365. RectAreaLight.prototype.isRectAreaLight = true;
  23366. /**
  23367. * Primary reference:
  23368. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23369. *
  23370. * Secondary reference:
  23371. * https://www.ppsloan.org/publications/StupidSH36.pdf
  23372. */
  23373. // 3-band SH defined by 9 coefficients
  23374. class SphericalHarmonics3 {
  23375. constructor() {
  23376. this.coefficients = [];
  23377. for (let i = 0; i < 9; i++) {
  23378. this.coefficients.push(new Vector3());
  23379. }
  23380. }
  23381. set(coefficients) {
  23382. for (let i = 0; i < 9; i++) {
  23383. this.coefficients[i].copy(coefficients[i]);
  23384. }
  23385. return this;
  23386. }
  23387. zero() {
  23388. for (let i = 0; i < 9; i++) {
  23389. this.coefficients[i].set(0, 0, 0);
  23390. }
  23391. return this;
  23392. } // get the radiance in the direction of the normal
  23393. // target is a Vector3
  23394. getAt(normal, target) {
  23395. // normal is assumed to be unit length
  23396. const x = normal.x,
  23397. y = normal.y,
  23398. z = normal.z;
  23399. const coeff = this.coefficients; // band 0
  23400. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  23401. target.addScaledVector(coeff[1], 0.488603 * y);
  23402. target.addScaledVector(coeff[2], 0.488603 * z);
  23403. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  23404. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  23405. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  23406. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  23407. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  23408. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  23409. return target;
  23410. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  23411. // target is a Vector3
  23412. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23413. getIrradianceAt(normal, target) {
  23414. // normal is assumed to be unit length
  23415. const x = normal.x,
  23416. y = normal.y,
  23417. z = normal.z;
  23418. const coeff = this.coefficients; // band 0
  23419. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  23420. // band 1
  23421. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  23422. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  23423. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  23424. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  23425. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  23426. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  23427. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  23428. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  23429. return target;
  23430. }
  23431. add(sh) {
  23432. for (let i = 0; i < 9; i++) {
  23433. this.coefficients[i].add(sh.coefficients[i]);
  23434. }
  23435. return this;
  23436. }
  23437. addScaledSH(sh, s) {
  23438. for (let i = 0; i < 9; i++) {
  23439. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  23440. }
  23441. return this;
  23442. }
  23443. scale(s) {
  23444. for (let i = 0; i < 9; i++) {
  23445. this.coefficients[i].multiplyScalar(s);
  23446. }
  23447. return this;
  23448. }
  23449. lerp(sh, alpha) {
  23450. for (let i = 0; i < 9; i++) {
  23451. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  23452. }
  23453. return this;
  23454. }
  23455. equals(sh) {
  23456. for (let i = 0; i < 9; i++) {
  23457. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  23458. return false;
  23459. }
  23460. }
  23461. return true;
  23462. }
  23463. copy(sh) {
  23464. return this.set(sh.coefficients);
  23465. }
  23466. clone() {
  23467. return new this.constructor().copy(this);
  23468. }
  23469. fromArray(array, offset = 0) {
  23470. const coefficients = this.coefficients;
  23471. for (let i = 0; i < 9; i++) {
  23472. coefficients[i].fromArray(array, offset + i * 3);
  23473. }
  23474. return this;
  23475. }
  23476. toArray(array = [], offset = 0) {
  23477. const coefficients = this.coefficients;
  23478. for (let i = 0; i < 9; i++) {
  23479. coefficients[i].toArray(array, offset + i * 3);
  23480. }
  23481. return array;
  23482. } // evaluate the basis functions
  23483. // shBasis is an Array[ 9 ]
  23484. static getBasisAt(normal, shBasis) {
  23485. // normal is assumed to be unit length
  23486. const x = normal.x,
  23487. y = normal.y,
  23488. z = normal.z; // band 0
  23489. shBasis[0] = 0.282095; // band 1
  23490. shBasis[1] = 0.488603 * y;
  23491. shBasis[2] = 0.488603 * z;
  23492. shBasis[3] = 0.488603 * x; // band 2
  23493. shBasis[4] = 1.092548 * x * y;
  23494. shBasis[5] = 1.092548 * y * z;
  23495. shBasis[6] = 0.315392 * (3 * z * z - 1);
  23496. shBasis[7] = 1.092548 * x * z;
  23497. shBasis[8] = 0.546274 * (x * x - y * y);
  23498. }
  23499. }
  23500. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  23501. class LightProbe extends Light {
  23502. constructor(sh = new SphericalHarmonics3(), intensity = 1) {
  23503. super(undefined, intensity);
  23504. this.sh = sh;
  23505. }
  23506. copy(source) {
  23507. super.copy(source);
  23508. this.sh.copy(source.sh);
  23509. return this;
  23510. }
  23511. fromJSON(json) {
  23512. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  23513. this.sh.fromArray(json.sh);
  23514. return this;
  23515. }
  23516. toJSON(meta) {
  23517. const data = super.toJSON(meta);
  23518. data.object.sh = this.sh.toArray();
  23519. return data;
  23520. }
  23521. }
  23522. LightProbe.prototype.isLightProbe = true;
  23523. class MaterialLoader extends Loader {
  23524. constructor(manager) {
  23525. super(manager);
  23526. this.textures = {};
  23527. }
  23528. load(url, onLoad, onProgress, onError) {
  23529. const scope = this;
  23530. const loader = new FileLoader(scope.manager);
  23531. loader.setPath(scope.path);
  23532. loader.setRequestHeader(scope.requestHeader);
  23533. loader.setWithCredentials(scope.withCredentials);
  23534. loader.load(url, function (text) {
  23535. try {
  23536. onLoad(scope.parse(JSON.parse(text)));
  23537. } catch (e) {
  23538. if (onError) {
  23539. onError(e);
  23540. } else {
  23541. console.error(e);
  23542. }
  23543. scope.manager.itemError(url);
  23544. }
  23545. }, onProgress, onError);
  23546. }
  23547. parse(json) {
  23548. const textures = this.textures;
  23549. function getTexture(name) {
  23550. if (textures[name] === undefined) {
  23551. console.warn('THREE.MaterialLoader: Undefined texture', name);
  23552. }
  23553. return textures[name];
  23554. }
  23555. const material = new Materials[json.type]();
  23556. if (json.uuid !== undefined) material.uuid = json.uuid;
  23557. if (json.name !== undefined) material.name = json.name;
  23558. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  23559. if (json.roughness !== undefined) material.roughness = json.roughness;
  23560. if (json.metalness !== undefined) material.metalness = json.metalness;
  23561. if (json.sheen !== undefined) material.sheen = json.sheen;
  23562. if (json.sheenTint !== undefined) material.sheenTint = new Color().setHex(json.sheenTint);
  23563. if (json.sheenRoughness !== undefined) material.sheenRoughness = json.sheenRoughness;
  23564. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  23565. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  23566. if (json.specularIntensity !== undefined) material.specularIntensity = json.specularIntensity;
  23567. if (json.specularTint !== undefined && material.specularTint !== undefined) material.specularTint.setHex(json.specularTint);
  23568. if (json.shininess !== undefined) material.shininess = json.shininess;
  23569. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  23570. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  23571. if (json.transmission !== undefined) material.transmission = json.transmission;
  23572. if (json.thickness !== undefined) material.thickness = json.thickness;
  23573. if (json.attenuationDistance !== undefined) material.attenuationDistance = json.attenuationDistance;
  23574. if (json.attenuationTint !== undefined && material.attenuationTint !== undefined) material.attenuationTint.setHex(json.attenuationTint);
  23575. if (json.fog !== undefined) material.fog = json.fog;
  23576. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  23577. if (json.blending !== undefined) material.blending = json.blending;
  23578. if (json.combine !== undefined) material.combine = json.combine;
  23579. if (json.side !== undefined) material.side = json.side;
  23580. if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
  23581. if (json.opacity !== undefined) material.opacity = json.opacity;
  23582. if (json.format !== undefined) material.format = json.format;
  23583. if (json.transparent !== undefined) material.transparent = json.transparent;
  23584. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  23585. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  23586. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  23587. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  23588. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  23589. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  23590. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  23591. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  23592. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  23593. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  23594. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  23595. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  23596. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  23597. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  23598. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  23599. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  23600. if (json.rotation !== undefined) material.rotation = json.rotation;
  23601. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  23602. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  23603. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  23604. if (json.scale !== undefined) material.scale = json.scale;
  23605. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  23606. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  23607. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  23608. if (json.dithering !== undefined) material.dithering = json.dithering;
  23609. if (json.alphaToCoverage !== undefined) material.alphaToCoverage = json.alphaToCoverage;
  23610. if (json.premultipliedAlpha !== undefined) material.premultipliedAlpha = json.premultipliedAlpha;
  23611. if (json.visible !== undefined) material.visible = json.visible;
  23612. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  23613. if (json.userData !== undefined) material.userData = json.userData;
  23614. if (json.vertexColors !== undefined) {
  23615. if (typeof json.vertexColors === 'number') {
  23616. material.vertexColors = json.vertexColors > 0 ? true : false;
  23617. } else {
  23618. material.vertexColors = json.vertexColors;
  23619. }
  23620. } // Shader Material
  23621. if (json.uniforms !== undefined) {
  23622. for (const name in json.uniforms) {
  23623. const uniform = json.uniforms[name];
  23624. material.uniforms[name] = {};
  23625. switch (uniform.type) {
  23626. case 't':
  23627. material.uniforms[name].value = getTexture(uniform.value);
  23628. break;
  23629. case 'c':
  23630. material.uniforms[name].value = new Color().setHex(uniform.value);
  23631. break;
  23632. case 'v2':
  23633. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  23634. break;
  23635. case 'v3':
  23636. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  23637. break;
  23638. case 'v4':
  23639. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  23640. break;
  23641. case 'm3':
  23642. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  23643. break;
  23644. case 'm4':
  23645. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  23646. break;
  23647. default:
  23648. material.uniforms[name].value = uniform.value;
  23649. }
  23650. }
  23651. }
  23652. if (json.defines !== undefined) material.defines = json.defines;
  23653. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  23654. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  23655. if (json.extensions !== undefined) {
  23656. for (const key in json.extensions) {
  23657. material.extensions[key] = json.extensions[key];
  23658. }
  23659. } // Deprecated
  23660. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  23661. // for PointsMaterial
  23662. if (json.size !== undefined) material.size = json.size;
  23663. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  23664. if (json.map !== undefined) material.map = getTexture(json.map);
  23665. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  23666. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  23667. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  23668. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  23669. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  23670. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  23671. if (json.normalScale !== undefined) {
  23672. let normalScale = json.normalScale;
  23673. if (Array.isArray(normalScale) === false) {
  23674. // Blender exporter used to export a scalar. See #7459
  23675. normalScale = [normalScale, normalScale];
  23676. }
  23677. material.normalScale = new Vector2().fromArray(normalScale);
  23678. }
  23679. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  23680. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  23681. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  23682. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  23683. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  23684. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  23685. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  23686. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  23687. if (json.specularIntensityMap !== undefined) material.specularIntensityMap = getTexture(json.specularIntensityMap);
  23688. if (json.specularTintMap !== undefined) material.specularTintMap = getTexture(json.specularTintMap);
  23689. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  23690. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  23691. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  23692. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  23693. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  23694. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  23695. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  23696. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  23697. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  23698. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  23699. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  23700. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  23701. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  23702. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  23703. if (json.thicknessMap !== undefined) material.thicknessMap = getTexture(json.thicknessMap);
  23704. return material;
  23705. }
  23706. setTextures(value) {
  23707. this.textures = value;
  23708. return this;
  23709. }
  23710. }
  23711. class LoaderUtils {
  23712. static decodeText(array) {
  23713. if (typeof TextDecoder !== 'undefined') {
  23714. return new TextDecoder().decode(array);
  23715. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  23716. // throws a "maximum call stack size exceeded" error for large arrays.
  23717. let s = '';
  23718. for (let i = 0, il = array.length; i < il; i++) {
  23719. // Implicitly assumes little-endian.
  23720. s += String.fromCharCode(array[i]);
  23721. }
  23722. try {
  23723. // merges multi-byte utf-8 characters.
  23724. return decodeURIComponent(escape(s));
  23725. } catch (e) {
  23726. // see #16358
  23727. return s;
  23728. }
  23729. }
  23730. static extractUrlBase(url) {
  23731. const index = url.lastIndexOf('/');
  23732. if (index === -1) return './';
  23733. return url.substr(0, index + 1);
  23734. }
  23735. }
  23736. class InstancedBufferGeometry extends BufferGeometry {
  23737. constructor() {
  23738. super();
  23739. this.type = 'InstancedBufferGeometry';
  23740. this.instanceCount = Infinity;
  23741. }
  23742. copy(source) {
  23743. super.copy(source);
  23744. this.instanceCount = source.instanceCount;
  23745. return this;
  23746. }
  23747. clone() {
  23748. return new this.constructor().copy(this);
  23749. }
  23750. toJSON() {
  23751. const data = super.toJSON(this);
  23752. data.instanceCount = this.instanceCount;
  23753. data.isInstancedBufferGeometry = true;
  23754. return data;
  23755. }
  23756. }
  23757. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  23758. class BufferGeometryLoader extends Loader {
  23759. constructor(manager) {
  23760. super(manager);
  23761. }
  23762. load(url, onLoad, onProgress, onError) {
  23763. const scope = this;
  23764. const loader = new FileLoader(scope.manager);
  23765. loader.setPath(scope.path);
  23766. loader.setRequestHeader(scope.requestHeader);
  23767. loader.setWithCredentials(scope.withCredentials);
  23768. loader.load(url, function (text) {
  23769. try {
  23770. onLoad(scope.parse(JSON.parse(text)));
  23771. } catch (e) {
  23772. if (onError) {
  23773. onError(e);
  23774. } else {
  23775. console.error(e);
  23776. }
  23777. scope.manager.itemError(url);
  23778. }
  23779. }, onProgress, onError);
  23780. }
  23781. parse(json) {
  23782. const interleavedBufferMap = {};
  23783. const arrayBufferMap = {};
  23784. function getInterleavedBuffer(json, uuid) {
  23785. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  23786. const interleavedBuffers = json.interleavedBuffers;
  23787. const interleavedBuffer = interleavedBuffers[uuid];
  23788. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  23789. const array = getTypedArray(interleavedBuffer.type, buffer);
  23790. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  23791. ib.uuid = interleavedBuffer.uuid;
  23792. interleavedBufferMap[uuid] = ib;
  23793. return ib;
  23794. }
  23795. function getArrayBuffer(json, uuid) {
  23796. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  23797. const arrayBuffers = json.arrayBuffers;
  23798. const arrayBuffer = arrayBuffers[uuid];
  23799. const ab = new Uint32Array(arrayBuffer).buffer;
  23800. arrayBufferMap[uuid] = ab;
  23801. return ab;
  23802. }
  23803. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  23804. const index = json.data.index;
  23805. if (index !== undefined) {
  23806. const typedArray = getTypedArray(index.type, index.array);
  23807. geometry.setIndex(new BufferAttribute(typedArray, 1));
  23808. }
  23809. const attributes = json.data.attributes;
  23810. for (const key in attributes) {
  23811. const attribute = attributes[key];
  23812. let bufferAttribute;
  23813. if (attribute.isInterleavedBufferAttribute) {
  23814. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  23815. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  23816. } else {
  23817. const typedArray = getTypedArray(attribute.type, attribute.array);
  23818. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  23819. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  23820. }
  23821. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  23822. if (attribute.usage !== undefined) bufferAttribute.setUsage(attribute.usage);
  23823. if (attribute.updateRange !== undefined) {
  23824. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  23825. bufferAttribute.updateRange.count = attribute.updateRange.count;
  23826. }
  23827. geometry.setAttribute(key, bufferAttribute);
  23828. }
  23829. const morphAttributes = json.data.morphAttributes;
  23830. if (morphAttributes) {
  23831. for (const key in morphAttributes) {
  23832. const attributeArray = morphAttributes[key];
  23833. const array = [];
  23834. for (let i = 0, il = attributeArray.length; i < il; i++) {
  23835. const attribute = attributeArray[i];
  23836. let bufferAttribute;
  23837. if (attribute.isInterleavedBufferAttribute) {
  23838. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  23839. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  23840. } else {
  23841. const typedArray = getTypedArray(attribute.type, attribute.array);
  23842. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  23843. }
  23844. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  23845. array.push(bufferAttribute);
  23846. }
  23847. geometry.morphAttributes[key] = array;
  23848. }
  23849. }
  23850. const morphTargetsRelative = json.data.morphTargetsRelative;
  23851. if (morphTargetsRelative) {
  23852. geometry.morphTargetsRelative = true;
  23853. }
  23854. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  23855. if (groups !== undefined) {
  23856. for (let i = 0, n = groups.length; i !== n; ++i) {
  23857. const group = groups[i];
  23858. geometry.addGroup(group.start, group.count, group.materialIndex);
  23859. }
  23860. }
  23861. const boundingSphere = json.data.boundingSphere;
  23862. if (boundingSphere !== undefined) {
  23863. const center = new Vector3();
  23864. if (boundingSphere.center !== undefined) {
  23865. center.fromArray(boundingSphere.center);
  23866. }
  23867. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  23868. }
  23869. if (json.name) geometry.name = json.name;
  23870. if (json.userData) geometry.userData = json.userData;
  23871. return geometry;
  23872. }
  23873. }
  23874. class ObjectLoader extends Loader {
  23875. constructor(manager) {
  23876. super(manager);
  23877. }
  23878. load(url, onLoad, onProgress, onError) {
  23879. const scope = this;
  23880. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  23881. this.resourcePath = this.resourcePath || path;
  23882. const loader = new FileLoader(this.manager);
  23883. loader.setPath(this.path);
  23884. loader.setRequestHeader(this.requestHeader);
  23885. loader.setWithCredentials(this.withCredentials);
  23886. loader.load(url, function (text) {
  23887. let json = null;
  23888. try {
  23889. json = JSON.parse(text);
  23890. } catch (error) {
  23891. if (onError !== undefined) onError(error);
  23892. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  23893. return;
  23894. }
  23895. const metadata = json.metadata;
  23896. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  23897. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  23898. return;
  23899. }
  23900. scope.parse(json, onLoad);
  23901. }, onProgress, onError);
  23902. }
  23903. async loadAsync(url, onProgress) {
  23904. const scope = this;
  23905. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  23906. this.resourcePath = this.resourcePath || path;
  23907. const loader = new FileLoader(this.manager);
  23908. loader.setPath(this.path);
  23909. loader.setRequestHeader(this.requestHeader);
  23910. loader.setWithCredentials(this.withCredentials);
  23911. const text = await loader.loadAsync(url, onProgress);
  23912. const json = JSON.parse(text);
  23913. const metadata = json.metadata;
  23914. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  23915. throw new Error('THREE.ObjectLoader: Can\'t load ' + url);
  23916. }
  23917. return await scope.parseAsync(json);
  23918. }
  23919. parse(json, onLoad) {
  23920. const animations = this.parseAnimations(json.animations);
  23921. const shapes = this.parseShapes(json.shapes);
  23922. const geometries = this.parseGeometries(json.geometries, shapes);
  23923. const images = this.parseImages(json.images, function () {
  23924. if (onLoad !== undefined) onLoad(object);
  23925. });
  23926. const textures = this.parseTextures(json.textures, images);
  23927. const materials = this.parseMaterials(json.materials, textures);
  23928. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  23929. const skeletons = this.parseSkeletons(json.skeletons, object);
  23930. this.bindSkeletons(object, skeletons); //
  23931. if (onLoad !== undefined) {
  23932. let hasImages = false;
  23933. for (const uuid in images) {
  23934. if (images[uuid] instanceof HTMLImageElement) {
  23935. hasImages = true;
  23936. break;
  23937. }
  23938. }
  23939. if (hasImages === false) onLoad(object);
  23940. }
  23941. return object;
  23942. }
  23943. async parseAsync(json) {
  23944. const animations = this.parseAnimations(json.animations);
  23945. const shapes = this.parseShapes(json.shapes);
  23946. const geometries = this.parseGeometries(json.geometries, shapes);
  23947. const images = await this.parseImagesAsync(json.images);
  23948. const textures = this.parseTextures(json.textures, images);
  23949. const materials = this.parseMaterials(json.materials, textures);
  23950. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  23951. const skeletons = this.parseSkeletons(json.skeletons, object);
  23952. this.bindSkeletons(object, skeletons);
  23953. return object;
  23954. }
  23955. parseShapes(json) {
  23956. const shapes = {};
  23957. if (json !== undefined) {
  23958. for (let i = 0, l = json.length; i < l; i++) {
  23959. const shape = new Shape().fromJSON(json[i]);
  23960. shapes[shape.uuid] = shape;
  23961. }
  23962. }
  23963. return shapes;
  23964. }
  23965. parseSkeletons(json, object) {
  23966. const skeletons = {};
  23967. const bones = {}; // generate bone lookup table
  23968. object.traverse(function (child) {
  23969. if (child.isBone) bones[child.uuid] = child;
  23970. }); // create skeletons
  23971. if (json !== undefined) {
  23972. for (let i = 0, l = json.length; i < l; i++) {
  23973. const skeleton = new Skeleton().fromJSON(json[i], bones);
  23974. skeletons[skeleton.uuid] = skeleton;
  23975. }
  23976. }
  23977. return skeletons;
  23978. }
  23979. parseGeometries(json, shapes) {
  23980. const geometries = {};
  23981. if (json !== undefined) {
  23982. const bufferGeometryLoader = new BufferGeometryLoader();
  23983. for (let i = 0, l = json.length; i < l; i++) {
  23984. let geometry;
  23985. const data = json[i];
  23986. switch (data.type) {
  23987. case 'BufferGeometry':
  23988. case 'InstancedBufferGeometry':
  23989. geometry = bufferGeometryLoader.parse(data);
  23990. break;
  23991. case 'Geometry':
  23992. console.error('THREE.ObjectLoader: The legacy Geometry type is no longer supported.');
  23993. break;
  23994. default:
  23995. if (data.type in Geometries) {
  23996. geometry = Geometries[data.type].fromJSON(data, shapes);
  23997. } else {
  23998. console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data.type}"`);
  23999. }
  24000. }
  24001. geometry.uuid = data.uuid;
  24002. if (data.name !== undefined) geometry.name = data.name;
  24003. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  24004. geometries[data.uuid] = geometry;
  24005. }
  24006. }
  24007. return geometries;
  24008. }
  24009. parseMaterials(json, textures) {
  24010. const cache = {}; // MultiMaterial
  24011. const materials = {};
  24012. if (json !== undefined) {
  24013. const loader = new MaterialLoader();
  24014. loader.setTextures(textures);
  24015. for (let i = 0, l = json.length; i < l; i++) {
  24016. const data = json[i];
  24017. if (data.type === 'MultiMaterial') {
  24018. // Deprecated
  24019. const array = [];
  24020. for (let j = 0; j < data.materials.length; j++) {
  24021. const material = data.materials[j];
  24022. if (cache[material.uuid] === undefined) {
  24023. cache[material.uuid] = loader.parse(material);
  24024. }
  24025. array.push(cache[material.uuid]);
  24026. }
  24027. materials[data.uuid] = array;
  24028. } else {
  24029. if (cache[data.uuid] === undefined) {
  24030. cache[data.uuid] = loader.parse(data);
  24031. }
  24032. materials[data.uuid] = cache[data.uuid];
  24033. }
  24034. }
  24035. }
  24036. return materials;
  24037. }
  24038. parseAnimations(json) {
  24039. const animations = {};
  24040. if (json !== undefined) {
  24041. for (let i = 0; i < json.length; i++) {
  24042. const data = json[i];
  24043. const clip = AnimationClip.parse(data);
  24044. animations[clip.uuid] = clip;
  24045. }
  24046. }
  24047. return animations;
  24048. }
  24049. parseImages(json, onLoad) {
  24050. const scope = this;
  24051. const images = {};
  24052. let loader;
  24053. function loadImage(url) {
  24054. scope.manager.itemStart(url);
  24055. return loader.load(url, function () {
  24056. scope.manager.itemEnd(url);
  24057. }, undefined, function () {
  24058. scope.manager.itemError(url);
  24059. scope.manager.itemEnd(url);
  24060. });
  24061. }
  24062. function deserializeImage(image) {
  24063. if (typeof image === 'string') {
  24064. const url = image;
  24065. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24066. return loadImage(path);
  24067. } else {
  24068. if (image.data) {
  24069. return {
  24070. data: getTypedArray(image.type, image.data),
  24071. width: image.width,
  24072. height: image.height
  24073. };
  24074. } else {
  24075. return null;
  24076. }
  24077. }
  24078. }
  24079. if (json !== undefined && json.length > 0) {
  24080. const manager = new LoadingManager(onLoad);
  24081. loader = new ImageLoader(manager);
  24082. loader.setCrossOrigin(this.crossOrigin);
  24083. for (let i = 0, il = json.length; i < il; i++) {
  24084. const image = json[i];
  24085. const url = image.url;
  24086. if (Array.isArray(url)) {
  24087. // load array of images e.g CubeTexture
  24088. images[image.uuid] = [];
  24089. for (let j = 0, jl = url.length; j < jl; j++) {
  24090. const currentUrl = url[j];
  24091. const deserializedImage = deserializeImage(currentUrl);
  24092. if (deserializedImage !== null) {
  24093. if (deserializedImage instanceof HTMLImageElement) {
  24094. images[image.uuid].push(deserializedImage);
  24095. } else {
  24096. // special case: handle array of data textures for cube textures
  24097. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24098. }
  24099. }
  24100. }
  24101. } else {
  24102. // load single image
  24103. const deserializedImage = deserializeImage(image.url);
  24104. if (deserializedImage !== null) {
  24105. images[image.uuid] = deserializedImage;
  24106. }
  24107. }
  24108. }
  24109. }
  24110. return images;
  24111. }
  24112. async parseImagesAsync(json) {
  24113. const scope = this;
  24114. const images = {};
  24115. let loader;
  24116. async function deserializeImage(image) {
  24117. if (typeof image === 'string') {
  24118. const url = image;
  24119. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24120. return await loader.loadAsync(path);
  24121. } else {
  24122. if (image.data) {
  24123. return {
  24124. data: getTypedArray(image.type, image.data),
  24125. width: image.width,
  24126. height: image.height
  24127. };
  24128. } else {
  24129. return null;
  24130. }
  24131. }
  24132. }
  24133. if (json !== undefined && json.length > 0) {
  24134. loader = new ImageLoader(this.manager);
  24135. loader.setCrossOrigin(this.crossOrigin);
  24136. for (let i = 0, il = json.length; i < il; i++) {
  24137. const image = json[i];
  24138. const url = image.url;
  24139. if (Array.isArray(url)) {
  24140. // load array of images e.g CubeTexture
  24141. images[image.uuid] = [];
  24142. for (let j = 0, jl = url.length; j < jl; j++) {
  24143. const currentUrl = url[j];
  24144. const deserializedImage = await deserializeImage(currentUrl);
  24145. if (deserializedImage !== null) {
  24146. if (deserializedImage instanceof HTMLImageElement) {
  24147. images[image.uuid].push(deserializedImage);
  24148. } else {
  24149. // special case: handle array of data textures for cube textures
  24150. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24151. }
  24152. }
  24153. }
  24154. } else {
  24155. // load single image
  24156. const deserializedImage = await deserializeImage(image.url);
  24157. if (deserializedImage !== null) {
  24158. images[image.uuid] = deserializedImage;
  24159. }
  24160. }
  24161. }
  24162. }
  24163. return images;
  24164. }
  24165. parseTextures(json, images) {
  24166. function parseConstant(value, type) {
  24167. if (typeof value === 'number') return value;
  24168. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24169. return type[value];
  24170. }
  24171. const textures = {};
  24172. if (json !== undefined) {
  24173. for (let i = 0, l = json.length; i < l; i++) {
  24174. const data = json[i];
  24175. if (data.image === undefined) {
  24176. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24177. }
  24178. if (images[data.image] === undefined) {
  24179. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24180. }
  24181. let texture;
  24182. const image = images[data.image];
  24183. if (Array.isArray(image)) {
  24184. texture = new CubeTexture(image);
  24185. if (image.length === 6) texture.needsUpdate = true;
  24186. } else {
  24187. if (image && image.data) {
  24188. texture = new DataTexture(image.data, image.width, image.height);
  24189. } else {
  24190. texture = new Texture(image);
  24191. }
  24192. if (image) texture.needsUpdate = true; // textures can have undefined image data
  24193. }
  24194. texture.uuid = data.uuid;
  24195. if (data.name !== undefined) texture.name = data.name;
  24196. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24197. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24198. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24199. if (data.center !== undefined) texture.center.fromArray(data.center);
  24200. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24201. if (data.wrap !== undefined) {
  24202. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24203. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24204. }
  24205. if (data.format !== undefined) texture.format = data.format;
  24206. if (data.type !== undefined) texture.type = data.type;
  24207. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24208. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24209. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24210. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24211. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24212. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24213. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24214. textures[data.uuid] = texture;
  24215. }
  24216. }
  24217. return textures;
  24218. }
  24219. parseObject(data, geometries, materials, textures, animations) {
  24220. let object;
  24221. function getGeometry(name) {
  24222. if (geometries[name] === undefined) {
  24223. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24224. }
  24225. return geometries[name];
  24226. }
  24227. function getMaterial(name) {
  24228. if (name === undefined) return undefined;
  24229. if (Array.isArray(name)) {
  24230. const array = [];
  24231. for (let i = 0, l = name.length; i < l; i++) {
  24232. const uuid = name[i];
  24233. if (materials[uuid] === undefined) {
  24234. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24235. }
  24236. array.push(materials[uuid]);
  24237. }
  24238. return array;
  24239. }
  24240. if (materials[name] === undefined) {
  24241. console.warn('THREE.ObjectLoader: Undefined material', name);
  24242. }
  24243. return materials[name];
  24244. }
  24245. function getTexture(uuid) {
  24246. if (textures[uuid] === undefined) {
  24247. console.warn('THREE.ObjectLoader: Undefined texture', uuid);
  24248. }
  24249. return textures[uuid];
  24250. }
  24251. let geometry, material;
  24252. switch (data.type) {
  24253. case 'Scene':
  24254. object = new Scene();
  24255. if (data.background !== undefined) {
  24256. if (Number.isInteger(data.background)) {
  24257. object.background = new Color(data.background);
  24258. } else {
  24259. object.background = getTexture(data.background);
  24260. }
  24261. }
  24262. if (data.environment !== undefined) {
  24263. object.environment = getTexture(data.environment);
  24264. }
  24265. if (data.fog !== undefined) {
  24266. if (data.fog.type === 'Fog') {
  24267. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  24268. } else if (data.fog.type === 'FogExp2') {
  24269. object.fog = new FogExp2(data.fog.color, data.fog.density);
  24270. }
  24271. }
  24272. break;
  24273. case 'PerspectiveCamera':
  24274. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  24275. if (data.focus !== undefined) object.focus = data.focus;
  24276. if (data.zoom !== undefined) object.zoom = data.zoom;
  24277. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  24278. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  24279. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24280. break;
  24281. case 'OrthographicCamera':
  24282. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  24283. if (data.zoom !== undefined) object.zoom = data.zoom;
  24284. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24285. break;
  24286. case 'AmbientLight':
  24287. object = new AmbientLight(data.color, data.intensity);
  24288. break;
  24289. case 'DirectionalLight':
  24290. object = new DirectionalLight(data.color, data.intensity);
  24291. break;
  24292. case 'PointLight':
  24293. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  24294. break;
  24295. case 'RectAreaLight':
  24296. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  24297. break;
  24298. case 'SpotLight':
  24299. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  24300. break;
  24301. case 'HemisphereLight':
  24302. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  24303. break;
  24304. case 'LightProbe':
  24305. object = new LightProbe().fromJSON(data);
  24306. break;
  24307. case 'SkinnedMesh':
  24308. geometry = getGeometry(data.geometry);
  24309. material = getMaterial(data.material);
  24310. object = new SkinnedMesh(geometry, material);
  24311. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  24312. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  24313. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  24314. break;
  24315. case 'Mesh':
  24316. geometry = getGeometry(data.geometry);
  24317. material = getMaterial(data.material);
  24318. object = new Mesh(geometry, material);
  24319. break;
  24320. case 'InstancedMesh':
  24321. geometry = getGeometry(data.geometry);
  24322. material = getMaterial(data.material);
  24323. const count = data.count;
  24324. const instanceMatrix = data.instanceMatrix;
  24325. const instanceColor = data.instanceColor;
  24326. object = new InstancedMesh(geometry, material, count);
  24327. object.instanceMatrix = new InstancedBufferAttribute(new Float32Array(instanceMatrix.array), 16);
  24328. if (instanceColor !== undefined) object.instanceColor = new InstancedBufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
  24329. break;
  24330. case 'LOD':
  24331. object = new LOD();
  24332. break;
  24333. case 'Line':
  24334. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  24335. break;
  24336. case 'LineLoop':
  24337. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  24338. break;
  24339. case 'LineSegments':
  24340. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  24341. break;
  24342. case 'PointCloud':
  24343. case 'Points':
  24344. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  24345. break;
  24346. case 'Sprite':
  24347. object = new Sprite(getMaterial(data.material));
  24348. break;
  24349. case 'Group':
  24350. object = new Group();
  24351. break;
  24352. case 'Bone':
  24353. object = new Bone();
  24354. break;
  24355. default:
  24356. object = new Object3D();
  24357. }
  24358. object.uuid = data.uuid;
  24359. if (data.name !== undefined) object.name = data.name;
  24360. if (data.matrix !== undefined) {
  24361. object.matrix.fromArray(data.matrix);
  24362. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  24363. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  24364. } else {
  24365. if (data.position !== undefined) object.position.fromArray(data.position);
  24366. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  24367. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  24368. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  24369. }
  24370. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  24371. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  24372. if (data.shadow) {
  24373. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  24374. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  24375. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  24376. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  24377. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  24378. }
  24379. if (data.visible !== undefined) object.visible = data.visible;
  24380. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  24381. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  24382. if (data.userData !== undefined) object.userData = data.userData;
  24383. if (data.layers !== undefined) object.layers.mask = data.layers;
  24384. if (data.children !== undefined) {
  24385. const children = data.children;
  24386. for (let i = 0; i < children.length; i++) {
  24387. object.add(this.parseObject(children[i], geometries, materials, textures, animations));
  24388. }
  24389. }
  24390. if (data.animations !== undefined) {
  24391. const objectAnimations = data.animations;
  24392. for (let i = 0; i < objectAnimations.length; i++) {
  24393. const uuid = objectAnimations[i];
  24394. object.animations.push(animations[uuid]);
  24395. }
  24396. }
  24397. if (data.type === 'LOD') {
  24398. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  24399. const levels = data.levels;
  24400. for (let l = 0; l < levels.length; l++) {
  24401. const level = levels[l];
  24402. const child = object.getObjectByProperty('uuid', level.object);
  24403. if (child !== undefined) {
  24404. object.addLevel(child, level.distance);
  24405. }
  24406. }
  24407. }
  24408. return object;
  24409. }
  24410. bindSkeletons(object, skeletons) {
  24411. if (Object.keys(skeletons).length === 0) return;
  24412. object.traverse(function (child) {
  24413. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  24414. const skeleton = skeletons[child.skeleton];
  24415. if (skeleton === undefined) {
  24416. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  24417. } else {
  24418. child.bind(skeleton, child.bindMatrix);
  24419. }
  24420. }
  24421. });
  24422. }
  24423. /* DEPRECATED */
  24424. setTexturePath(value) {
  24425. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  24426. return this.setResourcePath(value);
  24427. }
  24428. }
  24429. const TEXTURE_MAPPING = {
  24430. UVMapping: UVMapping,
  24431. CubeReflectionMapping: CubeReflectionMapping,
  24432. CubeRefractionMapping: CubeRefractionMapping,
  24433. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  24434. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  24435. CubeUVReflectionMapping: CubeUVReflectionMapping,
  24436. CubeUVRefractionMapping: CubeUVRefractionMapping
  24437. };
  24438. const TEXTURE_WRAPPING = {
  24439. RepeatWrapping: RepeatWrapping,
  24440. ClampToEdgeWrapping: ClampToEdgeWrapping,
  24441. MirroredRepeatWrapping: MirroredRepeatWrapping
  24442. };
  24443. const TEXTURE_FILTER = {
  24444. NearestFilter: NearestFilter,
  24445. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  24446. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  24447. LinearFilter: LinearFilter,
  24448. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  24449. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  24450. };
  24451. class ImageBitmapLoader extends Loader {
  24452. constructor(manager) {
  24453. super(manager);
  24454. if (typeof createImageBitmap === 'undefined') {
  24455. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  24456. }
  24457. if (typeof fetch === 'undefined') {
  24458. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  24459. }
  24460. this.options = {
  24461. premultiplyAlpha: 'none'
  24462. };
  24463. }
  24464. setOptions(options) {
  24465. this.options = options;
  24466. return this;
  24467. }
  24468. load(url, onLoad, onProgress, onError) {
  24469. if (url === undefined) url = '';
  24470. if (this.path !== undefined) url = this.path + url;
  24471. url = this.manager.resolveURL(url);
  24472. const scope = this;
  24473. const cached = Cache.get(url);
  24474. if (cached !== undefined) {
  24475. scope.manager.itemStart(url);
  24476. setTimeout(function () {
  24477. if (onLoad) onLoad(cached);
  24478. scope.manager.itemEnd(url);
  24479. }, 0);
  24480. return cached;
  24481. }
  24482. const fetchOptions = {};
  24483. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  24484. fetchOptions.headers = this.requestHeader;
  24485. fetch(url, fetchOptions).then(function (res) {
  24486. return res.blob();
  24487. }).then(function (blob) {
  24488. return createImageBitmap(blob, Object.assign(scope.options, {
  24489. colorSpaceConversion: 'none'
  24490. }));
  24491. }).then(function (imageBitmap) {
  24492. Cache.add(url, imageBitmap);
  24493. if (onLoad) onLoad(imageBitmap);
  24494. scope.manager.itemEnd(url);
  24495. }).catch(function (e) {
  24496. if (onError) onError(e);
  24497. scope.manager.itemError(url);
  24498. scope.manager.itemEnd(url);
  24499. });
  24500. scope.manager.itemStart(url);
  24501. }
  24502. }
  24503. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  24504. class ShapePath {
  24505. constructor() {
  24506. this.type = 'ShapePath';
  24507. this.color = new Color();
  24508. this.subPaths = [];
  24509. this.currentPath = null;
  24510. }
  24511. moveTo(x, y) {
  24512. this.currentPath = new Path();
  24513. this.subPaths.push(this.currentPath);
  24514. this.currentPath.moveTo(x, y);
  24515. return this;
  24516. }
  24517. lineTo(x, y) {
  24518. this.currentPath.lineTo(x, y);
  24519. return this;
  24520. }
  24521. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  24522. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  24523. return this;
  24524. }
  24525. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  24526. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  24527. return this;
  24528. }
  24529. splineThru(pts) {
  24530. this.currentPath.splineThru(pts);
  24531. return this;
  24532. }
  24533. toShapes(isCCW, noHoles) {
  24534. function toShapesNoHoles(inSubpaths) {
  24535. const shapes = [];
  24536. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  24537. const tmpPath = inSubpaths[i];
  24538. const tmpShape = new Shape();
  24539. tmpShape.curves = tmpPath.curves;
  24540. shapes.push(tmpShape);
  24541. }
  24542. return shapes;
  24543. }
  24544. function isPointInsidePolygon(inPt, inPolygon) {
  24545. const polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  24546. // toggling of inside/outside at every single! intersection point of an edge
  24547. // with the horizontal line through inPt, left of inPt
  24548. // not counting lowerY endpoints of edges and whole edges on that line
  24549. let inside = false;
  24550. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  24551. let edgeLowPt = inPolygon[p];
  24552. let edgeHighPt = inPolygon[q];
  24553. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  24554. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  24555. if (Math.abs(edgeDy) > Number.EPSILON) {
  24556. // not parallel
  24557. if (edgeDy < 0) {
  24558. edgeLowPt = inPolygon[q];
  24559. edgeDx = -edgeDx;
  24560. edgeHighPt = inPolygon[p];
  24561. edgeDy = -edgeDy;
  24562. }
  24563. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  24564. if (inPt.y === edgeLowPt.y) {
  24565. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  24566. // continue; // no intersection or edgeLowPt => doesn't count !!!
  24567. } else {
  24568. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  24569. if (perpEdge === 0) return true; // inPt is on contour ?
  24570. if (perpEdge < 0) continue;
  24571. inside = !inside; // true intersection left of inPt
  24572. }
  24573. } else {
  24574. // parallel or collinear
  24575. if (inPt.y !== edgeLowPt.y) continue; // parallel
  24576. // edge lies on the same horizontal line as inPt
  24577. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  24578. // continue;
  24579. }
  24580. }
  24581. return inside;
  24582. }
  24583. const isClockWise = ShapeUtils.isClockWise;
  24584. const subPaths = this.subPaths;
  24585. if (subPaths.length === 0) return [];
  24586. if (noHoles === true) return toShapesNoHoles(subPaths);
  24587. let solid, tmpPath, tmpShape;
  24588. const shapes = [];
  24589. if (subPaths.length === 1) {
  24590. tmpPath = subPaths[0];
  24591. tmpShape = new Shape();
  24592. tmpShape.curves = tmpPath.curves;
  24593. shapes.push(tmpShape);
  24594. return shapes;
  24595. }
  24596. let holesFirst = !isClockWise(subPaths[0].getPoints());
  24597. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  24598. const betterShapeHoles = [];
  24599. const newShapes = [];
  24600. let newShapeHoles = [];
  24601. let mainIdx = 0;
  24602. let tmpPoints;
  24603. newShapes[mainIdx] = undefined;
  24604. newShapeHoles[mainIdx] = [];
  24605. for (let i = 0, l = subPaths.length; i < l; i++) {
  24606. tmpPath = subPaths[i];
  24607. tmpPoints = tmpPath.getPoints();
  24608. solid = isClockWise(tmpPoints);
  24609. solid = isCCW ? !solid : solid;
  24610. if (solid) {
  24611. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  24612. newShapes[mainIdx] = {
  24613. s: new Shape(),
  24614. p: tmpPoints
  24615. };
  24616. newShapes[mainIdx].s.curves = tmpPath.curves;
  24617. if (holesFirst) mainIdx++;
  24618. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  24619. } else {
  24620. newShapeHoles[mainIdx].push({
  24621. h: tmpPath,
  24622. p: tmpPoints[0]
  24623. }); //console.log('ccw', i);
  24624. }
  24625. } // only Holes? -> probably all Shapes with wrong orientation
  24626. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  24627. if (newShapes.length > 1) {
  24628. let ambiguous = false;
  24629. const toChange = [];
  24630. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  24631. betterShapeHoles[sIdx] = [];
  24632. }
  24633. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  24634. const sho = newShapeHoles[sIdx];
  24635. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  24636. const ho = sho[hIdx];
  24637. let hole_unassigned = true;
  24638. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  24639. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  24640. if (sIdx !== s2Idx) toChange.push({
  24641. froms: sIdx,
  24642. tos: s2Idx,
  24643. hole: hIdx
  24644. });
  24645. if (hole_unassigned) {
  24646. hole_unassigned = false;
  24647. betterShapeHoles[s2Idx].push(ho);
  24648. } else {
  24649. ambiguous = true;
  24650. }
  24651. }
  24652. }
  24653. if (hole_unassigned) {
  24654. betterShapeHoles[sIdx].push(ho);
  24655. }
  24656. }
  24657. } // console.log("ambiguous: ", ambiguous);
  24658. if (toChange.length > 0) {
  24659. // console.log("to change: ", toChange);
  24660. if (!ambiguous) newShapeHoles = betterShapeHoles;
  24661. }
  24662. }
  24663. let tmpHoles;
  24664. for (let i = 0, il = newShapes.length; i < il; i++) {
  24665. tmpShape = newShapes[i].s;
  24666. shapes.push(tmpShape);
  24667. tmpHoles = newShapeHoles[i];
  24668. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  24669. tmpShape.holes.push(tmpHoles[j].h);
  24670. }
  24671. } //console.log("shape", shapes);
  24672. return shapes;
  24673. }
  24674. }
  24675. class Font {
  24676. constructor(data) {
  24677. this.type = 'Font';
  24678. this.data = data;
  24679. }
  24680. generateShapes(text, size = 100) {
  24681. const shapes = [];
  24682. const paths = createPaths(text, size, this.data);
  24683. for (let p = 0, pl = paths.length; p < pl; p++) {
  24684. Array.prototype.push.apply(shapes, paths[p].toShapes());
  24685. }
  24686. return shapes;
  24687. }
  24688. }
  24689. function createPaths(text, size, data) {
  24690. const chars = Array.from(text);
  24691. const scale = size / data.resolution;
  24692. const line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  24693. const paths = [];
  24694. let offsetX = 0,
  24695. offsetY = 0;
  24696. for (let i = 0; i < chars.length; i++) {
  24697. const char = chars[i];
  24698. if (char === '\n') {
  24699. offsetX = 0;
  24700. offsetY -= line_height;
  24701. } else {
  24702. const ret = createPath(char, scale, offsetX, offsetY, data);
  24703. offsetX += ret.offsetX;
  24704. paths.push(ret.path);
  24705. }
  24706. }
  24707. return paths;
  24708. }
  24709. function createPath(char, scale, offsetX, offsetY, data) {
  24710. const glyph = data.glyphs[char] || data.glyphs['?'];
  24711. if (!glyph) {
  24712. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  24713. return;
  24714. }
  24715. const path = new ShapePath();
  24716. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  24717. if (glyph.o) {
  24718. const outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  24719. for (let i = 0, l = outline.length; i < l;) {
  24720. const action = outline[i++];
  24721. switch (action) {
  24722. case 'm':
  24723. // moveTo
  24724. x = outline[i++] * scale + offsetX;
  24725. y = outline[i++] * scale + offsetY;
  24726. path.moveTo(x, y);
  24727. break;
  24728. case 'l':
  24729. // lineTo
  24730. x = outline[i++] * scale + offsetX;
  24731. y = outline[i++] * scale + offsetY;
  24732. path.lineTo(x, y);
  24733. break;
  24734. case 'q':
  24735. // quadraticCurveTo
  24736. cpx = outline[i++] * scale + offsetX;
  24737. cpy = outline[i++] * scale + offsetY;
  24738. cpx1 = outline[i++] * scale + offsetX;
  24739. cpy1 = outline[i++] * scale + offsetY;
  24740. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  24741. break;
  24742. case 'b':
  24743. // bezierCurveTo
  24744. cpx = outline[i++] * scale + offsetX;
  24745. cpy = outline[i++] * scale + offsetY;
  24746. cpx1 = outline[i++] * scale + offsetX;
  24747. cpy1 = outline[i++] * scale + offsetY;
  24748. cpx2 = outline[i++] * scale + offsetX;
  24749. cpy2 = outline[i++] * scale + offsetY;
  24750. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  24751. break;
  24752. }
  24753. }
  24754. }
  24755. return {
  24756. offsetX: glyph.ha * scale,
  24757. path: path
  24758. };
  24759. }
  24760. Font.prototype.isFont = true;
  24761. class FontLoader extends Loader {
  24762. constructor(manager) {
  24763. super(manager);
  24764. }
  24765. load(url, onLoad, onProgress, onError) {
  24766. const scope = this;
  24767. const loader = new FileLoader(this.manager);
  24768. loader.setPath(this.path);
  24769. loader.setRequestHeader(this.requestHeader);
  24770. loader.setWithCredentials(scope.withCredentials);
  24771. loader.load(url, function (text) {
  24772. let json;
  24773. try {
  24774. json = JSON.parse(text);
  24775. } catch (e) {
  24776. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  24777. json = JSON.parse(text.substring(65, text.length - 2));
  24778. }
  24779. const font = scope.parse(json);
  24780. if (onLoad) onLoad(font);
  24781. }, onProgress, onError);
  24782. }
  24783. parse(json) {
  24784. return new Font(json);
  24785. }
  24786. }
  24787. let _context;
  24788. const AudioContext = {
  24789. getContext: function () {
  24790. if (_context === undefined) {
  24791. _context = new (window.AudioContext || window.webkitAudioContext)();
  24792. }
  24793. return _context;
  24794. },
  24795. setContext: function (value) {
  24796. _context = value;
  24797. }
  24798. };
  24799. class AudioLoader extends Loader {
  24800. constructor(manager) {
  24801. super(manager);
  24802. }
  24803. load(url, onLoad, onProgress, onError) {
  24804. const scope = this;
  24805. const loader = new FileLoader(this.manager);
  24806. loader.setResponseType('arraybuffer');
  24807. loader.setPath(this.path);
  24808. loader.setRequestHeader(this.requestHeader);
  24809. loader.setWithCredentials(this.withCredentials);
  24810. loader.load(url, function (buffer) {
  24811. try {
  24812. // Create a copy of the buffer. The `decodeAudioData` method
  24813. // detaches the buffer when complete, preventing reuse.
  24814. const bufferCopy = buffer.slice(0);
  24815. const context = AudioContext.getContext();
  24816. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  24817. onLoad(audioBuffer);
  24818. });
  24819. } catch (e) {
  24820. if (onError) {
  24821. onError(e);
  24822. } else {
  24823. console.error(e);
  24824. }
  24825. scope.manager.itemError(url);
  24826. }
  24827. }, onProgress, onError);
  24828. }
  24829. }
  24830. class HemisphereLightProbe extends LightProbe {
  24831. constructor(skyColor, groundColor, intensity = 1) {
  24832. super(undefined, intensity);
  24833. const color1 = new Color().set(skyColor);
  24834. const color2 = new Color().set(groundColor);
  24835. const sky = new Vector3(color1.r, color1.g, color1.b);
  24836. const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  24837. const c0 = Math.sqrt(Math.PI);
  24838. const c1 = c0 * Math.sqrt(0.75);
  24839. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  24840. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  24841. }
  24842. }
  24843. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  24844. class AmbientLightProbe extends LightProbe {
  24845. constructor(color, intensity = 1) {
  24846. super(undefined, intensity);
  24847. const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  24848. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  24849. }
  24850. }
  24851. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  24852. const _eyeRight = /*@__PURE__*/new Matrix4();
  24853. const _eyeLeft = /*@__PURE__*/new Matrix4();
  24854. class StereoCamera {
  24855. constructor() {
  24856. this.type = 'StereoCamera';
  24857. this.aspect = 1;
  24858. this.eyeSep = 0.064;
  24859. this.cameraL = new PerspectiveCamera();
  24860. this.cameraL.layers.enable(1);
  24861. this.cameraL.matrixAutoUpdate = false;
  24862. this.cameraR = new PerspectiveCamera();
  24863. this.cameraR.layers.enable(2);
  24864. this.cameraR.matrixAutoUpdate = false;
  24865. this._cache = {
  24866. focus: null,
  24867. fov: null,
  24868. aspect: null,
  24869. near: null,
  24870. far: null,
  24871. zoom: null,
  24872. eyeSep: null
  24873. };
  24874. }
  24875. update(camera) {
  24876. const cache = this._cache;
  24877. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  24878. if (needsUpdate) {
  24879. cache.focus = camera.focus;
  24880. cache.fov = camera.fov;
  24881. cache.aspect = camera.aspect * this.aspect;
  24882. cache.near = camera.near;
  24883. cache.far = camera.far;
  24884. cache.zoom = camera.zoom;
  24885. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  24886. // http://paulbourke.net/stereographics/stereorender/
  24887. const projectionMatrix = camera.projectionMatrix.clone();
  24888. const eyeSepHalf = cache.eyeSep / 2;
  24889. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  24890. const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom;
  24891. let xmin, xmax; // translate xOffset
  24892. _eyeLeft.elements[12] = -eyeSepHalf;
  24893. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  24894. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  24895. xmax = ymax * cache.aspect + eyeSepOnProjection;
  24896. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  24897. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  24898. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  24899. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  24900. xmax = ymax * cache.aspect - eyeSepOnProjection;
  24901. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  24902. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  24903. this.cameraR.projectionMatrix.copy(projectionMatrix);
  24904. }
  24905. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  24906. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  24907. }
  24908. }
  24909. class Clock {
  24910. constructor(autoStart = true) {
  24911. this.autoStart = autoStart;
  24912. this.startTime = 0;
  24913. this.oldTime = 0;
  24914. this.elapsedTime = 0;
  24915. this.running = false;
  24916. }
  24917. start() {
  24918. this.startTime = now();
  24919. this.oldTime = this.startTime;
  24920. this.elapsedTime = 0;
  24921. this.running = true;
  24922. }
  24923. stop() {
  24924. this.getElapsedTime();
  24925. this.running = false;
  24926. this.autoStart = false;
  24927. }
  24928. getElapsedTime() {
  24929. this.getDelta();
  24930. return this.elapsedTime;
  24931. }
  24932. getDelta() {
  24933. let diff = 0;
  24934. if (this.autoStart && !this.running) {
  24935. this.start();
  24936. return 0;
  24937. }
  24938. if (this.running) {
  24939. const newTime = now();
  24940. diff = (newTime - this.oldTime) / 1000;
  24941. this.oldTime = newTime;
  24942. this.elapsedTime += diff;
  24943. }
  24944. return diff;
  24945. }
  24946. }
  24947. function now() {
  24948. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  24949. }
  24950. const _position$1 = /*@__PURE__*/new Vector3();
  24951. const _quaternion$1 = /*@__PURE__*/new Quaternion();
  24952. const _scale$1 = /*@__PURE__*/new Vector3();
  24953. const _orientation$1 = /*@__PURE__*/new Vector3();
  24954. class AudioListener extends Object3D {
  24955. constructor() {
  24956. super();
  24957. this.type = 'AudioListener';
  24958. this.context = AudioContext.getContext();
  24959. this.gain = this.context.createGain();
  24960. this.gain.connect(this.context.destination);
  24961. this.filter = null;
  24962. this.timeDelta = 0; // private
  24963. this._clock = new Clock();
  24964. }
  24965. getInput() {
  24966. return this.gain;
  24967. }
  24968. removeFilter() {
  24969. if (this.filter !== null) {
  24970. this.gain.disconnect(this.filter);
  24971. this.filter.disconnect(this.context.destination);
  24972. this.gain.connect(this.context.destination);
  24973. this.filter = null;
  24974. }
  24975. return this;
  24976. }
  24977. getFilter() {
  24978. return this.filter;
  24979. }
  24980. setFilter(value) {
  24981. if (this.filter !== null) {
  24982. this.gain.disconnect(this.filter);
  24983. this.filter.disconnect(this.context.destination);
  24984. } else {
  24985. this.gain.disconnect(this.context.destination);
  24986. }
  24987. this.filter = value;
  24988. this.gain.connect(this.filter);
  24989. this.filter.connect(this.context.destination);
  24990. return this;
  24991. }
  24992. getMasterVolume() {
  24993. return this.gain.gain.value;
  24994. }
  24995. setMasterVolume(value) {
  24996. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  24997. return this;
  24998. }
  24999. updateMatrixWorld(force) {
  25000. super.updateMatrixWorld(force);
  25001. const listener = this.context.listener;
  25002. const up = this.up;
  25003. this.timeDelta = this._clock.getDelta();
  25004. this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
  25005. _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
  25006. if (listener.positionX) {
  25007. // code path for Chrome (see #14393)
  25008. const endTime = this.context.currentTime + this.timeDelta;
  25009. listener.positionX.linearRampToValueAtTime(_position$1.x, endTime);
  25010. listener.positionY.linearRampToValueAtTime(_position$1.y, endTime);
  25011. listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime);
  25012. listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime);
  25013. listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
  25014. listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  25015. listener.upX.linearRampToValueAtTime(up.x, endTime);
  25016. listener.upY.linearRampToValueAtTime(up.y, endTime);
  25017. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  25018. } else {
  25019. listener.setPosition(_position$1.x, _position$1.y, _position$1.z);
  25020. listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
  25021. }
  25022. }
  25023. }
  25024. class Audio extends Object3D {
  25025. constructor(listener) {
  25026. super();
  25027. this.type = 'Audio';
  25028. this.listener = listener;
  25029. this.context = listener.context;
  25030. this.gain = this.context.createGain();
  25031. this.gain.connect(listener.getInput());
  25032. this.autoplay = false;
  25033. this.buffer = null;
  25034. this.detune = 0;
  25035. this.loop = false;
  25036. this.loopStart = 0;
  25037. this.loopEnd = 0;
  25038. this.offset = 0;
  25039. this.duration = undefined;
  25040. this.playbackRate = 1;
  25041. this.isPlaying = false;
  25042. this.hasPlaybackControl = true;
  25043. this.source = null;
  25044. this.sourceType = 'empty';
  25045. this._startedAt = 0;
  25046. this._progress = 0;
  25047. this._connected = false;
  25048. this.filters = [];
  25049. }
  25050. getOutput() {
  25051. return this.gain;
  25052. }
  25053. setNodeSource(audioNode) {
  25054. this.hasPlaybackControl = false;
  25055. this.sourceType = 'audioNode';
  25056. this.source = audioNode;
  25057. this.connect();
  25058. return this;
  25059. }
  25060. setMediaElementSource(mediaElement) {
  25061. this.hasPlaybackControl = false;
  25062. this.sourceType = 'mediaNode';
  25063. this.source = this.context.createMediaElementSource(mediaElement);
  25064. this.connect();
  25065. return this;
  25066. }
  25067. setMediaStreamSource(mediaStream) {
  25068. this.hasPlaybackControl = false;
  25069. this.sourceType = 'mediaStreamNode';
  25070. this.source = this.context.createMediaStreamSource(mediaStream);
  25071. this.connect();
  25072. return this;
  25073. }
  25074. setBuffer(audioBuffer) {
  25075. this.buffer = audioBuffer;
  25076. this.sourceType = 'buffer';
  25077. if (this.autoplay) this.play();
  25078. return this;
  25079. }
  25080. play(delay = 0) {
  25081. if (this.isPlaying === true) {
  25082. console.warn('THREE.Audio: Audio is already playing.');
  25083. return;
  25084. }
  25085. if (this.hasPlaybackControl === false) {
  25086. console.warn('THREE.Audio: this Audio has no playback control.');
  25087. return;
  25088. }
  25089. this._startedAt = this.context.currentTime + delay;
  25090. const source = this.context.createBufferSource();
  25091. source.buffer = this.buffer;
  25092. source.loop = this.loop;
  25093. source.loopStart = this.loopStart;
  25094. source.loopEnd = this.loopEnd;
  25095. source.onended = this.onEnded.bind(this);
  25096. source.start(this._startedAt, this._progress + this.offset, this.duration);
  25097. this.isPlaying = true;
  25098. this.source = source;
  25099. this.setDetune(this.detune);
  25100. this.setPlaybackRate(this.playbackRate);
  25101. return this.connect();
  25102. }
  25103. pause() {
  25104. if (this.hasPlaybackControl === false) {
  25105. console.warn('THREE.Audio: this Audio has no playback control.');
  25106. return;
  25107. }
  25108. if (this.isPlaying === true) {
  25109. // update current progress
  25110. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  25111. if (this.loop === true) {
  25112. // ensure _progress does not exceed duration with looped audios
  25113. this._progress = this._progress % (this.duration || this.buffer.duration);
  25114. }
  25115. this.source.stop();
  25116. this.source.onended = null;
  25117. this.isPlaying = false;
  25118. }
  25119. return this;
  25120. }
  25121. stop() {
  25122. if (this.hasPlaybackControl === false) {
  25123. console.warn('THREE.Audio: this Audio has no playback control.');
  25124. return;
  25125. }
  25126. this._progress = 0;
  25127. this.source.stop();
  25128. this.source.onended = null;
  25129. this.isPlaying = false;
  25130. return this;
  25131. }
  25132. connect() {
  25133. if (this.filters.length > 0) {
  25134. this.source.connect(this.filters[0]);
  25135. for (let i = 1, l = this.filters.length; i < l; i++) {
  25136. this.filters[i - 1].connect(this.filters[i]);
  25137. }
  25138. this.filters[this.filters.length - 1].connect(this.getOutput());
  25139. } else {
  25140. this.source.connect(this.getOutput());
  25141. }
  25142. this._connected = true;
  25143. return this;
  25144. }
  25145. disconnect() {
  25146. if (this.filters.length > 0) {
  25147. this.source.disconnect(this.filters[0]);
  25148. for (let i = 1, l = this.filters.length; i < l; i++) {
  25149. this.filters[i - 1].disconnect(this.filters[i]);
  25150. }
  25151. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  25152. } else {
  25153. this.source.disconnect(this.getOutput());
  25154. }
  25155. this._connected = false;
  25156. return this;
  25157. }
  25158. getFilters() {
  25159. return this.filters;
  25160. }
  25161. setFilters(value) {
  25162. if (!value) value = [];
  25163. if (this._connected === true) {
  25164. this.disconnect();
  25165. this.filters = value.slice();
  25166. this.connect();
  25167. } else {
  25168. this.filters = value.slice();
  25169. }
  25170. return this;
  25171. }
  25172. setDetune(value) {
  25173. this.detune = value;
  25174. if (this.source.detune === undefined) return; // only set detune when available
  25175. if (this.isPlaying === true) {
  25176. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  25177. }
  25178. return this;
  25179. }
  25180. getDetune() {
  25181. return this.detune;
  25182. }
  25183. getFilter() {
  25184. return this.getFilters()[0];
  25185. }
  25186. setFilter(filter) {
  25187. return this.setFilters(filter ? [filter] : []);
  25188. }
  25189. setPlaybackRate(value) {
  25190. if (this.hasPlaybackControl === false) {
  25191. console.warn('THREE.Audio: this Audio has no playback control.');
  25192. return;
  25193. }
  25194. this.playbackRate = value;
  25195. if (this.isPlaying === true) {
  25196. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  25197. }
  25198. return this;
  25199. }
  25200. getPlaybackRate() {
  25201. return this.playbackRate;
  25202. }
  25203. onEnded() {
  25204. this.isPlaying = false;
  25205. }
  25206. getLoop() {
  25207. if (this.hasPlaybackControl === false) {
  25208. console.warn('THREE.Audio: this Audio has no playback control.');
  25209. return false;
  25210. }
  25211. return this.loop;
  25212. }
  25213. setLoop(value) {
  25214. if (this.hasPlaybackControl === false) {
  25215. console.warn('THREE.Audio: this Audio has no playback control.');
  25216. return;
  25217. }
  25218. this.loop = value;
  25219. if (this.isPlaying === true) {
  25220. this.source.loop = this.loop;
  25221. }
  25222. return this;
  25223. }
  25224. setLoopStart(value) {
  25225. this.loopStart = value;
  25226. return this;
  25227. }
  25228. setLoopEnd(value) {
  25229. this.loopEnd = value;
  25230. return this;
  25231. }
  25232. getVolume() {
  25233. return this.gain.gain.value;
  25234. }
  25235. setVolume(value) {
  25236. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25237. return this;
  25238. }
  25239. }
  25240. const _position = /*@__PURE__*/new Vector3();
  25241. const _quaternion = /*@__PURE__*/new Quaternion();
  25242. const _scale = /*@__PURE__*/new Vector3();
  25243. const _orientation = /*@__PURE__*/new Vector3();
  25244. class PositionalAudio extends Audio {
  25245. constructor(listener) {
  25246. super(listener);
  25247. this.panner = this.context.createPanner();
  25248. this.panner.panningModel = 'HRTF';
  25249. this.panner.connect(this.gain);
  25250. }
  25251. getOutput() {
  25252. return this.panner;
  25253. }
  25254. getRefDistance() {
  25255. return this.panner.refDistance;
  25256. }
  25257. setRefDistance(value) {
  25258. this.panner.refDistance = value;
  25259. return this;
  25260. }
  25261. getRolloffFactor() {
  25262. return this.panner.rolloffFactor;
  25263. }
  25264. setRolloffFactor(value) {
  25265. this.panner.rolloffFactor = value;
  25266. return this;
  25267. }
  25268. getDistanceModel() {
  25269. return this.panner.distanceModel;
  25270. }
  25271. setDistanceModel(value) {
  25272. this.panner.distanceModel = value;
  25273. return this;
  25274. }
  25275. getMaxDistance() {
  25276. return this.panner.maxDistance;
  25277. }
  25278. setMaxDistance(value) {
  25279. this.panner.maxDistance = value;
  25280. return this;
  25281. }
  25282. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25283. this.panner.coneInnerAngle = coneInnerAngle;
  25284. this.panner.coneOuterAngle = coneOuterAngle;
  25285. this.panner.coneOuterGain = coneOuterGain;
  25286. return this;
  25287. }
  25288. updateMatrixWorld(force) {
  25289. super.updateMatrixWorld(force);
  25290. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  25291. this.matrixWorld.decompose(_position, _quaternion, _scale);
  25292. _orientation.set(0, 0, 1).applyQuaternion(_quaternion);
  25293. const panner = this.panner;
  25294. if (panner.positionX) {
  25295. // code path for Chrome and Firefox (see #14393)
  25296. const endTime = this.context.currentTime + this.listener.timeDelta;
  25297. panner.positionX.linearRampToValueAtTime(_position.x, endTime);
  25298. panner.positionY.linearRampToValueAtTime(_position.y, endTime);
  25299. panner.positionZ.linearRampToValueAtTime(_position.z, endTime);
  25300. panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime);
  25301. panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime);
  25302. panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime);
  25303. } else {
  25304. panner.setPosition(_position.x, _position.y, _position.z);
  25305. panner.setOrientation(_orientation.x, _orientation.y, _orientation.z);
  25306. }
  25307. }
  25308. }
  25309. class AudioAnalyser {
  25310. constructor(audio, fftSize = 2048) {
  25311. this.analyser = audio.context.createAnalyser();
  25312. this.analyser.fftSize = fftSize;
  25313. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  25314. audio.getOutput().connect(this.analyser);
  25315. }
  25316. getFrequencyData() {
  25317. this.analyser.getByteFrequencyData(this.data);
  25318. return this.data;
  25319. }
  25320. getAverageFrequency() {
  25321. let value = 0;
  25322. const data = this.getFrequencyData();
  25323. for (let i = 0; i < data.length; i++) {
  25324. value += data[i];
  25325. }
  25326. return value / data.length;
  25327. }
  25328. }
  25329. class PropertyMixer {
  25330. constructor(binding, typeName, valueSize) {
  25331. this.binding = binding;
  25332. this.valueSize = valueSize;
  25333. let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25334. //
  25335. // interpolators can use .buffer as their .result
  25336. // the data then goes to 'incoming'
  25337. //
  25338. // 'accu0' and 'accu1' are used frame-interleaved for
  25339. // the cumulative result and are compared to detect
  25340. // changes
  25341. //
  25342. // 'orig' stores the original state of the property
  25343. //
  25344. // 'add' is used for additive cumulative results
  25345. //
  25346. // 'work' is optional and is only present for quaternion types. It is used
  25347. // to store intermediate quaternion multiplication results
  25348. switch (typeName) {
  25349. case 'quaternion':
  25350. mixFunction = this._slerp;
  25351. mixFunctionAdditive = this._slerpAdditive;
  25352. setIdentity = this._setAdditiveIdentityQuaternion;
  25353. this.buffer = new Float64Array(valueSize * 6);
  25354. this._workIndex = 5;
  25355. break;
  25356. case 'string':
  25357. case 'bool':
  25358. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  25359. // additive is not relevant for non-numeric types
  25360. mixFunctionAdditive = this._select;
  25361. setIdentity = this._setAdditiveIdentityOther;
  25362. this.buffer = new Array(valueSize * 5);
  25363. break;
  25364. default:
  25365. mixFunction = this._lerp;
  25366. mixFunctionAdditive = this._lerpAdditive;
  25367. setIdentity = this._setAdditiveIdentityNumeric;
  25368. this.buffer = new Float64Array(valueSize * 5);
  25369. }
  25370. this._mixBufferRegion = mixFunction;
  25371. this._mixBufferRegionAdditive = mixFunctionAdditive;
  25372. this._setIdentity = setIdentity;
  25373. this._origIndex = 3;
  25374. this._addIndex = 4;
  25375. this.cumulativeWeight = 0;
  25376. this.cumulativeWeightAdditive = 0;
  25377. this.useCount = 0;
  25378. this.referenceCount = 0;
  25379. } // accumulate data in the 'incoming' region into 'accu<i>'
  25380. accumulate(accuIndex, weight) {
  25381. // note: happily accumulating nothing when weight = 0, the caller knows
  25382. // the weight and shouldn't have made the call in the first place
  25383. const buffer = this.buffer,
  25384. stride = this.valueSize,
  25385. offset = accuIndex * stride + stride;
  25386. let currentWeight = this.cumulativeWeight;
  25387. if (currentWeight === 0) {
  25388. // accuN := incoming * weight
  25389. for (let i = 0; i !== stride; ++i) {
  25390. buffer[offset + i] = buffer[i];
  25391. }
  25392. currentWeight = weight;
  25393. } else {
  25394. // accuN := accuN + incoming * weight
  25395. currentWeight += weight;
  25396. const mix = weight / currentWeight;
  25397. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  25398. }
  25399. this.cumulativeWeight = currentWeight;
  25400. } // accumulate data in the 'incoming' region into 'add'
  25401. accumulateAdditive(weight) {
  25402. const buffer = this.buffer,
  25403. stride = this.valueSize,
  25404. offset = stride * this._addIndex;
  25405. if (this.cumulativeWeightAdditive === 0) {
  25406. // add = identity
  25407. this._setIdentity();
  25408. } // add := add + incoming * weight
  25409. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  25410. this.cumulativeWeightAdditive += weight;
  25411. } // apply the state of 'accu<i>' to the binding when accus differ
  25412. apply(accuIndex) {
  25413. const stride = this.valueSize,
  25414. buffer = this.buffer,
  25415. offset = accuIndex * stride + stride,
  25416. weight = this.cumulativeWeight,
  25417. weightAdditive = this.cumulativeWeightAdditive,
  25418. binding = this.binding;
  25419. this.cumulativeWeight = 0;
  25420. this.cumulativeWeightAdditive = 0;
  25421. if (weight < 1) {
  25422. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25423. const originalValueOffset = stride * this._origIndex;
  25424. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  25425. }
  25426. if (weightAdditive > 0) {
  25427. // accuN := accuN + additive accuN
  25428. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  25429. }
  25430. for (let i = stride, e = stride + stride; i !== e; ++i) {
  25431. if (buffer[i] !== buffer[i + stride]) {
  25432. // value has changed -> update scene graph
  25433. binding.setValue(buffer, offset);
  25434. break;
  25435. }
  25436. }
  25437. } // remember the state of the bound property and copy it to both accus
  25438. saveOriginalState() {
  25439. const binding = this.binding;
  25440. const buffer = this.buffer,
  25441. stride = this.valueSize,
  25442. originalValueOffset = stride * this._origIndex;
  25443. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  25444. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  25445. buffer[i] = buffer[originalValueOffset + i % stride];
  25446. } // Add to identity for additive
  25447. this._setIdentity();
  25448. this.cumulativeWeight = 0;
  25449. this.cumulativeWeightAdditive = 0;
  25450. } // apply the state previously taken via 'saveOriginalState' to the binding
  25451. restoreOriginalState() {
  25452. const originalValueOffset = this.valueSize * 3;
  25453. this.binding.setValue(this.buffer, originalValueOffset);
  25454. }
  25455. _setAdditiveIdentityNumeric() {
  25456. const startIndex = this._addIndex * this.valueSize;
  25457. const endIndex = startIndex + this.valueSize;
  25458. for (let i = startIndex; i < endIndex; i++) {
  25459. this.buffer[i] = 0;
  25460. }
  25461. }
  25462. _setAdditiveIdentityQuaternion() {
  25463. this._setAdditiveIdentityNumeric();
  25464. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  25465. }
  25466. _setAdditiveIdentityOther() {
  25467. const startIndex = this._origIndex * this.valueSize;
  25468. const targetIndex = this._addIndex * this.valueSize;
  25469. for (let i = 0; i < this.valueSize; i++) {
  25470. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  25471. }
  25472. } // mix functions
  25473. _select(buffer, dstOffset, srcOffset, t, stride) {
  25474. if (t >= 0.5) {
  25475. for (let i = 0; i !== stride; ++i) {
  25476. buffer[dstOffset + i] = buffer[srcOffset + i];
  25477. }
  25478. }
  25479. }
  25480. _slerp(buffer, dstOffset, srcOffset, t) {
  25481. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  25482. }
  25483. _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25484. const workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  25485. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  25486. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  25487. }
  25488. _lerp(buffer, dstOffset, srcOffset, t, stride) {
  25489. const s = 1 - t;
  25490. for (let i = 0; i !== stride; ++i) {
  25491. const j = dstOffset + i;
  25492. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  25493. }
  25494. }
  25495. _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25496. for (let i = 0; i !== stride; ++i) {
  25497. const j = dstOffset + i;
  25498. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  25499. }
  25500. }
  25501. }
  25502. // Characters [].:/ are reserved for track binding syntax.
  25503. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  25504. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  25505. // only latin characters, and the unicode \p{L} is not yet supported. So
  25506. // instead, we exclude reserved characters and match everything else.
  25507. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  25508. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  25509. // be matched to parse the rest of the track name.
  25510. const _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  25511. const _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  25512. // characters. Accessor may contain any character except closing bracket.
  25513. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  25514. // contain any non-bracket characters.
  25515. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  25516. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  25517. const _supportedObjectNames = ['material', 'materials', 'bones'];
  25518. class Composite {
  25519. constructor(targetGroup, path, optionalParsedPath) {
  25520. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  25521. this._targetGroup = targetGroup;
  25522. this._bindings = targetGroup.subscribe_(path, parsedPath);
  25523. }
  25524. getValue(array, offset) {
  25525. this.bind(); // bind all binding
  25526. const firstValidIndex = this._targetGroup.nCachedObjects_,
  25527. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  25528. if (binding !== undefined) binding.getValue(array, offset);
  25529. }
  25530. setValue(array, offset) {
  25531. const bindings = this._bindings;
  25532. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25533. bindings[i].setValue(array, offset);
  25534. }
  25535. }
  25536. bind() {
  25537. const bindings = this._bindings;
  25538. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25539. bindings[i].bind();
  25540. }
  25541. }
  25542. unbind() {
  25543. const bindings = this._bindings;
  25544. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25545. bindings[i].unbind();
  25546. }
  25547. }
  25548. } // Note: This class uses a State pattern on a per-method basis:
  25549. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  25550. // prototype version of these methods with one that represents
  25551. // the bound state. When the property is not found, the methods
  25552. // become no-ops.
  25553. class PropertyBinding {
  25554. constructor(rootNode, path, parsedPath) {
  25555. this.path = path;
  25556. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  25557. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  25558. this.rootNode = rootNode; // initial state of these methods that calls 'bind'
  25559. this.getValue = this._getValue_unbound;
  25560. this.setValue = this._setValue_unbound;
  25561. }
  25562. static create(root, path, parsedPath) {
  25563. if (!(root && root.isAnimationObjectGroup)) {
  25564. return new PropertyBinding(root, path, parsedPath);
  25565. } else {
  25566. return new PropertyBinding.Composite(root, path, parsedPath);
  25567. }
  25568. }
  25569. /**
  25570. * Replaces spaces with underscores and removes unsupported characters from
  25571. * node names, to ensure compatibility with parseTrackName().
  25572. *
  25573. * @param {string} name Node name to be sanitized.
  25574. * @return {string}
  25575. */
  25576. static sanitizeNodeName(name) {
  25577. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  25578. }
  25579. static parseTrackName(trackName) {
  25580. const matches = _trackRe.exec(trackName);
  25581. if (!matches) {
  25582. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  25583. }
  25584. const results = {
  25585. // directoryName: matches[ 1 ], // (tschw) currently unused
  25586. nodeName: matches[2],
  25587. objectName: matches[3],
  25588. objectIndex: matches[4],
  25589. propertyName: matches[5],
  25590. // required
  25591. propertyIndex: matches[6]
  25592. };
  25593. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  25594. if (lastDot !== undefined && lastDot !== -1) {
  25595. const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  25596. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  25597. // 'bar' could be the objectName, or part of a nodeName (which can
  25598. // include '.' characters).
  25599. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  25600. results.nodeName = results.nodeName.substring(0, lastDot);
  25601. results.objectName = objectName;
  25602. }
  25603. }
  25604. if (results.propertyName === null || results.propertyName.length === 0) {
  25605. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  25606. }
  25607. return results;
  25608. }
  25609. static findNode(root, nodeName) {
  25610. if (!nodeName || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  25611. return root;
  25612. } // search into skeleton bones.
  25613. if (root.skeleton) {
  25614. const bone = root.skeleton.getBoneByName(nodeName);
  25615. if (bone !== undefined) {
  25616. return bone;
  25617. }
  25618. } // search into node subtree.
  25619. if (root.children) {
  25620. const searchNodeSubtree = function (children) {
  25621. for (let i = 0; i < children.length; i++) {
  25622. const childNode = children[i];
  25623. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  25624. return childNode;
  25625. }
  25626. const result = searchNodeSubtree(childNode.children);
  25627. if (result) return result;
  25628. }
  25629. return null;
  25630. };
  25631. const subTreeNode = searchNodeSubtree(root.children);
  25632. if (subTreeNode) {
  25633. return subTreeNode;
  25634. }
  25635. }
  25636. return null;
  25637. } // these are used to "bind" a nonexistent property
  25638. _getValue_unavailable() {}
  25639. _setValue_unavailable() {} // Getters
  25640. _getValue_direct(buffer, offset) {
  25641. buffer[offset] = this.targetObject[this.propertyName];
  25642. }
  25643. _getValue_array(buffer, offset) {
  25644. const source = this.resolvedProperty;
  25645. for (let i = 0, n = source.length; i !== n; ++i) {
  25646. buffer[offset++] = source[i];
  25647. }
  25648. }
  25649. _getValue_arrayElement(buffer, offset) {
  25650. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  25651. }
  25652. _getValue_toArray(buffer, offset) {
  25653. this.resolvedProperty.toArray(buffer, offset);
  25654. } // Direct
  25655. _setValue_direct(buffer, offset) {
  25656. this.targetObject[this.propertyName] = buffer[offset];
  25657. }
  25658. _setValue_direct_setNeedsUpdate(buffer, offset) {
  25659. this.targetObject[this.propertyName] = buffer[offset];
  25660. this.targetObject.needsUpdate = true;
  25661. }
  25662. _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  25663. this.targetObject[this.propertyName] = buffer[offset];
  25664. this.targetObject.matrixWorldNeedsUpdate = true;
  25665. } // EntireArray
  25666. _setValue_array(buffer, offset) {
  25667. const dest = this.resolvedProperty;
  25668. for (let i = 0, n = dest.length; i !== n; ++i) {
  25669. dest[i] = buffer[offset++];
  25670. }
  25671. }
  25672. _setValue_array_setNeedsUpdate(buffer, offset) {
  25673. const dest = this.resolvedProperty;
  25674. for (let i = 0, n = dest.length; i !== n; ++i) {
  25675. dest[i] = buffer[offset++];
  25676. }
  25677. this.targetObject.needsUpdate = true;
  25678. }
  25679. _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  25680. const dest = this.resolvedProperty;
  25681. for (let i = 0, n = dest.length; i !== n; ++i) {
  25682. dest[i] = buffer[offset++];
  25683. }
  25684. this.targetObject.matrixWorldNeedsUpdate = true;
  25685. } // ArrayElement
  25686. _setValue_arrayElement(buffer, offset) {
  25687. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25688. }
  25689. _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  25690. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25691. this.targetObject.needsUpdate = true;
  25692. }
  25693. _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  25694. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25695. this.targetObject.matrixWorldNeedsUpdate = true;
  25696. } // HasToFromArray
  25697. _setValue_fromArray(buffer, offset) {
  25698. this.resolvedProperty.fromArray(buffer, offset);
  25699. }
  25700. _setValue_fromArray_setNeedsUpdate(buffer, offset) {
  25701. this.resolvedProperty.fromArray(buffer, offset);
  25702. this.targetObject.needsUpdate = true;
  25703. }
  25704. _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  25705. this.resolvedProperty.fromArray(buffer, offset);
  25706. this.targetObject.matrixWorldNeedsUpdate = true;
  25707. }
  25708. _getValue_unbound(targetArray, offset) {
  25709. this.bind();
  25710. this.getValue(targetArray, offset);
  25711. }
  25712. _setValue_unbound(sourceArray, offset) {
  25713. this.bind();
  25714. this.setValue(sourceArray, offset);
  25715. } // create getter / setter pair for a property in the scene graph
  25716. bind() {
  25717. let targetObject = this.node;
  25718. const parsedPath = this.parsedPath;
  25719. const objectName = parsedPath.objectName;
  25720. const propertyName = parsedPath.propertyName;
  25721. let propertyIndex = parsedPath.propertyIndex;
  25722. if (!targetObject) {
  25723. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  25724. this.node = targetObject;
  25725. } // set fail state so we can just 'return' on error
  25726. this.getValue = this._getValue_unavailable;
  25727. this.setValue = this._setValue_unavailable; // ensure there is a value node
  25728. if (!targetObject) {
  25729. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  25730. return;
  25731. }
  25732. if (objectName) {
  25733. let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  25734. switch (objectName) {
  25735. case 'materials':
  25736. if (!targetObject.material) {
  25737. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  25738. return;
  25739. }
  25740. if (!targetObject.material.materials) {
  25741. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  25742. return;
  25743. }
  25744. targetObject = targetObject.material.materials;
  25745. break;
  25746. case 'bones':
  25747. if (!targetObject.skeleton) {
  25748. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  25749. return;
  25750. } // potential future optimization: skip this if propertyIndex is already an integer
  25751. // and convert the integer string to a true integer.
  25752. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  25753. for (let i = 0; i < targetObject.length; i++) {
  25754. if (targetObject[i].name === objectIndex) {
  25755. objectIndex = i;
  25756. break;
  25757. }
  25758. }
  25759. break;
  25760. default:
  25761. if (targetObject[objectName] === undefined) {
  25762. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  25763. return;
  25764. }
  25765. targetObject = targetObject[objectName];
  25766. }
  25767. if (objectIndex !== undefined) {
  25768. if (targetObject[objectIndex] === undefined) {
  25769. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  25770. return;
  25771. }
  25772. targetObject = targetObject[objectIndex];
  25773. }
  25774. } // resolve property
  25775. const nodeProperty = targetObject[propertyName];
  25776. if (nodeProperty === undefined) {
  25777. const nodeName = parsedPath.nodeName;
  25778. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  25779. return;
  25780. } // determine versioning scheme
  25781. let versioning = this.Versioning.None;
  25782. this.targetObject = targetObject;
  25783. if (targetObject.needsUpdate !== undefined) {
  25784. // material
  25785. versioning = this.Versioning.NeedsUpdate;
  25786. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  25787. // node transform
  25788. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  25789. } // determine how the property gets bound
  25790. let bindingType = this.BindingType.Direct;
  25791. if (propertyIndex !== undefined) {
  25792. // access a sub element of the property array (only primitives are supported right now)
  25793. if (propertyName === 'morphTargetInfluences') {
  25794. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  25795. // support resolving morphTarget names into indices.
  25796. if (!targetObject.geometry) {
  25797. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  25798. return;
  25799. }
  25800. if (targetObject.geometry.isBufferGeometry) {
  25801. if (!targetObject.geometry.morphAttributes) {
  25802. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  25803. return;
  25804. }
  25805. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  25806. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  25807. }
  25808. } else {
  25809. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
  25810. return;
  25811. }
  25812. }
  25813. bindingType = this.BindingType.ArrayElement;
  25814. this.resolvedProperty = nodeProperty;
  25815. this.propertyIndex = propertyIndex;
  25816. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  25817. // must use copy for Object3D.Euler/Quaternion
  25818. bindingType = this.BindingType.HasFromToArray;
  25819. this.resolvedProperty = nodeProperty;
  25820. } else if (Array.isArray(nodeProperty)) {
  25821. bindingType = this.BindingType.EntireArray;
  25822. this.resolvedProperty = nodeProperty;
  25823. } else {
  25824. this.propertyName = propertyName;
  25825. } // select getter / setter
  25826. this.getValue = this.GetterByBindingType[bindingType];
  25827. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  25828. }
  25829. unbind() {
  25830. this.node = null; // back to the prototype version of getValue / setValue
  25831. // note: avoiding to mutate the shape of 'this' via 'delete'
  25832. this.getValue = this._getValue_unbound;
  25833. this.setValue = this._setValue_unbound;
  25834. }
  25835. }
  25836. PropertyBinding.Composite = Composite;
  25837. PropertyBinding.prototype.BindingType = {
  25838. Direct: 0,
  25839. EntireArray: 1,
  25840. ArrayElement: 2,
  25841. HasFromToArray: 3
  25842. };
  25843. PropertyBinding.prototype.Versioning = {
  25844. None: 0,
  25845. NeedsUpdate: 1,
  25846. MatrixWorldNeedsUpdate: 2
  25847. };
  25848. PropertyBinding.prototype.GetterByBindingType = [PropertyBinding.prototype._getValue_direct, PropertyBinding.prototype._getValue_array, PropertyBinding.prototype._getValue_arrayElement, PropertyBinding.prototype._getValue_toArray];
  25849. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [[// Direct
  25850. PropertyBinding.prototype._setValue_direct, PropertyBinding.prototype._setValue_direct_setNeedsUpdate, PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate], [// EntireArray
  25851. PropertyBinding.prototype._setValue_array, PropertyBinding.prototype._setValue_array_setNeedsUpdate, PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate], [// ArrayElement
  25852. PropertyBinding.prototype._setValue_arrayElement, PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate], [// HasToFromArray
  25853. PropertyBinding.prototype._setValue_fromArray, PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];
  25854. /**
  25855. *
  25856. * A group of objects that receives a shared animation state.
  25857. *
  25858. * Usage:
  25859. *
  25860. * - Add objects you would otherwise pass as 'root' to the
  25861. * constructor or the .clipAction method of AnimationMixer.
  25862. *
  25863. * - Instead pass this object as 'root'.
  25864. *
  25865. * - You can also add and remove objects later when the mixer
  25866. * is running.
  25867. *
  25868. * Note:
  25869. *
  25870. * Objects of this class appear as one object to the mixer,
  25871. * so cache control of the individual objects must be done
  25872. * on the group.
  25873. *
  25874. * Limitation:
  25875. *
  25876. * - The animated properties must be compatible among the
  25877. * all objects in the group.
  25878. *
  25879. * - A single property can either be controlled through a
  25880. * target group or directly, but not both.
  25881. */
  25882. class AnimationObjectGroup {
  25883. constructor() {
  25884. this.uuid = generateUUID(); // cached objects followed by the active ones
  25885. this._objects = Array.prototype.slice.call(arguments);
  25886. this.nCachedObjects_ = 0; // threshold
  25887. // note: read by PropertyBinding.Composite
  25888. const indices = {};
  25889. this._indicesByUUID = indices; // for bookkeeping
  25890. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25891. indices[arguments[i].uuid] = i;
  25892. }
  25893. this._paths = []; // inside: string
  25894. this._parsedPaths = []; // inside: { we don't care, here }
  25895. this._bindings = []; // inside: Array< PropertyBinding >
  25896. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  25897. const scope = this;
  25898. this.stats = {
  25899. objects: {
  25900. get total() {
  25901. return scope._objects.length;
  25902. },
  25903. get inUse() {
  25904. return this.total - scope.nCachedObjects_;
  25905. }
  25906. },
  25907. get bindingsPerObject() {
  25908. return scope._bindings.length;
  25909. }
  25910. };
  25911. }
  25912. add() {
  25913. const objects = this._objects,
  25914. indicesByUUID = this._indicesByUUID,
  25915. paths = this._paths,
  25916. parsedPaths = this._parsedPaths,
  25917. bindings = this._bindings,
  25918. nBindings = bindings.length;
  25919. let knownObject = undefined,
  25920. nObjects = objects.length,
  25921. nCachedObjects = this.nCachedObjects_;
  25922. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25923. const object = arguments[i],
  25924. uuid = object.uuid;
  25925. let index = indicesByUUID[uuid];
  25926. if (index === undefined) {
  25927. // unknown object -> add it to the ACTIVE region
  25928. index = nObjects++;
  25929. indicesByUUID[uuid] = index;
  25930. objects.push(object); // accounting is done, now do the same for all bindings
  25931. for (let j = 0, m = nBindings; j !== m; ++j) {
  25932. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  25933. }
  25934. } else if (index < nCachedObjects) {
  25935. knownObject = objects[index]; // move existing object to the ACTIVE region
  25936. const firstActiveIndex = --nCachedObjects,
  25937. lastCachedObject = objects[firstActiveIndex];
  25938. indicesByUUID[lastCachedObject.uuid] = index;
  25939. objects[index] = lastCachedObject;
  25940. indicesByUUID[uuid] = firstActiveIndex;
  25941. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  25942. for (let j = 0, m = nBindings; j !== m; ++j) {
  25943. const bindingsForPath = bindings[j],
  25944. lastCached = bindingsForPath[firstActiveIndex];
  25945. let binding = bindingsForPath[index];
  25946. bindingsForPath[index] = lastCached;
  25947. if (binding === undefined) {
  25948. // since we do not bother to create new bindings
  25949. // for objects that are cached, the binding may
  25950. // or may not exist
  25951. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  25952. }
  25953. bindingsForPath[firstActiveIndex] = binding;
  25954. }
  25955. } else if (objects[index] !== knownObject) {
  25956. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  25957. } // else the object is already where we want it to be
  25958. } // for arguments
  25959. this.nCachedObjects_ = nCachedObjects;
  25960. }
  25961. remove() {
  25962. const objects = this._objects,
  25963. indicesByUUID = this._indicesByUUID,
  25964. bindings = this._bindings,
  25965. nBindings = bindings.length;
  25966. let nCachedObjects = this.nCachedObjects_;
  25967. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25968. const object = arguments[i],
  25969. uuid = object.uuid,
  25970. index = indicesByUUID[uuid];
  25971. if (index !== undefined && index >= nCachedObjects) {
  25972. // move existing object into the CACHED region
  25973. const lastCachedIndex = nCachedObjects++,
  25974. firstActiveObject = objects[lastCachedIndex];
  25975. indicesByUUID[firstActiveObject.uuid] = index;
  25976. objects[index] = firstActiveObject;
  25977. indicesByUUID[uuid] = lastCachedIndex;
  25978. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  25979. for (let j = 0, m = nBindings; j !== m; ++j) {
  25980. const bindingsForPath = bindings[j],
  25981. firstActive = bindingsForPath[lastCachedIndex],
  25982. binding = bindingsForPath[index];
  25983. bindingsForPath[index] = firstActive;
  25984. bindingsForPath[lastCachedIndex] = binding;
  25985. }
  25986. }
  25987. } // for arguments
  25988. this.nCachedObjects_ = nCachedObjects;
  25989. } // remove & forget
  25990. uncache() {
  25991. const objects = this._objects,
  25992. indicesByUUID = this._indicesByUUID,
  25993. bindings = this._bindings,
  25994. nBindings = bindings.length;
  25995. let nCachedObjects = this.nCachedObjects_,
  25996. nObjects = objects.length;
  25997. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25998. const object = arguments[i],
  25999. uuid = object.uuid,
  26000. index = indicesByUUID[uuid];
  26001. if (index !== undefined) {
  26002. delete indicesByUUID[uuid];
  26003. if (index < nCachedObjects) {
  26004. // object is cached, shrink the CACHED region
  26005. const firstActiveIndex = --nCachedObjects,
  26006. lastCachedObject = objects[firstActiveIndex],
  26007. lastIndex = --nObjects,
  26008. lastObject = objects[lastIndex]; // last cached object takes this object's place
  26009. indicesByUUID[lastCachedObject.uuid] = index;
  26010. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  26011. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  26012. objects[firstActiveIndex] = lastObject;
  26013. objects.pop(); // accounting is done, now do the same for all bindings
  26014. for (let j = 0, m = nBindings; j !== m; ++j) {
  26015. const bindingsForPath = bindings[j],
  26016. lastCached = bindingsForPath[firstActiveIndex],
  26017. last = bindingsForPath[lastIndex];
  26018. bindingsForPath[index] = lastCached;
  26019. bindingsForPath[firstActiveIndex] = last;
  26020. bindingsForPath.pop();
  26021. }
  26022. } else {
  26023. // object is active, just swap with the last and pop
  26024. const lastIndex = --nObjects,
  26025. lastObject = objects[lastIndex];
  26026. if (lastIndex > 0) {
  26027. indicesByUUID[lastObject.uuid] = index;
  26028. }
  26029. objects[index] = lastObject;
  26030. objects.pop(); // accounting is done, now do the same for all bindings
  26031. for (let j = 0, m = nBindings; j !== m; ++j) {
  26032. const bindingsForPath = bindings[j];
  26033. bindingsForPath[index] = bindingsForPath[lastIndex];
  26034. bindingsForPath.pop();
  26035. }
  26036. } // cached or active
  26037. } // if object is known
  26038. } // for arguments
  26039. this.nCachedObjects_ = nCachedObjects;
  26040. } // Internal interface used by befriended PropertyBinding.Composite:
  26041. subscribe_(path, parsedPath) {
  26042. // returns an array of bindings for the given path that is changed
  26043. // according to the contained objects in the group
  26044. const indicesByPath = this._bindingsIndicesByPath;
  26045. let index = indicesByPath[path];
  26046. const bindings = this._bindings;
  26047. if (index !== undefined) return bindings[index];
  26048. const paths = this._paths,
  26049. parsedPaths = this._parsedPaths,
  26050. objects = this._objects,
  26051. nObjects = objects.length,
  26052. nCachedObjects = this.nCachedObjects_,
  26053. bindingsForPath = new Array(nObjects);
  26054. index = bindings.length;
  26055. indicesByPath[path] = index;
  26056. paths.push(path);
  26057. parsedPaths.push(parsedPath);
  26058. bindings.push(bindingsForPath);
  26059. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  26060. const object = objects[i];
  26061. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  26062. }
  26063. return bindingsForPath;
  26064. }
  26065. unsubscribe_(path) {
  26066. // tells the group to forget about a property path and no longer
  26067. // update the array previously obtained with 'subscribe_'
  26068. const indicesByPath = this._bindingsIndicesByPath,
  26069. index = indicesByPath[path];
  26070. if (index !== undefined) {
  26071. const paths = this._paths,
  26072. parsedPaths = this._parsedPaths,
  26073. bindings = this._bindings,
  26074. lastBindingsIndex = bindings.length - 1,
  26075. lastBindings = bindings[lastBindingsIndex],
  26076. lastBindingsPath = path[lastBindingsIndex];
  26077. indicesByPath[lastBindingsPath] = index;
  26078. bindings[index] = lastBindings;
  26079. bindings.pop();
  26080. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  26081. parsedPaths.pop();
  26082. paths[index] = paths[lastBindingsIndex];
  26083. paths.pop();
  26084. }
  26085. }
  26086. }
  26087. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  26088. class AnimationAction {
  26089. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  26090. this._mixer = mixer;
  26091. this._clip = clip;
  26092. this._localRoot = localRoot;
  26093. this.blendMode = blendMode;
  26094. const tracks = clip.tracks,
  26095. nTracks = tracks.length,
  26096. interpolants = new Array(nTracks);
  26097. const interpolantSettings = {
  26098. endingStart: ZeroCurvatureEnding,
  26099. endingEnd: ZeroCurvatureEnding
  26100. };
  26101. for (let i = 0; i !== nTracks; ++i) {
  26102. const interpolant = tracks[i].createInterpolant(null);
  26103. interpolants[i] = interpolant;
  26104. interpolant.settings = interpolantSettings;
  26105. }
  26106. this._interpolantSettings = interpolantSettings;
  26107. this._interpolants = interpolants; // bound by the mixer
  26108. // inside: PropertyMixer (managed by the mixer)
  26109. this._propertyBindings = new Array(nTracks);
  26110. this._cacheIndex = null; // for the memory manager
  26111. this._byClipCacheIndex = null; // for the memory manager
  26112. this._timeScaleInterpolant = null;
  26113. this._weightInterpolant = null;
  26114. this.loop = LoopRepeat;
  26115. this._loopCount = -1; // global mixer time when the action is to be started
  26116. // it's set back to 'null' upon start of the action
  26117. this._startTime = null; // scaled local time of the action
  26118. // gets clamped or wrapped to 0..clip.duration according to loop
  26119. this.time = 0;
  26120. this.timeScale = 1;
  26121. this._effectiveTimeScale = 1;
  26122. this.weight = 1;
  26123. this._effectiveWeight = 1;
  26124. this.repetitions = Infinity; // no. of repetitions when looping
  26125. this.paused = false; // true -> zero effective time scale
  26126. this.enabled = true; // false -> zero effective weight
  26127. this.clampWhenFinished = false; // keep feeding the last frame?
  26128. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26129. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26130. } // State & Scheduling
  26131. play() {
  26132. this._mixer._activateAction(this);
  26133. return this;
  26134. }
  26135. stop() {
  26136. this._mixer._deactivateAction(this);
  26137. return this.reset();
  26138. }
  26139. reset() {
  26140. this.paused = false;
  26141. this.enabled = true;
  26142. this.time = 0; // restart clip
  26143. this._loopCount = -1; // forget previous loops
  26144. this._startTime = null; // forget scheduling
  26145. return this.stopFading().stopWarping();
  26146. }
  26147. isRunning() {
  26148. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  26149. } // return true when play has been called
  26150. isScheduled() {
  26151. return this._mixer._isActiveAction(this);
  26152. }
  26153. startAt(time) {
  26154. this._startTime = time;
  26155. return this;
  26156. }
  26157. setLoop(mode, repetitions) {
  26158. this.loop = mode;
  26159. this.repetitions = repetitions;
  26160. return this;
  26161. } // Weight
  26162. // set the weight stopping any scheduled fading
  26163. // although .enabled = false yields an effective weight of zero, this
  26164. // method does *not* change .enabled, because it would be confusing
  26165. setEffectiveWeight(weight) {
  26166. this.weight = weight; // note: same logic as when updated at runtime
  26167. this._effectiveWeight = this.enabled ? weight : 0;
  26168. return this.stopFading();
  26169. } // return the weight considering fading and .enabled
  26170. getEffectiveWeight() {
  26171. return this._effectiveWeight;
  26172. }
  26173. fadeIn(duration) {
  26174. return this._scheduleFading(duration, 0, 1);
  26175. }
  26176. fadeOut(duration) {
  26177. return this._scheduleFading(duration, 1, 0);
  26178. }
  26179. crossFadeFrom(fadeOutAction, duration, warp) {
  26180. fadeOutAction.fadeOut(duration);
  26181. this.fadeIn(duration);
  26182. if (warp) {
  26183. const fadeInDuration = this._clip.duration,
  26184. fadeOutDuration = fadeOutAction._clip.duration,
  26185. startEndRatio = fadeOutDuration / fadeInDuration,
  26186. endStartRatio = fadeInDuration / fadeOutDuration;
  26187. fadeOutAction.warp(1.0, startEndRatio, duration);
  26188. this.warp(endStartRatio, 1.0, duration);
  26189. }
  26190. return this;
  26191. }
  26192. crossFadeTo(fadeInAction, duration, warp) {
  26193. return fadeInAction.crossFadeFrom(this, duration, warp);
  26194. }
  26195. stopFading() {
  26196. const weightInterpolant = this._weightInterpolant;
  26197. if (weightInterpolant !== null) {
  26198. this._weightInterpolant = null;
  26199. this._mixer._takeBackControlInterpolant(weightInterpolant);
  26200. }
  26201. return this;
  26202. } // Time Scale Control
  26203. // set the time scale stopping any scheduled warping
  26204. // although .paused = true yields an effective time scale of zero, this
  26205. // method does *not* change .paused, because it would be confusing
  26206. setEffectiveTimeScale(timeScale) {
  26207. this.timeScale = timeScale;
  26208. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26209. return this.stopWarping();
  26210. } // return the time scale considering warping and .paused
  26211. getEffectiveTimeScale() {
  26212. return this._effectiveTimeScale;
  26213. }
  26214. setDuration(duration) {
  26215. this.timeScale = this._clip.duration / duration;
  26216. return this.stopWarping();
  26217. }
  26218. syncWith(action) {
  26219. this.time = action.time;
  26220. this.timeScale = action.timeScale;
  26221. return this.stopWarping();
  26222. }
  26223. halt(duration) {
  26224. return this.warp(this._effectiveTimeScale, 0, duration);
  26225. }
  26226. warp(startTimeScale, endTimeScale, duration) {
  26227. const mixer = this._mixer,
  26228. now = mixer.time,
  26229. timeScale = this.timeScale;
  26230. let interpolant = this._timeScaleInterpolant;
  26231. if (interpolant === null) {
  26232. interpolant = mixer._lendControlInterpolant();
  26233. this._timeScaleInterpolant = interpolant;
  26234. }
  26235. const times = interpolant.parameterPositions,
  26236. values = interpolant.sampleValues;
  26237. times[0] = now;
  26238. times[1] = now + duration;
  26239. values[0] = startTimeScale / timeScale;
  26240. values[1] = endTimeScale / timeScale;
  26241. return this;
  26242. }
  26243. stopWarping() {
  26244. const timeScaleInterpolant = this._timeScaleInterpolant;
  26245. if (timeScaleInterpolant !== null) {
  26246. this._timeScaleInterpolant = null;
  26247. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  26248. }
  26249. return this;
  26250. } // Object Accessors
  26251. getMixer() {
  26252. return this._mixer;
  26253. }
  26254. getClip() {
  26255. return this._clip;
  26256. }
  26257. getRoot() {
  26258. return this._localRoot || this._mixer._root;
  26259. } // Interna
  26260. _update(time, deltaTime, timeDirection, accuIndex) {
  26261. // called by the mixer
  26262. if (!this.enabled) {
  26263. // call ._updateWeight() to update ._effectiveWeight
  26264. this._updateWeight(time);
  26265. return;
  26266. }
  26267. const startTime = this._startTime;
  26268. if (startTime !== null) {
  26269. // check for scheduled start of action
  26270. const timeRunning = (time - startTime) * timeDirection;
  26271. if (timeRunning < 0 || timeDirection === 0) {
  26272. return; // yet to come / don't decide when delta = 0
  26273. } // start
  26274. this._startTime = null; // unschedule
  26275. deltaTime = timeDirection * timeRunning;
  26276. } // apply time scale and advance time
  26277. deltaTime *= this._updateTimeScale(time);
  26278. const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  26279. // an effective weight of 0
  26280. const weight = this._updateWeight(time);
  26281. if (weight > 0) {
  26282. const interpolants = this._interpolants;
  26283. const propertyMixers = this._propertyBindings;
  26284. switch (this.blendMode) {
  26285. case AdditiveAnimationBlendMode:
  26286. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26287. interpolants[j].evaluate(clipTime);
  26288. propertyMixers[j].accumulateAdditive(weight);
  26289. }
  26290. break;
  26291. case NormalAnimationBlendMode:
  26292. default:
  26293. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26294. interpolants[j].evaluate(clipTime);
  26295. propertyMixers[j].accumulate(accuIndex, weight);
  26296. }
  26297. }
  26298. }
  26299. }
  26300. _updateWeight(time) {
  26301. let weight = 0;
  26302. if (this.enabled) {
  26303. weight = this.weight;
  26304. const interpolant = this._weightInterpolant;
  26305. if (interpolant !== null) {
  26306. const interpolantValue = interpolant.evaluate(time)[0];
  26307. weight *= interpolantValue;
  26308. if (time > interpolant.parameterPositions[1]) {
  26309. this.stopFading();
  26310. if (interpolantValue === 0) {
  26311. // faded out, disable
  26312. this.enabled = false;
  26313. }
  26314. }
  26315. }
  26316. }
  26317. this._effectiveWeight = weight;
  26318. return weight;
  26319. }
  26320. _updateTimeScale(time) {
  26321. let timeScale = 0;
  26322. if (!this.paused) {
  26323. timeScale = this.timeScale;
  26324. const interpolant = this._timeScaleInterpolant;
  26325. if (interpolant !== null) {
  26326. const interpolantValue = interpolant.evaluate(time)[0];
  26327. timeScale *= interpolantValue;
  26328. if (time > interpolant.parameterPositions[1]) {
  26329. this.stopWarping();
  26330. if (timeScale === 0) {
  26331. // motion has halted, pause
  26332. this.paused = true;
  26333. } else {
  26334. // warp done - apply final time scale
  26335. this.timeScale = timeScale;
  26336. }
  26337. }
  26338. }
  26339. }
  26340. this._effectiveTimeScale = timeScale;
  26341. return timeScale;
  26342. }
  26343. _updateTime(deltaTime) {
  26344. const duration = this._clip.duration;
  26345. const loop = this.loop;
  26346. let time = this.time + deltaTime;
  26347. let loopCount = this._loopCount;
  26348. const pingPong = loop === LoopPingPong;
  26349. if (deltaTime === 0) {
  26350. if (loopCount === -1) return time;
  26351. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  26352. }
  26353. if (loop === LoopOnce) {
  26354. if (loopCount === -1) {
  26355. // just started
  26356. this._loopCount = 0;
  26357. this._setEndings(true, true, false);
  26358. }
  26359. handle_stop: {
  26360. if (time >= duration) {
  26361. time = duration;
  26362. } else if (time < 0) {
  26363. time = 0;
  26364. } else {
  26365. this.time = time;
  26366. break handle_stop;
  26367. }
  26368. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26369. this.time = time;
  26370. this._mixer.dispatchEvent({
  26371. type: 'finished',
  26372. action: this,
  26373. direction: deltaTime < 0 ? -1 : 1
  26374. });
  26375. }
  26376. } else {
  26377. // repetitive Repeat or PingPong
  26378. if (loopCount === -1) {
  26379. // just started
  26380. if (deltaTime >= 0) {
  26381. loopCount = 0;
  26382. this._setEndings(true, this.repetitions === 0, pingPong);
  26383. } else {
  26384. // when looping in reverse direction, the initial
  26385. // transition through zero counts as a repetition,
  26386. // so leave loopCount at -1
  26387. this._setEndings(this.repetitions === 0, true, pingPong);
  26388. }
  26389. }
  26390. if (time >= duration || time < 0) {
  26391. // wrap around
  26392. const loopDelta = Math.floor(time / duration); // signed
  26393. time -= duration * loopDelta;
  26394. loopCount += Math.abs(loopDelta);
  26395. const pending = this.repetitions - loopCount;
  26396. if (pending <= 0) {
  26397. // have to stop (switch state, clamp time, fire event)
  26398. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26399. time = deltaTime > 0 ? duration : 0;
  26400. this.time = time;
  26401. this._mixer.dispatchEvent({
  26402. type: 'finished',
  26403. action: this,
  26404. direction: deltaTime > 0 ? 1 : -1
  26405. });
  26406. } else {
  26407. // keep running
  26408. if (pending === 1) {
  26409. // entering the last round
  26410. const atStart = deltaTime < 0;
  26411. this._setEndings(atStart, !atStart, pingPong);
  26412. } else {
  26413. this._setEndings(false, false, pingPong);
  26414. }
  26415. this._loopCount = loopCount;
  26416. this.time = time;
  26417. this._mixer.dispatchEvent({
  26418. type: 'loop',
  26419. action: this,
  26420. loopDelta: loopDelta
  26421. });
  26422. }
  26423. } else {
  26424. this.time = time;
  26425. }
  26426. if (pingPong && (loopCount & 1) === 1) {
  26427. // invert time for the "pong round"
  26428. return duration - time;
  26429. }
  26430. }
  26431. return time;
  26432. }
  26433. _setEndings(atStart, atEnd, pingPong) {
  26434. const settings = this._interpolantSettings;
  26435. if (pingPong) {
  26436. settings.endingStart = ZeroSlopeEnding;
  26437. settings.endingEnd = ZeroSlopeEnding;
  26438. } else {
  26439. // assuming for LoopOnce atStart == atEnd == true
  26440. if (atStart) {
  26441. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26442. } else {
  26443. settings.endingStart = WrapAroundEnding;
  26444. }
  26445. if (atEnd) {
  26446. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26447. } else {
  26448. settings.endingEnd = WrapAroundEnding;
  26449. }
  26450. }
  26451. }
  26452. _scheduleFading(duration, weightNow, weightThen) {
  26453. const mixer = this._mixer,
  26454. now = mixer.time;
  26455. let interpolant = this._weightInterpolant;
  26456. if (interpolant === null) {
  26457. interpolant = mixer._lendControlInterpolant();
  26458. this._weightInterpolant = interpolant;
  26459. }
  26460. const times = interpolant.parameterPositions,
  26461. values = interpolant.sampleValues;
  26462. times[0] = now;
  26463. values[0] = weightNow;
  26464. times[1] = now + duration;
  26465. values[1] = weightThen;
  26466. return this;
  26467. }
  26468. }
  26469. class AnimationMixer extends EventDispatcher {
  26470. constructor(root) {
  26471. super();
  26472. this._root = root;
  26473. this._initMemoryManager();
  26474. this._accuIndex = 0;
  26475. this.time = 0;
  26476. this.timeScale = 1.0;
  26477. }
  26478. _bindAction(action, prototypeAction) {
  26479. const root = action._localRoot || this._root,
  26480. tracks = action._clip.tracks,
  26481. nTracks = tracks.length,
  26482. bindings = action._propertyBindings,
  26483. interpolants = action._interpolants,
  26484. rootUuid = root.uuid,
  26485. bindingsByRoot = this._bindingsByRootAndName;
  26486. let bindingsByName = bindingsByRoot[rootUuid];
  26487. if (bindingsByName === undefined) {
  26488. bindingsByName = {};
  26489. bindingsByRoot[rootUuid] = bindingsByName;
  26490. }
  26491. for (let i = 0; i !== nTracks; ++i) {
  26492. const track = tracks[i],
  26493. trackName = track.name;
  26494. let binding = bindingsByName[trackName];
  26495. if (binding !== undefined) {
  26496. bindings[i] = binding;
  26497. } else {
  26498. binding = bindings[i];
  26499. if (binding !== undefined) {
  26500. // existing binding, make sure the cache knows
  26501. if (binding._cacheIndex === null) {
  26502. ++binding.referenceCount;
  26503. this._addInactiveBinding(binding, rootUuid, trackName);
  26504. }
  26505. continue;
  26506. }
  26507. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  26508. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  26509. ++binding.referenceCount;
  26510. this._addInactiveBinding(binding, rootUuid, trackName);
  26511. bindings[i] = binding;
  26512. }
  26513. interpolants[i].resultBuffer = binding.buffer;
  26514. }
  26515. }
  26516. _activateAction(action) {
  26517. if (!this._isActiveAction(action)) {
  26518. if (action._cacheIndex === null) {
  26519. // this action has been forgotten by the cache, but the user
  26520. // appears to be still using it -> rebind
  26521. const rootUuid = (action._localRoot || this._root).uuid,
  26522. clipUuid = action._clip.uuid,
  26523. actionsForClip = this._actionsByClip[clipUuid];
  26524. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  26525. this._addInactiveAction(action, clipUuid, rootUuid);
  26526. }
  26527. const bindings = action._propertyBindings; // increment reference counts / sort out state
  26528. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26529. const binding = bindings[i];
  26530. if (binding.useCount++ === 0) {
  26531. this._lendBinding(binding);
  26532. binding.saveOriginalState();
  26533. }
  26534. }
  26535. this._lendAction(action);
  26536. }
  26537. }
  26538. _deactivateAction(action) {
  26539. if (this._isActiveAction(action)) {
  26540. const bindings = action._propertyBindings; // decrement reference counts / sort out state
  26541. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26542. const binding = bindings[i];
  26543. if (--binding.useCount === 0) {
  26544. binding.restoreOriginalState();
  26545. this._takeBackBinding(binding);
  26546. }
  26547. }
  26548. this._takeBackAction(action);
  26549. }
  26550. } // Memory manager
  26551. _initMemoryManager() {
  26552. this._actions = []; // 'nActiveActions' followed by inactive ones
  26553. this._nActiveActions = 0;
  26554. this._actionsByClip = {}; // inside:
  26555. // {
  26556. // knownActions: Array< AnimationAction > - used as prototypes
  26557. // actionByRoot: AnimationAction - lookup
  26558. // }
  26559. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  26560. this._nActiveBindings = 0;
  26561. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  26562. this._controlInterpolants = []; // same game as above
  26563. this._nActiveControlInterpolants = 0;
  26564. const scope = this;
  26565. this.stats = {
  26566. actions: {
  26567. get total() {
  26568. return scope._actions.length;
  26569. },
  26570. get inUse() {
  26571. return scope._nActiveActions;
  26572. }
  26573. },
  26574. bindings: {
  26575. get total() {
  26576. return scope._bindings.length;
  26577. },
  26578. get inUse() {
  26579. return scope._nActiveBindings;
  26580. }
  26581. },
  26582. controlInterpolants: {
  26583. get total() {
  26584. return scope._controlInterpolants.length;
  26585. },
  26586. get inUse() {
  26587. return scope._nActiveControlInterpolants;
  26588. }
  26589. }
  26590. };
  26591. } // Memory management for AnimationAction objects
  26592. _isActiveAction(action) {
  26593. const index = action._cacheIndex;
  26594. return index !== null && index < this._nActiveActions;
  26595. }
  26596. _addInactiveAction(action, clipUuid, rootUuid) {
  26597. const actions = this._actions,
  26598. actionsByClip = this._actionsByClip;
  26599. let actionsForClip = actionsByClip[clipUuid];
  26600. if (actionsForClip === undefined) {
  26601. actionsForClip = {
  26602. knownActions: [action],
  26603. actionByRoot: {}
  26604. };
  26605. action._byClipCacheIndex = 0;
  26606. actionsByClip[clipUuid] = actionsForClip;
  26607. } else {
  26608. const knownActions = actionsForClip.knownActions;
  26609. action._byClipCacheIndex = knownActions.length;
  26610. knownActions.push(action);
  26611. }
  26612. action._cacheIndex = actions.length;
  26613. actions.push(action);
  26614. actionsForClip.actionByRoot[rootUuid] = action;
  26615. }
  26616. _removeInactiveAction(action) {
  26617. const actions = this._actions,
  26618. lastInactiveAction = actions[actions.length - 1],
  26619. cacheIndex = action._cacheIndex;
  26620. lastInactiveAction._cacheIndex = cacheIndex;
  26621. actions[cacheIndex] = lastInactiveAction;
  26622. actions.pop();
  26623. action._cacheIndex = null;
  26624. const clipUuid = action._clip.uuid,
  26625. actionsByClip = this._actionsByClip,
  26626. actionsForClip = actionsByClip[clipUuid],
  26627. knownActionsForClip = actionsForClip.knownActions,
  26628. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  26629. byClipCacheIndex = action._byClipCacheIndex;
  26630. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  26631. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  26632. knownActionsForClip.pop();
  26633. action._byClipCacheIndex = null;
  26634. const actionByRoot = actionsForClip.actionByRoot,
  26635. rootUuid = (action._localRoot || this._root).uuid;
  26636. delete actionByRoot[rootUuid];
  26637. if (knownActionsForClip.length === 0) {
  26638. delete actionsByClip[clipUuid];
  26639. }
  26640. this._removeInactiveBindingsForAction(action);
  26641. }
  26642. _removeInactiveBindingsForAction(action) {
  26643. const bindings = action._propertyBindings;
  26644. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26645. const binding = bindings[i];
  26646. if (--binding.referenceCount === 0) {
  26647. this._removeInactiveBinding(binding);
  26648. }
  26649. }
  26650. }
  26651. _lendAction(action) {
  26652. // [ active actions | inactive actions ]
  26653. // [ active actions >| inactive actions ]
  26654. // s a
  26655. // <-swap->
  26656. // a s
  26657. const actions = this._actions,
  26658. prevIndex = action._cacheIndex,
  26659. lastActiveIndex = this._nActiveActions++,
  26660. firstInactiveAction = actions[lastActiveIndex];
  26661. action._cacheIndex = lastActiveIndex;
  26662. actions[lastActiveIndex] = action;
  26663. firstInactiveAction._cacheIndex = prevIndex;
  26664. actions[prevIndex] = firstInactiveAction;
  26665. }
  26666. _takeBackAction(action) {
  26667. // [ active actions | inactive actions ]
  26668. // [ active actions |< inactive actions ]
  26669. // a s
  26670. // <-swap->
  26671. // s a
  26672. const actions = this._actions,
  26673. prevIndex = action._cacheIndex,
  26674. firstInactiveIndex = --this._nActiveActions,
  26675. lastActiveAction = actions[firstInactiveIndex];
  26676. action._cacheIndex = firstInactiveIndex;
  26677. actions[firstInactiveIndex] = action;
  26678. lastActiveAction._cacheIndex = prevIndex;
  26679. actions[prevIndex] = lastActiveAction;
  26680. } // Memory management for PropertyMixer objects
  26681. _addInactiveBinding(binding, rootUuid, trackName) {
  26682. const bindingsByRoot = this._bindingsByRootAndName,
  26683. bindings = this._bindings;
  26684. let bindingByName = bindingsByRoot[rootUuid];
  26685. if (bindingByName === undefined) {
  26686. bindingByName = {};
  26687. bindingsByRoot[rootUuid] = bindingByName;
  26688. }
  26689. bindingByName[trackName] = binding;
  26690. binding._cacheIndex = bindings.length;
  26691. bindings.push(binding);
  26692. }
  26693. _removeInactiveBinding(binding) {
  26694. const bindings = this._bindings,
  26695. propBinding = binding.binding,
  26696. rootUuid = propBinding.rootNode.uuid,
  26697. trackName = propBinding.path,
  26698. bindingsByRoot = this._bindingsByRootAndName,
  26699. bindingByName = bindingsByRoot[rootUuid],
  26700. lastInactiveBinding = bindings[bindings.length - 1],
  26701. cacheIndex = binding._cacheIndex;
  26702. lastInactiveBinding._cacheIndex = cacheIndex;
  26703. bindings[cacheIndex] = lastInactiveBinding;
  26704. bindings.pop();
  26705. delete bindingByName[trackName];
  26706. if (Object.keys(bindingByName).length === 0) {
  26707. delete bindingsByRoot[rootUuid];
  26708. }
  26709. }
  26710. _lendBinding(binding) {
  26711. const bindings = this._bindings,
  26712. prevIndex = binding._cacheIndex,
  26713. lastActiveIndex = this._nActiveBindings++,
  26714. firstInactiveBinding = bindings[lastActiveIndex];
  26715. binding._cacheIndex = lastActiveIndex;
  26716. bindings[lastActiveIndex] = binding;
  26717. firstInactiveBinding._cacheIndex = prevIndex;
  26718. bindings[prevIndex] = firstInactiveBinding;
  26719. }
  26720. _takeBackBinding(binding) {
  26721. const bindings = this._bindings,
  26722. prevIndex = binding._cacheIndex,
  26723. firstInactiveIndex = --this._nActiveBindings,
  26724. lastActiveBinding = bindings[firstInactiveIndex];
  26725. binding._cacheIndex = firstInactiveIndex;
  26726. bindings[firstInactiveIndex] = binding;
  26727. lastActiveBinding._cacheIndex = prevIndex;
  26728. bindings[prevIndex] = lastActiveBinding;
  26729. } // Memory management of Interpolants for weight and time scale
  26730. _lendControlInterpolant() {
  26731. const interpolants = this._controlInterpolants,
  26732. lastActiveIndex = this._nActiveControlInterpolants++;
  26733. let interpolant = interpolants[lastActiveIndex];
  26734. if (interpolant === undefined) {
  26735. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  26736. interpolant.__cacheIndex = lastActiveIndex;
  26737. interpolants[lastActiveIndex] = interpolant;
  26738. }
  26739. return interpolant;
  26740. }
  26741. _takeBackControlInterpolant(interpolant) {
  26742. const interpolants = this._controlInterpolants,
  26743. prevIndex = interpolant.__cacheIndex,
  26744. firstInactiveIndex = --this._nActiveControlInterpolants,
  26745. lastActiveInterpolant = interpolants[firstInactiveIndex];
  26746. interpolant.__cacheIndex = firstInactiveIndex;
  26747. interpolants[firstInactiveIndex] = interpolant;
  26748. lastActiveInterpolant.__cacheIndex = prevIndex;
  26749. interpolants[prevIndex] = lastActiveInterpolant;
  26750. } // return an action for a clip optionally using a custom root target
  26751. // object (this method allocates a lot of dynamic memory in case a
  26752. // previously unknown clip/root combination is specified)
  26753. clipAction(clip, optionalRoot, blendMode) {
  26754. const root = optionalRoot || this._root,
  26755. rootUuid = root.uuid;
  26756. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  26757. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  26758. const actionsForClip = this._actionsByClip[clipUuid];
  26759. let prototypeAction = null;
  26760. if (blendMode === undefined) {
  26761. if (clipObject !== null) {
  26762. blendMode = clipObject.blendMode;
  26763. } else {
  26764. blendMode = NormalAnimationBlendMode;
  26765. }
  26766. }
  26767. if (actionsForClip !== undefined) {
  26768. const existingAction = actionsForClip.actionByRoot[rootUuid];
  26769. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  26770. return existingAction;
  26771. } // we know the clip, so we don't have to parse all
  26772. // the bindings again but can just copy
  26773. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  26774. if (clipObject === null) clipObject = prototypeAction._clip;
  26775. } // clip must be known when specified via string
  26776. if (clipObject === null) return null; // allocate all resources required to run it
  26777. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  26778. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  26779. this._addInactiveAction(newAction, clipUuid, rootUuid);
  26780. return newAction;
  26781. } // get an existing action
  26782. existingAction(clip, optionalRoot) {
  26783. const root = optionalRoot || this._root,
  26784. rootUuid = root.uuid,
  26785. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  26786. clipUuid = clipObject ? clipObject.uuid : clip,
  26787. actionsForClip = this._actionsByClip[clipUuid];
  26788. if (actionsForClip !== undefined) {
  26789. return actionsForClip.actionByRoot[rootUuid] || null;
  26790. }
  26791. return null;
  26792. } // deactivates all previously scheduled actions
  26793. stopAllAction() {
  26794. const actions = this._actions,
  26795. nActions = this._nActiveActions;
  26796. for (let i = nActions - 1; i >= 0; --i) {
  26797. actions[i].stop();
  26798. }
  26799. return this;
  26800. } // advance the time and update apply the animation
  26801. update(deltaTime) {
  26802. deltaTime *= this.timeScale;
  26803. const actions = this._actions,
  26804. nActions = this._nActiveActions,
  26805. time = this.time += deltaTime,
  26806. timeDirection = Math.sign(deltaTime),
  26807. accuIndex = this._accuIndex ^= 1; // run active actions
  26808. for (let i = 0; i !== nActions; ++i) {
  26809. const action = actions[i];
  26810. action._update(time, deltaTime, timeDirection, accuIndex);
  26811. } // update scene graph
  26812. const bindings = this._bindings,
  26813. nBindings = this._nActiveBindings;
  26814. for (let i = 0; i !== nBindings; ++i) {
  26815. bindings[i].apply(accuIndex);
  26816. }
  26817. return this;
  26818. } // Allows you to seek to a specific time in an animation.
  26819. setTime(timeInSeconds) {
  26820. this.time = 0; // Zero out time attribute for AnimationMixer object;
  26821. for (let i = 0; i < this._actions.length; i++) {
  26822. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  26823. }
  26824. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  26825. } // return this mixer's root target object
  26826. getRoot() {
  26827. return this._root;
  26828. } // free all resources specific to a particular clip
  26829. uncacheClip(clip) {
  26830. const actions = this._actions,
  26831. clipUuid = clip.uuid,
  26832. actionsByClip = this._actionsByClip,
  26833. actionsForClip = actionsByClip[clipUuid];
  26834. if (actionsForClip !== undefined) {
  26835. // note: just calling _removeInactiveAction would mess up the
  26836. // iteration state and also require updating the state we can
  26837. // just throw away
  26838. const actionsToRemove = actionsForClip.knownActions;
  26839. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  26840. const action = actionsToRemove[i];
  26841. this._deactivateAction(action);
  26842. const cacheIndex = action._cacheIndex,
  26843. lastInactiveAction = actions[actions.length - 1];
  26844. action._cacheIndex = null;
  26845. action._byClipCacheIndex = null;
  26846. lastInactiveAction._cacheIndex = cacheIndex;
  26847. actions[cacheIndex] = lastInactiveAction;
  26848. actions.pop();
  26849. this._removeInactiveBindingsForAction(action);
  26850. }
  26851. delete actionsByClip[clipUuid];
  26852. }
  26853. } // free all resources specific to a particular root target object
  26854. uncacheRoot(root) {
  26855. const rootUuid = root.uuid,
  26856. actionsByClip = this._actionsByClip;
  26857. for (const clipUuid in actionsByClip) {
  26858. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  26859. action = actionByRoot[rootUuid];
  26860. if (action !== undefined) {
  26861. this._deactivateAction(action);
  26862. this._removeInactiveAction(action);
  26863. }
  26864. }
  26865. const bindingsByRoot = this._bindingsByRootAndName,
  26866. bindingByName = bindingsByRoot[rootUuid];
  26867. if (bindingByName !== undefined) {
  26868. for (const trackName in bindingByName) {
  26869. const binding = bindingByName[trackName];
  26870. binding.restoreOriginalState();
  26871. this._removeInactiveBinding(binding);
  26872. }
  26873. }
  26874. } // remove a targeted clip from the cache
  26875. uncacheAction(clip, optionalRoot) {
  26876. const action = this.existingAction(clip, optionalRoot);
  26877. if (action !== null) {
  26878. this._deactivateAction(action);
  26879. this._removeInactiveAction(action);
  26880. }
  26881. }
  26882. }
  26883. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array(1);
  26884. class Uniform {
  26885. constructor(value) {
  26886. if (typeof value === 'string') {
  26887. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  26888. value = arguments[1];
  26889. }
  26890. this.value = value;
  26891. }
  26892. clone() {
  26893. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  26894. }
  26895. }
  26896. class InstancedInterleavedBuffer extends InterleavedBuffer {
  26897. constructor(array, stride, meshPerAttribute = 1) {
  26898. super(array, stride);
  26899. this.meshPerAttribute = meshPerAttribute;
  26900. }
  26901. copy(source) {
  26902. super.copy(source);
  26903. this.meshPerAttribute = source.meshPerAttribute;
  26904. return this;
  26905. }
  26906. clone(data) {
  26907. const ib = super.clone(data);
  26908. ib.meshPerAttribute = this.meshPerAttribute;
  26909. return ib;
  26910. }
  26911. toJSON(data) {
  26912. const json = super.toJSON(data);
  26913. json.isInstancedInterleavedBuffer = true;
  26914. json.meshPerAttribute = this.meshPerAttribute;
  26915. return json;
  26916. }
  26917. }
  26918. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  26919. class GLBufferAttribute {
  26920. constructor(buffer, type, itemSize, elementSize, count) {
  26921. this.buffer = buffer;
  26922. this.type = type;
  26923. this.itemSize = itemSize;
  26924. this.elementSize = elementSize;
  26925. this.count = count;
  26926. this.version = 0;
  26927. }
  26928. set needsUpdate(value) {
  26929. if (value === true) this.version++;
  26930. }
  26931. setBuffer(buffer) {
  26932. this.buffer = buffer;
  26933. return this;
  26934. }
  26935. setType(type, elementSize) {
  26936. this.type = type;
  26937. this.elementSize = elementSize;
  26938. return this;
  26939. }
  26940. setItemSize(itemSize) {
  26941. this.itemSize = itemSize;
  26942. return this;
  26943. }
  26944. setCount(count) {
  26945. this.count = count;
  26946. return this;
  26947. }
  26948. }
  26949. GLBufferAttribute.prototype.isGLBufferAttribute = true;
  26950. class Raycaster {
  26951. constructor(origin, direction, near = 0, far = Infinity) {
  26952. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  26953. this.near = near;
  26954. this.far = far;
  26955. this.camera = null;
  26956. this.layers = new Layers();
  26957. this.params = {
  26958. Mesh: {},
  26959. Line: {
  26960. threshold: 1
  26961. },
  26962. LOD: {},
  26963. Points: {
  26964. threshold: 1
  26965. },
  26966. Sprite: {}
  26967. };
  26968. }
  26969. set(origin, direction) {
  26970. // direction is assumed to be normalized (for accurate distance calculations)
  26971. this.ray.set(origin, direction);
  26972. }
  26973. setFromCamera(coords, camera) {
  26974. if (camera && camera.isPerspectiveCamera) {
  26975. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  26976. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  26977. this.camera = camera;
  26978. } else if (camera && camera.isOrthographicCamera) {
  26979. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  26980. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  26981. this.camera = camera;
  26982. } else {
  26983. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  26984. }
  26985. }
  26986. intersectObject(object, recursive = false, intersects = []) {
  26987. intersectObject(object, this, intersects, recursive);
  26988. intersects.sort(ascSort);
  26989. return intersects;
  26990. }
  26991. intersectObjects(objects, recursive = false, intersects = []) {
  26992. for (let i = 0, l = objects.length; i < l; i++) {
  26993. intersectObject(objects[i], this, intersects, recursive);
  26994. }
  26995. intersects.sort(ascSort);
  26996. return intersects;
  26997. }
  26998. }
  26999. function ascSort(a, b) {
  27000. return a.distance - b.distance;
  27001. }
  27002. function intersectObject(object, raycaster, intersects, recursive) {
  27003. if (object.layers.test(raycaster.layers)) {
  27004. object.raycast(raycaster, intersects);
  27005. }
  27006. if (recursive === true) {
  27007. const children = object.children;
  27008. for (let i = 0, l = children.length; i < l; i++) {
  27009. intersectObject(children[i], raycaster, intersects, true);
  27010. }
  27011. }
  27012. }
  27013. /**
  27014. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27015. *
  27016. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27017. * The azimuthal angle (theta) is measured from the positive z-axis.
  27018. */
  27019. class Spherical {
  27020. constructor(radius = 1, phi = 0, theta = 0) {
  27021. this.radius = radius;
  27022. this.phi = phi; // polar angle
  27023. this.theta = theta; // azimuthal angle
  27024. return this;
  27025. }
  27026. set(radius, phi, theta) {
  27027. this.radius = radius;
  27028. this.phi = phi;
  27029. this.theta = theta;
  27030. return this;
  27031. }
  27032. copy(other) {
  27033. this.radius = other.radius;
  27034. this.phi = other.phi;
  27035. this.theta = other.theta;
  27036. return this;
  27037. } // restrict phi to be betwee EPS and PI-EPS
  27038. makeSafe() {
  27039. const EPS = 0.000001;
  27040. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  27041. return this;
  27042. }
  27043. setFromVector3(v) {
  27044. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27045. }
  27046. setFromCartesianCoords(x, y, z) {
  27047. this.radius = Math.sqrt(x * x + y * y + z * z);
  27048. if (this.radius === 0) {
  27049. this.theta = 0;
  27050. this.phi = 0;
  27051. } else {
  27052. this.theta = Math.atan2(x, z);
  27053. this.phi = Math.acos(clamp(y / this.radius, -1, 1));
  27054. }
  27055. return this;
  27056. }
  27057. clone() {
  27058. return new this.constructor().copy(this);
  27059. }
  27060. }
  27061. /**
  27062. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27063. */
  27064. class Cylindrical {
  27065. constructor(radius = 1, theta = 0, y = 0) {
  27066. this.radius = radius; // distance from the origin to a point in the x-z plane
  27067. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27068. this.y = y; // height above the x-z plane
  27069. return this;
  27070. }
  27071. set(radius, theta, y) {
  27072. this.radius = radius;
  27073. this.theta = theta;
  27074. this.y = y;
  27075. return this;
  27076. }
  27077. copy(other) {
  27078. this.radius = other.radius;
  27079. this.theta = other.theta;
  27080. this.y = other.y;
  27081. return this;
  27082. }
  27083. setFromVector3(v) {
  27084. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27085. }
  27086. setFromCartesianCoords(x, y, z) {
  27087. this.radius = Math.sqrt(x * x + z * z);
  27088. this.theta = Math.atan2(x, z);
  27089. this.y = y;
  27090. return this;
  27091. }
  27092. clone() {
  27093. return new this.constructor().copy(this);
  27094. }
  27095. }
  27096. const _vector$4 = /*@__PURE__*/new Vector2();
  27097. class Box2 {
  27098. constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) {
  27099. this.min = min;
  27100. this.max = max;
  27101. }
  27102. set(min, max) {
  27103. this.min.copy(min);
  27104. this.max.copy(max);
  27105. return this;
  27106. }
  27107. setFromPoints(points) {
  27108. this.makeEmpty();
  27109. for (let i = 0, il = points.length; i < il; i++) {
  27110. this.expandByPoint(points[i]);
  27111. }
  27112. return this;
  27113. }
  27114. setFromCenterAndSize(center, size) {
  27115. const halfSize = _vector$4.copy(size).multiplyScalar(0.5);
  27116. this.min.copy(center).sub(halfSize);
  27117. this.max.copy(center).add(halfSize);
  27118. return this;
  27119. }
  27120. clone() {
  27121. return new this.constructor().copy(this);
  27122. }
  27123. copy(box) {
  27124. this.min.copy(box.min);
  27125. this.max.copy(box.max);
  27126. return this;
  27127. }
  27128. makeEmpty() {
  27129. this.min.x = this.min.y = +Infinity;
  27130. this.max.x = this.max.y = -Infinity;
  27131. return this;
  27132. }
  27133. isEmpty() {
  27134. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27135. return this.max.x < this.min.x || this.max.y < this.min.y;
  27136. }
  27137. getCenter(target) {
  27138. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  27139. }
  27140. getSize(target) {
  27141. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  27142. }
  27143. expandByPoint(point) {
  27144. this.min.min(point);
  27145. this.max.max(point);
  27146. return this;
  27147. }
  27148. expandByVector(vector) {
  27149. this.min.sub(vector);
  27150. this.max.add(vector);
  27151. return this;
  27152. }
  27153. expandByScalar(scalar) {
  27154. this.min.addScalar(-scalar);
  27155. this.max.addScalar(scalar);
  27156. return this;
  27157. }
  27158. containsPoint(point) {
  27159. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  27160. }
  27161. containsBox(box) {
  27162. return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y;
  27163. }
  27164. getParameter(point, target) {
  27165. // This can potentially have a divide by zero if the box
  27166. // has a size dimension of 0.
  27167. return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y));
  27168. }
  27169. intersectsBox(box) {
  27170. // using 4 splitting planes to rule out intersections
  27171. return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  27172. }
  27173. clampPoint(point, target) {
  27174. return target.copy(point).clamp(this.min, this.max);
  27175. }
  27176. distanceToPoint(point) {
  27177. const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max);
  27178. return clampedPoint.sub(point).length();
  27179. }
  27180. intersect(box) {
  27181. this.min.max(box.min);
  27182. this.max.min(box.max);
  27183. return this;
  27184. }
  27185. union(box) {
  27186. this.min.min(box.min);
  27187. this.max.max(box.max);
  27188. return this;
  27189. }
  27190. translate(offset) {
  27191. this.min.add(offset);
  27192. this.max.add(offset);
  27193. return this;
  27194. }
  27195. equals(box) {
  27196. return box.min.equals(this.min) && box.max.equals(this.max);
  27197. }
  27198. }
  27199. Box2.prototype.isBox2 = true;
  27200. const _startP = /*@__PURE__*/new Vector3();
  27201. const _startEnd = /*@__PURE__*/new Vector3();
  27202. class Line3 {
  27203. constructor(start = new Vector3(), end = new Vector3()) {
  27204. this.start = start;
  27205. this.end = end;
  27206. }
  27207. set(start, end) {
  27208. this.start.copy(start);
  27209. this.end.copy(end);
  27210. return this;
  27211. }
  27212. copy(line) {
  27213. this.start.copy(line.start);
  27214. this.end.copy(line.end);
  27215. return this;
  27216. }
  27217. getCenter(target) {
  27218. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  27219. }
  27220. delta(target) {
  27221. return target.subVectors(this.end, this.start);
  27222. }
  27223. distanceSq() {
  27224. return this.start.distanceToSquared(this.end);
  27225. }
  27226. distance() {
  27227. return this.start.distanceTo(this.end);
  27228. }
  27229. at(t, target) {
  27230. return this.delta(target).multiplyScalar(t).add(this.start);
  27231. }
  27232. closestPointToPointParameter(point, clampToLine) {
  27233. _startP.subVectors(point, this.start);
  27234. _startEnd.subVectors(this.end, this.start);
  27235. const startEnd2 = _startEnd.dot(_startEnd);
  27236. const startEnd_startP = _startEnd.dot(_startP);
  27237. let t = startEnd_startP / startEnd2;
  27238. if (clampToLine) {
  27239. t = clamp(t, 0, 1);
  27240. }
  27241. return t;
  27242. }
  27243. closestPointToPoint(point, clampToLine, target) {
  27244. const t = this.closestPointToPointParameter(point, clampToLine);
  27245. return this.delta(target).multiplyScalar(t).add(this.start);
  27246. }
  27247. applyMatrix4(matrix) {
  27248. this.start.applyMatrix4(matrix);
  27249. this.end.applyMatrix4(matrix);
  27250. return this;
  27251. }
  27252. equals(line) {
  27253. return line.start.equals(this.start) && line.end.equals(this.end);
  27254. }
  27255. clone() {
  27256. return new this.constructor().copy(this);
  27257. }
  27258. }
  27259. class ImmediateRenderObject extends Object3D {
  27260. constructor(material) {
  27261. super();
  27262. this.material = material;
  27263. this.render = function () {};
  27264. this.hasPositions = false;
  27265. this.hasNormals = false;
  27266. this.hasColors = false;
  27267. this.hasUvs = false;
  27268. this.positionArray = null;
  27269. this.normalArray = null;
  27270. this.colorArray = null;
  27271. this.uvArray = null;
  27272. this.count = 0;
  27273. }
  27274. }
  27275. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  27276. const _vector$3 = /*@__PURE__*/new Vector3();
  27277. class SpotLightHelper extends Object3D {
  27278. constructor(light, color) {
  27279. super();
  27280. this.light = light;
  27281. this.light.updateMatrixWorld();
  27282. this.matrix = light.matrixWorld;
  27283. this.matrixAutoUpdate = false;
  27284. this.color = color;
  27285. const geometry = new BufferGeometry();
  27286. const positions = [0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, -1, 1];
  27287. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  27288. const p1 = i / l * Math.PI * 2;
  27289. const p2 = j / l * Math.PI * 2;
  27290. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  27291. }
  27292. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27293. const material = new LineBasicMaterial({
  27294. fog: false,
  27295. toneMapped: false
  27296. });
  27297. this.cone = new LineSegments(geometry, material);
  27298. this.add(this.cone);
  27299. this.update();
  27300. }
  27301. dispose() {
  27302. this.cone.geometry.dispose();
  27303. this.cone.material.dispose();
  27304. }
  27305. update() {
  27306. this.light.updateMatrixWorld();
  27307. const coneLength = this.light.distance ? this.light.distance : 1000;
  27308. const coneWidth = coneLength * Math.tan(this.light.angle);
  27309. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  27310. _vector$3.setFromMatrixPosition(this.light.target.matrixWorld);
  27311. this.cone.lookAt(_vector$3);
  27312. if (this.color !== undefined) {
  27313. this.cone.material.color.set(this.color);
  27314. } else {
  27315. this.cone.material.color.copy(this.light.color);
  27316. }
  27317. }
  27318. }
  27319. const _vector$2 = /*@__PURE__*/new Vector3();
  27320. const _boneMatrix = /*@__PURE__*/new Matrix4();
  27321. const _matrixWorldInv = /*@__PURE__*/new Matrix4();
  27322. class SkeletonHelper extends LineSegments {
  27323. constructor(object) {
  27324. const bones = getBoneList(object);
  27325. const geometry = new BufferGeometry();
  27326. const vertices = [];
  27327. const colors = [];
  27328. const color1 = new Color(0, 0, 1);
  27329. const color2 = new Color(0, 1, 0);
  27330. for (let i = 0; i < bones.length; i++) {
  27331. const bone = bones[i];
  27332. if (bone.parent && bone.parent.isBone) {
  27333. vertices.push(0, 0, 0);
  27334. vertices.push(0, 0, 0);
  27335. colors.push(color1.r, color1.g, color1.b);
  27336. colors.push(color2.r, color2.g, color2.b);
  27337. }
  27338. }
  27339. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27340. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27341. const material = new LineBasicMaterial({
  27342. vertexColors: true,
  27343. depthTest: false,
  27344. depthWrite: false,
  27345. toneMapped: false,
  27346. transparent: true
  27347. });
  27348. super(geometry, material);
  27349. this.type = 'SkeletonHelper';
  27350. this.isSkeletonHelper = true;
  27351. this.root = object;
  27352. this.bones = bones;
  27353. this.matrix = object.matrixWorld;
  27354. this.matrixAutoUpdate = false;
  27355. }
  27356. updateMatrixWorld(force) {
  27357. const bones = this.bones;
  27358. const geometry = this.geometry;
  27359. const position = geometry.getAttribute('position');
  27360. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  27361. for (let i = 0, j = 0; i < bones.length; i++) {
  27362. const bone = bones[i];
  27363. if (bone.parent && bone.parent.isBone) {
  27364. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  27365. _vector$2.setFromMatrixPosition(_boneMatrix);
  27366. position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z);
  27367. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  27368. _vector$2.setFromMatrixPosition(_boneMatrix);
  27369. position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z);
  27370. j += 2;
  27371. }
  27372. }
  27373. geometry.getAttribute('position').needsUpdate = true;
  27374. super.updateMatrixWorld(force);
  27375. }
  27376. }
  27377. function getBoneList(object) {
  27378. const boneList = [];
  27379. if (object && object.isBone) {
  27380. boneList.push(object);
  27381. }
  27382. for (let i = 0; i < object.children.length; i++) {
  27383. boneList.push.apply(boneList, getBoneList(object.children[i]));
  27384. }
  27385. return boneList;
  27386. }
  27387. class PointLightHelper extends Mesh {
  27388. constructor(light, sphereSize, color) {
  27389. const geometry = new SphereGeometry(sphereSize, 4, 2);
  27390. const material = new MeshBasicMaterial({
  27391. wireframe: true,
  27392. fog: false,
  27393. toneMapped: false
  27394. });
  27395. super(geometry, material);
  27396. this.light = light;
  27397. this.light.updateMatrixWorld();
  27398. this.color = color;
  27399. this.type = 'PointLightHelper';
  27400. this.matrix = this.light.matrixWorld;
  27401. this.matrixAutoUpdate = false;
  27402. this.update();
  27403. /*
  27404. // TODO: delete this comment?
  27405. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  27406. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  27407. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  27408. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  27409. const d = light.distance;
  27410. if ( d === 0.0 ) {
  27411. this.lightDistance.visible = false;
  27412. } else {
  27413. this.lightDistance.scale.set( d, d, d );
  27414. }
  27415. this.add( this.lightDistance );
  27416. */
  27417. }
  27418. dispose() {
  27419. this.geometry.dispose();
  27420. this.material.dispose();
  27421. }
  27422. update() {
  27423. if (this.color !== undefined) {
  27424. this.material.color.set(this.color);
  27425. } else {
  27426. this.material.color.copy(this.light.color);
  27427. }
  27428. /*
  27429. const d = this.light.distance;
  27430. if ( d === 0.0 ) {
  27431. this.lightDistance.visible = false;
  27432. } else {
  27433. this.lightDistance.visible = true;
  27434. this.lightDistance.scale.set( d, d, d );
  27435. }
  27436. */
  27437. }
  27438. }
  27439. const _vector$1 = /*@__PURE__*/new Vector3();
  27440. const _color1 = /*@__PURE__*/new Color();
  27441. const _color2 = /*@__PURE__*/new Color();
  27442. class HemisphereLightHelper extends Object3D {
  27443. constructor(light, size, color) {
  27444. super();
  27445. this.light = light;
  27446. this.light.updateMatrixWorld();
  27447. this.matrix = light.matrixWorld;
  27448. this.matrixAutoUpdate = false;
  27449. this.color = color;
  27450. const geometry = new OctahedronGeometry(size);
  27451. geometry.rotateY(Math.PI * 0.5);
  27452. this.material = new MeshBasicMaterial({
  27453. wireframe: true,
  27454. fog: false,
  27455. toneMapped: false
  27456. });
  27457. if (this.color === undefined) this.material.vertexColors = true;
  27458. const position = geometry.getAttribute('position');
  27459. const colors = new Float32Array(position.count * 3);
  27460. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  27461. this.add(new Mesh(geometry, this.material));
  27462. this.update();
  27463. }
  27464. dispose() {
  27465. this.children[0].geometry.dispose();
  27466. this.children[0].material.dispose();
  27467. }
  27468. update() {
  27469. const mesh = this.children[0];
  27470. if (this.color !== undefined) {
  27471. this.material.color.set(this.color);
  27472. } else {
  27473. const colors = mesh.geometry.getAttribute('color');
  27474. _color1.copy(this.light.color);
  27475. _color2.copy(this.light.groundColor);
  27476. for (let i = 0, l = colors.count; i < l; i++) {
  27477. const color = i < l / 2 ? _color1 : _color2;
  27478. colors.setXYZ(i, color.r, color.g, color.b);
  27479. }
  27480. colors.needsUpdate = true;
  27481. }
  27482. mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
  27483. }
  27484. }
  27485. class GridHelper extends LineSegments {
  27486. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  27487. color1 = new Color(color1);
  27488. color2 = new Color(color2);
  27489. const center = divisions / 2;
  27490. const step = size / divisions;
  27491. const halfSize = size / 2;
  27492. const vertices = [],
  27493. colors = [];
  27494. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  27495. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  27496. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  27497. const color = i === center ? color1 : color2;
  27498. color.toArray(colors, j);
  27499. j += 3;
  27500. color.toArray(colors, j);
  27501. j += 3;
  27502. color.toArray(colors, j);
  27503. j += 3;
  27504. color.toArray(colors, j);
  27505. j += 3;
  27506. }
  27507. const geometry = new BufferGeometry();
  27508. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27509. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27510. const material = new LineBasicMaterial({
  27511. vertexColors: true,
  27512. toneMapped: false
  27513. });
  27514. super(geometry, material);
  27515. this.type = 'GridHelper';
  27516. }
  27517. }
  27518. class PolarGridHelper extends LineSegments {
  27519. constructor(radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  27520. color1 = new Color(color1);
  27521. color2 = new Color(color2);
  27522. const vertices = [];
  27523. const colors = []; // create the radials
  27524. for (let i = 0; i <= radials; i++) {
  27525. const v = i / radials * (Math.PI * 2);
  27526. const x = Math.sin(v) * radius;
  27527. const z = Math.cos(v) * radius;
  27528. vertices.push(0, 0, 0);
  27529. vertices.push(x, 0, z);
  27530. const color = i & 1 ? color1 : color2;
  27531. colors.push(color.r, color.g, color.b);
  27532. colors.push(color.r, color.g, color.b);
  27533. } // create the circles
  27534. for (let i = 0; i <= circles; i++) {
  27535. const color = i & 1 ? color1 : color2;
  27536. const r = radius - radius / circles * i;
  27537. for (let j = 0; j < divisions; j++) {
  27538. // first vertex
  27539. let v = j / divisions * (Math.PI * 2);
  27540. let x = Math.sin(v) * r;
  27541. let z = Math.cos(v) * r;
  27542. vertices.push(x, 0, z);
  27543. colors.push(color.r, color.g, color.b); // second vertex
  27544. v = (j + 1) / divisions * (Math.PI * 2);
  27545. x = Math.sin(v) * r;
  27546. z = Math.cos(v) * r;
  27547. vertices.push(x, 0, z);
  27548. colors.push(color.r, color.g, color.b);
  27549. }
  27550. }
  27551. const geometry = new BufferGeometry();
  27552. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27553. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27554. const material = new LineBasicMaterial({
  27555. vertexColors: true,
  27556. toneMapped: false
  27557. });
  27558. super(geometry, material);
  27559. this.type = 'PolarGridHelper';
  27560. }
  27561. }
  27562. const _v1 = /*@__PURE__*/new Vector3();
  27563. const _v2 = /*@__PURE__*/new Vector3();
  27564. const _v3 = /*@__PURE__*/new Vector3();
  27565. class DirectionalLightHelper extends Object3D {
  27566. constructor(light, size, color) {
  27567. super();
  27568. this.light = light;
  27569. this.light.updateMatrixWorld();
  27570. this.matrix = light.matrixWorld;
  27571. this.matrixAutoUpdate = false;
  27572. this.color = color;
  27573. if (size === undefined) size = 1;
  27574. let geometry = new BufferGeometry();
  27575. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  27576. const material = new LineBasicMaterial({
  27577. fog: false,
  27578. toneMapped: false
  27579. });
  27580. this.lightPlane = new Line(geometry, material);
  27581. this.add(this.lightPlane);
  27582. geometry = new BufferGeometry();
  27583. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  27584. this.targetLine = new Line(geometry, material);
  27585. this.add(this.targetLine);
  27586. this.update();
  27587. }
  27588. dispose() {
  27589. this.lightPlane.geometry.dispose();
  27590. this.lightPlane.material.dispose();
  27591. this.targetLine.geometry.dispose();
  27592. this.targetLine.material.dispose();
  27593. }
  27594. update() {
  27595. _v1.setFromMatrixPosition(this.light.matrixWorld);
  27596. _v2.setFromMatrixPosition(this.light.target.matrixWorld);
  27597. _v3.subVectors(_v2, _v1);
  27598. this.lightPlane.lookAt(_v2);
  27599. if (this.color !== undefined) {
  27600. this.lightPlane.material.color.set(this.color);
  27601. this.targetLine.material.color.set(this.color);
  27602. } else {
  27603. this.lightPlane.material.color.copy(this.light.color);
  27604. this.targetLine.material.color.copy(this.light.color);
  27605. }
  27606. this.targetLine.lookAt(_v2);
  27607. this.targetLine.scale.z = _v3.length();
  27608. }
  27609. }
  27610. const _vector = /*@__PURE__*/new Vector3();
  27611. const _camera = /*@__PURE__*/new Camera();
  27612. /**
  27613. * - shows frustum, line of sight and up of the camera
  27614. * - suitable for fast updates
  27615. * - based on frustum visualization in lightgl.js shadowmap example
  27616. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  27617. */
  27618. class CameraHelper extends LineSegments {
  27619. constructor(camera) {
  27620. const geometry = new BufferGeometry();
  27621. const material = new LineBasicMaterial({
  27622. color: 0xffffff,
  27623. vertexColors: true,
  27624. toneMapped: false
  27625. });
  27626. const vertices = [];
  27627. const colors = [];
  27628. const pointMap = {}; // colors
  27629. const colorFrustum = new Color(0xffaa00);
  27630. const colorCone = new Color(0xff0000);
  27631. const colorUp = new Color(0x00aaff);
  27632. const colorTarget = new Color(0xffffff);
  27633. const colorCross = new Color(0x333333); // near
  27634. addLine('n1', 'n2', colorFrustum);
  27635. addLine('n2', 'n4', colorFrustum);
  27636. addLine('n4', 'n3', colorFrustum);
  27637. addLine('n3', 'n1', colorFrustum); // far
  27638. addLine('f1', 'f2', colorFrustum);
  27639. addLine('f2', 'f4', colorFrustum);
  27640. addLine('f4', 'f3', colorFrustum);
  27641. addLine('f3', 'f1', colorFrustum); // sides
  27642. addLine('n1', 'f1', colorFrustum);
  27643. addLine('n2', 'f2', colorFrustum);
  27644. addLine('n3', 'f3', colorFrustum);
  27645. addLine('n4', 'f4', colorFrustum); // cone
  27646. addLine('p', 'n1', colorCone);
  27647. addLine('p', 'n2', colorCone);
  27648. addLine('p', 'n3', colorCone);
  27649. addLine('p', 'n4', colorCone); // up
  27650. addLine('u1', 'u2', colorUp);
  27651. addLine('u2', 'u3', colorUp);
  27652. addLine('u3', 'u1', colorUp); // target
  27653. addLine('c', 't', colorTarget);
  27654. addLine('p', 'c', colorCross); // cross
  27655. addLine('cn1', 'cn2', colorCross);
  27656. addLine('cn3', 'cn4', colorCross);
  27657. addLine('cf1', 'cf2', colorCross);
  27658. addLine('cf3', 'cf4', colorCross);
  27659. function addLine(a, b, color) {
  27660. addPoint(a, color);
  27661. addPoint(b, color);
  27662. }
  27663. function addPoint(id, color) {
  27664. vertices.push(0, 0, 0);
  27665. colors.push(color.r, color.g, color.b);
  27666. if (pointMap[id] === undefined) {
  27667. pointMap[id] = [];
  27668. }
  27669. pointMap[id].push(vertices.length / 3 - 1);
  27670. }
  27671. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27672. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27673. super(geometry, material);
  27674. this.type = 'CameraHelper';
  27675. this.camera = camera;
  27676. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  27677. this.matrix = camera.matrixWorld;
  27678. this.matrixAutoUpdate = false;
  27679. this.pointMap = pointMap;
  27680. this.update();
  27681. }
  27682. update() {
  27683. const geometry = this.geometry;
  27684. const pointMap = this.pointMap;
  27685. const w = 1,
  27686. h = 1; // we need just camera projection matrix inverse
  27687. // world matrix must be identity
  27688. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  27689. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  27690. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  27691. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  27692. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  27693. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  27694. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  27695. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  27696. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  27697. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  27698. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  27699. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  27700. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  27701. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  27702. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  27703. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  27704. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  27705. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  27706. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  27707. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  27708. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  27709. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  27710. geometry.getAttribute('position').needsUpdate = true;
  27711. }
  27712. dispose() {
  27713. this.geometry.dispose();
  27714. this.material.dispose();
  27715. }
  27716. }
  27717. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  27718. _vector.set(x, y, z).unproject(camera);
  27719. const points = pointMap[point];
  27720. if (points !== undefined) {
  27721. const position = geometry.getAttribute('position');
  27722. for (let i = 0, l = points.length; i < l; i++) {
  27723. position.setXYZ(points[i], _vector.x, _vector.y, _vector.z);
  27724. }
  27725. }
  27726. }
  27727. const _box = /*@__PURE__*/new Box3();
  27728. class BoxHelper extends LineSegments {
  27729. constructor(object, color = 0xffff00) {
  27730. 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]);
  27731. const positions = new Float32Array(8 * 3);
  27732. const geometry = new BufferGeometry();
  27733. geometry.setIndex(new BufferAttribute(indices, 1));
  27734. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  27735. super(geometry, new LineBasicMaterial({
  27736. color: color,
  27737. toneMapped: false
  27738. }));
  27739. this.object = object;
  27740. this.type = 'BoxHelper';
  27741. this.matrixAutoUpdate = false;
  27742. this.update();
  27743. }
  27744. update(object) {
  27745. if (object !== undefined) {
  27746. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  27747. }
  27748. if (this.object !== undefined) {
  27749. _box.setFromObject(this.object);
  27750. }
  27751. if (_box.isEmpty()) return;
  27752. const min = _box.min;
  27753. const max = _box.max;
  27754. /*
  27755. 5____4
  27756. 1/___0/|
  27757. | 6__|_7
  27758. 2/___3/
  27759. 0: max.x, max.y, max.z
  27760. 1: min.x, max.y, max.z
  27761. 2: min.x, min.y, max.z
  27762. 3: max.x, min.y, max.z
  27763. 4: max.x, max.y, min.z
  27764. 5: min.x, max.y, min.z
  27765. 6: min.x, min.y, min.z
  27766. 7: max.x, min.y, min.z
  27767. */
  27768. const position = this.geometry.attributes.position;
  27769. const array = position.array;
  27770. array[0] = max.x;
  27771. array[1] = max.y;
  27772. array[2] = max.z;
  27773. array[3] = min.x;
  27774. array[4] = max.y;
  27775. array[5] = max.z;
  27776. array[6] = min.x;
  27777. array[7] = min.y;
  27778. array[8] = max.z;
  27779. array[9] = max.x;
  27780. array[10] = min.y;
  27781. array[11] = max.z;
  27782. array[12] = max.x;
  27783. array[13] = max.y;
  27784. array[14] = min.z;
  27785. array[15] = min.x;
  27786. array[16] = max.y;
  27787. array[17] = min.z;
  27788. array[18] = min.x;
  27789. array[19] = min.y;
  27790. array[20] = min.z;
  27791. array[21] = max.x;
  27792. array[22] = min.y;
  27793. array[23] = min.z;
  27794. position.needsUpdate = true;
  27795. this.geometry.computeBoundingSphere();
  27796. }
  27797. setFromObject(object) {
  27798. this.object = object;
  27799. this.update();
  27800. return this;
  27801. }
  27802. copy(source) {
  27803. LineSegments.prototype.copy.call(this, source);
  27804. this.object = source.object;
  27805. return this;
  27806. }
  27807. }
  27808. class Box3Helper extends LineSegments {
  27809. constructor(box, color = 0xffff00) {
  27810. 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]);
  27811. 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];
  27812. const geometry = new BufferGeometry();
  27813. geometry.setIndex(new BufferAttribute(indices, 1));
  27814. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27815. super(geometry, new LineBasicMaterial({
  27816. color: color,
  27817. toneMapped: false
  27818. }));
  27819. this.box = box;
  27820. this.type = 'Box3Helper';
  27821. this.geometry.computeBoundingSphere();
  27822. }
  27823. updateMatrixWorld(force) {
  27824. const box = this.box;
  27825. if (box.isEmpty()) return;
  27826. box.getCenter(this.position);
  27827. box.getSize(this.scale);
  27828. this.scale.multiplyScalar(0.5);
  27829. super.updateMatrixWorld(force);
  27830. }
  27831. }
  27832. class PlaneHelper extends Line {
  27833. constructor(plane, size = 1, hex = 0xffff00) {
  27834. const color = hex;
  27835. 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, 0, 0, 1, 0, 0, 0];
  27836. const geometry = new BufferGeometry();
  27837. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27838. geometry.computeBoundingSphere();
  27839. super(geometry, new LineBasicMaterial({
  27840. color: color,
  27841. toneMapped: false
  27842. }));
  27843. this.type = 'PlaneHelper';
  27844. this.plane = plane;
  27845. this.size = size;
  27846. const positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  27847. const geometry2 = new BufferGeometry();
  27848. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  27849. geometry2.computeBoundingSphere();
  27850. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  27851. color: color,
  27852. opacity: 0.2,
  27853. transparent: true,
  27854. depthWrite: false,
  27855. toneMapped: false
  27856. })));
  27857. }
  27858. updateMatrixWorld(force) {
  27859. let scale = -this.plane.constant;
  27860. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  27861. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  27862. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  27863. this.lookAt(this.plane.normal);
  27864. super.updateMatrixWorld(force);
  27865. }
  27866. }
  27867. const _axis = /*@__PURE__*/new Vector3();
  27868. let _lineGeometry, _coneGeometry;
  27869. class ArrowHelper extends Object3D {
  27870. // dir is assumed to be normalized
  27871. 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) {
  27872. super();
  27873. this.type = 'ArrowHelper';
  27874. if (_lineGeometry === undefined) {
  27875. _lineGeometry = new BufferGeometry();
  27876. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  27877. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  27878. _coneGeometry.translate(0, -0.5, 0);
  27879. }
  27880. this.position.copy(origin);
  27881. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  27882. color: color,
  27883. toneMapped: false
  27884. }));
  27885. this.line.matrixAutoUpdate = false;
  27886. this.add(this.line);
  27887. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  27888. color: color,
  27889. toneMapped: false
  27890. }));
  27891. this.cone.matrixAutoUpdate = false;
  27892. this.add(this.cone);
  27893. this.setDirection(dir);
  27894. this.setLength(length, headLength, headWidth);
  27895. }
  27896. setDirection(dir) {
  27897. // dir is assumed to be normalized
  27898. if (dir.y > 0.99999) {
  27899. this.quaternion.set(0, 0, 0, 1);
  27900. } else if (dir.y < -0.99999) {
  27901. this.quaternion.set(1, 0, 0, 0);
  27902. } else {
  27903. _axis.set(dir.z, 0, -dir.x).normalize();
  27904. const radians = Math.acos(dir.y);
  27905. this.quaternion.setFromAxisAngle(_axis, radians);
  27906. }
  27907. }
  27908. setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
  27909. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  27910. this.line.updateMatrix();
  27911. this.cone.scale.set(headWidth, headLength, headWidth);
  27912. this.cone.position.y = length;
  27913. this.cone.updateMatrix();
  27914. }
  27915. setColor(color) {
  27916. this.line.material.color.set(color);
  27917. this.cone.material.color.set(color);
  27918. }
  27919. copy(source) {
  27920. super.copy(source, false);
  27921. this.line.copy(source.line);
  27922. this.cone.copy(source.cone);
  27923. return this;
  27924. }
  27925. }
  27926. class AxesHelper extends LineSegments {
  27927. constructor(size = 1) {
  27928. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  27929. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  27930. const geometry = new BufferGeometry();
  27931. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27932. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27933. const material = new LineBasicMaterial({
  27934. vertexColors: true,
  27935. toneMapped: false
  27936. });
  27937. super(geometry, material);
  27938. this.type = 'AxesHelper';
  27939. }
  27940. setColors(xAxisColor, yAxisColor, zAxisColor) {
  27941. const color = new Color();
  27942. const array = this.geometry.attributes.color.array;
  27943. color.set(xAxisColor);
  27944. color.toArray(array, 0);
  27945. color.toArray(array, 3);
  27946. color.set(yAxisColor);
  27947. color.toArray(array, 6);
  27948. color.toArray(array, 9);
  27949. color.set(zAxisColor);
  27950. color.toArray(array, 12);
  27951. color.toArray(array, 15);
  27952. this.geometry.attributes.color.needsUpdate = true;
  27953. return this;
  27954. }
  27955. dispose() {
  27956. this.geometry.dispose();
  27957. this.material.dispose();
  27958. }
  27959. }
  27960. const _floatView = new Float32Array(1);
  27961. const _int32View = new Int32Array(_floatView.buffer);
  27962. class DataUtils {
  27963. // Converts float32 to float16 (stored as uint16 value).
  27964. static toHalfFloat(val) {
  27965. if (val > 65504) {
  27966. console.warn('THREE.DataUtils.toHalfFloat(): value exceeds 65504.');
  27967. val = 65504; // maximum representable value in float16
  27968. } // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  27969. /* This method is faster than the OpenEXR implementation (very often
  27970. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  27971. * by James Tursa?s half-precision code. */
  27972. _floatView[0] = val;
  27973. const x = _int32View[0];
  27974. let bits = x >> 16 & 0x8000;
  27975. /* Get the sign */
  27976. let m = x >> 12 & 0x07ff;
  27977. /* Keep one extra bit for rounding */
  27978. const e = x >> 23 & 0xff;
  27979. /* Using int is faster here */
  27980. /* If zero, or denormal, or exponent underflows too much for a denormal
  27981. * half, return signed zero. */
  27982. if (e < 103) return bits;
  27983. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  27984. if (e > 142) {
  27985. bits |= 0x7c00;
  27986. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  27987. * not Inf, so make sure we set one mantissa bit too. */
  27988. bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
  27989. return bits;
  27990. }
  27991. /* If exponent underflows but not too much, return a denormal */
  27992. if (e < 113) {
  27993. m |= 0x0800;
  27994. /* Extra rounding may overflow and set mantissa to 0 and exponent
  27995. * to 1, which is OK. */
  27996. bits |= (m >> 114 - e) + (m >> 113 - e & 1);
  27997. return bits;
  27998. }
  27999. bits |= e - 112 << 10 | m >> 1;
  28000. /* Extra rounding. An overflow will set mantissa to 0 and increment
  28001. * the exponent, which is OK. */
  28002. bits += m & 1;
  28003. return bits;
  28004. }
  28005. }
  28006. const LineStrip = 0;
  28007. const LinePieces = 1;
  28008. const NoColors = 0;
  28009. const FaceColors = 1;
  28010. const VertexColors = 2;
  28011. function MeshFaceMaterial(materials) {
  28012. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  28013. return materials;
  28014. }
  28015. function MultiMaterial(materials = []) {
  28016. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  28017. materials.isMultiMaterial = true;
  28018. materials.materials = materials;
  28019. materials.clone = function () {
  28020. return materials.slice();
  28021. };
  28022. return materials;
  28023. }
  28024. function PointCloud(geometry, material) {
  28025. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  28026. return new Points(geometry, material);
  28027. }
  28028. function Particle(material) {
  28029. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  28030. return new Sprite(material);
  28031. }
  28032. function ParticleSystem(geometry, material) {
  28033. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  28034. return new Points(geometry, material);
  28035. }
  28036. function PointCloudMaterial(parameters) {
  28037. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  28038. return new PointsMaterial(parameters);
  28039. }
  28040. function ParticleBasicMaterial(parameters) {
  28041. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  28042. return new PointsMaterial(parameters);
  28043. }
  28044. function ParticleSystemMaterial(parameters) {
  28045. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  28046. return new PointsMaterial(parameters);
  28047. }
  28048. function Vertex(x, y, z) {
  28049. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  28050. return new Vector3(x, y, z);
  28051. } //
  28052. function DynamicBufferAttribute(array, itemSize) {
  28053. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  28054. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  28055. }
  28056. function Int8Attribute(array, itemSize) {
  28057. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  28058. return new Int8BufferAttribute(array, itemSize);
  28059. }
  28060. function Uint8Attribute(array, itemSize) {
  28061. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  28062. return new Uint8BufferAttribute(array, itemSize);
  28063. }
  28064. function Uint8ClampedAttribute(array, itemSize) {
  28065. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  28066. return new Uint8ClampedBufferAttribute(array, itemSize);
  28067. }
  28068. function Int16Attribute(array, itemSize) {
  28069. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  28070. return new Int16BufferAttribute(array, itemSize);
  28071. }
  28072. function Uint16Attribute(array, itemSize) {
  28073. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  28074. return new Uint16BufferAttribute(array, itemSize);
  28075. }
  28076. function Int32Attribute(array, itemSize) {
  28077. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  28078. return new Int32BufferAttribute(array, itemSize);
  28079. }
  28080. function Uint32Attribute(array, itemSize) {
  28081. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  28082. return new Uint32BufferAttribute(array, itemSize);
  28083. }
  28084. function Float32Attribute(array, itemSize) {
  28085. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  28086. return new Float32BufferAttribute(array, itemSize);
  28087. }
  28088. function Float64Attribute(array, itemSize) {
  28089. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  28090. return new Float64BufferAttribute(array, itemSize);
  28091. } //
  28092. Curve.create = function (construct, getPoint) {
  28093. console.log('THREE.Curve.create() has been deprecated');
  28094. construct.prototype = Object.create(Curve.prototype);
  28095. construct.prototype.constructor = construct;
  28096. construct.prototype.getPoint = getPoint;
  28097. return construct;
  28098. }; //
  28099. Path.prototype.fromPoints = function (points) {
  28100. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  28101. return this.setFromPoints(points);
  28102. }; //
  28103. function AxisHelper(size) {
  28104. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  28105. return new AxesHelper(size);
  28106. }
  28107. function BoundingBoxHelper(object, color) {
  28108. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  28109. return new BoxHelper(object, color);
  28110. }
  28111. function EdgesHelper(object, hex) {
  28112. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  28113. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  28114. color: hex !== undefined ? hex : 0xffffff
  28115. }));
  28116. }
  28117. GridHelper.prototype.setColors = function () {
  28118. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  28119. };
  28120. SkeletonHelper.prototype.update = function () {
  28121. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  28122. };
  28123. function WireframeHelper(object, hex) {
  28124. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  28125. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  28126. color: hex !== undefined ? hex : 0xffffff
  28127. }));
  28128. } //
  28129. Loader.prototype.extractUrlBase = function (url) {
  28130. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  28131. return LoaderUtils.extractUrlBase(url);
  28132. };
  28133. Loader.Handlers = {
  28134. add: function () {
  28135. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  28136. },
  28137. get: function () {
  28138. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  28139. }
  28140. };
  28141. function XHRLoader(manager) {
  28142. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  28143. return new FileLoader(manager);
  28144. }
  28145. function BinaryTextureLoader(manager) {
  28146. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  28147. return new DataTextureLoader(manager);
  28148. } //
  28149. Box2.prototype.center = function (optionalTarget) {
  28150. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  28151. return this.getCenter(optionalTarget);
  28152. };
  28153. Box2.prototype.empty = function () {
  28154. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  28155. return this.isEmpty();
  28156. };
  28157. Box2.prototype.isIntersectionBox = function (box) {
  28158. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  28159. return this.intersectsBox(box);
  28160. };
  28161. Box2.prototype.size = function (optionalTarget) {
  28162. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  28163. return this.getSize(optionalTarget);
  28164. }; //
  28165. Box3.prototype.center = function (optionalTarget) {
  28166. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  28167. return this.getCenter(optionalTarget);
  28168. };
  28169. Box3.prototype.empty = function () {
  28170. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  28171. return this.isEmpty();
  28172. };
  28173. Box3.prototype.isIntersectionBox = function (box) {
  28174. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  28175. return this.intersectsBox(box);
  28176. };
  28177. Box3.prototype.isIntersectionSphere = function (sphere) {
  28178. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28179. return this.intersectsSphere(sphere);
  28180. };
  28181. Box3.prototype.size = function (optionalTarget) {
  28182. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  28183. return this.getSize(optionalTarget);
  28184. }; //
  28185. Sphere.prototype.empty = function () {
  28186. console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
  28187. return this.isEmpty();
  28188. }; //
  28189. Frustum.prototype.setFromMatrix = function (m) {
  28190. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  28191. return this.setFromProjectionMatrix(m);
  28192. }; //
  28193. Line3.prototype.center = function (optionalTarget) {
  28194. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  28195. return this.getCenter(optionalTarget);
  28196. }; //
  28197. Matrix3.prototype.flattenToArrayOffset = function (array, offset) {
  28198. console.warn('THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  28199. return this.toArray(array, offset);
  28200. };
  28201. Matrix3.prototype.multiplyVector3 = function (vector) {
  28202. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  28203. return vector.applyMatrix3(this);
  28204. };
  28205. Matrix3.prototype.multiplyVector3Array = function () {
  28206. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  28207. };
  28208. Matrix3.prototype.applyToBufferAttribute = function (attribute) {
  28209. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  28210. return attribute.applyMatrix3(this);
  28211. };
  28212. Matrix3.prototype.applyToVector3Array = function () {
  28213. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  28214. };
  28215. Matrix3.prototype.getInverse = function (matrix) {
  28216. console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  28217. return this.copy(matrix).invert();
  28218. }; //
  28219. Matrix4.prototype.extractPosition = function (m) {
  28220. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  28221. return this.copyPosition(m);
  28222. };
  28223. Matrix4.prototype.flattenToArrayOffset = function (array, offset) {
  28224. console.warn('THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  28225. return this.toArray(array, offset);
  28226. };
  28227. Matrix4.prototype.getPosition = function () {
  28228. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  28229. return new Vector3().setFromMatrixColumn(this, 3);
  28230. };
  28231. Matrix4.prototype.setRotationFromQuaternion = function (q) {
  28232. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  28233. return this.makeRotationFromQuaternion(q);
  28234. };
  28235. Matrix4.prototype.multiplyToArray = function () {
  28236. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  28237. };
  28238. Matrix4.prototype.multiplyVector3 = function (vector) {
  28239. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28240. return vector.applyMatrix4(this);
  28241. };
  28242. Matrix4.prototype.multiplyVector4 = function (vector) {
  28243. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28244. return vector.applyMatrix4(this);
  28245. };
  28246. Matrix4.prototype.multiplyVector3Array = function () {
  28247. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  28248. };
  28249. Matrix4.prototype.rotateAxis = function (v) {
  28250. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  28251. v.transformDirection(this);
  28252. };
  28253. Matrix4.prototype.crossVector = function (vector) {
  28254. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28255. return vector.applyMatrix4(this);
  28256. };
  28257. Matrix4.prototype.translate = function () {
  28258. console.error('THREE.Matrix4: .translate() has been removed.');
  28259. };
  28260. Matrix4.prototype.rotateX = function () {
  28261. console.error('THREE.Matrix4: .rotateX() has been removed.');
  28262. };
  28263. Matrix4.prototype.rotateY = function () {
  28264. console.error('THREE.Matrix4: .rotateY() has been removed.');
  28265. };
  28266. Matrix4.prototype.rotateZ = function () {
  28267. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  28268. };
  28269. Matrix4.prototype.rotateByAxis = function () {
  28270. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  28271. };
  28272. Matrix4.prototype.applyToBufferAttribute = function (attribute) {
  28273. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  28274. return attribute.applyMatrix4(this);
  28275. };
  28276. Matrix4.prototype.applyToVector3Array = function () {
  28277. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  28278. };
  28279. Matrix4.prototype.makeFrustum = function (left, right, bottom, top, near, far) {
  28280. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  28281. return this.makePerspective(left, right, top, bottom, near, far);
  28282. };
  28283. Matrix4.prototype.getInverse = function (matrix) {
  28284. console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  28285. return this.copy(matrix).invert();
  28286. }; //
  28287. Plane.prototype.isIntersectionLine = function (line) {
  28288. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  28289. return this.intersectsLine(line);
  28290. }; //
  28291. Quaternion.prototype.multiplyVector3 = function (vector) {
  28292. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  28293. return vector.applyQuaternion(this);
  28294. };
  28295. Quaternion.prototype.inverse = function () {
  28296. console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
  28297. return this.invert();
  28298. }; //
  28299. Ray.prototype.isIntersectionBox = function (box) {
  28300. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  28301. return this.intersectsBox(box);
  28302. };
  28303. Ray.prototype.isIntersectionPlane = function (plane) {
  28304. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  28305. return this.intersectsPlane(plane);
  28306. };
  28307. Ray.prototype.isIntersectionSphere = function (sphere) {
  28308. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28309. return this.intersectsSphere(sphere);
  28310. }; //
  28311. Triangle.prototype.area = function () {
  28312. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  28313. return this.getArea();
  28314. };
  28315. Triangle.prototype.barycoordFromPoint = function (point, target) {
  28316. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28317. return this.getBarycoord(point, target);
  28318. };
  28319. Triangle.prototype.midpoint = function (target) {
  28320. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  28321. return this.getMidpoint(target);
  28322. };
  28323. Triangle.prototypenormal = function (target) {
  28324. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28325. return this.getNormal(target);
  28326. };
  28327. Triangle.prototype.plane = function (target) {
  28328. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  28329. return this.getPlane(target);
  28330. };
  28331. Triangle.barycoordFromPoint = function (point, a, b, c, target) {
  28332. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28333. return Triangle.getBarycoord(point, a, b, c, target);
  28334. };
  28335. Triangle.normal = function (a, b, c, target) {
  28336. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28337. return Triangle.getNormal(a, b, c, target);
  28338. }; //
  28339. Shape.prototype.extractAllPoints = function (divisions) {
  28340. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  28341. return this.extractPoints(divisions);
  28342. };
  28343. Shape.prototype.extrude = function (options) {
  28344. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  28345. return new ExtrudeGeometry(this, options);
  28346. };
  28347. Shape.prototype.makeGeometry = function (options) {
  28348. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  28349. return new ShapeGeometry(this, options);
  28350. }; //
  28351. Vector2.prototype.fromAttribute = function (attribute, index, offset) {
  28352. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28353. return this.fromBufferAttribute(attribute, index, offset);
  28354. };
  28355. Vector2.prototype.distanceToManhattan = function (v) {
  28356. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28357. return this.manhattanDistanceTo(v);
  28358. };
  28359. Vector2.prototype.lengthManhattan = function () {
  28360. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  28361. return this.manhattanLength();
  28362. }; //
  28363. Vector3.prototype.setEulerFromRotationMatrix = function () {
  28364. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  28365. };
  28366. Vector3.prototype.setEulerFromQuaternion = function () {
  28367. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  28368. };
  28369. Vector3.prototype.getPositionFromMatrix = function (m) {
  28370. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  28371. return this.setFromMatrixPosition(m);
  28372. };
  28373. Vector3.prototype.getScaleFromMatrix = function (m) {
  28374. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  28375. return this.setFromMatrixScale(m);
  28376. };
  28377. Vector3.prototype.getColumnFromMatrix = function (index, matrix) {
  28378. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  28379. return this.setFromMatrixColumn(matrix, index);
  28380. };
  28381. Vector3.prototype.applyProjection = function (m) {
  28382. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  28383. return this.applyMatrix4(m);
  28384. };
  28385. Vector3.prototype.fromAttribute = function (attribute, index, offset) {
  28386. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28387. return this.fromBufferAttribute(attribute, index, offset);
  28388. };
  28389. Vector3.prototype.distanceToManhattan = function (v) {
  28390. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28391. return this.manhattanDistanceTo(v);
  28392. };
  28393. Vector3.prototype.lengthManhattan = function () {
  28394. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  28395. return this.manhattanLength();
  28396. }; //
  28397. Vector4.prototype.fromAttribute = function (attribute, index, offset) {
  28398. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28399. return this.fromBufferAttribute(attribute, index, offset);
  28400. };
  28401. Vector4.prototype.lengthManhattan = function () {
  28402. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  28403. return this.manhattanLength();
  28404. }; //
  28405. Object3D.prototype.getChildByName = function (name) {
  28406. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  28407. return this.getObjectByName(name);
  28408. };
  28409. Object3D.prototype.renderDepth = function () {
  28410. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  28411. };
  28412. Object3D.prototype.translate = function (distance, axis) {
  28413. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  28414. return this.translateOnAxis(axis, distance);
  28415. };
  28416. Object3D.prototype.getWorldRotation = function () {
  28417. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  28418. };
  28419. Object3D.prototype.applyMatrix = function (matrix) {
  28420. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  28421. return this.applyMatrix4(matrix);
  28422. };
  28423. Object.defineProperties(Object3D.prototype, {
  28424. eulerOrder: {
  28425. get: function () {
  28426. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28427. return this.rotation.order;
  28428. },
  28429. set: function (value) {
  28430. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28431. this.rotation.order = value;
  28432. }
  28433. },
  28434. useQuaternion: {
  28435. get: function () {
  28436. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28437. },
  28438. set: function () {
  28439. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28440. }
  28441. }
  28442. });
  28443. Mesh.prototype.setDrawMode = function () {
  28444. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28445. };
  28446. Object.defineProperties(Mesh.prototype, {
  28447. drawMode: {
  28448. get: function () {
  28449. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  28450. return TrianglesDrawMode;
  28451. },
  28452. set: function () {
  28453. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28454. }
  28455. }
  28456. });
  28457. SkinnedMesh.prototype.initBones = function () {
  28458. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  28459. }; //
  28460. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  28461. console.warn('THREE.PerspectiveCamera.setLens is deprecated. ' + 'Use .setFocalLength and .filmGauge for a photographic setup.');
  28462. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  28463. this.setFocalLength(focalLength);
  28464. }; //
  28465. Object.defineProperties(Light.prototype, {
  28466. onlyShadow: {
  28467. set: function () {
  28468. console.warn('THREE.Light: .onlyShadow has been removed.');
  28469. }
  28470. },
  28471. shadowCameraFov: {
  28472. set: function (value) {
  28473. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  28474. this.shadow.camera.fov = value;
  28475. }
  28476. },
  28477. shadowCameraLeft: {
  28478. set: function (value) {
  28479. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  28480. this.shadow.camera.left = value;
  28481. }
  28482. },
  28483. shadowCameraRight: {
  28484. set: function (value) {
  28485. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  28486. this.shadow.camera.right = value;
  28487. }
  28488. },
  28489. shadowCameraTop: {
  28490. set: function (value) {
  28491. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  28492. this.shadow.camera.top = value;
  28493. }
  28494. },
  28495. shadowCameraBottom: {
  28496. set: function (value) {
  28497. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  28498. this.shadow.camera.bottom = value;
  28499. }
  28500. },
  28501. shadowCameraNear: {
  28502. set: function (value) {
  28503. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  28504. this.shadow.camera.near = value;
  28505. }
  28506. },
  28507. shadowCameraFar: {
  28508. set: function (value) {
  28509. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  28510. this.shadow.camera.far = value;
  28511. }
  28512. },
  28513. shadowCameraVisible: {
  28514. set: function () {
  28515. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  28516. }
  28517. },
  28518. shadowBias: {
  28519. set: function (value) {
  28520. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  28521. this.shadow.bias = value;
  28522. }
  28523. },
  28524. shadowDarkness: {
  28525. set: function () {
  28526. console.warn('THREE.Light: .shadowDarkness has been removed.');
  28527. }
  28528. },
  28529. shadowMapWidth: {
  28530. set: function (value) {
  28531. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  28532. this.shadow.mapSize.width = value;
  28533. }
  28534. },
  28535. shadowMapHeight: {
  28536. set: function (value) {
  28537. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  28538. this.shadow.mapSize.height = value;
  28539. }
  28540. }
  28541. }); //
  28542. Object.defineProperties(BufferAttribute.prototype, {
  28543. length: {
  28544. get: function () {
  28545. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  28546. return this.array.length;
  28547. }
  28548. },
  28549. dynamic: {
  28550. get: function () {
  28551. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28552. return this.usage === DynamicDrawUsage;
  28553. },
  28554. set: function () {
  28555. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28556. this.setUsage(DynamicDrawUsage);
  28557. }
  28558. }
  28559. });
  28560. BufferAttribute.prototype.setDynamic = function (value) {
  28561. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28562. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28563. return this;
  28564. };
  28565. BufferAttribute.prototype.copyIndicesArray = function () {
  28566. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  28567. }, BufferAttribute.prototype.setArray = function () {
  28568. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28569. }; //
  28570. BufferGeometry.prototype.addIndex = function (index) {
  28571. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  28572. this.setIndex(index);
  28573. };
  28574. BufferGeometry.prototype.addAttribute = function (name, attribute) {
  28575. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  28576. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  28577. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  28578. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  28579. }
  28580. if (name === 'index') {
  28581. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  28582. this.setIndex(attribute);
  28583. return this;
  28584. }
  28585. return this.setAttribute(name, attribute);
  28586. };
  28587. BufferGeometry.prototype.addDrawCall = function (start, count, indexOffset) {
  28588. if (indexOffset !== undefined) {
  28589. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  28590. }
  28591. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  28592. this.addGroup(start, count);
  28593. };
  28594. BufferGeometry.prototype.clearDrawCalls = function () {
  28595. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  28596. this.clearGroups();
  28597. };
  28598. BufferGeometry.prototype.computeOffsets = function () {
  28599. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  28600. };
  28601. BufferGeometry.prototype.removeAttribute = function (name) {
  28602. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  28603. return this.deleteAttribute(name);
  28604. };
  28605. BufferGeometry.prototype.applyMatrix = function (matrix) {
  28606. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  28607. return this.applyMatrix4(matrix);
  28608. };
  28609. Object.defineProperties(BufferGeometry.prototype, {
  28610. drawcalls: {
  28611. get: function () {
  28612. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  28613. return this.groups;
  28614. }
  28615. },
  28616. offsets: {
  28617. get: function () {
  28618. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  28619. return this.groups;
  28620. }
  28621. }
  28622. });
  28623. InterleavedBuffer.prototype.setDynamic = function (value) {
  28624. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28625. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28626. return this;
  28627. };
  28628. InterleavedBuffer.prototype.setArray = function () {
  28629. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28630. }; //
  28631. ExtrudeGeometry.prototype.getArrays = function () {
  28632. console.error('THREE.ExtrudeGeometry: .getArrays() has been removed.');
  28633. };
  28634. ExtrudeGeometry.prototype.addShapeList = function () {
  28635. console.error('THREE.ExtrudeGeometry: .addShapeList() has been removed.');
  28636. };
  28637. ExtrudeGeometry.prototype.addShape = function () {
  28638. console.error('THREE.ExtrudeGeometry: .addShape() has been removed.');
  28639. }; //
  28640. Scene.prototype.dispose = function () {
  28641. console.error('THREE.Scene: .dispose() has been removed.');
  28642. }; //
  28643. Uniform.prototype.onUpdate = function () {
  28644. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  28645. return this;
  28646. }; //
  28647. Object.defineProperties(Material.prototype, {
  28648. wrapAround: {
  28649. get: function () {
  28650. console.warn('THREE.Material: .wrapAround has been removed.');
  28651. },
  28652. set: function () {
  28653. console.warn('THREE.Material: .wrapAround has been removed.');
  28654. }
  28655. },
  28656. overdraw: {
  28657. get: function () {
  28658. console.warn('THREE.Material: .overdraw has been removed.');
  28659. },
  28660. set: function () {
  28661. console.warn('THREE.Material: .overdraw has been removed.');
  28662. }
  28663. },
  28664. wrapRGB: {
  28665. get: function () {
  28666. console.warn('THREE.Material: .wrapRGB has been removed.');
  28667. return new Color();
  28668. }
  28669. },
  28670. shading: {
  28671. get: function () {
  28672. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28673. },
  28674. set: function (value) {
  28675. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28676. this.flatShading = value === FlatShading;
  28677. }
  28678. },
  28679. stencilMask: {
  28680. get: function () {
  28681. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28682. return this.stencilFuncMask;
  28683. },
  28684. set: function (value) {
  28685. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28686. this.stencilFuncMask = value;
  28687. }
  28688. },
  28689. vertexTangents: {
  28690. get: function () {
  28691. console.warn('THREE.' + this.type + ': .vertexTangents has been removed.');
  28692. },
  28693. set: function () {
  28694. console.warn('THREE.' + this.type + ': .vertexTangents has been removed.');
  28695. }
  28696. }
  28697. });
  28698. Object.defineProperties(ShaderMaterial.prototype, {
  28699. derivatives: {
  28700. get: function () {
  28701. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28702. return this.extensions.derivatives;
  28703. },
  28704. set: function (value) {
  28705. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28706. this.extensions.derivatives = value;
  28707. }
  28708. }
  28709. }); //
  28710. WebGLRenderer.prototype.clearTarget = function (renderTarget, color, depth, stencil) {
  28711. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  28712. this.setRenderTarget(renderTarget);
  28713. this.clear(color, depth, stencil);
  28714. };
  28715. WebGLRenderer.prototype.animate = function (callback) {
  28716. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  28717. this.setAnimationLoop(callback);
  28718. };
  28719. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  28720. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  28721. return this.getRenderTarget();
  28722. };
  28723. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  28724. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  28725. return this.capabilities.getMaxAnisotropy();
  28726. };
  28727. WebGLRenderer.prototype.getPrecision = function () {
  28728. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  28729. return this.capabilities.precision;
  28730. };
  28731. WebGLRenderer.prototype.resetGLState = function () {
  28732. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  28733. return this.state.reset();
  28734. };
  28735. WebGLRenderer.prototype.supportsFloatTextures = function () {
  28736. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  28737. return this.extensions.get('OES_texture_float');
  28738. };
  28739. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  28740. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  28741. return this.extensions.get('OES_texture_half_float');
  28742. };
  28743. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  28744. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  28745. return this.extensions.get('OES_standard_derivatives');
  28746. };
  28747. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  28748. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  28749. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  28750. };
  28751. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  28752. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  28753. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  28754. };
  28755. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  28756. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  28757. return this.extensions.get('EXT_blend_minmax');
  28758. };
  28759. WebGLRenderer.prototype.supportsVertexTextures = function () {
  28760. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  28761. return this.capabilities.vertexTextures;
  28762. };
  28763. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  28764. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  28765. return this.extensions.get('ANGLE_instanced_arrays');
  28766. };
  28767. WebGLRenderer.prototype.enableScissorTest = function (boolean) {
  28768. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  28769. this.setScissorTest(boolean);
  28770. };
  28771. WebGLRenderer.prototype.initMaterial = function () {
  28772. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  28773. };
  28774. WebGLRenderer.prototype.addPrePlugin = function () {
  28775. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  28776. };
  28777. WebGLRenderer.prototype.addPostPlugin = function () {
  28778. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  28779. };
  28780. WebGLRenderer.prototype.updateShadowMap = function () {
  28781. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  28782. };
  28783. WebGLRenderer.prototype.setFaceCulling = function () {
  28784. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  28785. };
  28786. WebGLRenderer.prototype.allocTextureUnit = function () {
  28787. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  28788. };
  28789. WebGLRenderer.prototype.setTexture = function () {
  28790. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  28791. };
  28792. WebGLRenderer.prototype.setTexture2D = function () {
  28793. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  28794. };
  28795. WebGLRenderer.prototype.setTextureCube = function () {
  28796. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  28797. };
  28798. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  28799. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  28800. return this.getActiveMipmapLevel();
  28801. };
  28802. Object.defineProperties(WebGLRenderer.prototype, {
  28803. shadowMapEnabled: {
  28804. get: function () {
  28805. return this.shadowMap.enabled;
  28806. },
  28807. set: function (value) {
  28808. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  28809. this.shadowMap.enabled = value;
  28810. }
  28811. },
  28812. shadowMapType: {
  28813. get: function () {
  28814. return this.shadowMap.type;
  28815. },
  28816. set: function (value) {
  28817. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  28818. this.shadowMap.type = value;
  28819. }
  28820. },
  28821. shadowMapCullFace: {
  28822. get: function () {
  28823. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28824. return undefined;
  28825. },
  28826. set: function () {
  28827. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28828. }
  28829. },
  28830. context: {
  28831. get: function () {
  28832. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  28833. return this.getContext();
  28834. }
  28835. },
  28836. vr: {
  28837. get: function () {
  28838. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  28839. return this.xr;
  28840. }
  28841. },
  28842. gammaInput: {
  28843. get: function () {
  28844. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  28845. return false;
  28846. },
  28847. set: function () {
  28848. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  28849. }
  28850. },
  28851. gammaOutput: {
  28852. get: function () {
  28853. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  28854. return false;
  28855. },
  28856. set: function (value) {
  28857. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  28858. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  28859. }
  28860. },
  28861. toneMappingWhitePoint: {
  28862. get: function () {
  28863. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  28864. return 1.0;
  28865. },
  28866. set: function () {
  28867. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  28868. }
  28869. }
  28870. });
  28871. Object.defineProperties(WebGLShadowMap.prototype, {
  28872. cullFace: {
  28873. get: function () {
  28874. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  28875. return undefined;
  28876. },
  28877. set: function () {
  28878. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  28879. }
  28880. },
  28881. renderReverseSided: {
  28882. get: function () {
  28883. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  28884. return undefined;
  28885. },
  28886. set: function () {
  28887. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  28888. }
  28889. },
  28890. renderSingleSided: {
  28891. get: function () {
  28892. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  28893. return undefined;
  28894. },
  28895. set: function () {
  28896. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  28897. }
  28898. }
  28899. });
  28900. function WebGLRenderTargetCube(width, height, options) {
  28901. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  28902. return new WebGLCubeRenderTarget(width, options);
  28903. } //
  28904. Object.defineProperties(WebGLRenderTarget.prototype, {
  28905. wrapS: {
  28906. get: function () {
  28907. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  28908. return this.texture.wrapS;
  28909. },
  28910. set: function (value) {
  28911. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  28912. this.texture.wrapS = value;
  28913. }
  28914. },
  28915. wrapT: {
  28916. get: function () {
  28917. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  28918. return this.texture.wrapT;
  28919. },
  28920. set: function (value) {
  28921. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  28922. this.texture.wrapT = value;
  28923. }
  28924. },
  28925. magFilter: {
  28926. get: function () {
  28927. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  28928. return this.texture.magFilter;
  28929. },
  28930. set: function (value) {
  28931. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  28932. this.texture.magFilter = value;
  28933. }
  28934. },
  28935. minFilter: {
  28936. get: function () {
  28937. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  28938. return this.texture.minFilter;
  28939. },
  28940. set: function (value) {
  28941. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  28942. this.texture.minFilter = value;
  28943. }
  28944. },
  28945. anisotropy: {
  28946. get: function () {
  28947. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  28948. return this.texture.anisotropy;
  28949. },
  28950. set: function (value) {
  28951. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  28952. this.texture.anisotropy = value;
  28953. }
  28954. },
  28955. offset: {
  28956. get: function () {
  28957. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  28958. return this.texture.offset;
  28959. },
  28960. set: function (value) {
  28961. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  28962. this.texture.offset = value;
  28963. }
  28964. },
  28965. repeat: {
  28966. get: function () {
  28967. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  28968. return this.texture.repeat;
  28969. },
  28970. set: function (value) {
  28971. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  28972. this.texture.repeat = value;
  28973. }
  28974. },
  28975. format: {
  28976. get: function () {
  28977. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  28978. return this.texture.format;
  28979. },
  28980. set: function (value) {
  28981. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  28982. this.texture.format = value;
  28983. }
  28984. },
  28985. type: {
  28986. get: function () {
  28987. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  28988. return this.texture.type;
  28989. },
  28990. set: function (value) {
  28991. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  28992. this.texture.type = value;
  28993. }
  28994. },
  28995. generateMipmaps: {
  28996. get: function () {
  28997. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  28998. return this.texture.generateMipmaps;
  28999. },
  29000. set: function (value) {
  29001. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  29002. this.texture.generateMipmaps = value;
  29003. }
  29004. }
  29005. }); //
  29006. Audio.prototype.load = function (file) {
  29007. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  29008. const scope = this;
  29009. const audioLoader = new AudioLoader();
  29010. audioLoader.load(file, function (buffer) {
  29011. scope.setBuffer(buffer);
  29012. });
  29013. return this;
  29014. };
  29015. AudioAnalyser.prototype.getData = function () {
  29016. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  29017. return this.getFrequencyData();
  29018. }; //
  29019. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  29020. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  29021. return this.update(renderer, scene);
  29022. };
  29023. CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
  29024. console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
  29025. return this.renderTarget.clear(renderer, color, depth, stencil);
  29026. };
  29027. ImageUtils.crossOrigin = undefined;
  29028. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  29029. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  29030. const loader = new TextureLoader();
  29031. loader.setCrossOrigin(this.crossOrigin);
  29032. const texture = loader.load(url, onLoad, undefined, onError);
  29033. if (mapping) texture.mapping = mapping;
  29034. return texture;
  29035. };
  29036. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  29037. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  29038. const loader = new CubeTextureLoader();
  29039. loader.setCrossOrigin(this.crossOrigin);
  29040. const texture = loader.load(urls, onLoad, undefined, onError);
  29041. if (mapping) texture.mapping = mapping;
  29042. return texture;
  29043. };
  29044. ImageUtils.loadCompressedTexture = function () {
  29045. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  29046. };
  29047. ImageUtils.loadCompressedTextureCube = function () {
  29048. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  29049. }; //
  29050. function CanvasRenderer() {
  29051. console.error('THREE.CanvasRenderer has been removed');
  29052. } //
  29053. function JSONLoader() {
  29054. console.error('THREE.JSONLoader has been removed.');
  29055. } //
  29056. const SceneUtils = {
  29057. createMultiMaterialObject: function () {
  29058. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  29059. },
  29060. detach: function () {
  29061. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  29062. },
  29063. attach: function () {
  29064. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  29065. }
  29066. }; //
  29067. function LensFlare() {
  29068. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  29069. }
  29070. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  29071. /* eslint-disable no-undef */
  29072. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  29073. detail: {
  29074. revision: REVISION
  29075. }
  29076. }));
  29077. /* eslint-enable no-undef */
  29078. }
  29079. if (typeof window !== 'undefined') {
  29080. if (window.__THREE__) {
  29081. console.warn('WARNING: Multiple instances of Three.js being imported.');
  29082. } else {
  29083. window.__THREE__ = REVISION;
  29084. }
  29085. }
  29086. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  29087. exports.AddEquation = AddEquation;
  29088. exports.AddOperation = AddOperation;
  29089. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  29090. exports.AdditiveBlending = AdditiveBlending;
  29091. exports.AlphaFormat = AlphaFormat;
  29092. exports.AlwaysDepth = AlwaysDepth;
  29093. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  29094. exports.AmbientLight = AmbientLight;
  29095. exports.AmbientLightProbe = AmbientLightProbe;
  29096. exports.AnimationClip = AnimationClip;
  29097. exports.AnimationLoader = AnimationLoader;
  29098. exports.AnimationMixer = AnimationMixer;
  29099. exports.AnimationObjectGroup = AnimationObjectGroup;
  29100. exports.AnimationUtils = AnimationUtils;
  29101. exports.ArcCurve = ArcCurve;
  29102. exports.ArrayCamera = ArrayCamera;
  29103. exports.ArrowHelper = ArrowHelper;
  29104. exports.Audio = Audio;
  29105. exports.AudioAnalyser = AudioAnalyser;
  29106. exports.AudioContext = AudioContext;
  29107. exports.AudioListener = AudioListener;
  29108. exports.AudioLoader = AudioLoader;
  29109. exports.AxesHelper = AxesHelper;
  29110. exports.AxisHelper = AxisHelper;
  29111. exports.BackSide = BackSide;
  29112. exports.BasicDepthPacking = BasicDepthPacking;
  29113. exports.BasicShadowMap = BasicShadowMap;
  29114. exports.BinaryTextureLoader = BinaryTextureLoader;
  29115. exports.Bone = Bone;
  29116. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  29117. exports.BoundingBoxHelper = BoundingBoxHelper;
  29118. exports.Box2 = Box2;
  29119. exports.Box3 = Box3;
  29120. exports.Box3Helper = Box3Helper;
  29121. exports.BoxBufferGeometry = BoxGeometry;
  29122. exports.BoxGeometry = BoxGeometry;
  29123. exports.BoxHelper = BoxHelper;
  29124. exports.BufferAttribute = BufferAttribute;
  29125. exports.BufferGeometry = BufferGeometry;
  29126. exports.BufferGeometryLoader = BufferGeometryLoader;
  29127. exports.ByteType = ByteType;
  29128. exports.Cache = Cache;
  29129. exports.Camera = Camera;
  29130. exports.CameraHelper = CameraHelper;
  29131. exports.CanvasRenderer = CanvasRenderer;
  29132. exports.CanvasTexture = CanvasTexture;
  29133. exports.CatmullRomCurve3 = CatmullRomCurve3;
  29134. exports.CineonToneMapping = CineonToneMapping;
  29135. exports.CircleBufferGeometry = CircleGeometry;
  29136. exports.CircleGeometry = CircleGeometry;
  29137. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  29138. exports.Clock = Clock;
  29139. exports.Color = Color;
  29140. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  29141. exports.CompressedTexture = CompressedTexture;
  29142. exports.CompressedTextureLoader = CompressedTextureLoader;
  29143. exports.ConeBufferGeometry = ConeGeometry;
  29144. exports.ConeGeometry = ConeGeometry;
  29145. exports.CubeCamera = CubeCamera;
  29146. exports.CubeReflectionMapping = CubeReflectionMapping;
  29147. exports.CubeRefractionMapping = CubeRefractionMapping;
  29148. exports.CubeTexture = CubeTexture;
  29149. exports.CubeTextureLoader = CubeTextureLoader;
  29150. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  29151. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  29152. exports.CubicBezierCurve = CubicBezierCurve;
  29153. exports.CubicBezierCurve3 = CubicBezierCurve3;
  29154. exports.CubicInterpolant = CubicInterpolant;
  29155. exports.CullFaceBack = CullFaceBack;
  29156. exports.CullFaceFront = CullFaceFront;
  29157. exports.CullFaceFrontBack = CullFaceFrontBack;
  29158. exports.CullFaceNone = CullFaceNone;
  29159. exports.Curve = Curve;
  29160. exports.CurvePath = CurvePath;
  29161. exports.CustomBlending = CustomBlending;
  29162. exports.CustomToneMapping = CustomToneMapping;
  29163. exports.CylinderBufferGeometry = CylinderGeometry;
  29164. exports.CylinderGeometry = CylinderGeometry;
  29165. exports.Cylindrical = Cylindrical;
  29166. exports.DataTexture = DataTexture;
  29167. exports.DataTexture2DArray = DataTexture2DArray;
  29168. exports.DataTexture3D = DataTexture3D;
  29169. exports.DataTextureLoader = DataTextureLoader;
  29170. exports.DataUtils = DataUtils;
  29171. exports.DecrementStencilOp = DecrementStencilOp;
  29172. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  29173. exports.DefaultLoadingManager = DefaultLoadingManager;
  29174. exports.DepthFormat = DepthFormat;
  29175. exports.DepthStencilFormat = DepthStencilFormat;
  29176. exports.DepthTexture = DepthTexture;
  29177. exports.DirectionalLight = DirectionalLight;
  29178. exports.DirectionalLightHelper = DirectionalLightHelper;
  29179. exports.DiscreteInterpolant = DiscreteInterpolant;
  29180. exports.DodecahedronBufferGeometry = DodecahedronGeometry;
  29181. exports.DodecahedronGeometry = DodecahedronGeometry;
  29182. exports.DoubleSide = DoubleSide;
  29183. exports.DstAlphaFactor = DstAlphaFactor;
  29184. exports.DstColorFactor = DstColorFactor;
  29185. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  29186. exports.DynamicCopyUsage = DynamicCopyUsage;
  29187. exports.DynamicDrawUsage = DynamicDrawUsage;
  29188. exports.DynamicReadUsage = DynamicReadUsage;
  29189. exports.EdgesGeometry = EdgesGeometry;
  29190. exports.EdgesHelper = EdgesHelper;
  29191. exports.EllipseCurve = EllipseCurve;
  29192. exports.EqualDepth = EqualDepth;
  29193. exports.EqualStencilFunc = EqualStencilFunc;
  29194. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  29195. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  29196. exports.Euler = Euler;
  29197. exports.EventDispatcher = EventDispatcher;
  29198. exports.ExtrudeBufferGeometry = ExtrudeGeometry;
  29199. exports.ExtrudeGeometry = ExtrudeGeometry;
  29200. exports.FaceColors = FaceColors;
  29201. exports.FileLoader = FileLoader;
  29202. exports.FlatShading = FlatShading;
  29203. exports.Float16BufferAttribute = Float16BufferAttribute;
  29204. exports.Float32Attribute = Float32Attribute;
  29205. exports.Float32BufferAttribute = Float32BufferAttribute;
  29206. exports.Float64Attribute = Float64Attribute;
  29207. exports.Float64BufferAttribute = Float64BufferAttribute;
  29208. exports.FloatType = FloatType;
  29209. exports.Fog = Fog;
  29210. exports.FogExp2 = FogExp2;
  29211. exports.Font = Font;
  29212. exports.FontLoader = FontLoader;
  29213. exports.FrontSide = FrontSide;
  29214. exports.Frustum = Frustum;
  29215. exports.GLBufferAttribute = GLBufferAttribute;
  29216. exports.GLSL1 = GLSL1;
  29217. exports.GLSL3 = GLSL3;
  29218. exports.GammaEncoding = GammaEncoding;
  29219. exports.GreaterDepth = GreaterDepth;
  29220. exports.GreaterEqualDepth = GreaterEqualDepth;
  29221. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  29222. exports.GreaterStencilFunc = GreaterStencilFunc;
  29223. exports.GridHelper = GridHelper;
  29224. exports.Group = Group;
  29225. exports.HalfFloatType = HalfFloatType;
  29226. exports.HemisphereLight = HemisphereLight;
  29227. exports.HemisphereLightHelper = HemisphereLightHelper;
  29228. exports.HemisphereLightProbe = HemisphereLightProbe;
  29229. exports.IcosahedronBufferGeometry = IcosahedronGeometry;
  29230. exports.IcosahedronGeometry = IcosahedronGeometry;
  29231. exports.ImageBitmapLoader = ImageBitmapLoader;
  29232. exports.ImageLoader = ImageLoader;
  29233. exports.ImageUtils = ImageUtils;
  29234. exports.ImmediateRenderObject = ImmediateRenderObject;
  29235. exports.IncrementStencilOp = IncrementStencilOp;
  29236. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  29237. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  29238. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  29239. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  29240. exports.InstancedMesh = InstancedMesh;
  29241. exports.Int16Attribute = Int16Attribute;
  29242. exports.Int16BufferAttribute = Int16BufferAttribute;
  29243. exports.Int32Attribute = Int32Attribute;
  29244. exports.Int32BufferAttribute = Int32BufferAttribute;
  29245. exports.Int8Attribute = Int8Attribute;
  29246. exports.Int8BufferAttribute = Int8BufferAttribute;
  29247. exports.IntType = IntType;
  29248. exports.InterleavedBuffer = InterleavedBuffer;
  29249. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  29250. exports.Interpolant = Interpolant;
  29251. exports.InterpolateDiscrete = InterpolateDiscrete;
  29252. exports.InterpolateLinear = InterpolateLinear;
  29253. exports.InterpolateSmooth = InterpolateSmooth;
  29254. exports.InvertStencilOp = InvertStencilOp;
  29255. exports.JSONLoader = JSONLoader;
  29256. exports.KeepStencilOp = KeepStencilOp;
  29257. exports.KeyframeTrack = KeyframeTrack;
  29258. exports.LOD = LOD;
  29259. exports.LatheBufferGeometry = LatheGeometry;
  29260. exports.LatheGeometry = LatheGeometry;
  29261. exports.Layers = Layers;
  29262. exports.LensFlare = LensFlare;
  29263. exports.LessDepth = LessDepth;
  29264. exports.LessEqualDepth = LessEqualDepth;
  29265. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  29266. exports.LessStencilFunc = LessStencilFunc;
  29267. exports.Light = Light;
  29268. exports.LightProbe = LightProbe;
  29269. exports.Line = Line;
  29270. exports.Line3 = Line3;
  29271. exports.LineBasicMaterial = LineBasicMaterial;
  29272. exports.LineCurve = LineCurve;
  29273. exports.LineCurve3 = LineCurve3;
  29274. exports.LineDashedMaterial = LineDashedMaterial;
  29275. exports.LineLoop = LineLoop;
  29276. exports.LinePieces = LinePieces;
  29277. exports.LineSegments = LineSegments;
  29278. exports.LineStrip = LineStrip;
  29279. exports.LinearEncoding = LinearEncoding;
  29280. exports.LinearFilter = LinearFilter;
  29281. exports.LinearInterpolant = LinearInterpolant;
  29282. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  29283. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  29284. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  29285. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  29286. exports.LinearToneMapping = LinearToneMapping;
  29287. exports.Loader = Loader;
  29288. exports.LoaderUtils = LoaderUtils;
  29289. exports.LoadingManager = LoadingManager;
  29290. exports.LogLuvEncoding = LogLuvEncoding;
  29291. exports.LoopOnce = LoopOnce;
  29292. exports.LoopPingPong = LoopPingPong;
  29293. exports.LoopRepeat = LoopRepeat;
  29294. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  29295. exports.LuminanceFormat = LuminanceFormat;
  29296. exports.MOUSE = MOUSE;
  29297. exports.Material = Material;
  29298. exports.MaterialLoader = MaterialLoader;
  29299. exports.Math = MathUtils;
  29300. exports.MathUtils = MathUtils;
  29301. exports.Matrix3 = Matrix3;
  29302. exports.Matrix4 = Matrix4;
  29303. exports.MaxEquation = MaxEquation;
  29304. exports.Mesh = Mesh;
  29305. exports.MeshBasicMaterial = MeshBasicMaterial;
  29306. exports.MeshDepthMaterial = MeshDepthMaterial;
  29307. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  29308. exports.MeshFaceMaterial = MeshFaceMaterial;
  29309. exports.MeshLambertMaterial = MeshLambertMaterial;
  29310. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  29311. exports.MeshNormalMaterial = MeshNormalMaterial;
  29312. exports.MeshPhongMaterial = MeshPhongMaterial;
  29313. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  29314. exports.MeshStandardMaterial = MeshStandardMaterial;
  29315. exports.MeshToonMaterial = MeshToonMaterial;
  29316. exports.MinEquation = MinEquation;
  29317. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  29318. exports.MixOperation = MixOperation;
  29319. exports.MultiMaterial = MultiMaterial;
  29320. exports.MultiplyBlending = MultiplyBlending;
  29321. exports.MultiplyOperation = MultiplyOperation;
  29322. exports.NearestFilter = NearestFilter;
  29323. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  29324. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  29325. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  29326. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  29327. exports.NeverDepth = NeverDepth;
  29328. exports.NeverStencilFunc = NeverStencilFunc;
  29329. exports.NoBlending = NoBlending;
  29330. exports.NoColors = NoColors;
  29331. exports.NoToneMapping = NoToneMapping;
  29332. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  29333. exports.NormalBlending = NormalBlending;
  29334. exports.NotEqualDepth = NotEqualDepth;
  29335. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  29336. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  29337. exports.Object3D = Object3D;
  29338. exports.ObjectLoader = ObjectLoader;
  29339. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  29340. exports.OctahedronBufferGeometry = OctahedronGeometry;
  29341. exports.OctahedronGeometry = OctahedronGeometry;
  29342. exports.OneFactor = OneFactor;
  29343. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  29344. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  29345. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  29346. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  29347. exports.OrthographicCamera = OrthographicCamera;
  29348. exports.PCFShadowMap = PCFShadowMap;
  29349. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  29350. exports.PMREMGenerator = PMREMGenerator;
  29351. exports.ParametricBufferGeometry = ParametricGeometry;
  29352. exports.ParametricGeometry = ParametricGeometry;
  29353. exports.Particle = Particle;
  29354. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  29355. exports.ParticleSystem = ParticleSystem;
  29356. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  29357. exports.Path = Path;
  29358. exports.PerspectiveCamera = PerspectiveCamera;
  29359. exports.Plane = Plane;
  29360. exports.PlaneBufferGeometry = PlaneGeometry;
  29361. exports.PlaneGeometry = PlaneGeometry;
  29362. exports.PlaneHelper = PlaneHelper;
  29363. exports.PointCloud = PointCloud;
  29364. exports.PointCloudMaterial = PointCloudMaterial;
  29365. exports.PointLight = PointLight;
  29366. exports.PointLightHelper = PointLightHelper;
  29367. exports.Points = Points;
  29368. exports.PointsMaterial = PointsMaterial;
  29369. exports.PolarGridHelper = PolarGridHelper;
  29370. exports.PolyhedronBufferGeometry = PolyhedronGeometry;
  29371. exports.PolyhedronGeometry = PolyhedronGeometry;
  29372. exports.PositionalAudio = PositionalAudio;
  29373. exports.PropertyBinding = PropertyBinding;
  29374. exports.PropertyMixer = PropertyMixer;
  29375. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  29376. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  29377. exports.Quaternion = Quaternion;
  29378. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  29379. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  29380. exports.REVISION = REVISION;
  29381. exports.RGBADepthPacking = RGBADepthPacking;
  29382. exports.RGBAFormat = RGBAFormat;
  29383. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  29384. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  29385. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  29386. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  29387. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  29388. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  29389. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  29390. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  29391. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  29392. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  29393. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  29394. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  29395. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  29396. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  29397. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  29398. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  29399. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  29400. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  29401. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  29402. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  29403. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  29404. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  29405. exports.RGBDEncoding = RGBDEncoding;
  29406. exports.RGBEEncoding = RGBEEncoding;
  29407. exports.RGBEFormat = RGBEFormat;
  29408. exports.RGBFormat = RGBFormat;
  29409. exports.RGBIntegerFormat = RGBIntegerFormat;
  29410. exports.RGBM16Encoding = RGBM16Encoding;
  29411. exports.RGBM7Encoding = RGBM7Encoding;
  29412. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  29413. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  29414. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  29415. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  29416. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  29417. exports.RGFormat = RGFormat;
  29418. exports.RGIntegerFormat = RGIntegerFormat;
  29419. exports.RawShaderMaterial = RawShaderMaterial;
  29420. exports.Ray = Ray;
  29421. exports.Raycaster = Raycaster;
  29422. exports.RectAreaLight = RectAreaLight;
  29423. exports.RedFormat = RedFormat;
  29424. exports.RedIntegerFormat = RedIntegerFormat;
  29425. exports.ReinhardToneMapping = ReinhardToneMapping;
  29426. exports.RepeatWrapping = RepeatWrapping;
  29427. exports.ReplaceStencilOp = ReplaceStencilOp;
  29428. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  29429. exports.RingBufferGeometry = RingGeometry;
  29430. exports.RingGeometry = RingGeometry;
  29431. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  29432. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  29433. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  29434. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  29435. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  29436. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  29437. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  29438. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  29439. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  29440. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  29441. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  29442. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  29443. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  29444. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  29445. exports.Scene = Scene;
  29446. exports.SceneUtils = SceneUtils;
  29447. exports.ShaderChunk = ShaderChunk;
  29448. exports.ShaderLib = ShaderLib;
  29449. exports.ShaderMaterial = ShaderMaterial;
  29450. exports.ShadowMaterial = ShadowMaterial;
  29451. exports.Shape = Shape;
  29452. exports.ShapeBufferGeometry = ShapeGeometry;
  29453. exports.ShapeGeometry = ShapeGeometry;
  29454. exports.ShapePath = ShapePath;
  29455. exports.ShapeUtils = ShapeUtils;
  29456. exports.ShortType = ShortType;
  29457. exports.Skeleton = Skeleton;
  29458. exports.SkeletonHelper = SkeletonHelper;
  29459. exports.SkinnedMesh = SkinnedMesh;
  29460. exports.SmoothShading = SmoothShading;
  29461. exports.Sphere = Sphere;
  29462. exports.SphereBufferGeometry = SphereGeometry;
  29463. exports.SphereGeometry = SphereGeometry;
  29464. exports.Spherical = Spherical;
  29465. exports.SphericalHarmonics3 = SphericalHarmonics3;
  29466. exports.SplineCurve = SplineCurve;
  29467. exports.SpotLight = SpotLight;
  29468. exports.SpotLightHelper = SpotLightHelper;
  29469. exports.Sprite = Sprite;
  29470. exports.SpriteMaterial = SpriteMaterial;
  29471. exports.SrcAlphaFactor = SrcAlphaFactor;
  29472. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  29473. exports.SrcColorFactor = SrcColorFactor;
  29474. exports.StaticCopyUsage = StaticCopyUsage;
  29475. exports.StaticDrawUsage = StaticDrawUsage;
  29476. exports.StaticReadUsage = StaticReadUsage;
  29477. exports.StereoCamera = StereoCamera;
  29478. exports.StreamCopyUsage = StreamCopyUsage;
  29479. exports.StreamDrawUsage = StreamDrawUsage;
  29480. exports.StreamReadUsage = StreamReadUsage;
  29481. exports.StringKeyframeTrack = StringKeyframeTrack;
  29482. exports.SubtractEquation = SubtractEquation;
  29483. exports.SubtractiveBlending = SubtractiveBlending;
  29484. exports.TOUCH = TOUCH;
  29485. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  29486. exports.TetrahedronBufferGeometry = TetrahedronGeometry;
  29487. exports.TetrahedronGeometry = TetrahedronGeometry;
  29488. exports.TextBufferGeometry = TextGeometry;
  29489. exports.TextGeometry = TextGeometry;
  29490. exports.Texture = Texture;
  29491. exports.TextureLoader = TextureLoader;
  29492. exports.TorusBufferGeometry = TorusGeometry;
  29493. exports.TorusGeometry = TorusGeometry;
  29494. exports.TorusKnotBufferGeometry = TorusKnotGeometry;
  29495. exports.TorusKnotGeometry = TorusKnotGeometry;
  29496. exports.Triangle = Triangle;
  29497. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  29498. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  29499. exports.TrianglesDrawMode = TrianglesDrawMode;
  29500. exports.TubeBufferGeometry = TubeGeometry;
  29501. exports.TubeGeometry = TubeGeometry;
  29502. exports.UVMapping = UVMapping;
  29503. exports.Uint16Attribute = Uint16Attribute;
  29504. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  29505. exports.Uint32Attribute = Uint32Attribute;
  29506. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  29507. exports.Uint8Attribute = Uint8Attribute;
  29508. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  29509. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  29510. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  29511. exports.Uniform = Uniform;
  29512. exports.UniformsLib = UniformsLib;
  29513. exports.UniformsUtils = UniformsUtils;
  29514. exports.UnsignedByteType = UnsignedByteType;
  29515. exports.UnsignedInt248Type = UnsignedInt248Type;
  29516. exports.UnsignedIntType = UnsignedIntType;
  29517. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  29518. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  29519. exports.UnsignedShort565Type = UnsignedShort565Type;
  29520. exports.UnsignedShortType = UnsignedShortType;
  29521. exports.VSMShadowMap = VSMShadowMap;
  29522. exports.Vector2 = Vector2;
  29523. exports.Vector3 = Vector3;
  29524. exports.Vector4 = Vector4;
  29525. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  29526. exports.Vertex = Vertex;
  29527. exports.VertexColors = VertexColors;
  29528. exports.VideoTexture = VideoTexture;
  29529. exports.WebGL1Renderer = WebGL1Renderer;
  29530. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  29531. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  29532. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  29533. exports.WebGLRenderTarget = WebGLRenderTarget;
  29534. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  29535. exports.WebGLRenderer = WebGLRenderer;
  29536. exports.WebGLUtils = WebGLUtils;
  29537. exports.WireframeGeometry = WireframeGeometry;
  29538. exports.WireframeHelper = WireframeHelper;
  29539. exports.WrapAroundEnding = WrapAroundEnding;
  29540. exports.XHRLoader = XHRLoader;
  29541. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  29542. exports.ZeroFactor = ZeroFactor;
  29543. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  29544. exports.ZeroStencilOp = ZeroStencilOp;
  29545. exports.sRGBEncoding = sRGBEncoding;
  29546. Object.defineProperty(exports, '__esModule', { value: true });
  29547. })));