three.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258
  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 = '130dev';
  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. }
  993. updateMatrix() {
  994. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  995. }
  996. clone() {
  997. return new this.constructor().copy(this);
  998. }
  999. copy(source) {
  1000. this.name = source.name;
  1001. this.image = source.image;
  1002. this.mipmaps = source.mipmaps.slice(0);
  1003. this.mapping = source.mapping;
  1004. this.wrapS = source.wrapS;
  1005. this.wrapT = source.wrapT;
  1006. this.magFilter = source.magFilter;
  1007. this.minFilter = source.minFilter;
  1008. this.anisotropy = source.anisotropy;
  1009. this.format = source.format;
  1010. this.internalFormat = source.internalFormat;
  1011. this.type = source.type;
  1012. this.offset.copy(source.offset);
  1013. this.repeat.copy(source.repeat);
  1014. this.center.copy(source.center);
  1015. this.rotation = source.rotation;
  1016. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1017. this.matrix.copy(source.matrix);
  1018. this.generateMipmaps = source.generateMipmaps;
  1019. this.premultiplyAlpha = source.premultiplyAlpha;
  1020. this.flipY = source.flipY;
  1021. this.unpackAlignment = source.unpackAlignment;
  1022. this.encoding = source.encoding;
  1023. return this;
  1024. }
  1025. toJSON(meta) {
  1026. const isRootObject = meta === undefined || typeof meta === 'string';
  1027. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1028. return meta.textures[this.uuid];
  1029. }
  1030. const output = {
  1031. metadata: {
  1032. version: 4.5,
  1033. type: 'Texture',
  1034. generator: 'Texture.toJSON'
  1035. },
  1036. uuid: this.uuid,
  1037. name: this.name,
  1038. mapping: this.mapping,
  1039. repeat: [this.repeat.x, this.repeat.y],
  1040. offset: [this.offset.x, this.offset.y],
  1041. center: [this.center.x, this.center.y],
  1042. rotation: this.rotation,
  1043. wrap: [this.wrapS, this.wrapT],
  1044. format: this.format,
  1045. type: this.type,
  1046. encoding: this.encoding,
  1047. minFilter: this.minFilter,
  1048. magFilter: this.magFilter,
  1049. anisotropy: this.anisotropy,
  1050. flipY: this.flipY,
  1051. premultiplyAlpha: this.premultiplyAlpha,
  1052. unpackAlignment: this.unpackAlignment
  1053. };
  1054. if (this.image !== undefined) {
  1055. // TODO: Move to THREE.Image
  1056. const image = this.image;
  1057. if (image.uuid === undefined) {
  1058. image.uuid = generateUUID(); // UGH
  1059. }
  1060. if (!isRootObject && meta.images[image.uuid] === undefined) {
  1061. let url;
  1062. if (Array.isArray(image)) {
  1063. // process array of images e.g. CubeTexture
  1064. url = [];
  1065. for (let i = 0, l = image.length; i < l; i++) {
  1066. // check cube texture with data textures
  1067. if (image[i].isDataTexture) {
  1068. url.push(serializeImage(image[i].image));
  1069. } else {
  1070. url.push(serializeImage(image[i]));
  1071. }
  1072. }
  1073. } else {
  1074. // process single image
  1075. url = serializeImage(image);
  1076. }
  1077. meta.images[image.uuid] = {
  1078. uuid: image.uuid,
  1079. url: url
  1080. };
  1081. }
  1082. output.image = image.uuid;
  1083. }
  1084. if (!isRootObject) {
  1085. meta.textures[this.uuid] = output;
  1086. }
  1087. return output;
  1088. }
  1089. dispose() {
  1090. this.dispatchEvent({
  1091. type: 'dispose'
  1092. });
  1093. }
  1094. transformUv(uv) {
  1095. if (this.mapping !== UVMapping) return uv;
  1096. uv.applyMatrix3(this.matrix);
  1097. if (uv.x < 0 || uv.x > 1) {
  1098. switch (this.wrapS) {
  1099. case RepeatWrapping:
  1100. uv.x = uv.x - Math.floor(uv.x);
  1101. break;
  1102. case ClampToEdgeWrapping:
  1103. uv.x = uv.x < 0 ? 0 : 1;
  1104. break;
  1105. case MirroredRepeatWrapping:
  1106. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1107. uv.x = Math.ceil(uv.x) - uv.x;
  1108. } else {
  1109. uv.x = uv.x - Math.floor(uv.x);
  1110. }
  1111. break;
  1112. }
  1113. }
  1114. if (uv.y < 0 || uv.y > 1) {
  1115. switch (this.wrapT) {
  1116. case RepeatWrapping:
  1117. uv.y = uv.y - Math.floor(uv.y);
  1118. break;
  1119. case ClampToEdgeWrapping:
  1120. uv.y = uv.y < 0 ? 0 : 1;
  1121. break;
  1122. case MirroredRepeatWrapping:
  1123. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1124. uv.y = Math.ceil(uv.y) - uv.y;
  1125. } else {
  1126. uv.y = uv.y - Math.floor(uv.y);
  1127. }
  1128. break;
  1129. }
  1130. }
  1131. if (this.flipY) {
  1132. uv.y = 1 - uv.y;
  1133. }
  1134. return uv;
  1135. }
  1136. set needsUpdate(value) {
  1137. if (value === true) this.version++;
  1138. }
  1139. }
  1140. Texture.DEFAULT_IMAGE = undefined;
  1141. Texture.DEFAULT_MAPPING = UVMapping;
  1142. Texture.prototype.isTexture = true;
  1143. function serializeImage(image) {
  1144. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1145. // default images
  1146. return ImageUtils.getDataURL(image);
  1147. } else {
  1148. if (image.data) {
  1149. // images of DataTexture
  1150. return {
  1151. data: Array.prototype.slice.call(image.data),
  1152. width: image.width,
  1153. height: image.height,
  1154. type: image.data.constructor.name
  1155. };
  1156. } else {
  1157. console.warn('THREE.Texture: Unable to serialize Texture.');
  1158. return {};
  1159. }
  1160. }
  1161. }
  1162. class Vector4 {
  1163. constructor(x = 0, y = 0, z = 0, w = 1) {
  1164. this.x = x;
  1165. this.y = y;
  1166. this.z = z;
  1167. this.w = w;
  1168. }
  1169. get width() {
  1170. return this.z;
  1171. }
  1172. set width(value) {
  1173. this.z = value;
  1174. }
  1175. get height() {
  1176. return this.w;
  1177. }
  1178. set height(value) {
  1179. this.w = value;
  1180. }
  1181. set(x, y, z, w) {
  1182. this.x = x;
  1183. this.y = y;
  1184. this.z = z;
  1185. this.w = w;
  1186. return this;
  1187. }
  1188. setScalar(scalar) {
  1189. this.x = scalar;
  1190. this.y = scalar;
  1191. this.z = scalar;
  1192. this.w = scalar;
  1193. return this;
  1194. }
  1195. setX(x) {
  1196. this.x = x;
  1197. return this;
  1198. }
  1199. setY(y) {
  1200. this.y = y;
  1201. return this;
  1202. }
  1203. setZ(z) {
  1204. this.z = z;
  1205. return this;
  1206. }
  1207. setW(w) {
  1208. this.w = w;
  1209. return this;
  1210. }
  1211. setComponent(index, value) {
  1212. switch (index) {
  1213. case 0:
  1214. this.x = value;
  1215. break;
  1216. case 1:
  1217. this.y = value;
  1218. break;
  1219. case 2:
  1220. this.z = value;
  1221. break;
  1222. case 3:
  1223. this.w = value;
  1224. break;
  1225. default:
  1226. throw new Error('index is out of range: ' + index);
  1227. }
  1228. return this;
  1229. }
  1230. getComponent(index) {
  1231. switch (index) {
  1232. case 0:
  1233. return this.x;
  1234. case 1:
  1235. return this.y;
  1236. case 2:
  1237. return this.z;
  1238. case 3:
  1239. return this.w;
  1240. default:
  1241. throw new Error('index is out of range: ' + index);
  1242. }
  1243. }
  1244. clone() {
  1245. return new this.constructor(this.x, this.y, this.z, this.w);
  1246. }
  1247. copy(v) {
  1248. this.x = v.x;
  1249. this.y = v.y;
  1250. this.z = v.z;
  1251. this.w = v.w !== undefined ? v.w : 1;
  1252. return this;
  1253. }
  1254. add(v, w) {
  1255. if (w !== undefined) {
  1256. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  1257. return this.addVectors(v, w);
  1258. }
  1259. this.x += v.x;
  1260. this.y += v.y;
  1261. this.z += v.z;
  1262. this.w += v.w;
  1263. return this;
  1264. }
  1265. addScalar(s) {
  1266. this.x += s;
  1267. this.y += s;
  1268. this.z += s;
  1269. this.w += s;
  1270. return this;
  1271. }
  1272. addVectors(a, b) {
  1273. this.x = a.x + b.x;
  1274. this.y = a.y + b.y;
  1275. this.z = a.z + b.z;
  1276. this.w = a.w + b.w;
  1277. return this;
  1278. }
  1279. addScaledVector(v, s) {
  1280. this.x += v.x * s;
  1281. this.y += v.y * s;
  1282. this.z += v.z * s;
  1283. this.w += v.w * s;
  1284. return this;
  1285. }
  1286. sub(v, w) {
  1287. if (w !== undefined) {
  1288. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  1289. return this.subVectors(v, w);
  1290. }
  1291. this.x -= v.x;
  1292. this.y -= v.y;
  1293. this.z -= v.z;
  1294. this.w -= v.w;
  1295. return this;
  1296. }
  1297. subScalar(s) {
  1298. this.x -= s;
  1299. this.y -= s;
  1300. this.z -= s;
  1301. this.w -= s;
  1302. return this;
  1303. }
  1304. subVectors(a, b) {
  1305. this.x = a.x - b.x;
  1306. this.y = a.y - b.y;
  1307. this.z = a.z - b.z;
  1308. this.w = a.w - b.w;
  1309. return this;
  1310. }
  1311. multiply(v) {
  1312. this.x *= v.x;
  1313. this.y *= v.y;
  1314. this.z *= v.z;
  1315. this.w *= v.w;
  1316. return this;
  1317. }
  1318. multiplyScalar(scalar) {
  1319. this.x *= scalar;
  1320. this.y *= scalar;
  1321. this.z *= scalar;
  1322. this.w *= scalar;
  1323. return this;
  1324. }
  1325. applyMatrix4(m) {
  1326. const x = this.x,
  1327. y = this.y,
  1328. z = this.z,
  1329. w = this.w;
  1330. const e = m.elements;
  1331. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1332. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1333. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1334. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1335. return this;
  1336. }
  1337. divideScalar(scalar) {
  1338. return this.multiplyScalar(1 / scalar);
  1339. }
  1340. setAxisAngleFromQuaternion(q) {
  1341. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1342. // q is assumed to be normalized
  1343. this.w = 2 * Math.acos(q.w);
  1344. const s = Math.sqrt(1 - q.w * q.w);
  1345. if (s < 0.0001) {
  1346. this.x = 1;
  1347. this.y = 0;
  1348. this.z = 0;
  1349. } else {
  1350. this.x = q.x / s;
  1351. this.y = q.y / s;
  1352. this.z = q.z / s;
  1353. }
  1354. return this;
  1355. }
  1356. setAxisAngleFromRotationMatrix(m) {
  1357. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1358. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1359. let angle, x, y, z; // variables for result
  1360. const epsilon = 0.01,
  1361. // margin to allow for rounding errors
  1362. epsilon2 = 0.1,
  1363. // margin to distinguish between 0 and 180 degrees
  1364. te = m.elements,
  1365. m11 = te[0],
  1366. m12 = te[4],
  1367. m13 = te[8],
  1368. m21 = te[1],
  1369. m22 = te[5],
  1370. m23 = te[9],
  1371. m31 = te[2],
  1372. m32 = te[6],
  1373. m33 = te[10];
  1374. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  1375. // singularity found
  1376. // first check for identity matrix which must have +1 for all terms
  1377. // in leading diagonal and zero in other terms
  1378. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  1379. // this singularity is identity matrix so angle = 0
  1380. this.set(1, 0, 0, 0);
  1381. return this; // zero angle, arbitrary axis
  1382. } // otherwise this singularity is angle = 180
  1383. angle = Math.PI;
  1384. const xx = (m11 + 1) / 2;
  1385. const yy = (m22 + 1) / 2;
  1386. const zz = (m33 + 1) / 2;
  1387. const xy = (m12 + m21) / 4;
  1388. const xz = (m13 + m31) / 4;
  1389. const yz = (m23 + m32) / 4;
  1390. if (xx > yy && xx > zz) {
  1391. // m11 is the largest diagonal term
  1392. if (xx < epsilon) {
  1393. x = 0;
  1394. y = 0.707106781;
  1395. z = 0.707106781;
  1396. } else {
  1397. x = Math.sqrt(xx);
  1398. y = xy / x;
  1399. z = xz / x;
  1400. }
  1401. } else if (yy > zz) {
  1402. // m22 is the largest diagonal term
  1403. if (yy < epsilon) {
  1404. x = 0.707106781;
  1405. y = 0;
  1406. z = 0.707106781;
  1407. } else {
  1408. y = Math.sqrt(yy);
  1409. x = xy / y;
  1410. z = yz / y;
  1411. }
  1412. } else {
  1413. // m33 is the largest diagonal term so base result on this
  1414. if (zz < epsilon) {
  1415. x = 0.707106781;
  1416. y = 0.707106781;
  1417. z = 0;
  1418. } else {
  1419. z = Math.sqrt(zz);
  1420. x = xz / z;
  1421. y = yz / z;
  1422. }
  1423. }
  1424. this.set(x, y, z, angle);
  1425. return this; // return 180 deg rotation
  1426. } // as we have reached here there are no singularities so we can handle normally
  1427. let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  1428. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1429. // caught by singularity test above, but I've left it in just in case
  1430. this.x = (m32 - m23) / s;
  1431. this.y = (m13 - m31) / s;
  1432. this.z = (m21 - m12) / s;
  1433. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  1434. return this;
  1435. }
  1436. min(v) {
  1437. this.x = Math.min(this.x, v.x);
  1438. this.y = Math.min(this.y, v.y);
  1439. this.z = Math.min(this.z, v.z);
  1440. this.w = Math.min(this.w, v.w);
  1441. return this;
  1442. }
  1443. max(v) {
  1444. this.x = Math.max(this.x, v.x);
  1445. this.y = Math.max(this.y, v.y);
  1446. this.z = Math.max(this.z, v.z);
  1447. this.w = Math.max(this.w, v.w);
  1448. return this;
  1449. }
  1450. clamp(min, max) {
  1451. // assumes min < max, componentwise
  1452. this.x = Math.max(min.x, Math.min(max.x, this.x));
  1453. this.y = Math.max(min.y, Math.min(max.y, this.y));
  1454. this.z = Math.max(min.z, Math.min(max.z, this.z));
  1455. this.w = Math.max(min.w, Math.min(max.w, this.w));
  1456. return this;
  1457. }
  1458. clampScalar(minVal, maxVal) {
  1459. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  1460. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  1461. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  1462. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  1463. return this;
  1464. }
  1465. clampLength(min, max) {
  1466. const length = this.length();
  1467. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1468. }
  1469. floor() {
  1470. this.x = Math.floor(this.x);
  1471. this.y = Math.floor(this.y);
  1472. this.z = Math.floor(this.z);
  1473. this.w = Math.floor(this.w);
  1474. return this;
  1475. }
  1476. ceil() {
  1477. this.x = Math.ceil(this.x);
  1478. this.y = Math.ceil(this.y);
  1479. this.z = Math.ceil(this.z);
  1480. this.w = Math.ceil(this.w);
  1481. return this;
  1482. }
  1483. round() {
  1484. this.x = Math.round(this.x);
  1485. this.y = Math.round(this.y);
  1486. this.z = Math.round(this.z);
  1487. this.w = Math.round(this.w);
  1488. return this;
  1489. }
  1490. roundToZero() {
  1491. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1492. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1493. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  1494. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  1495. return this;
  1496. }
  1497. negate() {
  1498. this.x = -this.x;
  1499. this.y = -this.y;
  1500. this.z = -this.z;
  1501. this.w = -this.w;
  1502. return this;
  1503. }
  1504. dot(v) {
  1505. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1506. }
  1507. lengthSq() {
  1508. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1509. }
  1510. length() {
  1511. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1512. }
  1513. manhattanLength() {
  1514. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  1515. }
  1516. normalize() {
  1517. return this.divideScalar(this.length() || 1);
  1518. }
  1519. setLength(length) {
  1520. return this.normalize().multiplyScalar(length);
  1521. }
  1522. lerp(v, alpha) {
  1523. this.x += (v.x - this.x) * alpha;
  1524. this.y += (v.y - this.y) * alpha;
  1525. this.z += (v.z - this.z) * alpha;
  1526. this.w += (v.w - this.w) * alpha;
  1527. return this;
  1528. }
  1529. lerpVectors(v1, v2, alpha) {
  1530. this.x = v1.x + (v2.x - v1.x) * alpha;
  1531. this.y = v1.y + (v2.y - v1.y) * alpha;
  1532. this.z = v1.z + (v2.z - v1.z) * alpha;
  1533. this.w = v1.w + (v2.w - v1.w) * alpha;
  1534. return this;
  1535. }
  1536. equals(v) {
  1537. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  1538. }
  1539. fromArray(array, offset = 0) {
  1540. this.x = array[offset];
  1541. this.y = array[offset + 1];
  1542. this.z = array[offset + 2];
  1543. this.w = array[offset + 3];
  1544. return this;
  1545. }
  1546. toArray(array = [], offset = 0) {
  1547. array[offset] = this.x;
  1548. array[offset + 1] = this.y;
  1549. array[offset + 2] = this.z;
  1550. array[offset + 3] = this.w;
  1551. return array;
  1552. }
  1553. fromBufferAttribute(attribute, index, offset) {
  1554. if (offset !== undefined) {
  1555. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  1556. }
  1557. this.x = attribute.getX(index);
  1558. this.y = attribute.getY(index);
  1559. this.z = attribute.getZ(index);
  1560. this.w = attribute.getW(index);
  1561. return this;
  1562. }
  1563. random() {
  1564. this.x = Math.random();
  1565. this.y = Math.random();
  1566. this.z = Math.random();
  1567. this.w = Math.random();
  1568. return this;
  1569. }
  1570. }
  1571. Vector4.prototype.isVector4 = true;
  1572. /*
  1573. In options, we can specify:
  1574. * Texture parameters for an auto-generated target texture
  1575. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1576. */
  1577. class WebGLRenderTarget extends EventDispatcher {
  1578. constructor(width, height, options) {
  1579. super();
  1580. this.width = width;
  1581. this.height = height;
  1582. this.depth = 1;
  1583. this.scissor = new Vector4(0, 0, width, height);
  1584. this.scissorTest = false;
  1585. this.viewport = new Vector4(0, 0, width, height);
  1586. options = options || {};
  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.image = {
  1589. width: width,
  1590. height: height,
  1591. depth: 1
  1592. };
  1593. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1594. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1595. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1596. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1597. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1598. }
  1599. setTexture(texture) {
  1600. texture.image = {
  1601. width: this.width,
  1602. height: this.height,
  1603. depth: this.depth
  1604. };
  1605. this.texture = texture;
  1606. }
  1607. setSize(width, height, depth = 1) {
  1608. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1609. this.width = width;
  1610. this.height = height;
  1611. this.depth = depth;
  1612. this.texture.image.width = width;
  1613. this.texture.image.height = height;
  1614. this.texture.image.depth = depth;
  1615. this.dispose();
  1616. }
  1617. this.viewport.set(0, 0, width, height);
  1618. this.scissor.set(0, 0, width, height);
  1619. }
  1620. clone() {
  1621. return new this.constructor().copy(this);
  1622. }
  1623. copy(source) {
  1624. this.width = source.width;
  1625. this.height = source.height;
  1626. this.depth = source.depth;
  1627. this.viewport.copy(source.viewport);
  1628. this.texture = source.texture.clone();
  1629. this.texture.image = { ...this.texture.image
  1630. }; // See #20328.
  1631. this.depthBuffer = source.depthBuffer;
  1632. this.stencilBuffer = source.stencilBuffer;
  1633. this.depthTexture = source.depthTexture;
  1634. return this;
  1635. }
  1636. dispose() {
  1637. this.dispatchEvent({
  1638. type: 'dispose'
  1639. });
  1640. }
  1641. }
  1642. WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
  1643. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1644. constructor(width, height, count) {
  1645. super(width, height);
  1646. const texture = this.texture;
  1647. this.texture = [];
  1648. for (let i = 0; i < count; i++) {
  1649. this.texture[i] = texture.clone();
  1650. }
  1651. }
  1652. setSize(width, height, depth = 1) {
  1653. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1654. this.width = width;
  1655. this.height = height;
  1656. this.depth = depth;
  1657. for (let i = 0, il = this.texture.length; i < il; i++) {
  1658. this.texture[i].image.width = width;
  1659. this.texture[i].image.height = height;
  1660. this.texture[i].image.depth = depth;
  1661. }
  1662. this.dispose();
  1663. }
  1664. this.viewport.set(0, 0, width, height);
  1665. this.scissor.set(0, 0, width, height);
  1666. return this;
  1667. }
  1668. copy(source) {
  1669. this.dispose();
  1670. this.width = source.width;
  1671. this.height = source.height;
  1672. this.depth = source.depth;
  1673. this.viewport.set(0, 0, this.width, this.height);
  1674. this.scissor.set(0, 0, this.width, this.height);
  1675. this.depthBuffer = source.depthBuffer;
  1676. this.stencilBuffer = source.stencilBuffer;
  1677. this.depthTexture = source.depthTexture;
  1678. this.texture.length = 0;
  1679. for (let i = 0, il = source.texture.length; i < il; i++) {
  1680. this.texture[i] = source.texture[i].clone();
  1681. }
  1682. return this;
  1683. }
  1684. }
  1685. WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true;
  1686. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  1687. constructor(width, height, options) {
  1688. super(width, height, options);
  1689. this.samples = 4;
  1690. }
  1691. copy(source) {
  1692. super.copy.call(this, source);
  1693. this.samples = source.samples;
  1694. return this;
  1695. }
  1696. }
  1697. WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true;
  1698. class Quaternion {
  1699. constructor(x = 0, y = 0, z = 0, w = 1) {
  1700. this._x = x;
  1701. this._y = y;
  1702. this._z = z;
  1703. this._w = w;
  1704. }
  1705. static slerp(qa, qb, qm, t) {
  1706. console.warn('THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.');
  1707. return qm.slerpQuaternions(qa, qb, t);
  1708. }
  1709. static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  1710. // fuzz-free, array-based Quaternion SLERP operation
  1711. let x0 = src0[srcOffset0 + 0],
  1712. y0 = src0[srcOffset0 + 1],
  1713. z0 = src0[srcOffset0 + 2],
  1714. w0 = src0[srcOffset0 + 3];
  1715. const x1 = src1[srcOffset1 + 0],
  1716. y1 = src1[srcOffset1 + 1],
  1717. z1 = src1[srcOffset1 + 2],
  1718. w1 = src1[srcOffset1 + 3];
  1719. if (t === 0) {
  1720. dst[dstOffset + 0] = x0;
  1721. dst[dstOffset + 1] = y0;
  1722. dst[dstOffset + 2] = z0;
  1723. dst[dstOffset + 3] = w0;
  1724. return;
  1725. }
  1726. if (t === 1) {
  1727. dst[dstOffset + 0] = x1;
  1728. dst[dstOffset + 1] = y1;
  1729. dst[dstOffset + 2] = z1;
  1730. dst[dstOffset + 3] = w1;
  1731. return;
  1732. }
  1733. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  1734. let s = 1 - t;
  1735. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1736. dir = cos >= 0 ? 1 : -1,
  1737. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  1738. if (sqrSin > Number.EPSILON) {
  1739. const sin = Math.sqrt(sqrSin),
  1740. len = Math.atan2(sin, cos * dir);
  1741. s = Math.sin(s * len) / sin;
  1742. t = Math.sin(t * len) / sin;
  1743. }
  1744. const tDir = t * dir;
  1745. x0 = x0 * s + x1 * tDir;
  1746. y0 = y0 * s + y1 * tDir;
  1747. z0 = z0 * s + z1 * tDir;
  1748. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  1749. if (s === 1 - t) {
  1750. const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  1751. x0 *= f;
  1752. y0 *= f;
  1753. z0 *= f;
  1754. w0 *= f;
  1755. }
  1756. }
  1757. dst[dstOffset] = x0;
  1758. dst[dstOffset + 1] = y0;
  1759. dst[dstOffset + 2] = z0;
  1760. dst[dstOffset + 3] = w0;
  1761. }
  1762. static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  1763. const x0 = src0[srcOffset0];
  1764. const y0 = src0[srcOffset0 + 1];
  1765. const z0 = src0[srcOffset0 + 2];
  1766. const w0 = src0[srcOffset0 + 3];
  1767. const x1 = src1[srcOffset1];
  1768. const y1 = src1[srcOffset1 + 1];
  1769. const z1 = src1[srcOffset1 + 2];
  1770. const w1 = src1[srcOffset1 + 3];
  1771. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1772. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1773. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1774. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1775. return dst;
  1776. }
  1777. get x() {
  1778. return this._x;
  1779. }
  1780. set x(value) {
  1781. this._x = value;
  1782. this._onChangeCallback();
  1783. }
  1784. get y() {
  1785. return this._y;
  1786. }
  1787. set y(value) {
  1788. this._y = value;
  1789. this._onChangeCallback();
  1790. }
  1791. get z() {
  1792. return this._z;
  1793. }
  1794. set z(value) {
  1795. this._z = value;
  1796. this._onChangeCallback();
  1797. }
  1798. get w() {
  1799. return this._w;
  1800. }
  1801. set w(value) {
  1802. this._w = value;
  1803. this._onChangeCallback();
  1804. }
  1805. set(x, y, z, w) {
  1806. this._x = x;
  1807. this._y = y;
  1808. this._z = z;
  1809. this._w = w;
  1810. this._onChangeCallback();
  1811. return this;
  1812. }
  1813. clone() {
  1814. return new this.constructor(this._x, this._y, this._z, this._w);
  1815. }
  1816. copy(quaternion) {
  1817. this._x = quaternion.x;
  1818. this._y = quaternion.y;
  1819. this._z = quaternion.z;
  1820. this._w = quaternion.w;
  1821. this._onChangeCallback();
  1822. return this;
  1823. }
  1824. setFromEuler(euler, update) {
  1825. if (!(euler && euler.isEuler)) {
  1826. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  1827. }
  1828. const x = euler._x,
  1829. y = euler._y,
  1830. z = euler._z,
  1831. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  1832. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1833. // content/SpinCalc.m
  1834. const cos = Math.cos;
  1835. const sin = Math.sin;
  1836. const c1 = cos(x / 2);
  1837. const c2 = cos(y / 2);
  1838. const c3 = cos(z / 2);
  1839. const s1 = sin(x / 2);
  1840. const s2 = sin(y / 2);
  1841. const s3 = sin(z / 2);
  1842. switch (order) {
  1843. case 'XYZ':
  1844. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1845. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1846. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1847. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1848. break;
  1849. case 'YXZ':
  1850. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1851. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1852. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1853. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1854. break;
  1855. case 'ZXY':
  1856. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1857. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1858. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1859. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1860. break;
  1861. case 'ZYX':
  1862. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1863. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1864. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1865. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1866. break;
  1867. case 'YZX':
  1868. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1869. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1870. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1871. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1872. break;
  1873. case 'XZY':
  1874. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1875. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1876. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1877. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1878. break;
  1879. default:
  1880. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  1881. }
  1882. if (update !== false) this._onChangeCallback();
  1883. return this;
  1884. }
  1885. setFromAxisAngle(axis, angle) {
  1886. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1887. // assumes axis is normalized
  1888. const halfAngle = angle / 2,
  1889. s = Math.sin(halfAngle);
  1890. this._x = axis.x * s;
  1891. this._y = axis.y * s;
  1892. this._z = axis.z * s;
  1893. this._w = Math.cos(halfAngle);
  1894. this._onChangeCallback();
  1895. return this;
  1896. }
  1897. setFromRotationMatrix(m) {
  1898. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1899. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1900. const te = m.elements,
  1901. m11 = te[0],
  1902. m12 = te[4],
  1903. m13 = te[8],
  1904. m21 = te[1],
  1905. m22 = te[5],
  1906. m23 = te[9],
  1907. m31 = te[2],
  1908. m32 = te[6],
  1909. m33 = te[10],
  1910. trace = m11 + m22 + m33;
  1911. if (trace > 0) {
  1912. const s = 0.5 / Math.sqrt(trace + 1.0);
  1913. this._w = 0.25 / s;
  1914. this._x = (m32 - m23) * s;
  1915. this._y = (m13 - m31) * s;
  1916. this._z = (m21 - m12) * s;
  1917. } else if (m11 > m22 && m11 > m33) {
  1918. const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1919. this._w = (m32 - m23) / s;
  1920. this._x = 0.25 * s;
  1921. this._y = (m12 + m21) / s;
  1922. this._z = (m13 + m31) / s;
  1923. } else if (m22 > m33) {
  1924. const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1925. this._w = (m13 - m31) / s;
  1926. this._x = (m12 + m21) / s;
  1927. this._y = 0.25 * s;
  1928. this._z = (m23 + m32) / s;
  1929. } else {
  1930. const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1931. this._w = (m21 - m12) / s;
  1932. this._x = (m13 + m31) / s;
  1933. this._y = (m23 + m32) / s;
  1934. this._z = 0.25 * s;
  1935. }
  1936. this._onChangeCallback();
  1937. return this;
  1938. }
  1939. setFromUnitVectors(vFrom, vTo) {
  1940. // assumes direction vectors vFrom and vTo are normalized
  1941. let r = vFrom.dot(vTo) + 1;
  1942. if (r < Number.EPSILON) {
  1943. // vFrom and vTo point in opposite directions
  1944. r = 0;
  1945. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  1946. this._x = -vFrom.y;
  1947. this._y = vFrom.x;
  1948. this._z = 0;
  1949. this._w = r;
  1950. } else {
  1951. this._x = 0;
  1952. this._y = -vFrom.z;
  1953. this._z = vFrom.y;
  1954. this._w = r;
  1955. }
  1956. } else {
  1957. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  1958. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  1959. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  1960. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  1961. this._w = r;
  1962. }
  1963. return this.normalize();
  1964. }
  1965. angleTo(q) {
  1966. return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1)));
  1967. }
  1968. rotateTowards(q, step) {
  1969. const angle = this.angleTo(q);
  1970. if (angle === 0) return this;
  1971. const t = Math.min(1, step / angle);
  1972. this.slerp(q, t);
  1973. return this;
  1974. }
  1975. identity() {
  1976. return this.set(0, 0, 0, 1);
  1977. }
  1978. invert() {
  1979. // quaternion is assumed to have unit length
  1980. return this.conjugate();
  1981. }
  1982. conjugate() {
  1983. this._x *= -1;
  1984. this._y *= -1;
  1985. this._z *= -1;
  1986. this._onChangeCallback();
  1987. return this;
  1988. }
  1989. dot(v) {
  1990. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1991. }
  1992. lengthSq() {
  1993. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1994. }
  1995. length() {
  1996. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  1997. }
  1998. normalize() {
  1999. let l = this.length();
  2000. if (l === 0) {
  2001. this._x = 0;
  2002. this._y = 0;
  2003. this._z = 0;
  2004. this._w = 1;
  2005. } else {
  2006. l = 1 / l;
  2007. this._x = this._x * l;
  2008. this._y = this._y * l;
  2009. this._z = this._z * l;
  2010. this._w = this._w * l;
  2011. }
  2012. this._onChangeCallback();
  2013. return this;
  2014. }
  2015. multiply(q, p) {
  2016. if (p !== undefined) {
  2017. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2018. return this.multiplyQuaternions(q, p);
  2019. }
  2020. return this.multiplyQuaternions(this, q);
  2021. }
  2022. premultiply(q) {
  2023. return this.multiplyQuaternions(q, this);
  2024. }
  2025. multiplyQuaternions(a, b) {
  2026. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2027. const qax = a._x,
  2028. qay = a._y,
  2029. qaz = a._z,
  2030. qaw = a._w;
  2031. const qbx = b._x,
  2032. qby = b._y,
  2033. qbz = b._z,
  2034. qbw = b._w;
  2035. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2036. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2037. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2038. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2039. this._onChangeCallback();
  2040. return this;
  2041. }
  2042. slerp(qb, t) {
  2043. if (t === 0) return this;
  2044. if (t === 1) return this.copy(qb);
  2045. const x = this._x,
  2046. y = this._y,
  2047. z = this._z,
  2048. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2049. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2050. if (cosHalfTheta < 0) {
  2051. this._w = -qb._w;
  2052. this._x = -qb._x;
  2053. this._y = -qb._y;
  2054. this._z = -qb._z;
  2055. cosHalfTheta = -cosHalfTheta;
  2056. } else {
  2057. this.copy(qb);
  2058. }
  2059. if (cosHalfTheta >= 1.0) {
  2060. this._w = w;
  2061. this._x = x;
  2062. this._y = y;
  2063. this._z = z;
  2064. return this;
  2065. }
  2066. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2067. if (sqrSinHalfTheta <= Number.EPSILON) {
  2068. const s = 1 - t;
  2069. this._w = s * w + t * this._w;
  2070. this._x = s * x + t * this._x;
  2071. this._y = s * y + t * this._y;
  2072. this._z = s * z + t * this._z;
  2073. this.normalize();
  2074. this._onChangeCallback();
  2075. return this;
  2076. }
  2077. const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2078. const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2079. const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2080. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2081. this._w = w * ratioA + this._w * ratioB;
  2082. this._x = x * ratioA + this._x * ratioB;
  2083. this._y = y * ratioA + this._y * ratioB;
  2084. this._z = z * ratioA + this._z * ratioB;
  2085. this._onChangeCallback();
  2086. return this;
  2087. }
  2088. slerpQuaternions(qa, qb, t) {
  2089. this.copy(qa).slerp(qb, t);
  2090. }
  2091. equals(quaternion) {
  2092. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2093. }
  2094. fromArray(array, offset = 0) {
  2095. this._x = array[offset];
  2096. this._y = array[offset + 1];
  2097. this._z = array[offset + 2];
  2098. this._w = array[offset + 3];
  2099. this._onChangeCallback();
  2100. return this;
  2101. }
  2102. toArray(array = [], offset = 0) {
  2103. array[offset] = this._x;
  2104. array[offset + 1] = this._y;
  2105. array[offset + 2] = this._z;
  2106. array[offset + 3] = this._w;
  2107. return array;
  2108. }
  2109. fromBufferAttribute(attribute, index) {
  2110. this._x = attribute.getX(index);
  2111. this._y = attribute.getY(index);
  2112. this._z = attribute.getZ(index);
  2113. this._w = attribute.getW(index);
  2114. return this;
  2115. }
  2116. _onChange(callback) {
  2117. this._onChangeCallback = callback;
  2118. return this;
  2119. }
  2120. _onChangeCallback() {}
  2121. }
  2122. Quaternion.prototype.isQuaternion = true;
  2123. class Vector3 {
  2124. constructor(x = 0, y = 0, z = 0) {
  2125. this.x = x;
  2126. this.y = y;
  2127. this.z = z;
  2128. }
  2129. set(x, y, z) {
  2130. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  2131. this.x = x;
  2132. this.y = y;
  2133. this.z = z;
  2134. return this;
  2135. }
  2136. setScalar(scalar) {
  2137. this.x = scalar;
  2138. this.y = scalar;
  2139. this.z = scalar;
  2140. return this;
  2141. }
  2142. setX(x) {
  2143. this.x = x;
  2144. return this;
  2145. }
  2146. setY(y) {
  2147. this.y = y;
  2148. return this;
  2149. }
  2150. setZ(z) {
  2151. this.z = z;
  2152. return this;
  2153. }
  2154. setComponent(index, value) {
  2155. switch (index) {
  2156. case 0:
  2157. this.x = value;
  2158. break;
  2159. case 1:
  2160. this.y = value;
  2161. break;
  2162. case 2:
  2163. this.z = value;
  2164. break;
  2165. default:
  2166. throw new Error('index is out of range: ' + index);
  2167. }
  2168. return this;
  2169. }
  2170. getComponent(index) {
  2171. switch (index) {
  2172. case 0:
  2173. return this.x;
  2174. case 1:
  2175. return this.y;
  2176. case 2:
  2177. return this.z;
  2178. default:
  2179. throw new Error('index is out of range: ' + index);
  2180. }
  2181. }
  2182. clone() {
  2183. return new this.constructor(this.x, this.y, this.z);
  2184. }
  2185. copy(v) {
  2186. this.x = v.x;
  2187. this.y = v.y;
  2188. this.z = v.z;
  2189. return this;
  2190. }
  2191. add(v, w) {
  2192. if (w !== undefined) {
  2193. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2194. return this.addVectors(v, w);
  2195. }
  2196. this.x += v.x;
  2197. this.y += v.y;
  2198. this.z += v.z;
  2199. return this;
  2200. }
  2201. addScalar(s) {
  2202. this.x += s;
  2203. this.y += s;
  2204. this.z += s;
  2205. return this;
  2206. }
  2207. addVectors(a, b) {
  2208. this.x = a.x + b.x;
  2209. this.y = a.y + b.y;
  2210. this.z = a.z + b.z;
  2211. return this;
  2212. }
  2213. addScaledVector(v, s) {
  2214. this.x += v.x * s;
  2215. this.y += v.y * s;
  2216. this.z += v.z * s;
  2217. return this;
  2218. }
  2219. sub(v, w) {
  2220. if (w !== undefined) {
  2221. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2222. return this.subVectors(v, w);
  2223. }
  2224. this.x -= v.x;
  2225. this.y -= v.y;
  2226. this.z -= v.z;
  2227. return this;
  2228. }
  2229. subScalar(s) {
  2230. this.x -= s;
  2231. this.y -= s;
  2232. this.z -= s;
  2233. return this;
  2234. }
  2235. subVectors(a, b) {
  2236. this.x = a.x - b.x;
  2237. this.y = a.y - b.y;
  2238. this.z = a.z - b.z;
  2239. return this;
  2240. }
  2241. multiply(v, w) {
  2242. if (w !== undefined) {
  2243. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2244. return this.multiplyVectors(v, w);
  2245. }
  2246. this.x *= v.x;
  2247. this.y *= v.y;
  2248. this.z *= v.z;
  2249. return this;
  2250. }
  2251. multiplyScalar(scalar) {
  2252. this.x *= scalar;
  2253. this.y *= scalar;
  2254. this.z *= scalar;
  2255. return this;
  2256. }
  2257. multiplyVectors(a, b) {
  2258. this.x = a.x * b.x;
  2259. this.y = a.y * b.y;
  2260. this.z = a.z * b.z;
  2261. return this;
  2262. }
  2263. applyEuler(euler) {
  2264. if (!(euler && euler.isEuler)) {
  2265. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2266. }
  2267. return this.applyQuaternion(_quaternion$4.setFromEuler(euler));
  2268. }
  2269. applyAxisAngle(axis, angle) {
  2270. return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle));
  2271. }
  2272. applyMatrix3(m) {
  2273. const x = this.x,
  2274. y = this.y,
  2275. z = this.z;
  2276. const e = m.elements;
  2277. this.x = e[0] * x + e[3] * y + e[6] * z;
  2278. this.y = e[1] * x + e[4] * y + e[7] * z;
  2279. this.z = e[2] * x + e[5] * y + e[8] * z;
  2280. return this;
  2281. }
  2282. applyNormalMatrix(m) {
  2283. return this.applyMatrix3(m).normalize();
  2284. }
  2285. applyMatrix4(m) {
  2286. const x = this.x,
  2287. y = this.y,
  2288. z = this.z;
  2289. const e = m.elements;
  2290. const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2291. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2292. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2293. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2294. return this;
  2295. }
  2296. applyQuaternion(q) {
  2297. const x = this.x,
  2298. y = this.y,
  2299. z = this.z;
  2300. const qx = q.x,
  2301. qy = q.y,
  2302. qz = q.z,
  2303. qw = q.w; // calculate quat * vector
  2304. const ix = qw * x + qy * z - qz * y;
  2305. const iy = qw * y + qz * x - qx * z;
  2306. const iz = qw * z + qx * y - qy * x;
  2307. const iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2308. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2309. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2310. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2311. return this;
  2312. }
  2313. project(camera) {
  2314. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2315. }
  2316. unproject(camera) {
  2317. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2318. }
  2319. transformDirection(m) {
  2320. // input: THREE.Matrix4 affine matrix
  2321. // vector interpreted as a direction
  2322. const x = this.x,
  2323. y = this.y,
  2324. z = this.z;
  2325. const e = m.elements;
  2326. this.x = e[0] * x + e[4] * y + e[8] * z;
  2327. this.y = e[1] * x + e[5] * y + e[9] * z;
  2328. this.z = e[2] * x + e[6] * y + e[10] * z;
  2329. return this.normalize();
  2330. }
  2331. divide(v) {
  2332. this.x /= v.x;
  2333. this.y /= v.y;
  2334. this.z /= v.z;
  2335. return this;
  2336. }
  2337. divideScalar(scalar) {
  2338. return this.multiplyScalar(1 / scalar);
  2339. }
  2340. min(v) {
  2341. this.x = Math.min(this.x, v.x);
  2342. this.y = Math.min(this.y, v.y);
  2343. this.z = Math.min(this.z, v.z);
  2344. return this;
  2345. }
  2346. max(v) {
  2347. this.x = Math.max(this.x, v.x);
  2348. this.y = Math.max(this.y, v.y);
  2349. this.z = Math.max(this.z, v.z);
  2350. return this;
  2351. }
  2352. clamp(min, max) {
  2353. // assumes min < max, componentwise
  2354. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2355. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2356. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2357. return this;
  2358. }
  2359. clampScalar(minVal, maxVal) {
  2360. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2361. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2362. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2363. return this;
  2364. }
  2365. clampLength(min, max) {
  2366. const length = this.length();
  2367. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2368. }
  2369. floor() {
  2370. this.x = Math.floor(this.x);
  2371. this.y = Math.floor(this.y);
  2372. this.z = Math.floor(this.z);
  2373. return this;
  2374. }
  2375. ceil() {
  2376. this.x = Math.ceil(this.x);
  2377. this.y = Math.ceil(this.y);
  2378. this.z = Math.ceil(this.z);
  2379. return this;
  2380. }
  2381. round() {
  2382. this.x = Math.round(this.x);
  2383. this.y = Math.round(this.y);
  2384. this.z = Math.round(this.z);
  2385. return this;
  2386. }
  2387. roundToZero() {
  2388. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2389. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2390. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2391. return this;
  2392. }
  2393. negate() {
  2394. this.x = -this.x;
  2395. this.y = -this.y;
  2396. this.z = -this.z;
  2397. return this;
  2398. }
  2399. dot(v) {
  2400. return this.x * v.x + this.y * v.y + this.z * v.z;
  2401. } // TODO lengthSquared?
  2402. lengthSq() {
  2403. return this.x * this.x + this.y * this.y + this.z * this.z;
  2404. }
  2405. length() {
  2406. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2407. }
  2408. manhattanLength() {
  2409. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2410. }
  2411. normalize() {
  2412. return this.divideScalar(this.length() || 1);
  2413. }
  2414. setLength(length) {
  2415. return this.normalize().multiplyScalar(length);
  2416. }
  2417. lerp(v, alpha) {
  2418. this.x += (v.x - this.x) * alpha;
  2419. this.y += (v.y - this.y) * alpha;
  2420. this.z += (v.z - this.z) * alpha;
  2421. return this;
  2422. }
  2423. lerpVectors(v1, v2, alpha) {
  2424. this.x = v1.x + (v2.x - v1.x) * alpha;
  2425. this.y = v1.y + (v2.y - v1.y) * alpha;
  2426. this.z = v1.z + (v2.z - v1.z) * alpha;
  2427. return this;
  2428. }
  2429. cross(v, w) {
  2430. if (w !== undefined) {
  2431. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2432. return this.crossVectors(v, w);
  2433. }
  2434. return this.crossVectors(this, v);
  2435. }
  2436. crossVectors(a, b) {
  2437. const ax = a.x,
  2438. ay = a.y,
  2439. az = a.z;
  2440. const bx = b.x,
  2441. by = b.y,
  2442. bz = b.z;
  2443. this.x = ay * bz - az * by;
  2444. this.y = az * bx - ax * bz;
  2445. this.z = ax * by - ay * bx;
  2446. return this;
  2447. }
  2448. projectOnVector(v) {
  2449. const denominator = v.lengthSq();
  2450. if (denominator === 0) return this.set(0, 0, 0);
  2451. const scalar = v.dot(this) / denominator;
  2452. return this.copy(v).multiplyScalar(scalar);
  2453. }
  2454. projectOnPlane(planeNormal) {
  2455. _vector$c.copy(this).projectOnVector(planeNormal);
  2456. return this.sub(_vector$c);
  2457. }
  2458. reflect(normal) {
  2459. // reflect incident vector off plane orthogonal to normal
  2460. // normal is assumed to have unit length
  2461. return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal)));
  2462. }
  2463. angleTo(v) {
  2464. const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  2465. if (denominator === 0) return Math.PI / 2;
  2466. const theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  2467. return Math.acos(clamp(theta, -1, 1));
  2468. }
  2469. distanceTo(v) {
  2470. return Math.sqrt(this.distanceToSquared(v));
  2471. }
  2472. distanceToSquared(v) {
  2473. const dx = this.x - v.x,
  2474. dy = this.y - v.y,
  2475. dz = this.z - v.z;
  2476. return dx * dx + dy * dy + dz * dz;
  2477. }
  2478. manhattanDistanceTo(v) {
  2479. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  2480. }
  2481. setFromSpherical(s) {
  2482. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  2483. }
  2484. setFromSphericalCoords(radius, phi, theta) {
  2485. const sinPhiRadius = Math.sin(phi) * radius;
  2486. this.x = sinPhiRadius * Math.sin(theta);
  2487. this.y = Math.cos(phi) * radius;
  2488. this.z = sinPhiRadius * Math.cos(theta);
  2489. return this;
  2490. }
  2491. setFromCylindrical(c) {
  2492. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  2493. }
  2494. setFromCylindricalCoords(radius, theta, y) {
  2495. this.x = radius * Math.sin(theta);
  2496. this.y = y;
  2497. this.z = radius * Math.cos(theta);
  2498. return this;
  2499. }
  2500. setFromMatrixPosition(m) {
  2501. const e = m.elements;
  2502. this.x = e[12];
  2503. this.y = e[13];
  2504. this.z = e[14];
  2505. return this;
  2506. }
  2507. setFromMatrixScale(m) {
  2508. const sx = this.setFromMatrixColumn(m, 0).length();
  2509. const sy = this.setFromMatrixColumn(m, 1).length();
  2510. const sz = this.setFromMatrixColumn(m, 2).length();
  2511. this.x = sx;
  2512. this.y = sy;
  2513. this.z = sz;
  2514. return this;
  2515. }
  2516. setFromMatrixColumn(m, index) {
  2517. return this.fromArray(m.elements, index * 4);
  2518. }
  2519. setFromMatrix3Column(m, index) {
  2520. return this.fromArray(m.elements, index * 3);
  2521. }
  2522. equals(v) {
  2523. return v.x === this.x && v.y === this.y && v.z === this.z;
  2524. }
  2525. fromArray(array, offset = 0) {
  2526. this.x = array[offset];
  2527. this.y = array[offset + 1];
  2528. this.z = array[offset + 2];
  2529. return this;
  2530. }
  2531. toArray(array = [], offset = 0) {
  2532. array[offset] = this.x;
  2533. array[offset + 1] = this.y;
  2534. array[offset + 2] = this.z;
  2535. return array;
  2536. }
  2537. fromBufferAttribute(attribute, index, offset) {
  2538. if (offset !== undefined) {
  2539. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  2540. }
  2541. this.x = attribute.getX(index);
  2542. this.y = attribute.getY(index);
  2543. this.z = attribute.getZ(index);
  2544. return this;
  2545. }
  2546. random() {
  2547. this.x = Math.random();
  2548. this.y = Math.random();
  2549. this.z = Math.random();
  2550. return this;
  2551. }
  2552. }
  2553. Vector3.prototype.isVector3 = true;
  2554. const _vector$c = /*@__PURE__*/new Vector3();
  2555. const _quaternion$4 = /*@__PURE__*/new Quaternion();
  2556. class Box3 {
  2557. constructor(min = new Vector3(+Infinity, +Infinity, +Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) {
  2558. this.min = min;
  2559. this.max = max;
  2560. }
  2561. set(min, max) {
  2562. this.min.copy(min);
  2563. this.max.copy(max);
  2564. return this;
  2565. }
  2566. setFromArray(array) {
  2567. let minX = +Infinity;
  2568. let minY = +Infinity;
  2569. let minZ = +Infinity;
  2570. let maxX = -Infinity;
  2571. let maxY = -Infinity;
  2572. let maxZ = -Infinity;
  2573. for (let i = 0, l = array.length; i < l; i += 3) {
  2574. const x = array[i];
  2575. const y = array[i + 1];
  2576. const z = array[i + 2];
  2577. if (x < minX) minX = x;
  2578. if (y < minY) minY = y;
  2579. if (z < minZ) minZ = z;
  2580. if (x > maxX) maxX = x;
  2581. if (y > maxY) maxY = y;
  2582. if (z > maxZ) maxZ = z;
  2583. }
  2584. this.min.set(minX, minY, minZ);
  2585. this.max.set(maxX, maxY, maxZ);
  2586. return this;
  2587. }
  2588. setFromBufferAttribute(attribute) {
  2589. let minX = +Infinity;
  2590. let minY = +Infinity;
  2591. let minZ = +Infinity;
  2592. let maxX = -Infinity;
  2593. let maxY = -Infinity;
  2594. let maxZ = -Infinity;
  2595. for (let i = 0, l = attribute.count; i < l; i++) {
  2596. const x = attribute.getX(i);
  2597. const y = attribute.getY(i);
  2598. const z = attribute.getZ(i);
  2599. if (x < minX) minX = x;
  2600. if (y < minY) minY = y;
  2601. if (z < minZ) minZ = z;
  2602. if (x > maxX) maxX = x;
  2603. if (y > maxY) maxY = y;
  2604. if (z > maxZ) maxZ = z;
  2605. }
  2606. this.min.set(minX, minY, minZ);
  2607. this.max.set(maxX, maxY, maxZ);
  2608. return this;
  2609. }
  2610. setFromPoints(points) {
  2611. this.makeEmpty();
  2612. for (let i = 0, il = points.length; i < il; i++) {
  2613. this.expandByPoint(points[i]);
  2614. }
  2615. return this;
  2616. }
  2617. setFromCenterAndSize(center, size) {
  2618. const halfSize = _vector$b.copy(size).multiplyScalar(0.5);
  2619. this.min.copy(center).sub(halfSize);
  2620. this.max.copy(center).add(halfSize);
  2621. return this;
  2622. }
  2623. setFromObject(object) {
  2624. this.makeEmpty();
  2625. return this.expandByObject(object);
  2626. }
  2627. clone() {
  2628. return new this.constructor().copy(this);
  2629. }
  2630. copy(box) {
  2631. this.min.copy(box.min);
  2632. this.max.copy(box.max);
  2633. return this;
  2634. }
  2635. makeEmpty() {
  2636. this.min.x = this.min.y = this.min.z = +Infinity;
  2637. this.max.x = this.max.y = this.max.z = -Infinity;
  2638. return this;
  2639. }
  2640. isEmpty() {
  2641. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2642. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  2643. }
  2644. getCenter(target) {
  2645. if (target === undefined) {
  2646. console.warn('THREE.Box3: .getCenter() target is now required');
  2647. target = new Vector3();
  2648. }
  2649. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  2650. }
  2651. getSize(target) {
  2652. if (target === undefined) {
  2653. console.warn('THREE.Box3: .getSize() target is now required');
  2654. target = new Vector3();
  2655. }
  2656. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  2657. }
  2658. expandByPoint(point) {
  2659. this.min.min(point);
  2660. this.max.max(point);
  2661. return this;
  2662. }
  2663. expandByVector(vector) {
  2664. this.min.sub(vector);
  2665. this.max.add(vector);
  2666. return this;
  2667. }
  2668. expandByScalar(scalar) {
  2669. this.min.addScalar(-scalar);
  2670. this.max.addScalar(scalar);
  2671. return this;
  2672. }
  2673. expandByObject(object) {
  2674. // Computes the world-axis-aligned bounding box of an object (including its children),
  2675. // accounting for both the object's, and children's, world transforms
  2676. object.updateWorldMatrix(false, false);
  2677. const geometry = object.geometry;
  2678. if (geometry !== undefined) {
  2679. if (geometry.boundingBox === null) {
  2680. geometry.computeBoundingBox();
  2681. }
  2682. _box$3.copy(geometry.boundingBox);
  2683. _box$3.applyMatrix4(object.matrixWorld);
  2684. this.union(_box$3);
  2685. }
  2686. const children = object.children;
  2687. for (let i = 0, l = children.length; i < l; i++) {
  2688. this.expandByObject(children[i]);
  2689. }
  2690. return this;
  2691. }
  2692. containsPoint(point) {
  2693. 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;
  2694. }
  2695. containsBox(box) {
  2696. 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;
  2697. }
  2698. getParameter(point, target) {
  2699. // This can potentially have a divide by zero if the box
  2700. // has a size dimension of 0.
  2701. if (target === undefined) {
  2702. console.warn('THREE.Box3: .getParameter() target is now required');
  2703. target = new Vector3();
  2704. }
  2705. 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));
  2706. }
  2707. intersectsBox(box) {
  2708. // using 6 splitting planes to rule out intersections.
  2709. 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;
  2710. }
  2711. intersectsSphere(sphere) {
  2712. // Find the point on the AABB closest to the sphere center.
  2713. this.clampPoint(sphere.center, _vector$b); // If that point is inside the sphere, the AABB and sphere intersect.
  2714. return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  2715. }
  2716. intersectsPlane(plane) {
  2717. // We compute the minimum and maximum dot product values. If those values
  2718. // are on the same side (back or front) of the plane, then there is no intersection.
  2719. let min, max;
  2720. if (plane.normal.x > 0) {
  2721. min = plane.normal.x * this.min.x;
  2722. max = plane.normal.x * this.max.x;
  2723. } else {
  2724. min = plane.normal.x * this.max.x;
  2725. max = plane.normal.x * this.min.x;
  2726. }
  2727. if (plane.normal.y > 0) {
  2728. min += plane.normal.y * this.min.y;
  2729. max += plane.normal.y * this.max.y;
  2730. } else {
  2731. min += plane.normal.y * this.max.y;
  2732. max += plane.normal.y * this.min.y;
  2733. }
  2734. if (plane.normal.z > 0) {
  2735. min += plane.normal.z * this.min.z;
  2736. max += plane.normal.z * this.max.z;
  2737. } else {
  2738. min += plane.normal.z * this.max.z;
  2739. max += plane.normal.z * this.min.z;
  2740. }
  2741. return min <= -plane.constant && max >= -plane.constant;
  2742. }
  2743. intersectsTriangle(triangle) {
  2744. if (this.isEmpty()) {
  2745. return false;
  2746. } // compute box center and extents
  2747. this.getCenter(_center);
  2748. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  2749. _v0$2.subVectors(triangle.a, _center);
  2750. _v1$7.subVectors(triangle.b, _center);
  2751. _v2$3.subVectors(triangle.c, _center); // compute edge vectors for triangle
  2752. _f0.subVectors(_v1$7, _v0$2);
  2753. _f1.subVectors(_v2$3, _v1$7);
  2754. _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
  2755. // 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
  2756. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2757. 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];
  2758. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2759. return false;
  2760. } // test 3 face normals from the aabb
  2761. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  2762. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2763. return false;
  2764. } // finally testing the face normal of the triangle
  2765. // use already existing triangle edge vectors here
  2766. _triangleNormal.crossVectors(_f0, _f1);
  2767. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  2768. return satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents);
  2769. }
  2770. clampPoint(point, target) {
  2771. if (target === undefined) {
  2772. console.warn('THREE.Box3: .clampPoint() target is now required');
  2773. target = new Vector3();
  2774. }
  2775. return target.copy(point).clamp(this.min, this.max);
  2776. }
  2777. distanceToPoint(point) {
  2778. const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max);
  2779. return clampedPoint.sub(point).length();
  2780. }
  2781. getBoundingSphere(target) {
  2782. if (target === undefined) {
  2783. console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependency
  2784. }
  2785. this.getCenter(target.center);
  2786. target.radius = this.getSize(_vector$b).length() * 0.5;
  2787. return target;
  2788. }
  2789. intersect(box) {
  2790. this.min.max(box.min);
  2791. 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.
  2792. if (this.isEmpty()) this.makeEmpty();
  2793. return this;
  2794. }
  2795. union(box) {
  2796. this.min.min(box.min);
  2797. this.max.max(box.max);
  2798. return this;
  2799. }
  2800. applyMatrix4(matrix) {
  2801. // transform of empty box is an empty box.
  2802. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2803. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  2804. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  2805. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  2806. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  2807. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  2808. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  2809. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  2810. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  2811. this.setFromPoints(_points);
  2812. return this;
  2813. }
  2814. translate(offset) {
  2815. this.min.add(offset);
  2816. this.max.add(offset);
  2817. return this;
  2818. }
  2819. equals(box) {
  2820. return box.min.equals(this.min) && box.max.equals(this.max);
  2821. }
  2822. }
  2823. Box3.prototype.isBox3 = true;
  2824. 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()];
  2825. const _vector$b = /*@__PURE__*/new Vector3();
  2826. const _box$3 = /*@__PURE__*/new Box3(); // triangle centered vertices
  2827. const _v0$2 = /*@__PURE__*/new Vector3();
  2828. const _v1$7 = /*@__PURE__*/new Vector3();
  2829. const _v2$3 = /*@__PURE__*/new Vector3(); // triangle edge vectors
  2830. const _f0 = /*@__PURE__*/new Vector3();
  2831. const _f1 = /*@__PURE__*/new Vector3();
  2832. const _f2 = /*@__PURE__*/new Vector3();
  2833. const _center = /*@__PURE__*/new Vector3();
  2834. const _extents = /*@__PURE__*/new Vector3();
  2835. const _triangleNormal = /*@__PURE__*/new Vector3();
  2836. const _testAxis = /*@__PURE__*/new Vector3();
  2837. function satForAxes(axes, v0, v1, v2, extents) {
  2838. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  2839. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  2840. 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
  2841. const p0 = v0.dot(_testAxis);
  2842. const p1 = v1.dot(_testAxis);
  2843. const p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  2844. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  2845. // points of the projected triangle are outside the projected half-length of the aabb
  2846. // the axis is seperating and we can exit
  2847. return false;
  2848. }
  2849. }
  2850. return true;
  2851. }
  2852. const _box$2 = /*@__PURE__*/new Box3();
  2853. const _v1$6 = /*@__PURE__*/new Vector3();
  2854. const _toFarthestPoint = /*@__PURE__*/new Vector3();
  2855. const _toPoint = /*@__PURE__*/new Vector3();
  2856. class Sphere {
  2857. constructor(center = new Vector3(), radius = -1) {
  2858. this.center = center;
  2859. this.radius = radius;
  2860. }
  2861. set(center, radius) {
  2862. this.center.copy(center);
  2863. this.radius = radius;
  2864. return this;
  2865. }
  2866. setFromPoints(points, optionalCenter) {
  2867. const center = this.center;
  2868. if (optionalCenter !== undefined) {
  2869. center.copy(optionalCenter);
  2870. } else {
  2871. _box$2.setFromPoints(points).getCenter(center);
  2872. }
  2873. let maxRadiusSq = 0;
  2874. for (let i = 0, il = points.length; i < il; i++) {
  2875. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  2876. }
  2877. this.radius = Math.sqrt(maxRadiusSq);
  2878. return this;
  2879. }
  2880. copy(sphere) {
  2881. this.center.copy(sphere.center);
  2882. this.radius = sphere.radius;
  2883. return this;
  2884. }
  2885. isEmpty() {
  2886. return this.radius < 0;
  2887. }
  2888. makeEmpty() {
  2889. this.center.set(0, 0, 0);
  2890. this.radius = -1;
  2891. return this;
  2892. }
  2893. containsPoint(point) {
  2894. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  2895. }
  2896. distanceToPoint(point) {
  2897. return point.distanceTo(this.center) - this.radius;
  2898. }
  2899. intersectsSphere(sphere) {
  2900. const radiusSum = this.radius + sphere.radius;
  2901. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  2902. }
  2903. intersectsBox(box) {
  2904. return box.intersectsSphere(this);
  2905. }
  2906. intersectsPlane(plane) {
  2907. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  2908. }
  2909. clampPoint(point, target) {
  2910. const deltaLengthSq = this.center.distanceToSquared(point);
  2911. if (target === undefined) {
  2912. console.warn('THREE.Sphere: .clampPoint() target is now required');
  2913. target = new Vector3();
  2914. }
  2915. target.copy(point);
  2916. if (deltaLengthSq > this.radius * this.radius) {
  2917. target.sub(this.center).normalize();
  2918. target.multiplyScalar(this.radius).add(this.center);
  2919. }
  2920. return target;
  2921. }
  2922. getBoundingBox(target) {
  2923. if (target === undefined) {
  2924. console.warn('THREE.Sphere: .getBoundingBox() target is now required');
  2925. target = new Box3();
  2926. }
  2927. if (this.isEmpty()) {
  2928. // Empty sphere produces empty bounding box
  2929. target.makeEmpty();
  2930. return target;
  2931. }
  2932. target.set(this.center, this.center);
  2933. target.expandByScalar(this.radius);
  2934. return target;
  2935. }
  2936. applyMatrix4(matrix) {
  2937. this.center.applyMatrix4(matrix);
  2938. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2939. return this;
  2940. }
  2941. translate(offset) {
  2942. this.center.add(offset);
  2943. return this;
  2944. }
  2945. expandByPoint(point) {
  2946. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  2947. _toPoint.subVectors(point, this.center);
  2948. const lengthSq = _toPoint.lengthSq();
  2949. if (lengthSq > this.radius * this.radius) {
  2950. const length = Math.sqrt(lengthSq);
  2951. const missingRadiusHalf = (length - this.radius) * 0.5; // Nudge this sphere towards the target point. Add half the missing distance to radius,
  2952. // and the other half to position. This gives a tighter enclosure, instead of if
  2953. // the whole missing distance were just added to radius.
  2954. this.center.add(_toPoint.multiplyScalar(missingRadiusHalf / length));
  2955. this.radius += missingRadiusHalf;
  2956. }
  2957. return this;
  2958. }
  2959. union(sphere) {
  2960. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  2961. // To enclose another sphere into this sphere, we only need to enclose two points:
  2962. // 1) Enclose the farthest point on the other sphere into this sphere.
  2963. // 2) Enclose the opposite point of the farthest point into this sphere.
  2964. _toFarthestPoint.subVectors(sphere.center, this.center).normalize().multiplyScalar(sphere.radius);
  2965. this.expandByPoint(_v1$6.copy(sphere.center).add(_toFarthestPoint));
  2966. this.expandByPoint(_v1$6.copy(sphere.center).sub(_toFarthestPoint));
  2967. return this;
  2968. }
  2969. equals(sphere) {
  2970. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  2971. }
  2972. clone() {
  2973. return new this.constructor().copy(this);
  2974. }
  2975. }
  2976. const _vector$a = /*@__PURE__*/new Vector3();
  2977. const _segCenter = /*@__PURE__*/new Vector3();
  2978. const _segDir = /*@__PURE__*/new Vector3();
  2979. const _diff = /*@__PURE__*/new Vector3();
  2980. const _edge1 = /*@__PURE__*/new Vector3();
  2981. const _edge2 = /*@__PURE__*/new Vector3();
  2982. const _normal$1 = /*@__PURE__*/new Vector3();
  2983. class Ray {
  2984. constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) {
  2985. this.origin = origin;
  2986. this.direction = direction;
  2987. }
  2988. set(origin, direction) {
  2989. this.origin.copy(origin);
  2990. this.direction.copy(direction);
  2991. return this;
  2992. }
  2993. copy(ray) {
  2994. this.origin.copy(ray.origin);
  2995. this.direction.copy(ray.direction);
  2996. return this;
  2997. }
  2998. at(t, target) {
  2999. if (target === undefined) {
  3000. console.warn('THREE.Ray: .at() target is now required');
  3001. target = new Vector3();
  3002. }
  3003. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  3004. }
  3005. lookAt(v) {
  3006. this.direction.copy(v).sub(this.origin).normalize();
  3007. return this;
  3008. }
  3009. recast(t) {
  3010. this.origin.copy(this.at(t, _vector$a));
  3011. return this;
  3012. }
  3013. closestPointToPoint(point, target) {
  3014. if (target === undefined) {
  3015. console.warn('THREE.Ray: .closestPointToPoint() target is now required');
  3016. target = new Vector3();
  3017. }
  3018. target.subVectors(point, this.origin);
  3019. const directionDistance = target.dot(this.direction);
  3020. if (directionDistance < 0) {
  3021. return target.copy(this.origin);
  3022. }
  3023. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3024. }
  3025. distanceToPoint(point) {
  3026. return Math.sqrt(this.distanceSqToPoint(point));
  3027. }
  3028. distanceSqToPoint(point) {
  3029. const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  3030. if (directionDistance < 0) {
  3031. return this.origin.distanceToSquared(point);
  3032. }
  3033. _vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3034. return _vector$a.distanceToSquared(point);
  3035. }
  3036. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  3037. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3038. // It returns the min distance between the ray and the segment
  3039. // defined by v0 and v1
  3040. // It can also set two optional targets :
  3041. // - The closest point on the ray
  3042. // - The closest point on the segment
  3043. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  3044. _segDir.copy(v1).sub(v0).normalize();
  3045. _diff.copy(this.origin).sub(_segCenter);
  3046. const segExtent = v0.distanceTo(v1) * 0.5;
  3047. const a01 = -this.direction.dot(_segDir);
  3048. const b0 = _diff.dot(this.direction);
  3049. const b1 = -_diff.dot(_segDir);
  3050. const c = _diff.lengthSq();
  3051. const det = Math.abs(1 - a01 * a01);
  3052. let s0, s1, sqrDist, extDet;
  3053. if (det > 0) {
  3054. // The ray and segment are not parallel.
  3055. s0 = a01 * b1 - b0;
  3056. s1 = a01 * b0 - b1;
  3057. extDet = segExtent * det;
  3058. if (s0 >= 0) {
  3059. if (s1 >= -extDet) {
  3060. if (s1 <= extDet) {
  3061. // region 0
  3062. // Minimum at interior points of ray and segment.
  3063. const invDet = 1 / det;
  3064. s0 *= invDet;
  3065. s1 *= invDet;
  3066. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  3067. } else {
  3068. // region 1
  3069. s1 = segExtent;
  3070. s0 = Math.max(0, -(a01 * s1 + b0));
  3071. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3072. }
  3073. } else {
  3074. // region 5
  3075. s1 = -segExtent;
  3076. s0 = Math.max(0, -(a01 * s1 + b0));
  3077. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3078. }
  3079. } else {
  3080. if (s1 <= -extDet) {
  3081. // region 4
  3082. s0 = Math.max(0, -(-a01 * segExtent + b0));
  3083. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3084. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3085. } else if (s1 <= extDet) {
  3086. // region 3
  3087. s0 = 0;
  3088. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  3089. sqrDist = s1 * (s1 + 2 * b1) + c;
  3090. } else {
  3091. // region 2
  3092. s0 = Math.max(0, -(a01 * segExtent + b0));
  3093. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3094. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3095. }
  3096. }
  3097. } else {
  3098. // Ray and segment are parallel.
  3099. s1 = a01 > 0 ? -segExtent : segExtent;
  3100. s0 = Math.max(0, -(a01 * s1 + b0));
  3101. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3102. }
  3103. if (optionalPointOnRay) {
  3104. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  3105. }
  3106. if (optionalPointOnSegment) {
  3107. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  3108. }
  3109. return sqrDist;
  3110. }
  3111. intersectSphere(sphere, target) {
  3112. _vector$a.subVectors(sphere.center, this.origin);
  3113. const tca = _vector$a.dot(this.direction);
  3114. const d2 = _vector$a.dot(_vector$a) - tca * tca;
  3115. const radius2 = sphere.radius * sphere.radius;
  3116. if (d2 > radius2) return null;
  3117. const thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  3118. const t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  3119. const t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  3120. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  3121. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3122. // in order to always return an intersect point that is in front of the ray.
  3123. 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
  3124. return this.at(t0, target);
  3125. }
  3126. intersectsSphere(sphere) {
  3127. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  3128. }
  3129. distanceToPlane(plane) {
  3130. const denominator = plane.normal.dot(this.direction);
  3131. if (denominator === 0) {
  3132. // line is coplanar, return origin
  3133. if (plane.distanceToPoint(this.origin) === 0) {
  3134. return 0;
  3135. } // Null is preferable to undefined since undefined means.... it is undefined
  3136. return null;
  3137. }
  3138. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  3139. return t >= 0 ? t : null;
  3140. }
  3141. intersectPlane(plane, target) {
  3142. const t = this.distanceToPlane(plane);
  3143. if (t === null) {
  3144. return null;
  3145. }
  3146. return this.at(t, target);
  3147. }
  3148. intersectsPlane(plane) {
  3149. // check if the ray lies on the plane first
  3150. const distToPoint = plane.distanceToPoint(this.origin);
  3151. if (distToPoint === 0) {
  3152. return true;
  3153. }
  3154. const denominator = plane.normal.dot(this.direction);
  3155. if (denominator * distToPoint < 0) {
  3156. return true;
  3157. } // ray origin is behind the plane (and is pointing behind it)
  3158. return false;
  3159. }
  3160. intersectBox(box, target) {
  3161. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3162. const invdirx = 1 / this.direction.x,
  3163. invdiry = 1 / this.direction.y,
  3164. invdirz = 1 / this.direction.z;
  3165. const origin = this.origin;
  3166. if (invdirx >= 0) {
  3167. tmin = (box.min.x - origin.x) * invdirx;
  3168. tmax = (box.max.x - origin.x) * invdirx;
  3169. } else {
  3170. tmin = (box.max.x - origin.x) * invdirx;
  3171. tmax = (box.min.x - origin.x) * invdirx;
  3172. }
  3173. if (invdiry >= 0) {
  3174. tymin = (box.min.y - origin.y) * invdiry;
  3175. tymax = (box.max.y - origin.y) * invdiry;
  3176. } else {
  3177. tymin = (box.max.y - origin.y) * invdiry;
  3178. tymax = (box.min.y - origin.y) * invdiry;
  3179. }
  3180. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  3181. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3182. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  3183. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  3184. if (invdirz >= 0) {
  3185. tzmin = (box.min.z - origin.z) * invdirz;
  3186. tzmax = (box.max.z - origin.z) * invdirz;
  3187. } else {
  3188. tzmin = (box.max.z - origin.z) * invdirz;
  3189. tzmax = (box.min.z - origin.z) * invdirz;
  3190. }
  3191. if (tmin > tzmax || tzmin > tmax) return null;
  3192. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  3193. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  3194. if (tmax < 0) return null;
  3195. return this.at(tmin >= 0 ? tmin : tmax, target);
  3196. }
  3197. intersectsBox(box) {
  3198. return this.intersectBox(box, _vector$a) !== null;
  3199. }
  3200. intersectTriangle(a, b, c, backfaceCulling, target) {
  3201. // Compute the offset origin, edges, and normal.
  3202. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3203. _edge1.subVectors(b, a);
  3204. _edge2.subVectors(c, a);
  3205. _normal$1.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3206. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3207. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3208. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3209. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3210. let DdN = this.direction.dot(_normal$1);
  3211. let sign;
  3212. if (DdN > 0) {
  3213. if (backfaceCulling) return null;
  3214. sign = 1;
  3215. } else if (DdN < 0) {
  3216. sign = -1;
  3217. DdN = -DdN;
  3218. } else {
  3219. return null;
  3220. }
  3221. _diff.subVectors(this.origin, a);
  3222. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  3223. if (DdQxE2 < 0) {
  3224. return null;
  3225. }
  3226. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  3227. if (DdE1xQ < 0) {
  3228. return null;
  3229. } // b1+b2 > 1, no intersection
  3230. if (DdQxE2 + DdE1xQ > DdN) {
  3231. return null;
  3232. } // Line intersects triangle, check if ray does.
  3233. const QdN = -sign * _diff.dot(_normal$1); // t < 0, no intersection
  3234. if (QdN < 0) {
  3235. return null;
  3236. } // Ray intersects triangle.
  3237. return this.at(QdN / DdN, target);
  3238. }
  3239. applyMatrix4(matrix4) {
  3240. this.origin.applyMatrix4(matrix4);
  3241. this.direction.transformDirection(matrix4);
  3242. return this;
  3243. }
  3244. equals(ray) {
  3245. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  3246. }
  3247. clone() {
  3248. return new this.constructor().copy(this);
  3249. }
  3250. }
  3251. class Matrix4 {
  3252. constructor() {
  3253. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3254. if (arguments.length > 0) {
  3255. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  3256. }
  3257. }
  3258. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3259. const te = this.elements;
  3260. te[0] = n11;
  3261. te[4] = n12;
  3262. te[8] = n13;
  3263. te[12] = n14;
  3264. te[1] = n21;
  3265. te[5] = n22;
  3266. te[9] = n23;
  3267. te[13] = n24;
  3268. te[2] = n31;
  3269. te[6] = n32;
  3270. te[10] = n33;
  3271. te[14] = n34;
  3272. te[3] = n41;
  3273. te[7] = n42;
  3274. te[11] = n43;
  3275. te[15] = n44;
  3276. return this;
  3277. }
  3278. identity() {
  3279. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3280. return this;
  3281. }
  3282. clone() {
  3283. return new Matrix4().fromArray(this.elements);
  3284. }
  3285. copy(m) {
  3286. const te = this.elements;
  3287. const me = m.elements;
  3288. te[0] = me[0];
  3289. te[1] = me[1];
  3290. te[2] = me[2];
  3291. te[3] = me[3];
  3292. te[4] = me[4];
  3293. te[5] = me[5];
  3294. te[6] = me[6];
  3295. te[7] = me[7];
  3296. te[8] = me[8];
  3297. te[9] = me[9];
  3298. te[10] = me[10];
  3299. te[11] = me[11];
  3300. te[12] = me[12];
  3301. te[13] = me[13];
  3302. te[14] = me[14];
  3303. te[15] = me[15];
  3304. return this;
  3305. }
  3306. copyPosition(m) {
  3307. const te = this.elements,
  3308. me = m.elements;
  3309. te[12] = me[12];
  3310. te[13] = me[13];
  3311. te[14] = me[14];
  3312. return this;
  3313. }
  3314. setFromMatrix3(m) {
  3315. const me = m.elements;
  3316. 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);
  3317. return this;
  3318. }
  3319. extractBasis(xAxis, yAxis, zAxis) {
  3320. xAxis.setFromMatrixColumn(this, 0);
  3321. yAxis.setFromMatrixColumn(this, 1);
  3322. zAxis.setFromMatrixColumn(this, 2);
  3323. return this;
  3324. }
  3325. makeBasis(xAxis, yAxis, zAxis) {
  3326. 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);
  3327. return this;
  3328. }
  3329. extractRotation(m) {
  3330. // this method does not support reflection matrices
  3331. const te = this.elements;
  3332. const me = m.elements;
  3333. const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length();
  3334. const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length();
  3335. const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length();
  3336. te[0] = me[0] * scaleX;
  3337. te[1] = me[1] * scaleX;
  3338. te[2] = me[2] * scaleX;
  3339. te[3] = 0;
  3340. te[4] = me[4] * scaleY;
  3341. te[5] = me[5] * scaleY;
  3342. te[6] = me[6] * scaleY;
  3343. te[7] = 0;
  3344. te[8] = me[8] * scaleZ;
  3345. te[9] = me[9] * scaleZ;
  3346. te[10] = me[10] * scaleZ;
  3347. te[11] = 0;
  3348. te[12] = 0;
  3349. te[13] = 0;
  3350. te[14] = 0;
  3351. te[15] = 1;
  3352. return this;
  3353. }
  3354. makeRotationFromEuler(euler) {
  3355. if (!(euler && euler.isEuler)) {
  3356. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  3357. }
  3358. const te = this.elements;
  3359. const x = euler.x,
  3360. y = euler.y,
  3361. z = euler.z;
  3362. const a = Math.cos(x),
  3363. b = Math.sin(x);
  3364. const c = Math.cos(y),
  3365. d = Math.sin(y);
  3366. const e = Math.cos(z),
  3367. f = Math.sin(z);
  3368. if (euler.order === 'XYZ') {
  3369. const ae = a * e,
  3370. af = a * f,
  3371. be = b * e,
  3372. bf = b * f;
  3373. te[0] = c * e;
  3374. te[4] = -c * f;
  3375. te[8] = d;
  3376. te[1] = af + be * d;
  3377. te[5] = ae - bf * d;
  3378. te[9] = -b * c;
  3379. te[2] = bf - ae * d;
  3380. te[6] = be + af * d;
  3381. te[10] = a * c;
  3382. } else if (euler.order === 'YXZ') {
  3383. const ce = c * e,
  3384. cf = c * f,
  3385. de = d * e,
  3386. df = d * f;
  3387. te[0] = ce + df * b;
  3388. te[4] = de * b - cf;
  3389. te[8] = a * d;
  3390. te[1] = a * f;
  3391. te[5] = a * e;
  3392. te[9] = -b;
  3393. te[2] = cf * b - de;
  3394. te[6] = df + ce * b;
  3395. te[10] = a * c;
  3396. } else if (euler.order === 'ZXY') {
  3397. const ce = c * e,
  3398. cf = c * f,
  3399. de = d * e,
  3400. df = d * f;
  3401. te[0] = ce - df * b;
  3402. te[4] = -a * f;
  3403. te[8] = de + cf * b;
  3404. te[1] = cf + de * b;
  3405. te[5] = a * e;
  3406. te[9] = df - ce * b;
  3407. te[2] = -a * d;
  3408. te[6] = b;
  3409. te[10] = a * c;
  3410. } else if (euler.order === 'ZYX') {
  3411. const ae = a * e,
  3412. af = a * f,
  3413. be = b * e,
  3414. bf = b * f;
  3415. te[0] = c * e;
  3416. te[4] = be * d - af;
  3417. te[8] = ae * d + bf;
  3418. te[1] = c * f;
  3419. te[5] = bf * d + ae;
  3420. te[9] = af * d - be;
  3421. te[2] = -d;
  3422. te[6] = b * c;
  3423. te[10] = a * c;
  3424. } else if (euler.order === 'YZX') {
  3425. const ac = a * c,
  3426. ad = a * d,
  3427. bc = b * c,
  3428. bd = b * d;
  3429. te[0] = c * e;
  3430. te[4] = bd - ac * f;
  3431. te[8] = bc * f + ad;
  3432. te[1] = f;
  3433. te[5] = a * e;
  3434. te[9] = -b * e;
  3435. te[2] = -d * e;
  3436. te[6] = ad * f + bc;
  3437. te[10] = ac - bd * f;
  3438. } else if (euler.order === 'XZY') {
  3439. const ac = a * c,
  3440. ad = a * d,
  3441. bc = b * c,
  3442. bd = b * d;
  3443. te[0] = c * e;
  3444. te[4] = -f;
  3445. te[8] = d * e;
  3446. te[1] = ac * f + bd;
  3447. te[5] = a * e;
  3448. te[9] = ad * f - bc;
  3449. te[2] = bc * f - ad;
  3450. te[6] = b * e;
  3451. te[10] = bd * f + ac;
  3452. } // bottom row
  3453. te[3] = 0;
  3454. te[7] = 0;
  3455. te[11] = 0; // last column
  3456. te[12] = 0;
  3457. te[13] = 0;
  3458. te[14] = 0;
  3459. te[15] = 1;
  3460. return this;
  3461. }
  3462. makeRotationFromQuaternion(q) {
  3463. return this.compose(_zero, q, _one);
  3464. }
  3465. lookAt(eye, target, up) {
  3466. const te = this.elements;
  3467. _z.subVectors(eye, target);
  3468. if (_z.lengthSq() === 0) {
  3469. // eye and target are in the same position
  3470. _z.z = 1;
  3471. }
  3472. _z.normalize();
  3473. _x.crossVectors(up, _z);
  3474. if (_x.lengthSq() === 0) {
  3475. // up and z are parallel
  3476. if (Math.abs(up.z) === 1) {
  3477. _z.x += 0.0001;
  3478. } else {
  3479. _z.z += 0.0001;
  3480. }
  3481. _z.normalize();
  3482. _x.crossVectors(up, _z);
  3483. }
  3484. _x.normalize();
  3485. _y.crossVectors(_z, _x);
  3486. te[0] = _x.x;
  3487. te[4] = _y.x;
  3488. te[8] = _z.x;
  3489. te[1] = _x.y;
  3490. te[5] = _y.y;
  3491. te[9] = _z.y;
  3492. te[2] = _x.z;
  3493. te[6] = _y.z;
  3494. te[10] = _z.z;
  3495. return this;
  3496. }
  3497. multiply(m, n) {
  3498. if (n !== undefined) {
  3499. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  3500. return this.multiplyMatrices(m, n);
  3501. }
  3502. return this.multiplyMatrices(this, m);
  3503. }
  3504. premultiply(m) {
  3505. return this.multiplyMatrices(m, this);
  3506. }
  3507. multiplyMatrices(a, b) {
  3508. const ae = a.elements;
  3509. const be = b.elements;
  3510. const te = this.elements;
  3511. const a11 = ae[0],
  3512. a12 = ae[4],
  3513. a13 = ae[8],
  3514. a14 = ae[12];
  3515. const a21 = ae[1],
  3516. a22 = ae[5],
  3517. a23 = ae[9],
  3518. a24 = ae[13];
  3519. const a31 = ae[2],
  3520. a32 = ae[6],
  3521. a33 = ae[10],
  3522. a34 = ae[14];
  3523. const a41 = ae[3],
  3524. a42 = ae[7],
  3525. a43 = ae[11],
  3526. a44 = ae[15];
  3527. const b11 = be[0],
  3528. b12 = be[4],
  3529. b13 = be[8],
  3530. b14 = be[12];
  3531. const b21 = be[1],
  3532. b22 = be[5],
  3533. b23 = be[9],
  3534. b24 = be[13];
  3535. const b31 = be[2],
  3536. b32 = be[6],
  3537. b33 = be[10],
  3538. b34 = be[14];
  3539. const b41 = be[3],
  3540. b42 = be[7],
  3541. b43 = be[11],
  3542. b44 = be[15];
  3543. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3544. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3545. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3546. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3547. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3548. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3549. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3550. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3551. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3552. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3553. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3554. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3555. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3556. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3557. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3558. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3559. return this;
  3560. }
  3561. multiplyScalar(s) {
  3562. const te = this.elements;
  3563. te[0] *= s;
  3564. te[4] *= s;
  3565. te[8] *= s;
  3566. te[12] *= s;
  3567. te[1] *= s;
  3568. te[5] *= s;
  3569. te[9] *= s;
  3570. te[13] *= s;
  3571. te[2] *= s;
  3572. te[6] *= s;
  3573. te[10] *= s;
  3574. te[14] *= s;
  3575. te[3] *= s;
  3576. te[7] *= s;
  3577. te[11] *= s;
  3578. te[15] *= s;
  3579. return this;
  3580. }
  3581. determinant() {
  3582. const te = this.elements;
  3583. const n11 = te[0],
  3584. n12 = te[4],
  3585. n13 = te[8],
  3586. n14 = te[12];
  3587. const n21 = te[1],
  3588. n22 = te[5],
  3589. n23 = te[9],
  3590. n24 = te[13];
  3591. const n31 = te[2],
  3592. n32 = te[6],
  3593. n33 = te[10],
  3594. n34 = te[14];
  3595. const n41 = te[3],
  3596. n42 = te[7],
  3597. n43 = te[11],
  3598. n44 = te[15]; //TODO: make this more efficient
  3599. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3600. 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);
  3601. }
  3602. transpose() {
  3603. const te = this.elements;
  3604. let tmp;
  3605. tmp = te[1];
  3606. te[1] = te[4];
  3607. te[4] = tmp;
  3608. tmp = te[2];
  3609. te[2] = te[8];
  3610. te[8] = tmp;
  3611. tmp = te[6];
  3612. te[6] = te[9];
  3613. te[9] = tmp;
  3614. tmp = te[3];
  3615. te[3] = te[12];
  3616. te[12] = tmp;
  3617. tmp = te[7];
  3618. te[7] = te[13];
  3619. te[13] = tmp;
  3620. tmp = te[11];
  3621. te[11] = te[14];
  3622. te[14] = tmp;
  3623. return this;
  3624. }
  3625. setPosition(x, y, z) {
  3626. const te = this.elements;
  3627. if (x.isVector3) {
  3628. te[12] = x.x;
  3629. te[13] = x.y;
  3630. te[14] = x.z;
  3631. } else {
  3632. te[12] = x;
  3633. te[13] = y;
  3634. te[14] = z;
  3635. }
  3636. return this;
  3637. }
  3638. invert() {
  3639. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3640. const te = this.elements,
  3641. n11 = te[0],
  3642. n21 = te[1],
  3643. n31 = te[2],
  3644. n41 = te[3],
  3645. n12 = te[4],
  3646. n22 = te[5],
  3647. n32 = te[6],
  3648. n42 = te[7],
  3649. n13 = te[8],
  3650. n23 = te[9],
  3651. n33 = te[10],
  3652. n43 = te[11],
  3653. n14 = te[12],
  3654. n24 = te[13],
  3655. n34 = te[14],
  3656. n44 = te[15],
  3657. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3658. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3659. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3660. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3661. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3662. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  3663. const detInv = 1 / det;
  3664. te[0] = t11 * detInv;
  3665. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  3666. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  3667. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  3668. te[4] = t12 * detInv;
  3669. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  3670. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  3671. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  3672. te[8] = t13 * detInv;
  3673. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  3674. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  3675. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  3676. te[12] = t14 * detInv;
  3677. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  3678. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  3679. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  3680. return this;
  3681. }
  3682. scale(v) {
  3683. const te = this.elements;
  3684. const x = v.x,
  3685. y = v.y,
  3686. z = v.z;
  3687. te[0] *= x;
  3688. te[4] *= y;
  3689. te[8] *= z;
  3690. te[1] *= x;
  3691. te[5] *= y;
  3692. te[9] *= z;
  3693. te[2] *= x;
  3694. te[6] *= y;
  3695. te[10] *= z;
  3696. te[3] *= x;
  3697. te[7] *= y;
  3698. te[11] *= z;
  3699. return this;
  3700. }
  3701. getMaxScaleOnAxis() {
  3702. const te = this.elements;
  3703. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  3704. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  3705. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  3706. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  3707. }
  3708. makeTranslation(x, y, z) {
  3709. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  3710. return this;
  3711. }
  3712. makeRotationX(theta) {
  3713. const c = Math.cos(theta),
  3714. s = Math.sin(theta);
  3715. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  3716. return this;
  3717. }
  3718. makeRotationY(theta) {
  3719. const c = Math.cos(theta),
  3720. s = Math.sin(theta);
  3721. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  3722. return this;
  3723. }
  3724. makeRotationZ(theta) {
  3725. const c = Math.cos(theta),
  3726. s = Math.sin(theta);
  3727. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3728. return this;
  3729. }
  3730. makeRotationAxis(axis, angle) {
  3731. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3732. const c = Math.cos(angle);
  3733. const s = Math.sin(angle);
  3734. const t = 1 - c;
  3735. const x = axis.x,
  3736. y = axis.y,
  3737. z = axis.z;
  3738. const tx = t * x,
  3739. ty = t * y;
  3740. 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);
  3741. return this;
  3742. }
  3743. makeScale(x, y, z) {
  3744. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  3745. return this;
  3746. }
  3747. makeShear(xy, xz, yx, yz, zx, zy) {
  3748. this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1);
  3749. return this;
  3750. }
  3751. compose(position, quaternion, scale) {
  3752. const te = this.elements;
  3753. const x = quaternion._x,
  3754. y = quaternion._y,
  3755. z = quaternion._z,
  3756. w = quaternion._w;
  3757. const x2 = x + x,
  3758. y2 = y + y,
  3759. z2 = z + z;
  3760. const xx = x * x2,
  3761. xy = x * y2,
  3762. xz = x * z2;
  3763. const yy = y * y2,
  3764. yz = y * z2,
  3765. zz = z * z2;
  3766. const wx = w * x2,
  3767. wy = w * y2,
  3768. wz = w * z2;
  3769. const sx = scale.x,
  3770. sy = scale.y,
  3771. sz = scale.z;
  3772. te[0] = (1 - (yy + zz)) * sx;
  3773. te[1] = (xy + wz) * sx;
  3774. te[2] = (xz - wy) * sx;
  3775. te[3] = 0;
  3776. te[4] = (xy - wz) * sy;
  3777. te[5] = (1 - (xx + zz)) * sy;
  3778. te[6] = (yz + wx) * sy;
  3779. te[7] = 0;
  3780. te[8] = (xz + wy) * sz;
  3781. te[9] = (yz - wx) * sz;
  3782. te[10] = (1 - (xx + yy)) * sz;
  3783. te[11] = 0;
  3784. te[12] = position.x;
  3785. te[13] = position.y;
  3786. te[14] = position.z;
  3787. te[15] = 1;
  3788. return this;
  3789. }
  3790. decompose(position, quaternion, scale) {
  3791. const te = this.elements;
  3792. let sx = _v1$5.set(te[0], te[1], te[2]).length();
  3793. const sy = _v1$5.set(te[4], te[5], te[6]).length();
  3794. const sz = _v1$5.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  3795. const det = this.determinant();
  3796. if (det < 0) sx = -sx;
  3797. position.x = te[12];
  3798. position.y = te[13];
  3799. position.z = te[14]; // scale the rotation part
  3800. _m1$2.copy(this);
  3801. const invSX = 1 / sx;
  3802. const invSY = 1 / sy;
  3803. const invSZ = 1 / sz;
  3804. _m1$2.elements[0] *= invSX;
  3805. _m1$2.elements[1] *= invSX;
  3806. _m1$2.elements[2] *= invSX;
  3807. _m1$2.elements[4] *= invSY;
  3808. _m1$2.elements[5] *= invSY;
  3809. _m1$2.elements[6] *= invSY;
  3810. _m1$2.elements[8] *= invSZ;
  3811. _m1$2.elements[9] *= invSZ;
  3812. _m1$2.elements[10] *= invSZ;
  3813. quaternion.setFromRotationMatrix(_m1$2);
  3814. scale.x = sx;
  3815. scale.y = sy;
  3816. scale.z = sz;
  3817. return this;
  3818. }
  3819. makePerspective(left, right, top, bottom, near, far) {
  3820. if (far === undefined) {
  3821. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  3822. }
  3823. const te = this.elements;
  3824. const x = 2 * near / (right - left);
  3825. const y = 2 * near / (top - bottom);
  3826. const a = (right + left) / (right - left);
  3827. const b = (top + bottom) / (top - bottom);
  3828. const c = -(far + near) / (far - near);
  3829. const d = -2 * far * near / (far - near);
  3830. te[0] = x;
  3831. te[4] = 0;
  3832. te[8] = a;
  3833. te[12] = 0;
  3834. te[1] = 0;
  3835. te[5] = y;
  3836. te[9] = b;
  3837. te[13] = 0;
  3838. te[2] = 0;
  3839. te[6] = 0;
  3840. te[10] = c;
  3841. te[14] = d;
  3842. te[3] = 0;
  3843. te[7] = 0;
  3844. te[11] = -1;
  3845. te[15] = 0;
  3846. return this;
  3847. }
  3848. makeOrthographic(left, right, top, bottom, near, far) {
  3849. const te = this.elements;
  3850. const w = 1.0 / (right - left);
  3851. const h = 1.0 / (top - bottom);
  3852. const p = 1.0 / (far - near);
  3853. const x = (right + left) * w;
  3854. const y = (top + bottom) * h;
  3855. const z = (far + near) * p;
  3856. te[0] = 2 * w;
  3857. te[4] = 0;
  3858. te[8] = 0;
  3859. te[12] = -x;
  3860. te[1] = 0;
  3861. te[5] = 2 * h;
  3862. te[9] = 0;
  3863. te[13] = -y;
  3864. te[2] = 0;
  3865. te[6] = 0;
  3866. te[10] = -2 * p;
  3867. te[14] = -z;
  3868. te[3] = 0;
  3869. te[7] = 0;
  3870. te[11] = 0;
  3871. te[15] = 1;
  3872. return this;
  3873. }
  3874. equals(matrix) {
  3875. const te = this.elements;
  3876. const me = matrix.elements;
  3877. for (let i = 0; i < 16; i++) {
  3878. if (te[i] !== me[i]) return false;
  3879. }
  3880. return true;
  3881. }
  3882. fromArray(array, offset = 0) {
  3883. for (let i = 0; i < 16; i++) {
  3884. this.elements[i] = array[i + offset];
  3885. }
  3886. return this;
  3887. }
  3888. toArray(array = [], offset = 0) {
  3889. const te = this.elements;
  3890. array[offset] = te[0];
  3891. array[offset + 1] = te[1];
  3892. array[offset + 2] = te[2];
  3893. array[offset + 3] = te[3];
  3894. array[offset + 4] = te[4];
  3895. array[offset + 5] = te[5];
  3896. array[offset + 6] = te[6];
  3897. array[offset + 7] = te[7];
  3898. array[offset + 8] = te[8];
  3899. array[offset + 9] = te[9];
  3900. array[offset + 10] = te[10];
  3901. array[offset + 11] = te[11];
  3902. array[offset + 12] = te[12];
  3903. array[offset + 13] = te[13];
  3904. array[offset + 14] = te[14];
  3905. array[offset + 15] = te[15];
  3906. return array;
  3907. }
  3908. }
  3909. Matrix4.prototype.isMatrix4 = true;
  3910. const _v1$5 = /*@__PURE__*/new Vector3();
  3911. const _m1$2 = /*@__PURE__*/new Matrix4();
  3912. const _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  3913. const _one = /*@__PURE__*/new Vector3(1, 1, 1);
  3914. const _x = /*@__PURE__*/new Vector3();
  3915. const _y = /*@__PURE__*/new Vector3();
  3916. const _z = /*@__PURE__*/new Vector3();
  3917. const _matrix$1 = /*@__PURE__*/new Matrix4();
  3918. const _quaternion$3 = /*@__PURE__*/new Quaternion();
  3919. class Euler {
  3920. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  3921. this._x = x;
  3922. this._y = y;
  3923. this._z = z;
  3924. this._order = order;
  3925. }
  3926. get x() {
  3927. return this._x;
  3928. }
  3929. set x(value) {
  3930. this._x = value;
  3931. this._onChangeCallback();
  3932. }
  3933. get y() {
  3934. return this._y;
  3935. }
  3936. set y(value) {
  3937. this._y = value;
  3938. this._onChangeCallback();
  3939. }
  3940. get z() {
  3941. return this._z;
  3942. }
  3943. set z(value) {
  3944. this._z = value;
  3945. this._onChangeCallback();
  3946. }
  3947. get order() {
  3948. return this._order;
  3949. }
  3950. set order(value) {
  3951. this._order = value;
  3952. this._onChangeCallback();
  3953. }
  3954. set(x, y, z, order) {
  3955. this._x = x;
  3956. this._y = y;
  3957. this._z = z;
  3958. this._order = order || this._order;
  3959. this._onChangeCallback();
  3960. return this;
  3961. }
  3962. clone() {
  3963. return new this.constructor(this._x, this._y, this._z, this._order);
  3964. }
  3965. copy(euler) {
  3966. this._x = euler._x;
  3967. this._y = euler._y;
  3968. this._z = euler._z;
  3969. this._order = euler._order;
  3970. this._onChangeCallback();
  3971. return this;
  3972. }
  3973. setFromRotationMatrix(m, order, update) {
  3974. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3975. const te = m.elements;
  3976. const m11 = te[0],
  3977. m12 = te[4],
  3978. m13 = te[8];
  3979. const m21 = te[1],
  3980. m22 = te[5],
  3981. m23 = te[9];
  3982. const m31 = te[2],
  3983. m32 = te[6],
  3984. m33 = te[10];
  3985. order = order || this._order;
  3986. switch (order) {
  3987. case 'XYZ':
  3988. this._y = Math.asin(clamp(m13, -1, 1));
  3989. if (Math.abs(m13) < 0.9999999) {
  3990. this._x = Math.atan2(-m23, m33);
  3991. this._z = Math.atan2(-m12, m11);
  3992. } else {
  3993. this._x = Math.atan2(m32, m22);
  3994. this._z = 0;
  3995. }
  3996. break;
  3997. case 'YXZ':
  3998. this._x = Math.asin(-clamp(m23, -1, 1));
  3999. if (Math.abs(m23) < 0.9999999) {
  4000. this._y = Math.atan2(m13, m33);
  4001. this._z = Math.atan2(m21, m22);
  4002. } else {
  4003. this._y = Math.atan2(-m31, m11);
  4004. this._z = 0;
  4005. }
  4006. break;
  4007. case 'ZXY':
  4008. this._x = Math.asin(clamp(m32, -1, 1));
  4009. if (Math.abs(m32) < 0.9999999) {
  4010. this._y = Math.atan2(-m31, m33);
  4011. this._z = Math.atan2(-m12, m22);
  4012. } else {
  4013. this._y = 0;
  4014. this._z = Math.atan2(m21, m11);
  4015. }
  4016. break;
  4017. case 'ZYX':
  4018. this._y = Math.asin(-clamp(m31, -1, 1));
  4019. if (Math.abs(m31) < 0.9999999) {
  4020. this._x = Math.atan2(m32, m33);
  4021. this._z = Math.atan2(m21, m11);
  4022. } else {
  4023. this._x = 0;
  4024. this._z = Math.atan2(-m12, m22);
  4025. }
  4026. break;
  4027. case 'YZX':
  4028. this._z = Math.asin(clamp(m21, -1, 1));
  4029. if (Math.abs(m21) < 0.9999999) {
  4030. this._x = Math.atan2(-m23, m22);
  4031. this._y = Math.atan2(-m31, m11);
  4032. } else {
  4033. this._x = 0;
  4034. this._y = Math.atan2(m13, m33);
  4035. }
  4036. break;
  4037. case 'XZY':
  4038. this._z = Math.asin(-clamp(m12, -1, 1));
  4039. if (Math.abs(m12) < 0.9999999) {
  4040. this._x = Math.atan2(m32, m22);
  4041. this._y = Math.atan2(m13, m11);
  4042. } else {
  4043. this._x = Math.atan2(-m23, m33);
  4044. this._y = 0;
  4045. }
  4046. break;
  4047. default:
  4048. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  4049. }
  4050. this._order = order;
  4051. if (update !== false) this._onChangeCallback();
  4052. return this;
  4053. }
  4054. setFromQuaternion(q, order, update) {
  4055. _matrix$1.makeRotationFromQuaternion(q);
  4056. return this.setFromRotationMatrix(_matrix$1, order, update);
  4057. }
  4058. setFromVector3(v, order) {
  4059. return this.set(v.x, v.y, v.z, order || this._order);
  4060. }
  4061. reorder(newOrder) {
  4062. // WARNING: this discards revolution information -bhouston
  4063. _quaternion$3.setFromEuler(this);
  4064. return this.setFromQuaternion(_quaternion$3, newOrder);
  4065. }
  4066. equals(euler) {
  4067. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4068. }
  4069. fromArray(array) {
  4070. this._x = array[0];
  4071. this._y = array[1];
  4072. this._z = array[2];
  4073. if (array[3] !== undefined) this._order = array[3];
  4074. this._onChangeCallback();
  4075. return this;
  4076. }
  4077. toArray(array = [], offset = 0) {
  4078. array[offset] = this._x;
  4079. array[offset + 1] = this._y;
  4080. array[offset + 2] = this._z;
  4081. array[offset + 3] = this._order;
  4082. return array;
  4083. }
  4084. toVector3(optionalResult) {
  4085. if (optionalResult) {
  4086. return optionalResult.set(this._x, this._y, this._z);
  4087. } else {
  4088. return new Vector3(this._x, this._y, this._z);
  4089. }
  4090. }
  4091. _onChange(callback) {
  4092. this._onChangeCallback = callback;
  4093. return this;
  4094. }
  4095. _onChangeCallback() {}
  4096. }
  4097. Euler.prototype.isEuler = true;
  4098. Euler.DefaultOrder = 'XYZ';
  4099. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4100. class Layers {
  4101. constructor() {
  4102. this.mask = 1 | 0;
  4103. }
  4104. set(channel) {
  4105. this.mask = 1 << channel | 0;
  4106. }
  4107. enable(channel) {
  4108. this.mask |= 1 << channel | 0;
  4109. }
  4110. enableAll() {
  4111. this.mask = 0xffffffff | 0;
  4112. }
  4113. toggle(channel) {
  4114. this.mask ^= 1 << channel | 0;
  4115. }
  4116. disable(channel) {
  4117. this.mask &= ~(1 << channel | 0);
  4118. }
  4119. disableAll() {
  4120. this.mask = 0;
  4121. }
  4122. test(layers) {
  4123. return (this.mask & layers.mask) !== 0;
  4124. }
  4125. }
  4126. let _object3DId = 0;
  4127. const _v1$4 = /*@__PURE__*/new Vector3();
  4128. const _q1 = /*@__PURE__*/new Quaternion();
  4129. const _m1$1 = /*@__PURE__*/new Matrix4();
  4130. const _target = /*@__PURE__*/new Vector3();
  4131. const _position$3 = /*@__PURE__*/new Vector3();
  4132. const _scale$2 = /*@__PURE__*/new Vector3();
  4133. const _quaternion$2 = /*@__PURE__*/new Quaternion();
  4134. const _xAxis = /*@__PURE__*/new Vector3(1, 0, 0);
  4135. const _yAxis = /*@__PURE__*/new Vector3(0, 1, 0);
  4136. const _zAxis = /*@__PURE__*/new Vector3(0, 0, 1);
  4137. const _addedEvent = {
  4138. type: 'added'
  4139. };
  4140. const _removedEvent = {
  4141. type: 'removed'
  4142. };
  4143. class Object3D extends EventDispatcher {
  4144. constructor() {
  4145. super();
  4146. Object.defineProperty(this, 'id', {
  4147. value: _object3DId++
  4148. });
  4149. this.uuid = generateUUID();
  4150. this.name = '';
  4151. this.type = 'Object3D';
  4152. this.parent = null;
  4153. this.children = [];
  4154. this.up = Object3D.DefaultUp.clone();
  4155. const position = new Vector3();
  4156. const rotation = new Euler();
  4157. const quaternion = new Quaternion();
  4158. const scale = new Vector3(1, 1, 1);
  4159. function onRotationChange() {
  4160. quaternion.setFromEuler(rotation, false);
  4161. }
  4162. function onQuaternionChange() {
  4163. rotation.setFromQuaternion(quaternion, undefined, false);
  4164. }
  4165. rotation._onChange(onRotationChange);
  4166. quaternion._onChange(onQuaternionChange);
  4167. Object.defineProperties(this, {
  4168. position: {
  4169. configurable: true,
  4170. enumerable: true,
  4171. value: position
  4172. },
  4173. rotation: {
  4174. configurable: true,
  4175. enumerable: true,
  4176. value: rotation
  4177. },
  4178. quaternion: {
  4179. configurable: true,
  4180. enumerable: true,
  4181. value: quaternion
  4182. },
  4183. scale: {
  4184. configurable: true,
  4185. enumerable: true,
  4186. value: scale
  4187. },
  4188. modelViewMatrix: {
  4189. value: new Matrix4()
  4190. },
  4191. normalMatrix: {
  4192. value: new Matrix3()
  4193. }
  4194. });
  4195. this.matrix = new Matrix4();
  4196. this.matrixWorld = new Matrix4();
  4197. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4198. this.matrixWorldNeedsUpdate = false;
  4199. this.layers = new Layers();
  4200. this.visible = true;
  4201. this.castShadow = false;
  4202. this.receiveShadow = false;
  4203. this.frustumCulled = true;
  4204. this.renderOrder = 0;
  4205. this.animations = [];
  4206. this.userData = {};
  4207. }
  4208. onBeforeRender() {}
  4209. onAfterRender() {}
  4210. applyMatrix4(matrix) {
  4211. if (this.matrixAutoUpdate) this.updateMatrix();
  4212. this.matrix.premultiply(matrix);
  4213. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4214. }
  4215. applyQuaternion(q) {
  4216. this.quaternion.premultiply(q);
  4217. return this;
  4218. }
  4219. setRotationFromAxisAngle(axis, angle) {
  4220. // assumes axis is normalized
  4221. this.quaternion.setFromAxisAngle(axis, angle);
  4222. }
  4223. setRotationFromEuler(euler) {
  4224. this.quaternion.setFromEuler(euler, true);
  4225. }
  4226. setRotationFromMatrix(m) {
  4227. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4228. this.quaternion.setFromRotationMatrix(m);
  4229. }
  4230. setRotationFromQuaternion(q) {
  4231. // assumes q is normalized
  4232. this.quaternion.copy(q);
  4233. }
  4234. rotateOnAxis(axis, angle) {
  4235. // rotate object on axis in object space
  4236. // axis is assumed to be normalized
  4237. _q1.setFromAxisAngle(axis, angle);
  4238. this.quaternion.multiply(_q1);
  4239. return this;
  4240. }
  4241. rotateOnWorldAxis(axis, angle) {
  4242. // rotate object on axis in world space
  4243. // axis is assumed to be normalized
  4244. // method assumes no rotated parent
  4245. _q1.setFromAxisAngle(axis, angle);
  4246. this.quaternion.premultiply(_q1);
  4247. return this;
  4248. }
  4249. rotateX(angle) {
  4250. return this.rotateOnAxis(_xAxis, angle);
  4251. }
  4252. rotateY(angle) {
  4253. return this.rotateOnAxis(_yAxis, angle);
  4254. }
  4255. rotateZ(angle) {
  4256. return this.rotateOnAxis(_zAxis, angle);
  4257. }
  4258. translateOnAxis(axis, distance) {
  4259. // translate object by distance along axis in object space
  4260. // axis is assumed to be normalized
  4261. _v1$4.copy(axis).applyQuaternion(this.quaternion);
  4262. this.position.add(_v1$4.multiplyScalar(distance));
  4263. return this;
  4264. }
  4265. translateX(distance) {
  4266. return this.translateOnAxis(_xAxis, distance);
  4267. }
  4268. translateY(distance) {
  4269. return this.translateOnAxis(_yAxis, distance);
  4270. }
  4271. translateZ(distance) {
  4272. return this.translateOnAxis(_zAxis, distance);
  4273. }
  4274. localToWorld(vector) {
  4275. return vector.applyMatrix4(this.matrixWorld);
  4276. }
  4277. worldToLocal(vector) {
  4278. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  4279. }
  4280. lookAt(x, y, z) {
  4281. // This method does not support objects having non-uniformly-scaled parent(s)
  4282. if (x.isVector3) {
  4283. _target.copy(x);
  4284. } else {
  4285. _target.set(x, y, z);
  4286. }
  4287. const parent = this.parent;
  4288. this.updateWorldMatrix(true, false);
  4289. _position$3.setFromMatrixPosition(this.matrixWorld);
  4290. if (this.isCamera || this.isLight) {
  4291. _m1$1.lookAt(_position$3, _target, this.up);
  4292. } else {
  4293. _m1$1.lookAt(_target, _position$3, this.up);
  4294. }
  4295. this.quaternion.setFromRotationMatrix(_m1$1);
  4296. if (parent) {
  4297. _m1$1.extractRotation(parent.matrixWorld);
  4298. _q1.setFromRotationMatrix(_m1$1);
  4299. this.quaternion.premultiply(_q1.invert());
  4300. }
  4301. }
  4302. add(object) {
  4303. if (arguments.length > 1) {
  4304. for (let i = 0; i < arguments.length; i++) {
  4305. this.add(arguments[i]);
  4306. }
  4307. return this;
  4308. }
  4309. if (object === this) {
  4310. console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
  4311. return this;
  4312. }
  4313. if (object && object.isObject3D) {
  4314. if (object.parent !== null) {
  4315. object.parent.remove(object);
  4316. }
  4317. object.parent = this;
  4318. this.children.push(object);
  4319. object.dispatchEvent(_addedEvent);
  4320. } else {
  4321. console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
  4322. }
  4323. return this;
  4324. }
  4325. remove(object) {
  4326. if (arguments.length > 1) {
  4327. for (let i = 0; i < arguments.length; i++) {
  4328. this.remove(arguments[i]);
  4329. }
  4330. return this;
  4331. }
  4332. const index = this.children.indexOf(object);
  4333. if (index !== -1) {
  4334. object.parent = null;
  4335. this.children.splice(index, 1);
  4336. object.dispatchEvent(_removedEvent);
  4337. }
  4338. return this;
  4339. }
  4340. removeFromParent() {
  4341. const parent = this.parent;
  4342. if (parent !== null) {
  4343. parent.remove(this);
  4344. }
  4345. return this;
  4346. }
  4347. clear() {
  4348. for (let i = 0; i < this.children.length; i++) {
  4349. const object = this.children[i];
  4350. object.parent = null;
  4351. object.dispatchEvent(_removedEvent);
  4352. }
  4353. this.children.length = 0;
  4354. return this;
  4355. }
  4356. attach(object) {
  4357. // adds object as a child of this, while maintaining the object's world transform
  4358. this.updateWorldMatrix(true, false);
  4359. _m1$1.copy(this.matrixWorld).invert();
  4360. if (object.parent !== null) {
  4361. object.parent.updateWorldMatrix(true, false);
  4362. _m1$1.multiply(object.parent.matrixWorld);
  4363. }
  4364. object.applyMatrix4(_m1$1);
  4365. this.add(object);
  4366. object.updateWorldMatrix(false, true);
  4367. return this;
  4368. }
  4369. getObjectById(id) {
  4370. return this.getObjectByProperty('id', id);
  4371. }
  4372. getObjectByName(name) {
  4373. return this.getObjectByProperty('name', name);
  4374. }
  4375. getObjectByProperty(name, value) {
  4376. if (this[name] === value) return this;
  4377. for (let i = 0, l = this.children.length; i < l; i++) {
  4378. const child = this.children[i];
  4379. const object = child.getObjectByProperty(name, value);
  4380. if (object !== undefined) {
  4381. return object;
  4382. }
  4383. }
  4384. return undefined;
  4385. }
  4386. getWorldPosition(target) {
  4387. if (target === undefined) {
  4388. console.warn('THREE.Object3D: .getWorldPosition() target is now required');
  4389. target = new Vector3();
  4390. }
  4391. this.updateWorldMatrix(true, false);
  4392. return target.setFromMatrixPosition(this.matrixWorld);
  4393. }
  4394. getWorldQuaternion(target) {
  4395. if (target === undefined) {
  4396. console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');
  4397. target = new Quaternion();
  4398. }
  4399. this.updateWorldMatrix(true, false);
  4400. this.matrixWorld.decompose(_position$3, target, _scale$2);
  4401. return target;
  4402. }
  4403. getWorldScale(target) {
  4404. if (target === undefined) {
  4405. console.warn('THREE.Object3D: .getWorldScale() target is now required');
  4406. target = new Vector3();
  4407. }
  4408. this.updateWorldMatrix(true, false);
  4409. this.matrixWorld.decompose(_position$3, _quaternion$2, target);
  4410. return target;
  4411. }
  4412. getWorldDirection(target) {
  4413. if (target === undefined) {
  4414. console.warn('THREE.Object3D: .getWorldDirection() target is now required');
  4415. target = new Vector3();
  4416. }
  4417. this.updateWorldMatrix(true, false);
  4418. const e = this.matrixWorld.elements;
  4419. return target.set(e[8], e[9], e[10]).normalize();
  4420. }
  4421. raycast() {}
  4422. traverse(callback) {
  4423. callback(this);
  4424. const children = this.children;
  4425. for (let i = 0, l = children.length; i < l; i++) {
  4426. children[i].traverse(callback);
  4427. }
  4428. }
  4429. traverseVisible(callback) {
  4430. if (this.visible === false) return;
  4431. callback(this);
  4432. const children = this.children;
  4433. for (let i = 0, l = children.length; i < l; i++) {
  4434. children[i].traverseVisible(callback);
  4435. }
  4436. }
  4437. traverseAncestors(callback) {
  4438. const parent = this.parent;
  4439. if (parent !== null) {
  4440. callback(parent);
  4441. parent.traverseAncestors(callback);
  4442. }
  4443. }
  4444. updateMatrix() {
  4445. this.matrix.compose(this.position, this.quaternion, this.scale);
  4446. this.matrixWorldNeedsUpdate = true;
  4447. }
  4448. updateMatrixWorld(force) {
  4449. if (this.matrixAutoUpdate) this.updateMatrix();
  4450. if (this.matrixWorldNeedsUpdate || force) {
  4451. if (this.parent === null) {
  4452. this.matrixWorld.copy(this.matrix);
  4453. } else {
  4454. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4455. }
  4456. this.matrixWorldNeedsUpdate = false;
  4457. force = true;
  4458. } // update children
  4459. const children = this.children;
  4460. for (let i = 0, l = children.length; i < l; i++) {
  4461. children[i].updateMatrixWorld(force);
  4462. }
  4463. }
  4464. updateWorldMatrix(updateParents, updateChildren) {
  4465. const parent = this.parent;
  4466. if (updateParents === true && parent !== null) {
  4467. parent.updateWorldMatrix(true, false);
  4468. }
  4469. if (this.matrixAutoUpdate) this.updateMatrix();
  4470. if (this.parent === null) {
  4471. this.matrixWorld.copy(this.matrix);
  4472. } else {
  4473. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4474. } // update children
  4475. if (updateChildren === true) {
  4476. const children = this.children;
  4477. for (let i = 0, l = children.length; i < l; i++) {
  4478. children[i].updateWorldMatrix(false, true);
  4479. }
  4480. }
  4481. }
  4482. toJSON(meta) {
  4483. // meta is a string when called from JSON.stringify
  4484. const isRootObject = meta === undefined || typeof meta === 'string';
  4485. const output = {}; // meta is a hash used to collect geometries, materials.
  4486. // not providing it implies that this is the root object
  4487. // being serialized.
  4488. if (isRootObject) {
  4489. // initialize meta obj
  4490. meta = {
  4491. geometries: {},
  4492. materials: {},
  4493. textures: {},
  4494. images: {},
  4495. shapes: {},
  4496. skeletons: {},
  4497. animations: {}
  4498. };
  4499. output.metadata = {
  4500. version: 4.5,
  4501. type: 'Object',
  4502. generator: 'Object3D.toJSON'
  4503. };
  4504. } // standard Object3D serialization
  4505. const object = {};
  4506. object.uuid = this.uuid;
  4507. object.type = this.type;
  4508. if (this.name !== '') object.name = this.name;
  4509. if (this.castShadow === true) object.castShadow = true;
  4510. if (this.receiveShadow === true) object.receiveShadow = true;
  4511. if (this.visible === false) object.visible = false;
  4512. if (this.frustumCulled === false) object.frustumCulled = false;
  4513. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  4514. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  4515. object.layers = this.layers.mask;
  4516. object.matrix = this.matrix.toArray();
  4517. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  4518. if (this.isInstancedMesh) {
  4519. object.type = 'InstancedMesh';
  4520. object.count = this.count;
  4521. object.instanceMatrix = this.instanceMatrix.toJSON();
  4522. if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON();
  4523. } //
  4524. function serialize(library, element) {
  4525. if (library[element.uuid] === undefined) {
  4526. library[element.uuid] = element.toJSON(meta);
  4527. }
  4528. return element.uuid;
  4529. }
  4530. if (this.isMesh || this.isLine || this.isPoints) {
  4531. object.geometry = serialize(meta.geometries, this.geometry);
  4532. const parameters = this.geometry.parameters;
  4533. if (parameters !== undefined && parameters.shapes !== undefined) {
  4534. const shapes = parameters.shapes;
  4535. if (Array.isArray(shapes)) {
  4536. for (let i = 0, l = shapes.length; i < l; i++) {
  4537. const shape = shapes[i];
  4538. serialize(meta.shapes, shape);
  4539. }
  4540. } else {
  4541. serialize(meta.shapes, shapes);
  4542. }
  4543. }
  4544. }
  4545. if (this.isSkinnedMesh) {
  4546. object.bindMode = this.bindMode;
  4547. object.bindMatrix = this.bindMatrix.toArray();
  4548. if (this.skeleton !== undefined) {
  4549. serialize(meta.skeletons, this.skeleton);
  4550. object.skeleton = this.skeleton.uuid;
  4551. }
  4552. }
  4553. if (this.material !== undefined) {
  4554. if (Array.isArray(this.material)) {
  4555. const uuids = [];
  4556. for (let i = 0, l = this.material.length; i < l; i++) {
  4557. uuids.push(serialize(meta.materials, this.material[i]));
  4558. }
  4559. object.material = uuids;
  4560. } else {
  4561. object.material = serialize(meta.materials, this.material);
  4562. }
  4563. } //
  4564. if (this.children.length > 0) {
  4565. object.children = [];
  4566. for (let i = 0; i < this.children.length; i++) {
  4567. object.children.push(this.children[i].toJSON(meta).object);
  4568. }
  4569. } //
  4570. if (this.animations.length > 0) {
  4571. object.animations = [];
  4572. for (let i = 0; i < this.animations.length; i++) {
  4573. const animation = this.animations[i];
  4574. object.animations.push(serialize(meta.animations, animation));
  4575. }
  4576. }
  4577. if (isRootObject) {
  4578. const geometries = extractFromCache(meta.geometries);
  4579. const materials = extractFromCache(meta.materials);
  4580. const textures = extractFromCache(meta.textures);
  4581. const images = extractFromCache(meta.images);
  4582. const shapes = extractFromCache(meta.shapes);
  4583. const skeletons = extractFromCache(meta.skeletons);
  4584. const animations = extractFromCache(meta.animations);
  4585. if (geometries.length > 0) output.geometries = geometries;
  4586. if (materials.length > 0) output.materials = materials;
  4587. if (textures.length > 0) output.textures = textures;
  4588. if (images.length > 0) output.images = images;
  4589. if (shapes.length > 0) output.shapes = shapes;
  4590. if (skeletons.length > 0) output.skeletons = skeletons;
  4591. if (animations.length > 0) output.animations = animations;
  4592. }
  4593. output.object = object;
  4594. return output; // extract data from the cache hash
  4595. // remove metadata on each item
  4596. // and return as array
  4597. function extractFromCache(cache) {
  4598. const values = [];
  4599. for (const key in cache) {
  4600. const data = cache[key];
  4601. delete data.metadata;
  4602. values.push(data);
  4603. }
  4604. return values;
  4605. }
  4606. }
  4607. clone(recursive) {
  4608. return new this.constructor().copy(this, recursive);
  4609. }
  4610. copy(source, recursive = true) {
  4611. this.name = source.name;
  4612. this.up.copy(source.up);
  4613. this.position.copy(source.position);
  4614. this.rotation.order = source.rotation.order;
  4615. this.quaternion.copy(source.quaternion);
  4616. this.scale.copy(source.scale);
  4617. this.matrix.copy(source.matrix);
  4618. this.matrixWorld.copy(source.matrixWorld);
  4619. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4620. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4621. this.layers.mask = source.layers.mask;
  4622. this.visible = source.visible;
  4623. this.castShadow = source.castShadow;
  4624. this.receiveShadow = source.receiveShadow;
  4625. this.frustumCulled = source.frustumCulled;
  4626. this.renderOrder = source.renderOrder;
  4627. this.userData = JSON.parse(JSON.stringify(source.userData));
  4628. if (recursive === true) {
  4629. for (let i = 0; i < source.children.length; i++) {
  4630. const child = source.children[i];
  4631. this.add(child.clone());
  4632. }
  4633. }
  4634. return this;
  4635. }
  4636. }
  4637. Object3D.DefaultUp = new Vector3(0, 1, 0);
  4638. Object3D.DefaultMatrixAutoUpdate = true;
  4639. Object3D.prototype.isObject3D = true;
  4640. const _vector1 = /*@__PURE__*/new Vector3();
  4641. const _vector2$1 = /*@__PURE__*/new Vector3();
  4642. const _normalMatrix = /*@__PURE__*/new Matrix3();
  4643. class Plane {
  4644. constructor(normal = new Vector3(1, 0, 0), constant = 0) {
  4645. // normal is assumed to be normalized
  4646. this.normal = normal;
  4647. this.constant = constant;
  4648. }
  4649. set(normal, constant) {
  4650. this.normal.copy(normal);
  4651. this.constant = constant;
  4652. return this;
  4653. }
  4654. setComponents(x, y, z, w) {
  4655. this.normal.set(x, y, z);
  4656. this.constant = w;
  4657. return this;
  4658. }
  4659. setFromNormalAndCoplanarPoint(normal, point) {
  4660. this.normal.copy(normal);
  4661. this.constant = -point.dot(this.normal);
  4662. return this;
  4663. }
  4664. setFromCoplanarPoints(a, b, c) {
  4665. const normal = _vector1.subVectors(c, b).cross(_vector2$1.subVectors(a, b)).normalize(); // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  4666. this.setFromNormalAndCoplanarPoint(normal, a);
  4667. return this;
  4668. }
  4669. copy(plane) {
  4670. this.normal.copy(plane.normal);
  4671. this.constant = plane.constant;
  4672. return this;
  4673. }
  4674. normalize() {
  4675. // Note: will lead to a divide by zero if the plane is invalid.
  4676. const inverseNormalLength = 1.0 / this.normal.length();
  4677. this.normal.multiplyScalar(inverseNormalLength);
  4678. this.constant *= inverseNormalLength;
  4679. return this;
  4680. }
  4681. negate() {
  4682. this.constant *= -1;
  4683. this.normal.negate();
  4684. return this;
  4685. }
  4686. distanceToPoint(point) {
  4687. return this.normal.dot(point) + this.constant;
  4688. }
  4689. distanceToSphere(sphere) {
  4690. return this.distanceToPoint(sphere.center) - sphere.radius;
  4691. }
  4692. projectPoint(point, target) {
  4693. if (target === undefined) {
  4694. console.warn('THREE.Plane: .projectPoint() target is now required');
  4695. target = new Vector3();
  4696. }
  4697. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  4698. }
  4699. intersectLine(line, target) {
  4700. if (target === undefined) {
  4701. console.warn('THREE.Plane: .intersectLine() target is now required');
  4702. target = new Vector3();
  4703. }
  4704. const direction = line.delta(_vector1);
  4705. const denominator = this.normal.dot(direction);
  4706. if (denominator === 0) {
  4707. // line is coplanar, return origin
  4708. if (this.distanceToPoint(line.start) === 0) {
  4709. return target.copy(line.start);
  4710. } // Unsure if this is the correct method to handle this case.
  4711. return null;
  4712. }
  4713. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  4714. if (t < 0 || t > 1) {
  4715. return null;
  4716. }
  4717. return target.copy(direction).multiplyScalar(t).add(line.start);
  4718. }
  4719. intersectsLine(line) {
  4720. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  4721. const startSign = this.distanceToPoint(line.start);
  4722. const endSign = this.distanceToPoint(line.end);
  4723. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  4724. }
  4725. intersectsBox(box) {
  4726. return box.intersectsPlane(this);
  4727. }
  4728. intersectsSphere(sphere) {
  4729. return sphere.intersectsPlane(this);
  4730. }
  4731. coplanarPoint(target) {
  4732. if (target === undefined) {
  4733. console.warn('THREE.Plane: .coplanarPoint() target is now required');
  4734. target = new Vector3();
  4735. }
  4736. return target.copy(this.normal).multiplyScalar(-this.constant);
  4737. }
  4738. applyMatrix4(matrix, optionalNormalMatrix) {
  4739. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  4740. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  4741. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  4742. this.constant = -referencePoint.dot(normal);
  4743. return this;
  4744. }
  4745. translate(offset) {
  4746. this.constant -= offset.dot(this.normal);
  4747. return this;
  4748. }
  4749. equals(plane) {
  4750. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  4751. }
  4752. clone() {
  4753. return new this.constructor().copy(this);
  4754. }
  4755. }
  4756. Plane.prototype.isPlane = true;
  4757. const _v0$1 = /*@__PURE__*/new Vector3();
  4758. const _v1$3 = /*@__PURE__*/new Vector3();
  4759. const _v2$2 = /*@__PURE__*/new Vector3();
  4760. const _v3$1 = /*@__PURE__*/new Vector3();
  4761. const _vab = /*@__PURE__*/new Vector3();
  4762. const _vac = /*@__PURE__*/new Vector3();
  4763. const _vbc = /*@__PURE__*/new Vector3();
  4764. const _vap = /*@__PURE__*/new Vector3();
  4765. const _vbp = /*@__PURE__*/new Vector3();
  4766. const _vcp = /*@__PURE__*/new Vector3();
  4767. class Triangle {
  4768. constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) {
  4769. this.a = a;
  4770. this.b = b;
  4771. this.c = c;
  4772. }
  4773. static getNormal(a, b, c, target) {
  4774. if (target === undefined) {
  4775. console.warn('THREE.Triangle: .getNormal() target is now required');
  4776. target = new Vector3();
  4777. }
  4778. target.subVectors(c, b);
  4779. _v0$1.subVectors(a, b);
  4780. target.cross(_v0$1);
  4781. const targetLengthSq = target.lengthSq();
  4782. if (targetLengthSq > 0) {
  4783. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  4784. }
  4785. return target.set(0, 0, 0);
  4786. } // static/instance method to calculate barycentric coordinates
  4787. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4788. static getBarycoord(point, a, b, c, target) {
  4789. _v0$1.subVectors(c, a);
  4790. _v1$3.subVectors(b, a);
  4791. _v2$2.subVectors(point, a);
  4792. const dot00 = _v0$1.dot(_v0$1);
  4793. const dot01 = _v0$1.dot(_v1$3);
  4794. const dot02 = _v0$1.dot(_v2$2);
  4795. const dot11 = _v1$3.dot(_v1$3);
  4796. const dot12 = _v1$3.dot(_v2$2);
  4797. const denom = dot00 * dot11 - dot01 * dot01;
  4798. if (target === undefined) {
  4799. console.warn('THREE.Triangle: .getBarycoord() target is now required');
  4800. target = new Vector3();
  4801. } // collinear or singular triangle
  4802. if (denom === 0) {
  4803. // arbitrary location outside of triangle?
  4804. // not sure if this is the best idea, maybe should be returning undefined
  4805. return target.set(-2, -1, -1);
  4806. }
  4807. const invDenom = 1 / denom;
  4808. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  4809. const v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  4810. return target.set(1 - u - v, v, u);
  4811. }
  4812. static containsPoint(point, a, b, c) {
  4813. this.getBarycoord(point, a, b, c, _v3$1);
  4814. return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1;
  4815. }
  4816. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  4817. this.getBarycoord(point, p1, p2, p3, _v3$1);
  4818. target.set(0, 0);
  4819. target.addScaledVector(uv1, _v3$1.x);
  4820. target.addScaledVector(uv2, _v3$1.y);
  4821. target.addScaledVector(uv3, _v3$1.z);
  4822. return target;
  4823. }
  4824. static isFrontFacing(a, b, c, direction) {
  4825. _v0$1.subVectors(c, b);
  4826. _v1$3.subVectors(a, b); // strictly front facing
  4827. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  4828. }
  4829. set(a, b, c) {
  4830. this.a.copy(a);
  4831. this.b.copy(b);
  4832. this.c.copy(c);
  4833. return this;
  4834. }
  4835. setFromPointsAndIndices(points, i0, i1, i2) {
  4836. this.a.copy(points[i0]);
  4837. this.b.copy(points[i1]);
  4838. this.c.copy(points[i2]);
  4839. return this;
  4840. }
  4841. clone() {
  4842. return new this.constructor().copy(this);
  4843. }
  4844. copy(triangle) {
  4845. this.a.copy(triangle.a);
  4846. this.b.copy(triangle.b);
  4847. this.c.copy(triangle.c);
  4848. return this;
  4849. }
  4850. getArea() {
  4851. _v0$1.subVectors(this.c, this.b);
  4852. _v1$3.subVectors(this.a, this.b);
  4853. return _v0$1.cross(_v1$3).length() * 0.5;
  4854. }
  4855. getMidpoint(target) {
  4856. if (target === undefined) {
  4857. console.warn('THREE.Triangle: .getMidpoint() target is now required');
  4858. target = new Vector3();
  4859. }
  4860. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  4861. }
  4862. getNormal(target) {
  4863. return Triangle.getNormal(this.a, this.b, this.c, target);
  4864. }
  4865. getPlane(target) {
  4866. if (target === undefined) {
  4867. console.warn('THREE.Triangle: .getPlane() target is now required');
  4868. target = new Plane();
  4869. }
  4870. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  4871. }
  4872. getBarycoord(point, target) {
  4873. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  4874. }
  4875. getUV(point, uv1, uv2, uv3, target) {
  4876. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  4877. }
  4878. containsPoint(point) {
  4879. return Triangle.containsPoint(point, this.a, this.b, this.c);
  4880. }
  4881. isFrontFacing(direction) {
  4882. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  4883. }
  4884. intersectsBox(box) {
  4885. return box.intersectsTriangle(this);
  4886. }
  4887. closestPointToPoint(p, target) {
  4888. if (target === undefined) {
  4889. console.warn('THREE.Triangle: .closestPointToPoint() target is now required');
  4890. target = new Vector3();
  4891. }
  4892. const a = this.a,
  4893. b = this.b,
  4894. c = this.c;
  4895. let v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4896. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4897. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4898. // basically, we're distinguishing which of the voronoi regions of the triangle
  4899. // the point lies in with the minimum amount of redundant computation.
  4900. _vab.subVectors(b, a);
  4901. _vac.subVectors(c, a);
  4902. _vap.subVectors(p, a);
  4903. const d1 = _vab.dot(_vap);
  4904. const d2 = _vac.dot(_vap);
  4905. if (d1 <= 0 && d2 <= 0) {
  4906. // vertex region of A; barycentric coords (1, 0, 0)
  4907. return target.copy(a);
  4908. }
  4909. _vbp.subVectors(p, b);
  4910. const d3 = _vab.dot(_vbp);
  4911. const d4 = _vac.dot(_vbp);
  4912. if (d3 >= 0 && d4 <= d3) {
  4913. // vertex region of B; barycentric coords (0, 1, 0)
  4914. return target.copy(b);
  4915. }
  4916. const vc = d1 * d4 - d3 * d2;
  4917. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  4918. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  4919. return target.copy(a).addScaledVector(_vab, v);
  4920. }
  4921. _vcp.subVectors(p, c);
  4922. const d5 = _vab.dot(_vcp);
  4923. const d6 = _vac.dot(_vcp);
  4924. if (d6 >= 0 && d5 <= d6) {
  4925. // vertex region of C; barycentric coords (0, 0, 1)
  4926. return target.copy(c);
  4927. }
  4928. const vb = d5 * d2 - d1 * d6;
  4929. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  4930. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  4931. return target.copy(a).addScaledVector(_vac, w);
  4932. }
  4933. const va = d3 * d6 - d5 * d4;
  4934. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  4935. _vbc.subVectors(c, b);
  4936. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  4937. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  4938. } // face region
  4939. const denom = 1 / (va + vb + vc); // u = va * denom
  4940. v = vb * denom;
  4941. w = vc * denom;
  4942. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  4943. }
  4944. equals(triangle) {
  4945. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  4946. }
  4947. }
  4948. let materialId = 0;
  4949. class Material extends EventDispatcher {
  4950. constructor() {
  4951. super();
  4952. Object.defineProperty(this, 'id', {
  4953. value: materialId++
  4954. });
  4955. this.uuid = generateUUID();
  4956. this.name = '';
  4957. this.type = 'Material';
  4958. this.fog = true;
  4959. this.blending = NormalBlending;
  4960. this.side = FrontSide;
  4961. this.vertexColors = false;
  4962. this.opacity = 1;
  4963. this.transparent = false;
  4964. this.blendSrc = SrcAlphaFactor;
  4965. this.blendDst = OneMinusSrcAlphaFactor;
  4966. this.blendEquation = AddEquation;
  4967. this.blendSrcAlpha = null;
  4968. this.blendDstAlpha = null;
  4969. this.blendEquationAlpha = null;
  4970. this.depthFunc = LessEqualDepth;
  4971. this.depthTest = true;
  4972. this.depthWrite = true;
  4973. this.stencilWriteMask = 0xff;
  4974. this.stencilFunc = AlwaysStencilFunc;
  4975. this.stencilRef = 0;
  4976. this.stencilFuncMask = 0xff;
  4977. this.stencilFail = KeepStencilOp;
  4978. this.stencilZFail = KeepStencilOp;
  4979. this.stencilZPass = KeepStencilOp;
  4980. this.stencilWrite = false;
  4981. this.clippingPlanes = null;
  4982. this.clipIntersection = false;
  4983. this.clipShadows = false;
  4984. this.shadowSide = null;
  4985. this.colorWrite = true;
  4986. this.precision = null; // override the renderer's default precision for this material
  4987. this.polygonOffset = false;
  4988. this.polygonOffsetFactor = 0;
  4989. this.polygonOffsetUnits = 0;
  4990. this.dithering = false;
  4991. this.alphaTest = 0;
  4992. this.alphaToCoverage = false;
  4993. this.premultipliedAlpha = false;
  4994. this.visible = true;
  4995. this.toneMapped = true;
  4996. this.userData = {};
  4997. this.version = 0;
  4998. }
  4999. onBuild()
  5000. /* shaderobject, renderer */
  5001. {}
  5002. onBeforeCompile()
  5003. /* shaderobject, renderer */
  5004. {}
  5005. customProgramCacheKey() {
  5006. return this.onBeforeCompile.toString();
  5007. }
  5008. setValues(values) {
  5009. if (values === undefined) return;
  5010. for (const key in values) {
  5011. const newValue = values[key];
  5012. if (newValue === undefined) {
  5013. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  5014. continue;
  5015. } // for backward compatability if shading is set in the constructor
  5016. if (key === 'shading') {
  5017. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  5018. this.flatShading = newValue === FlatShading ? true : false;
  5019. continue;
  5020. }
  5021. const currentValue = this[key];
  5022. if (currentValue === undefined) {
  5023. console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
  5024. continue;
  5025. }
  5026. if (currentValue && currentValue.isColor) {
  5027. currentValue.set(newValue);
  5028. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  5029. currentValue.copy(newValue);
  5030. } else {
  5031. this[key] = newValue;
  5032. }
  5033. }
  5034. }
  5035. toJSON(meta) {
  5036. const isRoot = meta === undefined || typeof meta === 'string';
  5037. if (isRoot) {
  5038. meta = {
  5039. textures: {},
  5040. images: {}
  5041. };
  5042. }
  5043. const data = {
  5044. metadata: {
  5045. version: 4.5,
  5046. type: 'Material',
  5047. generator: 'Material.toJSON'
  5048. }
  5049. }; // standard Material serialization
  5050. data.uuid = this.uuid;
  5051. data.type = this.type;
  5052. if (this.name !== '') data.name = this.name;
  5053. if (this.color && this.color.isColor) data.color = this.color.getHex();
  5054. if (this.roughness !== undefined) data.roughness = this.roughness;
  5055. if (this.metalness !== undefined) data.metalness = this.metalness;
  5056. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  5057. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  5058. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  5059. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  5060. if (this.shininess !== undefined) data.shininess = this.shininess;
  5061. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  5062. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  5063. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  5064. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  5065. }
  5066. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  5067. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  5068. }
  5069. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  5070. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  5071. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5072. }
  5073. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  5074. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  5075. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  5076. if (this.lightMap && this.lightMap.isTexture) {
  5077. data.lightMap = this.lightMap.toJSON(meta).uuid;
  5078. data.lightMapIntensity = this.lightMapIntensity;
  5079. }
  5080. if (this.aoMap && this.aoMap.isTexture) {
  5081. data.aoMap = this.aoMap.toJSON(meta).uuid;
  5082. data.aoMapIntensity = this.aoMapIntensity;
  5083. }
  5084. if (this.bumpMap && this.bumpMap.isTexture) {
  5085. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  5086. data.bumpScale = this.bumpScale;
  5087. }
  5088. if (this.normalMap && this.normalMap.isTexture) {
  5089. data.normalMap = this.normalMap.toJSON(meta).uuid;
  5090. data.normalMapType = this.normalMapType;
  5091. data.normalScale = this.normalScale.toArray();
  5092. }
  5093. if (this.displacementMap && this.displacementMap.isTexture) {
  5094. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  5095. data.displacementScale = this.displacementScale;
  5096. data.displacementBias = this.displacementBias;
  5097. }
  5098. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  5099. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  5100. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  5101. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  5102. if (this.envMap && this.envMap.isTexture) {
  5103. data.envMap = this.envMap.toJSON(meta).uuid;
  5104. if (this.combine !== undefined) data.combine = this.combine;
  5105. }
  5106. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  5107. if (this.reflectivity !== undefined) data.reflectivity = this.reflectivity;
  5108. if (this.refractionRatio !== undefined) data.refractionRatio = this.refractionRatio;
  5109. if (this.gradientMap && this.gradientMap.isTexture) {
  5110. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  5111. }
  5112. if (this.transmission !== undefined) data.transmission = this.transmission;
  5113. if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid;
  5114. if (this.thickness !== undefined) data.thickness = this.thickness;
  5115. if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid;
  5116. if (this.attenuationDistance !== undefined) data.attenuationDistance = this.attenuationDistance;
  5117. if (this.attenuationColor !== undefined) data.attenuationColor = this.attenuationColor.getHex();
  5118. if (this.size !== undefined) data.size = this.size;
  5119. if (this.shadowSide !== null) data.shadowSide = this.shadowSide;
  5120. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  5121. if (this.blending !== NormalBlending) data.blending = this.blending;
  5122. if (this.side !== FrontSide) data.side = this.side;
  5123. if (this.vertexColors) data.vertexColors = true;
  5124. if (this.opacity < 1) data.opacity = this.opacity;
  5125. if (this.transparent === true) data.transparent = this.transparent;
  5126. data.depthFunc = this.depthFunc;
  5127. data.depthTest = this.depthTest;
  5128. data.depthWrite = this.depthWrite;
  5129. data.colorWrite = this.colorWrite;
  5130. data.stencilWrite = this.stencilWrite;
  5131. data.stencilWriteMask = this.stencilWriteMask;
  5132. data.stencilFunc = this.stencilFunc;
  5133. data.stencilRef = this.stencilRef;
  5134. data.stencilFuncMask = this.stencilFuncMask;
  5135. data.stencilFail = this.stencilFail;
  5136. data.stencilZFail = this.stencilZFail;
  5137. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  5138. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  5139. if (this.polygonOffset === true) data.polygonOffset = true;
  5140. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5141. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5142. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  5143. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  5144. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  5145. if (this.scale !== undefined) data.scale = this.scale;
  5146. if (this.dithering === true) data.dithering = true;
  5147. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  5148. if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage;
  5149. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  5150. if (this.wireframe === true) data.wireframe = this.wireframe;
  5151. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  5152. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  5153. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  5154. if (this.morphTargets === true) data.morphTargets = true;
  5155. if (this.morphNormals === true) data.morphNormals = true;
  5156. if (this.flatShading === true) data.flatShading = this.flatShading;
  5157. if (this.visible === false) data.visible = false;
  5158. if (this.toneMapped === false) data.toneMapped = false;
  5159. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  5160. function extractFromCache(cache) {
  5161. const values = [];
  5162. for (const key in cache) {
  5163. const data = cache[key];
  5164. delete data.metadata;
  5165. values.push(data);
  5166. }
  5167. return values;
  5168. }
  5169. if (isRoot) {
  5170. const textures = extractFromCache(meta.textures);
  5171. const images = extractFromCache(meta.images);
  5172. if (textures.length > 0) data.textures = textures;
  5173. if (images.length > 0) data.images = images;
  5174. }
  5175. return data;
  5176. }
  5177. clone() {
  5178. return new this.constructor().copy(this);
  5179. }
  5180. copy(source) {
  5181. this.name = source.name;
  5182. this.fog = source.fog;
  5183. this.blending = source.blending;
  5184. this.side = source.side;
  5185. this.vertexColors = source.vertexColors;
  5186. this.opacity = source.opacity;
  5187. this.transparent = source.transparent;
  5188. this.blendSrc = source.blendSrc;
  5189. this.blendDst = source.blendDst;
  5190. this.blendEquation = source.blendEquation;
  5191. this.blendSrcAlpha = source.blendSrcAlpha;
  5192. this.blendDstAlpha = source.blendDstAlpha;
  5193. this.blendEquationAlpha = source.blendEquationAlpha;
  5194. this.depthFunc = source.depthFunc;
  5195. this.depthTest = source.depthTest;
  5196. this.depthWrite = source.depthWrite;
  5197. this.stencilWriteMask = source.stencilWriteMask;
  5198. this.stencilFunc = source.stencilFunc;
  5199. this.stencilRef = source.stencilRef;
  5200. this.stencilFuncMask = source.stencilFuncMask;
  5201. this.stencilFail = source.stencilFail;
  5202. this.stencilZFail = source.stencilZFail;
  5203. this.stencilZPass = source.stencilZPass;
  5204. this.stencilWrite = source.stencilWrite;
  5205. const srcPlanes = source.clippingPlanes;
  5206. let dstPlanes = null;
  5207. if (srcPlanes !== null) {
  5208. const n = srcPlanes.length;
  5209. dstPlanes = new Array(n);
  5210. for (let i = 0; i !== n; ++i) {
  5211. dstPlanes[i] = srcPlanes[i].clone();
  5212. }
  5213. }
  5214. this.clippingPlanes = dstPlanes;
  5215. this.clipIntersection = source.clipIntersection;
  5216. this.clipShadows = source.clipShadows;
  5217. this.shadowSide = source.shadowSide;
  5218. this.colorWrite = source.colorWrite;
  5219. this.precision = source.precision;
  5220. this.polygonOffset = source.polygonOffset;
  5221. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5222. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5223. this.dithering = source.dithering;
  5224. this.alphaTest = source.alphaTest;
  5225. this.alphaToCoverage = source.alphaToCoverage;
  5226. this.premultipliedAlpha = source.premultipliedAlpha;
  5227. this.visible = source.visible;
  5228. this.toneMapped = source.toneMapped;
  5229. this.userData = JSON.parse(JSON.stringify(source.userData));
  5230. return this;
  5231. }
  5232. dispose() {
  5233. this.dispatchEvent({
  5234. type: 'dispose'
  5235. });
  5236. }
  5237. set needsUpdate(value) {
  5238. if (value === true) this.version++;
  5239. }
  5240. }
  5241. Material.prototype.isMaterial = true;
  5242. const _colorKeywords = {
  5243. 'aliceblue': 0xF0F8FF,
  5244. 'antiquewhite': 0xFAEBD7,
  5245. 'aqua': 0x00FFFF,
  5246. 'aquamarine': 0x7FFFD4,
  5247. 'azure': 0xF0FFFF,
  5248. 'beige': 0xF5F5DC,
  5249. 'bisque': 0xFFE4C4,
  5250. 'black': 0x000000,
  5251. 'blanchedalmond': 0xFFEBCD,
  5252. 'blue': 0x0000FF,
  5253. 'blueviolet': 0x8A2BE2,
  5254. 'brown': 0xA52A2A,
  5255. 'burlywood': 0xDEB887,
  5256. 'cadetblue': 0x5F9EA0,
  5257. 'chartreuse': 0x7FFF00,
  5258. 'chocolate': 0xD2691E,
  5259. 'coral': 0xFF7F50,
  5260. 'cornflowerblue': 0x6495ED,
  5261. 'cornsilk': 0xFFF8DC,
  5262. 'crimson': 0xDC143C,
  5263. 'cyan': 0x00FFFF,
  5264. 'darkblue': 0x00008B,
  5265. 'darkcyan': 0x008B8B,
  5266. 'darkgoldenrod': 0xB8860B,
  5267. 'darkgray': 0xA9A9A9,
  5268. 'darkgreen': 0x006400,
  5269. 'darkgrey': 0xA9A9A9,
  5270. 'darkkhaki': 0xBDB76B,
  5271. 'darkmagenta': 0x8B008B,
  5272. 'darkolivegreen': 0x556B2F,
  5273. 'darkorange': 0xFF8C00,
  5274. 'darkorchid': 0x9932CC,
  5275. 'darkred': 0x8B0000,
  5276. 'darksalmon': 0xE9967A,
  5277. 'darkseagreen': 0x8FBC8F,
  5278. 'darkslateblue': 0x483D8B,
  5279. 'darkslategray': 0x2F4F4F,
  5280. 'darkslategrey': 0x2F4F4F,
  5281. 'darkturquoise': 0x00CED1,
  5282. 'darkviolet': 0x9400D3,
  5283. 'deeppink': 0xFF1493,
  5284. 'deepskyblue': 0x00BFFF,
  5285. 'dimgray': 0x696969,
  5286. 'dimgrey': 0x696969,
  5287. 'dodgerblue': 0x1E90FF,
  5288. 'firebrick': 0xB22222,
  5289. 'floralwhite': 0xFFFAF0,
  5290. 'forestgreen': 0x228B22,
  5291. 'fuchsia': 0xFF00FF,
  5292. 'gainsboro': 0xDCDCDC,
  5293. 'ghostwhite': 0xF8F8FF,
  5294. 'gold': 0xFFD700,
  5295. 'goldenrod': 0xDAA520,
  5296. 'gray': 0x808080,
  5297. 'green': 0x008000,
  5298. 'greenyellow': 0xADFF2F,
  5299. 'grey': 0x808080,
  5300. 'honeydew': 0xF0FFF0,
  5301. 'hotpink': 0xFF69B4,
  5302. 'indianred': 0xCD5C5C,
  5303. 'indigo': 0x4B0082,
  5304. 'ivory': 0xFFFFF0,
  5305. 'khaki': 0xF0E68C,
  5306. 'lavender': 0xE6E6FA,
  5307. 'lavenderblush': 0xFFF0F5,
  5308. 'lawngreen': 0x7CFC00,
  5309. 'lemonchiffon': 0xFFFACD,
  5310. 'lightblue': 0xADD8E6,
  5311. 'lightcoral': 0xF08080,
  5312. 'lightcyan': 0xE0FFFF,
  5313. 'lightgoldenrodyellow': 0xFAFAD2,
  5314. 'lightgray': 0xD3D3D3,
  5315. 'lightgreen': 0x90EE90,
  5316. 'lightgrey': 0xD3D3D3,
  5317. 'lightpink': 0xFFB6C1,
  5318. 'lightsalmon': 0xFFA07A,
  5319. 'lightseagreen': 0x20B2AA,
  5320. 'lightskyblue': 0x87CEFA,
  5321. 'lightslategray': 0x778899,
  5322. 'lightslategrey': 0x778899,
  5323. 'lightsteelblue': 0xB0C4DE,
  5324. 'lightyellow': 0xFFFFE0,
  5325. 'lime': 0x00FF00,
  5326. 'limegreen': 0x32CD32,
  5327. 'linen': 0xFAF0E6,
  5328. 'magenta': 0xFF00FF,
  5329. 'maroon': 0x800000,
  5330. 'mediumaquamarine': 0x66CDAA,
  5331. 'mediumblue': 0x0000CD,
  5332. 'mediumorchid': 0xBA55D3,
  5333. 'mediumpurple': 0x9370DB,
  5334. 'mediumseagreen': 0x3CB371,
  5335. 'mediumslateblue': 0x7B68EE,
  5336. 'mediumspringgreen': 0x00FA9A,
  5337. 'mediumturquoise': 0x48D1CC,
  5338. 'mediumvioletred': 0xC71585,
  5339. 'midnightblue': 0x191970,
  5340. 'mintcream': 0xF5FFFA,
  5341. 'mistyrose': 0xFFE4E1,
  5342. 'moccasin': 0xFFE4B5,
  5343. 'navajowhite': 0xFFDEAD,
  5344. 'navy': 0x000080,
  5345. 'oldlace': 0xFDF5E6,
  5346. 'olive': 0x808000,
  5347. 'olivedrab': 0x6B8E23,
  5348. 'orange': 0xFFA500,
  5349. 'orangered': 0xFF4500,
  5350. 'orchid': 0xDA70D6,
  5351. 'palegoldenrod': 0xEEE8AA,
  5352. 'palegreen': 0x98FB98,
  5353. 'paleturquoise': 0xAFEEEE,
  5354. 'palevioletred': 0xDB7093,
  5355. 'papayawhip': 0xFFEFD5,
  5356. 'peachpuff': 0xFFDAB9,
  5357. 'peru': 0xCD853F,
  5358. 'pink': 0xFFC0CB,
  5359. 'plum': 0xDDA0DD,
  5360. 'powderblue': 0xB0E0E6,
  5361. 'purple': 0x800080,
  5362. 'rebeccapurple': 0x663399,
  5363. 'red': 0xFF0000,
  5364. 'rosybrown': 0xBC8F8F,
  5365. 'royalblue': 0x4169E1,
  5366. 'saddlebrown': 0x8B4513,
  5367. 'salmon': 0xFA8072,
  5368. 'sandybrown': 0xF4A460,
  5369. 'seagreen': 0x2E8B57,
  5370. 'seashell': 0xFFF5EE,
  5371. 'sienna': 0xA0522D,
  5372. 'silver': 0xC0C0C0,
  5373. 'skyblue': 0x87CEEB,
  5374. 'slateblue': 0x6A5ACD,
  5375. 'slategray': 0x708090,
  5376. 'slategrey': 0x708090,
  5377. 'snow': 0xFFFAFA,
  5378. 'springgreen': 0x00FF7F,
  5379. 'steelblue': 0x4682B4,
  5380. 'tan': 0xD2B48C,
  5381. 'teal': 0x008080,
  5382. 'thistle': 0xD8BFD8,
  5383. 'tomato': 0xFF6347,
  5384. 'turquoise': 0x40E0D0,
  5385. 'violet': 0xEE82EE,
  5386. 'wheat': 0xF5DEB3,
  5387. 'white': 0xFFFFFF,
  5388. 'whitesmoke': 0xF5F5F5,
  5389. 'yellow': 0xFFFF00,
  5390. 'yellowgreen': 0x9ACD32
  5391. };
  5392. const _hslA = {
  5393. h: 0,
  5394. s: 0,
  5395. l: 0
  5396. };
  5397. const _hslB = {
  5398. h: 0,
  5399. s: 0,
  5400. l: 0
  5401. };
  5402. function hue2rgb(p, q, t) {
  5403. if (t < 0) t += 1;
  5404. if (t > 1) t -= 1;
  5405. if (t < 1 / 6) return p + (q - p) * 6 * t;
  5406. if (t < 1 / 2) return q;
  5407. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  5408. return p;
  5409. }
  5410. function SRGBToLinear(c) {
  5411. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  5412. }
  5413. function LinearToSRGB(c) {
  5414. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  5415. }
  5416. class Color {
  5417. constructor(r, g, b) {
  5418. if (g === undefined && b === undefined) {
  5419. // r is THREE.Color, hex or string
  5420. return this.set(r);
  5421. }
  5422. return this.setRGB(r, g, b);
  5423. }
  5424. set(value) {
  5425. if (value && value.isColor) {
  5426. this.copy(value);
  5427. } else if (typeof value === 'number') {
  5428. this.setHex(value);
  5429. } else if (typeof value === 'string') {
  5430. this.setStyle(value);
  5431. }
  5432. return this;
  5433. }
  5434. setScalar(scalar) {
  5435. this.r = scalar;
  5436. this.g = scalar;
  5437. this.b = scalar;
  5438. return this;
  5439. }
  5440. setHex(hex) {
  5441. hex = Math.floor(hex);
  5442. this.r = (hex >> 16 & 255) / 255;
  5443. this.g = (hex >> 8 & 255) / 255;
  5444. this.b = (hex & 255) / 255;
  5445. return this;
  5446. }
  5447. setRGB(r, g, b) {
  5448. this.r = r;
  5449. this.g = g;
  5450. this.b = b;
  5451. return this;
  5452. }
  5453. setHSL(h, s, l) {
  5454. // h,s,l ranges are in 0.0 - 1.0
  5455. h = euclideanModulo(h, 1);
  5456. s = clamp(s, 0, 1);
  5457. l = clamp(l, 0, 1);
  5458. if (s === 0) {
  5459. this.r = this.g = this.b = l;
  5460. } else {
  5461. const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  5462. const q = 2 * l - p;
  5463. this.r = hue2rgb(q, p, h + 1 / 3);
  5464. this.g = hue2rgb(q, p, h);
  5465. this.b = hue2rgb(q, p, h - 1 / 3);
  5466. }
  5467. return this;
  5468. }
  5469. setStyle(style) {
  5470. function handleAlpha(string) {
  5471. if (string === undefined) return;
  5472. if (parseFloat(string) < 1) {
  5473. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  5474. }
  5475. }
  5476. let m;
  5477. if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
  5478. // rgb / hsl
  5479. let color;
  5480. const name = m[1];
  5481. const components = m[2];
  5482. switch (name) {
  5483. case 'rgb':
  5484. case 'rgba':
  5485. if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5486. // rgb(255,0,0) rgba(255,0,0,0.5)
  5487. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  5488. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  5489. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  5490. handleAlpha(color[4]);
  5491. return this;
  5492. }
  5493. if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5494. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5495. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  5496. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  5497. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  5498. handleAlpha(color[4]);
  5499. return this;
  5500. }
  5501. break;
  5502. case 'hsl':
  5503. case 'hsla':
  5504. if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5505. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5506. const h = parseFloat(color[1]) / 360;
  5507. const s = parseInt(color[2], 10) / 100;
  5508. const l = parseInt(color[3], 10) / 100;
  5509. handleAlpha(color[4]);
  5510. return this.setHSL(h, s, l);
  5511. }
  5512. break;
  5513. }
  5514. } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
  5515. // hex color
  5516. const hex = m[1];
  5517. const size = hex.length;
  5518. if (size === 3) {
  5519. // #ff0
  5520. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  5521. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  5522. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  5523. return this;
  5524. } else if (size === 6) {
  5525. // #ff0000
  5526. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  5527. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  5528. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  5529. return this;
  5530. }
  5531. }
  5532. if (style && style.length > 0) {
  5533. return this.setColorName(style);
  5534. }
  5535. return this;
  5536. }
  5537. setColorName(style) {
  5538. // color keywords
  5539. const hex = _colorKeywords[style.toLowerCase()];
  5540. if (hex !== undefined) {
  5541. // red
  5542. this.setHex(hex);
  5543. } else {
  5544. // unknown color
  5545. console.warn('THREE.Color: Unknown color ' + style);
  5546. }
  5547. return this;
  5548. }
  5549. clone() {
  5550. return new this.constructor(this.r, this.g, this.b);
  5551. }
  5552. copy(color) {
  5553. this.r = color.r;
  5554. this.g = color.g;
  5555. this.b = color.b;
  5556. return this;
  5557. }
  5558. copyGammaToLinear(color, gammaFactor = 2.0) {
  5559. this.r = Math.pow(color.r, gammaFactor);
  5560. this.g = Math.pow(color.g, gammaFactor);
  5561. this.b = Math.pow(color.b, gammaFactor);
  5562. return this;
  5563. }
  5564. copyLinearToGamma(color, gammaFactor = 2.0) {
  5565. const safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  5566. this.r = Math.pow(color.r, safeInverse);
  5567. this.g = Math.pow(color.g, safeInverse);
  5568. this.b = Math.pow(color.b, safeInverse);
  5569. return this;
  5570. }
  5571. convertGammaToLinear(gammaFactor) {
  5572. this.copyGammaToLinear(this, gammaFactor);
  5573. return this;
  5574. }
  5575. convertLinearToGamma(gammaFactor) {
  5576. this.copyLinearToGamma(this, gammaFactor);
  5577. return this;
  5578. }
  5579. copySRGBToLinear(color) {
  5580. this.r = SRGBToLinear(color.r);
  5581. this.g = SRGBToLinear(color.g);
  5582. this.b = SRGBToLinear(color.b);
  5583. return this;
  5584. }
  5585. copyLinearToSRGB(color) {
  5586. this.r = LinearToSRGB(color.r);
  5587. this.g = LinearToSRGB(color.g);
  5588. this.b = LinearToSRGB(color.b);
  5589. return this;
  5590. }
  5591. convertSRGBToLinear() {
  5592. this.copySRGBToLinear(this);
  5593. return this;
  5594. }
  5595. convertLinearToSRGB() {
  5596. this.copyLinearToSRGB(this);
  5597. return this;
  5598. }
  5599. getHex() {
  5600. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  5601. }
  5602. getHexString() {
  5603. return ('000000' + this.getHex().toString(16)).slice(-6);
  5604. }
  5605. getHSL(target) {
  5606. // h,s,l ranges are in 0.0 - 1.0
  5607. if (target === undefined) {
  5608. console.warn('THREE.Color: .getHSL() target is now required');
  5609. target = {
  5610. h: 0,
  5611. s: 0,
  5612. l: 0
  5613. };
  5614. }
  5615. const r = this.r,
  5616. g = this.g,
  5617. b = this.b;
  5618. const max = Math.max(r, g, b);
  5619. const min = Math.min(r, g, b);
  5620. let hue, saturation;
  5621. const lightness = (min + max) / 2.0;
  5622. if (min === max) {
  5623. hue = 0;
  5624. saturation = 0;
  5625. } else {
  5626. const delta = max - min;
  5627. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  5628. switch (max) {
  5629. case r:
  5630. hue = (g - b) / delta + (g < b ? 6 : 0);
  5631. break;
  5632. case g:
  5633. hue = (b - r) / delta + 2;
  5634. break;
  5635. case b:
  5636. hue = (r - g) / delta + 4;
  5637. break;
  5638. }
  5639. hue /= 6;
  5640. }
  5641. target.h = hue;
  5642. target.s = saturation;
  5643. target.l = lightness;
  5644. return target;
  5645. }
  5646. getStyle() {
  5647. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  5648. }
  5649. offsetHSL(h, s, l) {
  5650. this.getHSL(_hslA);
  5651. _hslA.h += h;
  5652. _hslA.s += s;
  5653. _hslA.l += l;
  5654. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  5655. return this;
  5656. }
  5657. add(color) {
  5658. this.r += color.r;
  5659. this.g += color.g;
  5660. this.b += color.b;
  5661. return this;
  5662. }
  5663. addColors(color1, color2) {
  5664. this.r = color1.r + color2.r;
  5665. this.g = color1.g + color2.g;
  5666. this.b = color1.b + color2.b;
  5667. return this;
  5668. }
  5669. addScalar(s) {
  5670. this.r += s;
  5671. this.g += s;
  5672. this.b += s;
  5673. return this;
  5674. }
  5675. sub(color) {
  5676. this.r = Math.max(0, this.r - color.r);
  5677. this.g = Math.max(0, this.g - color.g);
  5678. this.b = Math.max(0, this.b - color.b);
  5679. return this;
  5680. }
  5681. multiply(color) {
  5682. this.r *= color.r;
  5683. this.g *= color.g;
  5684. this.b *= color.b;
  5685. return this;
  5686. }
  5687. multiplyScalar(s) {
  5688. this.r *= s;
  5689. this.g *= s;
  5690. this.b *= s;
  5691. return this;
  5692. }
  5693. lerp(color, alpha) {
  5694. this.r += (color.r - this.r) * alpha;
  5695. this.g += (color.g - this.g) * alpha;
  5696. this.b += (color.b - this.b) * alpha;
  5697. return this;
  5698. }
  5699. lerpColors(color1, color2, alpha) {
  5700. this.r = color1.r + (color2.r - color1.r) * alpha;
  5701. this.g = color1.g + (color2.g - color1.g) * alpha;
  5702. this.b = color1.b + (color2.b - color1.b) * alpha;
  5703. return this;
  5704. }
  5705. lerpHSL(color, alpha) {
  5706. this.getHSL(_hslA);
  5707. color.getHSL(_hslB);
  5708. const h = lerp(_hslA.h, _hslB.h, alpha);
  5709. const s = lerp(_hslA.s, _hslB.s, alpha);
  5710. const l = lerp(_hslA.l, _hslB.l, alpha);
  5711. this.setHSL(h, s, l);
  5712. return this;
  5713. }
  5714. equals(c) {
  5715. return c.r === this.r && c.g === this.g && c.b === this.b;
  5716. }
  5717. fromArray(array, offset = 0) {
  5718. this.r = array[offset];
  5719. this.g = array[offset + 1];
  5720. this.b = array[offset + 2];
  5721. return this;
  5722. }
  5723. toArray(array = [], offset = 0) {
  5724. array[offset] = this.r;
  5725. array[offset + 1] = this.g;
  5726. array[offset + 2] = this.b;
  5727. return array;
  5728. }
  5729. fromBufferAttribute(attribute, index) {
  5730. this.r = attribute.getX(index);
  5731. this.g = attribute.getY(index);
  5732. this.b = attribute.getZ(index);
  5733. if (attribute.normalized === true) {
  5734. // assuming Uint8Array
  5735. this.r /= 255;
  5736. this.g /= 255;
  5737. this.b /= 255;
  5738. }
  5739. return this;
  5740. }
  5741. toJSON() {
  5742. return this.getHex();
  5743. }
  5744. }
  5745. Color.NAMES = _colorKeywords;
  5746. Color.prototype.isColor = true;
  5747. Color.prototype.r = 1;
  5748. Color.prototype.g = 1;
  5749. Color.prototype.b = 1;
  5750. /**
  5751. * parameters = {
  5752. * color: <hex>,
  5753. * opacity: <float>,
  5754. * map: new THREE.Texture( <Image> ),
  5755. *
  5756. * lightMap: new THREE.Texture( <Image> ),
  5757. * lightMapIntensity: <float>
  5758. *
  5759. * aoMap: new THREE.Texture( <Image> ),
  5760. * aoMapIntensity: <float>
  5761. *
  5762. * specularMap: new THREE.Texture( <Image> ),
  5763. *
  5764. * alphaMap: new THREE.Texture( <Image> ),
  5765. *
  5766. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  5767. * combine: THREE.Multiply,
  5768. * reflectivity: <float>,
  5769. * refractionRatio: <float>,
  5770. *
  5771. * depthTest: <bool>,
  5772. * depthWrite: <bool>,
  5773. *
  5774. * wireframe: <boolean>,
  5775. * wireframeLinewidth: <float>,
  5776. *
  5777. * morphTargets: <bool>
  5778. * }
  5779. */
  5780. class MeshBasicMaterial extends Material {
  5781. constructor(parameters) {
  5782. super();
  5783. this.type = 'MeshBasicMaterial';
  5784. this.color = new Color(0xffffff); // emissive
  5785. this.map = null;
  5786. this.lightMap = null;
  5787. this.lightMapIntensity = 1.0;
  5788. this.aoMap = null;
  5789. this.aoMapIntensity = 1.0;
  5790. this.specularMap = null;
  5791. this.alphaMap = null;
  5792. this.envMap = null;
  5793. this.combine = MultiplyOperation;
  5794. this.reflectivity = 1;
  5795. this.refractionRatio = 0.98;
  5796. this.wireframe = false;
  5797. this.wireframeLinewidth = 1;
  5798. this.wireframeLinecap = 'round';
  5799. this.wireframeLinejoin = 'round';
  5800. this.morphTargets = false;
  5801. this.setValues(parameters);
  5802. }
  5803. copy(source) {
  5804. super.copy(source);
  5805. this.color.copy(source.color);
  5806. this.map = source.map;
  5807. this.lightMap = source.lightMap;
  5808. this.lightMapIntensity = source.lightMapIntensity;
  5809. this.aoMap = source.aoMap;
  5810. this.aoMapIntensity = source.aoMapIntensity;
  5811. this.specularMap = source.specularMap;
  5812. this.alphaMap = source.alphaMap;
  5813. this.envMap = source.envMap;
  5814. this.combine = source.combine;
  5815. this.reflectivity = source.reflectivity;
  5816. this.refractionRatio = source.refractionRatio;
  5817. this.wireframe = source.wireframe;
  5818. this.wireframeLinewidth = source.wireframeLinewidth;
  5819. this.wireframeLinecap = source.wireframeLinecap;
  5820. this.wireframeLinejoin = source.wireframeLinejoin;
  5821. this.morphTargets = source.morphTargets;
  5822. return this;
  5823. }
  5824. }
  5825. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  5826. const _vector$9 = /*@__PURE__*/new Vector3();
  5827. const _vector2 = /*@__PURE__*/new Vector2();
  5828. class BufferAttribute {
  5829. constructor(array, itemSize, normalized) {
  5830. if (Array.isArray(array)) {
  5831. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  5832. }
  5833. this.name = '';
  5834. this.array = array;
  5835. this.itemSize = itemSize;
  5836. this.count = array !== undefined ? array.length / itemSize : 0;
  5837. this.normalized = normalized === true;
  5838. this.usage = StaticDrawUsage;
  5839. this.updateRange = {
  5840. offset: 0,
  5841. count: -1
  5842. };
  5843. this.version = 0;
  5844. }
  5845. onUploadCallback() {}
  5846. set needsUpdate(value) {
  5847. if (value === true) this.version++;
  5848. }
  5849. setUsage(value) {
  5850. this.usage = value;
  5851. return this;
  5852. }
  5853. copy(source) {
  5854. this.name = source.name;
  5855. this.array = new source.array.constructor(source.array);
  5856. this.itemSize = source.itemSize;
  5857. this.count = source.count;
  5858. this.normalized = source.normalized;
  5859. this.usage = source.usage;
  5860. return this;
  5861. }
  5862. copyAt(index1, attribute, index2) {
  5863. index1 *= this.itemSize;
  5864. index2 *= attribute.itemSize;
  5865. for (let i = 0, l = this.itemSize; i < l; i++) {
  5866. this.array[index1 + i] = attribute.array[index2 + i];
  5867. }
  5868. return this;
  5869. }
  5870. copyArray(array) {
  5871. this.array.set(array);
  5872. return this;
  5873. }
  5874. copyColorsArray(colors) {
  5875. const array = this.array;
  5876. let offset = 0;
  5877. for (let i = 0, l = colors.length; i < l; i++) {
  5878. let color = colors[i];
  5879. if (color === undefined) {
  5880. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  5881. color = new Color();
  5882. }
  5883. array[offset++] = color.r;
  5884. array[offset++] = color.g;
  5885. array[offset++] = color.b;
  5886. }
  5887. return this;
  5888. }
  5889. copyVector2sArray(vectors) {
  5890. const array = this.array;
  5891. let offset = 0;
  5892. for (let i = 0, l = vectors.length; i < l; i++) {
  5893. let vector = vectors[i];
  5894. if (vector === undefined) {
  5895. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  5896. vector = new Vector2();
  5897. }
  5898. array[offset++] = vector.x;
  5899. array[offset++] = vector.y;
  5900. }
  5901. return this;
  5902. }
  5903. copyVector3sArray(vectors) {
  5904. const array = this.array;
  5905. let offset = 0;
  5906. for (let i = 0, l = vectors.length; i < l; i++) {
  5907. let vector = vectors[i];
  5908. if (vector === undefined) {
  5909. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  5910. vector = new Vector3();
  5911. }
  5912. array[offset++] = vector.x;
  5913. array[offset++] = vector.y;
  5914. array[offset++] = vector.z;
  5915. }
  5916. return this;
  5917. }
  5918. copyVector4sArray(vectors) {
  5919. const array = this.array;
  5920. let offset = 0;
  5921. for (let i = 0, l = vectors.length; i < l; i++) {
  5922. let vector = vectors[i];
  5923. if (vector === undefined) {
  5924. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  5925. vector = new Vector4();
  5926. }
  5927. array[offset++] = vector.x;
  5928. array[offset++] = vector.y;
  5929. array[offset++] = vector.z;
  5930. array[offset++] = vector.w;
  5931. }
  5932. return this;
  5933. }
  5934. applyMatrix3(m) {
  5935. if (this.itemSize === 2) {
  5936. for (let i = 0, l = this.count; i < l; i++) {
  5937. _vector2.fromBufferAttribute(this, i);
  5938. _vector2.applyMatrix3(m);
  5939. this.setXY(i, _vector2.x, _vector2.y);
  5940. }
  5941. } else if (this.itemSize === 3) {
  5942. for (let i = 0, l = this.count; i < l; i++) {
  5943. _vector$9.fromBufferAttribute(this, i);
  5944. _vector$9.applyMatrix3(m);
  5945. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5946. }
  5947. }
  5948. return this;
  5949. }
  5950. applyMatrix4(m) {
  5951. for (let i = 0, l = this.count; i < l; i++) {
  5952. _vector$9.x = this.getX(i);
  5953. _vector$9.y = this.getY(i);
  5954. _vector$9.z = this.getZ(i);
  5955. _vector$9.applyMatrix4(m);
  5956. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5957. }
  5958. return this;
  5959. }
  5960. applyNormalMatrix(m) {
  5961. for (let i = 0, l = this.count; i < l; i++) {
  5962. _vector$9.x = this.getX(i);
  5963. _vector$9.y = this.getY(i);
  5964. _vector$9.z = this.getZ(i);
  5965. _vector$9.applyNormalMatrix(m);
  5966. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5967. }
  5968. return this;
  5969. }
  5970. transformDirection(m) {
  5971. for (let i = 0, l = this.count; i < l; i++) {
  5972. _vector$9.x = this.getX(i);
  5973. _vector$9.y = this.getY(i);
  5974. _vector$9.z = this.getZ(i);
  5975. _vector$9.transformDirection(m);
  5976. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5977. }
  5978. return this;
  5979. }
  5980. set(value, offset = 0) {
  5981. this.array.set(value, offset);
  5982. return this;
  5983. }
  5984. getX(index) {
  5985. return this.array[index * this.itemSize];
  5986. }
  5987. setX(index, x) {
  5988. this.array[index * this.itemSize] = x;
  5989. return this;
  5990. }
  5991. getY(index) {
  5992. return this.array[index * this.itemSize + 1];
  5993. }
  5994. setY(index, y) {
  5995. this.array[index * this.itemSize + 1] = y;
  5996. return this;
  5997. }
  5998. getZ(index) {
  5999. return this.array[index * this.itemSize + 2];
  6000. }
  6001. setZ(index, z) {
  6002. this.array[index * this.itemSize + 2] = z;
  6003. return this;
  6004. }
  6005. getW(index) {
  6006. return this.array[index * this.itemSize + 3];
  6007. }
  6008. setW(index, w) {
  6009. this.array[index * this.itemSize + 3] = w;
  6010. return this;
  6011. }
  6012. setXY(index, x, y) {
  6013. index *= this.itemSize;
  6014. this.array[index + 0] = x;
  6015. this.array[index + 1] = y;
  6016. return this;
  6017. }
  6018. setXYZ(index, x, y, z) {
  6019. index *= this.itemSize;
  6020. this.array[index + 0] = x;
  6021. this.array[index + 1] = y;
  6022. this.array[index + 2] = z;
  6023. return this;
  6024. }
  6025. setXYZW(index, x, y, z, w) {
  6026. index *= this.itemSize;
  6027. this.array[index + 0] = x;
  6028. this.array[index + 1] = y;
  6029. this.array[index + 2] = z;
  6030. this.array[index + 3] = w;
  6031. return this;
  6032. }
  6033. onUpload(callback) {
  6034. this.onUploadCallback = callback;
  6035. return this;
  6036. }
  6037. clone() {
  6038. return new this.constructor(this.array, this.itemSize).copy(this);
  6039. }
  6040. toJSON() {
  6041. const data = {
  6042. itemSize: this.itemSize,
  6043. type: this.array.constructor.name,
  6044. array: Array.prototype.slice.call(this.array),
  6045. normalized: this.normalized
  6046. };
  6047. if (this.name !== '') data.name = this.name;
  6048. if (this.usage !== StaticDrawUsage) data.usage = this.usage;
  6049. if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange;
  6050. return data;
  6051. }
  6052. }
  6053. BufferAttribute.prototype.isBufferAttribute = true; //
  6054. class Int8BufferAttribute extends BufferAttribute {
  6055. constructor(array, itemSize, normalized) {
  6056. super(new Int8Array(array), itemSize, normalized);
  6057. }
  6058. }
  6059. class Uint8BufferAttribute extends BufferAttribute {
  6060. constructor(array, itemSize, normalized) {
  6061. super(new Uint8Array(array), itemSize, normalized);
  6062. }
  6063. }
  6064. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6065. constructor(array, itemSize, normalized) {
  6066. super(new Uint8ClampedArray(array), itemSize, normalized);
  6067. }
  6068. }
  6069. class Int16BufferAttribute extends BufferAttribute {
  6070. constructor(array, itemSize, normalized) {
  6071. super(new Int16Array(array), itemSize, normalized);
  6072. }
  6073. }
  6074. class Uint16BufferAttribute extends BufferAttribute {
  6075. constructor(array, itemSize, normalized) {
  6076. super(new Uint16Array(array), itemSize, normalized);
  6077. }
  6078. }
  6079. class Int32BufferAttribute extends BufferAttribute {
  6080. constructor(array, itemSize, normalized) {
  6081. super(new Int32Array(array), itemSize, normalized);
  6082. }
  6083. }
  6084. class Uint32BufferAttribute extends BufferAttribute {
  6085. constructor(array, itemSize, normalized) {
  6086. super(new Uint32Array(array), itemSize, normalized);
  6087. }
  6088. }
  6089. class Float16BufferAttribute extends BufferAttribute {
  6090. constructor(array, itemSize, normalized) {
  6091. super(new Uint16Array(array), itemSize, normalized);
  6092. }
  6093. }
  6094. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  6095. class Float32BufferAttribute extends BufferAttribute {
  6096. constructor(array, itemSize, normalized) {
  6097. super(new Float32Array(array), itemSize, normalized);
  6098. }
  6099. }
  6100. class Float64BufferAttribute extends BufferAttribute {
  6101. constructor(array, itemSize, normalized) {
  6102. super(new Float64Array(array), itemSize, normalized);
  6103. }
  6104. } //
  6105. function arrayMax(array) {
  6106. if (array.length === 0) return -Infinity;
  6107. let max = array[0];
  6108. for (let i = 1, l = array.length; i < l; ++i) {
  6109. if (array[i] > max) max = array[i];
  6110. }
  6111. return max;
  6112. }
  6113. const TYPED_ARRAYS = {
  6114. Int8Array: Int8Array,
  6115. Uint8Array: Uint8Array,
  6116. Uint8ClampedArray: Uint8ClampedArray,
  6117. Int16Array: Int16Array,
  6118. Uint16Array: Uint16Array,
  6119. Int32Array: Int32Array,
  6120. Uint32Array: Uint32Array,
  6121. Float32Array: Float32Array,
  6122. Float64Array: Float64Array
  6123. };
  6124. function getTypedArray(type, buffer) {
  6125. return new TYPED_ARRAYS[type](buffer);
  6126. }
  6127. let _id = 0;
  6128. const _m1 = /*@__PURE__*/new Matrix4();
  6129. const _obj = /*@__PURE__*/new Object3D();
  6130. const _offset = /*@__PURE__*/new Vector3();
  6131. const _box$1 = /*@__PURE__*/new Box3();
  6132. const _boxMorphTargets = /*@__PURE__*/new Box3();
  6133. const _vector$8 = /*@__PURE__*/new Vector3();
  6134. class BufferGeometry extends EventDispatcher {
  6135. constructor() {
  6136. super();
  6137. Object.defineProperty(this, 'id', {
  6138. value: _id++
  6139. });
  6140. this.uuid = generateUUID();
  6141. this.name = '';
  6142. this.type = 'BufferGeometry';
  6143. this.index = null;
  6144. this.attributes = {};
  6145. this.morphAttributes = {};
  6146. this.morphTargetsRelative = false;
  6147. this.groups = [];
  6148. this.boundingBox = null;
  6149. this.boundingSphere = null;
  6150. this.drawRange = {
  6151. start: 0,
  6152. count: Infinity
  6153. };
  6154. this.userData = {};
  6155. }
  6156. getIndex() {
  6157. return this.index;
  6158. }
  6159. setIndex(index) {
  6160. if (Array.isArray(index)) {
  6161. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  6162. } else {
  6163. this.index = index;
  6164. }
  6165. return this;
  6166. }
  6167. getAttribute(name) {
  6168. return this.attributes[name];
  6169. }
  6170. setAttribute(name, attribute) {
  6171. this.attributes[name] = attribute;
  6172. return this;
  6173. }
  6174. deleteAttribute(name) {
  6175. delete this.attributes[name];
  6176. return this;
  6177. }
  6178. hasAttribute(name) {
  6179. return this.attributes[name] !== undefined;
  6180. }
  6181. addGroup(start, count, materialIndex = 0) {
  6182. this.groups.push({
  6183. start: start,
  6184. count: count,
  6185. materialIndex: materialIndex
  6186. });
  6187. }
  6188. clearGroups() {
  6189. this.groups = [];
  6190. }
  6191. setDrawRange(start, count) {
  6192. this.drawRange.start = start;
  6193. this.drawRange.count = count;
  6194. }
  6195. applyMatrix4(matrix) {
  6196. const position = this.attributes.position;
  6197. if (position !== undefined) {
  6198. position.applyMatrix4(matrix);
  6199. position.needsUpdate = true;
  6200. }
  6201. const normal = this.attributes.normal;
  6202. if (normal !== undefined) {
  6203. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6204. normal.applyNormalMatrix(normalMatrix);
  6205. normal.needsUpdate = true;
  6206. }
  6207. const tangent = this.attributes.tangent;
  6208. if (tangent !== undefined) {
  6209. tangent.transformDirection(matrix);
  6210. tangent.needsUpdate = true;
  6211. }
  6212. if (this.boundingBox !== null) {
  6213. this.computeBoundingBox();
  6214. }
  6215. if (this.boundingSphere !== null) {
  6216. this.computeBoundingSphere();
  6217. }
  6218. return this;
  6219. }
  6220. applyQuaternion(q) {
  6221. _m1.makeRotationFromQuaternion(q);
  6222. this.applyMatrix4(_m1);
  6223. return this;
  6224. }
  6225. rotateX(angle) {
  6226. // rotate geometry around world x-axis
  6227. _m1.makeRotationX(angle);
  6228. this.applyMatrix4(_m1);
  6229. return this;
  6230. }
  6231. rotateY(angle) {
  6232. // rotate geometry around world y-axis
  6233. _m1.makeRotationY(angle);
  6234. this.applyMatrix4(_m1);
  6235. return this;
  6236. }
  6237. rotateZ(angle) {
  6238. // rotate geometry around world z-axis
  6239. _m1.makeRotationZ(angle);
  6240. this.applyMatrix4(_m1);
  6241. return this;
  6242. }
  6243. translate(x, y, z) {
  6244. // translate geometry
  6245. _m1.makeTranslation(x, y, z);
  6246. this.applyMatrix4(_m1);
  6247. return this;
  6248. }
  6249. scale(x, y, z) {
  6250. // scale geometry
  6251. _m1.makeScale(x, y, z);
  6252. this.applyMatrix4(_m1);
  6253. return this;
  6254. }
  6255. lookAt(vector) {
  6256. _obj.lookAt(vector);
  6257. _obj.updateMatrix();
  6258. this.applyMatrix4(_obj.matrix);
  6259. return this;
  6260. }
  6261. center() {
  6262. this.computeBoundingBox();
  6263. this.boundingBox.getCenter(_offset).negate();
  6264. this.translate(_offset.x, _offset.y, _offset.z);
  6265. return this;
  6266. }
  6267. setFromPoints(points) {
  6268. const position = [];
  6269. for (let i = 0, l = points.length; i < l; i++) {
  6270. const point = points[i];
  6271. position.push(point.x, point.y, point.z || 0);
  6272. }
  6273. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6274. return this;
  6275. }
  6276. computeBoundingBox() {
  6277. if (this.boundingBox === null) {
  6278. this.boundingBox = new Box3();
  6279. }
  6280. const position = this.attributes.position;
  6281. const morphAttributesPosition = this.morphAttributes.position;
  6282. if (position && position.isGLBufferAttribute) {
  6283. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  6284. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  6285. return;
  6286. }
  6287. if (position !== undefined) {
  6288. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  6289. if (morphAttributesPosition) {
  6290. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6291. const morphAttribute = morphAttributesPosition[i];
  6292. _box$1.setFromBufferAttribute(morphAttribute);
  6293. if (this.morphTargetsRelative) {
  6294. _vector$8.addVectors(this.boundingBox.min, _box$1.min);
  6295. this.boundingBox.expandByPoint(_vector$8);
  6296. _vector$8.addVectors(this.boundingBox.max, _box$1.max);
  6297. this.boundingBox.expandByPoint(_vector$8);
  6298. } else {
  6299. this.boundingBox.expandByPoint(_box$1.min);
  6300. this.boundingBox.expandByPoint(_box$1.max);
  6301. }
  6302. }
  6303. }
  6304. } else {
  6305. this.boundingBox.makeEmpty();
  6306. }
  6307. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  6308. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  6309. }
  6310. }
  6311. computeBoundingSphere() {
  6312. if (this.boundingSphere === null) {
  6313. this.boundingSphere = new Sphere();
  6314. }
  6315. const position = this.attributes.position;
  6316. const morphAttributesPosition = this.morphAttributes.position;
  6317. if (position && position.isGLBufferAttribute) {
  6318. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  6319. this.boundingSphere.set(new Vector3(), Infinity);
  6320. return;
  6321. }
  6322. if (position) {
  6323. // first, find the center of the bounding sphere
  6324. const center = this.boundingSphere.center;
  6325. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  6326. if (morphAttributesPosition) {
  6327. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6328. const morphAttribute = morphAttributesPosition[i];
  6329. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  6330. if (this.morphTargetsRelative) {
  6331. _vector$8.addVectors(_box$1.min, _boxMorphTargets.min);
  6332. _box$1.expandByPoint(_vector$8);
  6333. _vector$8.addVectors(_box$1.max, _boxMorphTargets.max);
  6334. _box$1.expandByPoint(_vector$8);
  6335. } else {
  6336. _box$1.expandByPoint(_boxMorphTargets.min);
  6337. _box$1.expandByPoint(_boxMorphTargets.max);
  6338. }
  6339. }
  6340. }
  6341. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  6342. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6343. let maxRadiusSq = 0;
  6344. for (let i = 0, il = position.count; i < il; i++) {
  6345. _vector$8.fromBufferAttribute(position, i);
  6346. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6347. } // process morph attributes if present
  6348. if (morphAttributesPosition) {
  6349. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6350. const morphAttribute = morphAttributesPosition[i];
  6351. const morphTargetsRelative = this.morphTargetsRelative;
  6352. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  6353. _vector$8.fromBufferAttribute(morphAttribute, j);
  6354. if (morphTargetsRelative) {
  6355. _offset.fromBufferAttribute(position, j);
  6356. _vector$8.add(_offset);
  6357. }
  6358. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6359. }
  6360. }
  6361. }
  6362. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  6363. if (isNaN(this.boundingSphere.radius)) {
  6364. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  6365. }
  6366. }
  6367. }
  6368. computeFaceNormals() {// backwards compatibility
  6369. }
  6370. computeTangents() {
  6371. const index = this.index;
  6372. const attributes = this.attributes; // based on http://www.terathon.com/code/tangent.html
  6373. // (per vertex tangents)
  6374. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  6375. console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  6376. return;
  6377. }
  6378. const indices = index.array;
  6379. const positions = attributes.position.array;
  6380. const normals = attributes.normal.array;
  6381. const uvs = attributes.uv.array;
  6382. const nVertices = positions.length / 3;
  6383. if (attributes.tangent === undefined) {
  6384. this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
  6385. }
  6386. const tangents = attributes.tangent.array;
  6387. const tan1 = [],
  6388. tan2 = [];
  6389. for (let i = 0; i < nVertices; i++) {
  6390. tan1[i] = new Vector3();
  6391. tan2[i] = new Vector3();
  6392. }
  6393. const vA = new Vector3(),
  6394. vB = new Vector3(),
  6395. vC = new Vector3(),
  6396. uvA = new Vector2(),
  6397. uvB = new Vector2(),
  6398. uvC = new Vector2(),
  6399. sdir = new Vector3(),
  6400. tdir = new Vector3();
  6401. function handleTriangle(a, b, c) {
  6402. vA.fromArray(positions, a * 3);
  6403. vB.fromArray(positions, b * 3);
  6404. vC.fromArray(positions, c * 3);
  6405. uvA.fromArray(uvs, a * 2);
  6406. uvB.fromArray(uvs, b * 2);
  6407. uvC.fromArray(uvs, c * 2);
  6408. vB.sub(vA);
  6409. vC.sub(vA);
  6410. uvB.sub(uvA);
  6411. uvC.sub(uvA);
  6412. const r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  6413. if (!isFinite(r)) return;
  6414. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  6415. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  6416. tan1[a].add(sdir);
  6417. tan1[b].add(sdir);
  6418. tan1[c].add(sdir);
  6419. tan2[a].add(tdir);
  6420. tan2[b].add(tdir);
  6421. tan2[c].add(tdir);
  6422. }
  6423. let groups = this.groups;
  6424. if (groups.length === 0) {
  6425. groups = [{
  6426. start: 0,
  6427. count: indices.length
  6428. }];
  6429. }
  6430. for (let i = 0, il = groups.length; i < il; ++i) {
  6431. const group = groups[i];
  6432. const start = group.start;
  6433. const count = group.count;
  6434. for (let j = start, jl = start + count; j < jl; j += 3) {
  6435. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  6436. }
  6437. }
  6438. const tmp = new Vector3(),
  6439. tmp2 = new Vector3();
  6440. const n = new Vector3(),
  6441. n2 = new Vector3();
  6442. function handleVertex(v) {
  6443. n.fromArray(normals, v * 3);
  6444. n2.copy(n);
  6445. const t = tan1[v]; // Gram-Schmidt orthogonalize
  6446. tmp.copy(t);
  6447. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  6448. tmp2.crossVectors(n2, t);
  6449. const test = tmp2.dot(tan2[v]);
  6450. const w = test < 0.0 ? -1.0 : 1.0;
  6451. tangents[v * 4] = tmp.x;
  6452. tangents[v * 4 + 1] = tmp.y;
  6453. tangents[v * 4 + 2] = tmp.z;
  6454. tangents[v * 4 + 3] = w;
  6455. }
  6456. for (let i = 0, il = groups.length; i < il; ++i) {
  6457. const group = groups[i];
  6458. const start = group.start;
  6459. const count = group.count;
  6460. for (let j = start, jl = start + count; j < jl; j += 3) {
  6461. handleVertex(indices[j + 0]);
  6462. handleVertex(indices[j + 1]);
  6463. handleVertex(indices[j + 2]);
  6464. }
  6465. }
  6466. }
  6467. computeVertexNormals() {
  6468. const index = this.index;
  6469. const positionAttribute = this.getAttribute('position');
  6470. if (positionAttribute !== undefined) {
  6471. let normalAttribute = this.getAttribute('normal');
  6472. if (normalAttribute === undefined) {
  6473. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  6474. this.setAttribute('normal', normalAttribute);
  6475. } else {
  6476. // reset existing normals to zero
  6477. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  6478. normalAttribute.setXYZ(i, 0, 0, 0);
  6479. }
  6480. }
  6481. const pA = new Vector3(),
  6482. pB = new Vector3(),
  6483. pC = new Vector3();
  6484. const nA = new Vector3(),
  6485. nB = new Vector3(),
  6486. nC = new Vector3();
  6487. const cb = new Vector3(),
  6488. ab = new Vector3(); // indexed elements
  6489. if (index) {
  6490. for (let i = 0, il = index.count; i < il; i += 3) {
  6491. const vA = index.getX(i + 0);
  6492. const vB = index.getX(i + 1);
  6493. const vC = index.getX(i + 2);
  6494. pA.fromBufferAttribute(positionAttribute, vA);
  6495. pB.fromBufferAttribute(positionAttribute, vB);
  6496. pC.fromBufferAttribute(positionAttribute, vC);
  6497. cb.subVectors(pC, pB);
  6498. ab.subVectors(pA, pB);
  6499. cb.cross(ab);
  6500. nA.fromBufferAttribute(normalAttribute, vA);
  6501. nB.fromBufferAttribute(normalAttribute, vB);
  6502. nC.fromBufferAttribute(normalAttribute, vC);
  6503. nA.add(cb);
  6504. nB.add(cb);
  6505. nC.add(cb);
  6506. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  6507. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  6508. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  6509. }
  6510. } else {
  6511. // non-indexed elements (unconnected triangle soup)
  6512. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  6513. pA.fromBufferAttribute(positionAttribute, i + 0);
  6514. pB.fromBufferAttribute(positionAttribute, i + 1);
  6515. pC.fromBufferAttribute(positionAttribute, i + 2);
  6516. cb.subVectors(pC, pB);
  6517. ab.subVectors(pA, pB);
  6518. cb.cross(ab);
  6519. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  6520. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  6521. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  6522. }
  6523. }
  6524. this.normalizeNormals();
  6525. normalAttribute.needsUpdate = true;
  6526. }
  6527. }
  6528. merge(geometry, offset) {
  6529. if (!(geometry && geometry.isBufferGeometry)) {
  6530. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  6531. return;
  6532. }
  6533. if (offset === undefined) {
  6534. offset = 0;
  6535. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  6536. }
  6537. const attributes = this.attributes;
  6538. for (const key in attributes) {
  6539. if (geometry.attributes[key] === undefined) continue;
  6540. const attribute1 = attributes[key];
  6541. const attributeArray1 = attribute1.array;
  6542. const attribute2 = geometry.attributes[key];
  6543. const attributeArray2 = attribute2.array;
  6544. const attributeOffset = attribute2.itemSize * offset;
  6545. const length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  6546. for (let i = 0, j = attributeOffset; i < length; i++, j++) {
  6547. attributeArray1[j] = attributeArray2[i];
  6548. }
  6549. }
  6550. return this;
  6551. }
  6552. normalizeNormals() {
  6553. const normals = this.attributes.normal;
  6554. for (let i = 0, il = normals.count; i < il; i++) {
  6555. _vector$8.fromBufferAttribute(normals, i);
  6556. _vector$8.normalize();
  6557. normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z);
  6558. }
  6559. }
  6560. toNonIndexed() {
  6561. function convertBufferAttribute(attribute, indices) {
  6562. const array = attribute.array;
  6563. const itemSize = attribute.itemSize;
  6564. const normalized = attribute.normalized;
  6565. const array2 = new array.constructor(indices.length * itemSize);
  6566. let index = 0,
  6567. index2 = 0;
  6568. for (let i = 0, l = indices.length; i < l; i++) {
  6569. index = indices[i] * itemSize;
  6570. for (let j = 0; j < itemSize; j++) {
  6571. array2[index2++] = array[index++];
  6572. }
  6573. }
  6574. return new BufferAttribute(array2, itemSize, normalized);
  6575. } //
  6576. if (this.index === null) {
  6577. console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
  6578. return this;
  6579. }
  6580. const geometry2 = new BufferGeometry();
  6581. const indices = this.index.array;
  6582. const attributes = this.attributes; // attributes
  6583. for (const name in attributes) {
  6584. const attribute = attributes[name];
  6585. const newAttribute = convertBufferAttribute(attribute, indices);
  6586. geometry2.setAttribute(name, newAttribute);
  6587. } // morph attributes
  6588. const morphAttributes = this.morphAttributes;
  6589. for (const name in morphAttributes) {
  6590. const morphArray = [];
  6591. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6592. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  6593. const attribute = morphAttribute[i];
  6594. const newAttribute = convertBufferAttribute(attribute, indices);
  6595. morphArray.push(newAttribute);
  6596. }
  6597. geometry2.morphAttributes[name] = morphArray;
  6598. }
  6599. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  6600. const groups = this.groups;
  6601. for (let i = 0, l = groups.length; i < l; i++) {
  6602. const group = groups[i];
  6603. geometry2.addGroup(group.start, group.count, group.materialIndex);
  6604. }
  6605. return geometry2;
  6606. }
  6607. toJSON() {
  6608. const data = {
  6609. metadata: {
  6610. version: 4.5,
  6611. type: 'BufferGeometry',
  6612. generator: 'BufferGeometry.toJSON'
  6613. }
  6614. }; // standard BufferGeometry serialization
  6615. data.uuid = this.uuid;
  6616. data.type = this.type;
  6617. if (this.name !== '') data.name = this.name;
  6618. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  6619. if (this.parameters !== undefined) {
  6620. const parameters = this.parameters;
  6621. for (const key in parameters) {
  6622. if (parameters[key] !== undefined) data[key] = parameters[key];
  6623. }
  6624. return data;
  6625. } // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6626. data.data = {
  6627. attributes: {}
  6628. };
  6629. const index = this.index;
  6630. if (index !== null) {
  6631. data.data.index = {
  6632. type: index.array.constructor.name,
  6633. array: Array.prototype.slice.call(index.array)
  6634. };
  6635. }
  6636. const attributes = this.attributes;
  6637. for (const key in attributes) {
  6638. const attribute = attributes[key];
  6639. data.data.attributes[key] = attribute.toJSON(data.data);
  6640. }
  6641. const morphAttributes = {};
  6642. let hasMorphAttributes = false;
  6643. for (const key in this.morphAttributes) {
  6644. const attributeArray = this.morphAttributes[key];
  6645. const array = [];
  6646. for (let i = 0, il = attributeArray.length; i < il; i++) {
  6647. const attribute = attributeArray[i];
  6648. array.push(attribute.toJSON(data.data));
  6649. }
  6650. if (array.length > 0) {
  6651. morphAttributes[key] = array;
  6652. hasMorphAttributes = true;
  6653. }
  6654. }
  6655. if (hasMorphAttributes) {
  6656. data.data.morphAttributes = morphAttributes;
  6657. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6658. }
  6659. const groups = this.groups;
  6660. if (groups.length > 0) {
  6661. data.data.groups = JSON.parse(JSON.stringify(groups));
  6662. }
  6663. const boundingSphere = this.boundingSphere;
  6664. if (boundingSphere !== null) {
  6665. data.data.boundingSphere = {
  6666. center: boundingSphere.center.toArray(),
  6667. radius: boundingSphere.radius
  6668. };
  6669. }
  6670. return data;
  6671. }
  6672. clone() {
  6673. /*
  6674. // Handle primitives
  6675. const parameters = this.parameters;
  6676. if ( parameters !== undefined ) {
  6677. const values = [];
  6678. for ( const key in parameters ) {
  6679. values.push( parameters[ key ] );
  6680. }
  6681. const geometry = Object.create( this.constructor.prototype );
  6682. this.constructor.apply( geometry, values );
  6683. return geometry;
  6684. }
  6685. return new this.constructor().copy( this );
  6686. */
  6687. return new BufferGeometry().copy(this);
  6688. }
  6689. copy(source) {
  6690. // reset
  6691. this.index = null;
  6692. this.attributes = {};
  6693. this.morphAttributes = {};
  6694. this.groups = [];
  6695. this.boundingBox = null;
  6696. this.boundingSphere = null; // used for storing cloned, shared data
  6697. const data = {}; // name
  6698. this.name = source.name; // index
  6699. const index = source.index;
  6700. if (index !== null) {
  6701. this.setIndex(index.clone(data));
  6702. } // attributes
  6703. const attributes = source.attributes;
  6704. for (const name in attributes) {
  6705. const attribute = attributes[name];
  6706. this.setAttribute(name, attribute.clone(data));
  6707. } // morph attributes
  6708. const morphAttributes = source.morphAttributes;
  6709. for (const name in morphAttributes) {
  6710. const array = [];
  6711. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6712. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  6713. array.push(morphAttribute[i].clone(data));
  6714. }
  6715. this.morphAttributes[name] = array;
  6716. }
  6717. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  6718. const groups = source.groups;
  6719. for (let i = 0, l = groups.length; i < l; i++) {
  6720. const group = groups[i];
  6721. this.addGroup(group.start, group.count, group.materialIndex);
  6722. } // bounding box
  6723. const boundingBox = source.boundingBox;
  6724. if (boundingBox !== null) {
  6725. this.boundingBox = boundingBox.clone();
  6726. } // bounding sphere
  6727. const boundingSphere = source.boundingSphere;
  6728. if (boundingSphere !== null) {
  6729. this.boundingSphere = boundingSphere.clone();
  6730. } // draw range
  6731. this.drawRange.start = source.drawRange.start;
  6732. this.drawRange.count = source.drawRange.count; // user data
  6733. this.userData = source.userData;
  6734. return this;
  6735. }
  6736. dispose() {
  6737. this.dispatchEvent({
  6738. type: 'dispose'
  6739. });
  6740. }
  6741. }
  6742. BufferGeometry.prototype.isBufferGeometry = true;
  6743. const _inverseMatrix$2 = /*@__PURE__*/new Matrix4();
  6744. const _ray$2 = /*@__PURE__*/new Ray();
  6745. const _sphere$3 = /*@__PURE__*/new Sphere();
  6746. const _vA$1 = /*@__PURE__*/new Vector3();
  6747. const _vB$1 = /*@__PURE__*/new Vector3();
  6748. const _vC$1 = /*@__PURE__*/new Vector3();
  6749. const _tempA = /*@__PURE__*/new Vector3();
  6750. const _tempB = /*@__PURE__*/new Vector3();
  6751. const _tempC = /*@__PURE__*/new Vector3();
  6752. const _morphA = /*@__PURE__*/new Vector3();
  6753. const _morphB = /*@__PURE__*/new Vector3();
  6754. const _morphC = /*@__PURE__*/new Vector3();
  6755. const _uvA$1 = /*@__PURE__*/new Vector2();
  6756. const _uvB$1 = /*@__PURE__*/new Vector2();
  6757. const _uvC$1 = /*@__PURE__*/new Vector2();
  6758. const _intersectionPoint = /*@__PURE__*/new Vector3();
  6759. const _intersectionPointWorld = /*@__PURE__*/new Vector3();
  6760. class Mesh extends Object3D {
  6761. constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) {
  6762. super();
  6763. this.type = 'Mesh';
  6764. this.geometry = geometry;
  6765. this.material = material;
  6766. this.updateMorphTargets();
  6767. }
  6768. copy(source) {
  6769. super.copy(source);
  6770. if (source.morphTargetInfluences !== undefined) {
  6771. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6772. }
  6773. if (source.morphTargetDictionary !== undefined) {
  6774. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  6775. }
  6776. this.material = source.material;
  6777. this.geometry = source.geometry;
  6778. return this;
  6779. }
  6780. updateMorphTargets() {
  6781. const geometry = this.geometry;
  6782. if (geometry.isBufferGeometry) {
  6783. const morphAttributes = geometry.morphAttributes;
  6784. const keys = Object.keys(morphAttributes);
  6785. if (keys.length > 0) {
  6786. const morphAttribute = morphAttributes[keys[0]];
  6787. if (morphAttribute !== undefined) {
  6788. this.morphTargetInfluences = [];
  6789. this.morphTargetDictionary = {};
  6790. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  6791. const name = morphAttribute[m].name || String(m);
  6792. this.morphTargetInfluences.push(0);
  6793. this.morphTargetDictionary[name] = m;
  6794. }
  6795. }
  6796. }
  6797. } else {
  6798. const morphTargets = geometry.morphTargets;
  6799. if (morphTargets !== undefined && morphTargets.length > 0) {
  6800. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6801. }
  6802. }
  6803. }
  6804. raycast(raycaster, intersects) {
  6805. const geometry = this.geometry;
  6806. const material = this.material;
  6807. const matrixWorld = this.matrixWorld;
  6808. if (material === undefined) return; // Checking boundingSphere distance to ray
  6809. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  6810. _sphere$3.copy(geometry.boundingSphere);
  6811. _sphere$3.applyMatrix4(matrixWorld);
  6812. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  6813. _inverseMatrix$2.copy(matrixWorld).invert();
  6814. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); // Check boundingBox before continuing
  6815. if (geometry.boundingBox !== null) {
  6816. if (_ray$2.intersectsBox(geometry.boundingBox) === false) return;
  6817. }
  6818. let intersection;
  6819. if (geometry.isBufferGeometry) {
  6820. const index = geometry.index;
  6821. const position = geometry.attributes.position;
  6822. const morphPosition = geometry.morphAttributes.position;
  6823. const morphTargetsRelative = geometry.morphTargetsRelative;
  6824. const uv = geometry.attributes.uv;
  6825. const uv2 = geometry.attributes.uv2;
  6826. const groups = geometry.groups;
  6827. const drawRange = geometry.drawRange;
  6828. if (index !== null) {
  6829. // indexed buffer geometry
  6830. if (Array.isArray(material)) {
  6831. for (let i = 0, il = groups.length; i < il; i++) {
  6832. const group = groups[i];
  6833. const groupMaterial = material[group.materialIndex];
  6834. const start = Math.max(group.start, drawRange.start);
  6835. const end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  6836. for (let j = start, jl = end; j < jl; j += 3) {
  6837. const a = index.getX(j);
  6838. const b = index.getX(j + 1);
  6839. const c = index.getX(j + 2);
  6840. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6841. if (intersection) {
  6842. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  6843. intersection.face.materialIndex = group.materialIndex;
  6844. intersects.push(intersection);
  6845. }
  6846. }
  6847. }
  6848. } else {
  6849. const start = Math.max(0, drawRange.start);
  6850. const end = Math.min(index.count, drawRange.start + drawRange.count);
  6851. for (let i = start, il = end; i < il; i += 3) {
  6852. const a = index.getX(i);
  6853. const b = index.getX(i + 1);
  6854. const c = index.getX(i + 2);
  6855. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6856. if (intersection) {
  6857. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  6858. intersects.push(intersection);
  6859. }
  6860. }
  6861. }
  6862. } else if (position !== undefined) {
  6863. // non-indexed buffer geometry
  6864. if (Array.isArray(material)) {
  6865. for (let i = 0, il = groups.length; i < il; i++) {
  6866. const group = groups[i];
  6867. const groupMaterial = material[group.materialIndex];
  6868. const start = Math.max(group.start, drawRange.start);
  6869. const end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  6870. for (let j = start, jl = end; j < jl; j += 3) {
  6871. const a = j;
  6872. const b = j + 1;
  6873. const c = j + 2;
  6874. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6875. if (intersection) {
  6876. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  6877. intersection.face.materialIndex = group.materialIndex;
  6878. intersects.push(intersection);
  6879. }
  6880. }
  6881. }
  6882. } else {
  6883. const start = Math.max(0, drawRange.start);
  6884. const end = Math.min(position.count, drawRange.start + drawRange.count);
  6885. for (let i = start, il = end; i < il; i += 3) {
  6886. const a = i;
  6887. const b = i + 1;
  6888. const c = i + 2;
  6889. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6890. if (intersection) {
  6891. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  6892. intersects.push(intersection);
  6893. }
  6894. }
  6895. }
  6896. }
  6897. } else if (geometry.isGeometry) {
  6898. console.error('THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6899. }
  6900. }
  6901. }
  6902. Mesh.prototype.isMesh = true;
  6903. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  6904. let intersect;
  6905. if (material.side === BackSide) {
  6906. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  6907. } else {
  6908. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  6909. }
  6910. if (intersect === null) return null;
  6911. _intersectionPointWorld.copy(point);
  6912. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  6913. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  6914. if (distance < raycaster.near || distance > raycaster.far) return null;
  6915. return {
  6916. distance: distance,
  6917. point: _intersectionPointWorld.clone(),
  6918. object: object
  6919. };
  6920. }
  6921. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  6922. _vA$1.fromBufferAttribute(position, a);
  6923. _vB$1.fromBufferAttribute(position, b);
  6924. _vC$1.fromBufferAttribute(position, c);
  6925. const morphInfluences = object.morphTargetInfluences;
  6926. if (material.morphTargets && morphPosition && morphInfluences) {
  6927. _morphA.set(0, 0, 0);
  6928. _morphB.set(0, 0, 0);
  6929. _morphC.set(0, 0, 0);
  6930. for (let i = 0, il = morphPosition.length; i < il; i++) {
  6931. const influence = morphInfluences[i];
  6932. const morphAttribute = morphPosition[i];
  6933. if (influence === 0) continue;
  6934. _tempA.fromBufferAttribute(morphAttribute, a);
  6935. _tempB.fromBufferAttribute(morphAttribute, b);
  6936. _tempC.fromBufferAttribute(morphAttribute, c);
  6937. if (morphTargetsRelative) {
  6938. _morphA.addScaledVector(_tempA, influence);
  6939. _morphB.addScaledVector(_tempB, influence);
  6940. _morphC.addScaledVector(_tempC, influence);
  6941. } else {
  6942. _morphA.addScaledVector(_tempA.sub(_vA$1), influence);
  6943. _morphB.addScaledVector(_tempB.sub(_vB$1), influence);
  6944. _morphC.addScaledVector(_tempC.sub(_vC$1), influence);
  6945. }
  6946. }
  6947. _vA$1.add(_morphA);
  6948. _vB$1.add(_morphB);
  6949. _vC$1.add(_morphC);
  6950. }
  6951. if (object.isSkinnedMesh) {
  6952. object.boneTransform(a, _vA$1);
  6953. object.boneTransform(b, _vB$1);
  6954. object.boneTransform(c, _vC$1);
  6955. }
  6956. const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
  6957. if (intersection) {
  6958. if (uv) {
  6959. _uvA$1.fromBufferAttribute(uv, a);
  6960. _uvB$1.fromBufferAttribute(uv, b);
  6961. _uvC$1.fromBufferAttribute(uv, c);
  6962. intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6963. }
  6964. if (uv2) {
  6965. _uvA$1.fromBufferAttribute(uv2, a);
  6966. _uvB$1.fromBufferAttribute(uv2, b);
  6967. _uvC$1.fromBufferAttribute(uv2, c);
  6968. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6969. }
  6970. const face = {
  6971. a: a,
  6972. b: b,
  6973. c: c,
  6974. normal: new Vector3(),
  6975. materialIndex: 0
  6976. };
  6977. Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
  6978. intersection.face = face;
  6979. }
  6980. return intersection;
  6981. }
  6982. class BoxGeometry extends BufferGeometry {
  6983. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  6984. super();
  6985. this.type = 'BoxGeometry';
  6986. this.parameters = {
  6987. width: width,
  6988. height: height,
  6989. depth: depth,
  6990. widthSegments: widthSegments,
  6991. heightSegments: heightSegments,
  6992. depthSegments: depthSegments
  6993. };
  6994. const scope = this; // segments
  6995. widthSegments = Math.floor(widthSegments);
  6996. heightSegments = Math.floor(heightSegments);
  6997. depthSegments = Math.floor(depthSegments); // buffers
  6998. const indices = [];
  6999. const vertices = [];
  7000. const normals = [];
  7001. const uvs = []; // helper variables
  7002. let numberOfVertices = 0;
  7003. let groupStart = 0; // build each side of the box geometry
  7004. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  7005. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  7006. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  7007. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  7008. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  7009. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  7010. // build geometry
  7011. this.setIndex(indices);
  7012. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7013. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7014. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7015. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  7016. const segmentWidth = width / gridX;
  7017. const segmentHeight = height / gridY;
  7018. const widthHalf = width / 2;
  7019. const heightHalf = height / 2;
  7020. const depthHalf = depth / 2;
  7021. const gridX1 = gridX + 1;
  7022. const gridY1 = gridY + 1;
  7023. let vertexCounter = 0;
  7024. let groupCount = 0;
  7025. const vector = new Vector3(); // generate vertices, normals and uvs
  7026. for (let iy = 0; iy < gridY1; iy++) {
  7027. const y = iy * segmentHeight - heightHalf;
  7028. for (let ix = 0; ix < gridX1; ix++) {
  7029. const x = ix * segmentWidth - widthHalf; // set values to correct vector component
  7030. vector[u] = x * udir;
  7031. vector[v] = y * vdir;
  7032. vector[w] = depthHalf; // now apply vector to vertex buffer
  7033. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  7034. vector[u] = 0;
  7035. vector[v] = 0;
  7036. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  7037. normals.push(vector.x, vector.y, vector.z); // uvs
  7038. uvs.push(ix / gridX);
  7039. uvs.push(1 - iy / gridY); // counters
  7040. vertexCounter += 1;
  7041. }
  7042. } // indices
  7043. // 1. you need three indices to draw a single face
  7044. // 2. a single segment consists of two faces
  7045. // 3. so we need to generate six (2*3) indices per segment
  7046. for (let iy = 0; iy < gridY; iy++) {
  7047. for (let ix = 0; ix < gridX; ix++) {
  7048. const a = numberOfVertices + ix + gridX1 * iy;
  7049. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  7050. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  7051. const d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  7052. indices.push(a, b, d);
  7053. indices.push(b, c, d); // increase counter
  7054. groupCount += 6;
  7055. }
  7056. } // add a group to the geometry. this will ensure multi material support
  7057. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  7058. groupStart += groupCount; // update total number of vertices
  7059. numberOfVertices += vertexCounter;
  7060. }
  7061. }
  7062. }
  7063. /**
  7064. * Uniform Utilities
  7065. */
  7066. function cloneUniforms(src) {
  7067. const dst = {};
  7068. for (const u in src) {
  7069. dst[u] = {};
  7070. for (const p in src[u]) {
  7071. const property = src[u][p];
  7072. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
  7073. dst[u][p] = property.clone();
  7074. } else if (Array.isArray(property)) {
  7075. dst[u][p] = property.slice();
  7076. } else {
  7077. dst[u][p] = property;
  7078. }
  7079. }
  7080. }
  7081. return dst;
  7082. }
  7083. function mergeUniforms(uniforms) {
  7084. const merged = {};
  7085. for (let u = 0; u < uniforms.length; u++) {
  7086. const tmp = cloneUniforms(uniforms[u]);
  7087. for (const p in tmp) {
  7088. merged[p] = tmp[p];
  7089. }
  7090. }
  7091. return merged;
  7092. } // Legacy
  7093. const UniformsUtils = {
  7094. clone: cloneUniforms,
  7095. merge: mergeUniforms
  7096. };
  7097. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7098. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7099. /**
  7100. * parameters = {
  7101. * defines: { "label" : "value" },
  7102. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  7103. *
  7104. * fragmentShader: <string>,
  7105. * vertexShader: <string>,
  7106. *
  7107. * wireframe: <boolean>,
  7108. * wireframeLinewidth: <float>,
  7109. *
  7110. * lights: <bool>,
  7111. *
  7112. * morphTargets: <bool>,
  7113. * morphNormals: <bool>
  7114. * }
  7115. */
  7116. class ShaderMaterial extends Material {
  7117. constructor(parameters) {
  7118. super();
  7119. this.type = 'ShaderMaterial';
  7120. this.defines = {};
  7121. this.uniforms = {};
  7122. this.vertexShader = default_vertex;
  7123. this.fragmentShader = default_fragment;
  7124. this.linewidth = 1;
  7125. this.wireframe = false;
  7126. this.wireframeLinewidth = 1;
  7127. this.fog = false; // set to use scene fog
  7128. this.lights = false; // set to use scene lights
  7129. this.clipping = false; // set to use user-defined clipping planes
  7130. this.morphTargets = false; // set to use morph targets
  7131. this.morphNormals = false; // set to use morph normals
  7132. this.extensions = {
  7133. derivatives: false,
  7134. // set to use derivatives
  7135. fragDepth: false,
  7136. // set to use fragment depth values
  7137. drawBuffers: false,
  7138. // set to use draw buffers
  7139. shaderTextureLOD: false // set to use shader texture LOD
  7140. }; // When rendered geometry doesn't include these attributes but the material does,
  7141. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7142. this.defaultAttributeValues = {
  7143. 'color': [1, 1, 1],
  7144. 'uv': [0, 0],
  7145. 'uv2': [0, 0]
  7146. };
  7147. this.index0AttributeName = undefined;
  7148. this.uniformsNeedUpdate = false;
  7149. this.glslVersion = null;
  7150. if (parameters !== undefined) {
  7151. if (parameters.attributes !== undefined) {
  7152. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  7153. }
  7154. this.setValues(parameters);
  7155. }
  7156. }
  7157. copy(source) {
  7158. super.copy(source);
  7159. this.fragmentShader = source.fragmentShader;
  7160. this.vertexShader = source.vertexShader;
  7161. this.uniforms = cloneUniforms(source.uniforms);
  7162. this.defines = Object.assign({}, source.defines);
  7163. this.wireframe = source.wireframe;
  7164. this.wireframeLinewidth = source.wireframeLinewidth;
  7165. this.lights = source.lights;
  7166. this.clipping = source.clipping;
  7167. this.morphTargets = source.morphTargets;
  7168. this.morphNormals = source.morphNormals;
  7169. this.extensions = Object.assign({}, source.extensions);
  7170. this.glslVersion = source.glslVersion;
  7171. return this;
  7172. }
  7173. toJSON(meta) {
  7174. const data = super.toJSON(meta);
  7175. data.glslVersion = this.glslVersion;
  7176. data.uniforms = {};
  7177. for (const name in this.uniforms) {
  7178. const uniform = this.uniforms[name];
  7179. const value = uniform.value;
  7180. if (value && value.isTexture) {
  7181. data.uniforms[name] = {
  7182. type: 't',
  7183. value: value.toJSON(meta).uuid
  7184. };
  7185. } else if (value && value.isColor) {
  7186. data.uniforms[name] = {
  7187. type: 'c',
  7188. value: value.getHex()
  7189. };
  7190. } else if (value && value.isVector2) {
  7191. data.uniforms[name] = {
  7192. type: 'v2',
  7193. value: value.toArray()
  7194. };
  7195. } else if (value && value.isVector3) {
  7196. data.uniforms[name] = {
  7197. type: 'v3',
  7198. value: value.toArray()
  7199. };
  7200. } else if (value && value.isVector4) {
  7201. data.uniforms[name] = {
  7202. type: 'v4',
  7203. value: value.toArray()
  7204. };
  7205. } else if (value && value.isMatrix3) {
  7206. data.uniforms[name] = {
  7207. type: 'm3',
  7208. value: value.toArray()
  7209. };
  7210. } else if (value && value.isMatrix4) {
  7211. data.uniforms[name] = {
  7212. type: 'm4',
  7213. value: value.toArray()
  7214. };
  7215. } else {
  7216. data.uniforms[name] = {
  7217. value: value
  7218. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7219. }
  7220. }
  7221. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  7222. data.vertexShader = this.vertexShader;
  7223. data.fragmentShader = this.fragmentShader;
  7224. const extensions = {};
  7225. for (const key in this.extensions) {
  7226. if (this.extensions[key] === true) extensions[key] = true;
  7227. }
  7228. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  7229. return data;
  7230. }
  7231. }
  7232. ShaderMaterial.prototype.isShaderMaterial = true;
  7233. class Camera extends Object3D {
  7234. constructor() {
  7235. super();
  7236. this.type = 'Camera';
  7237. this.matrixWorldInverse = new Matrix4();
  7238. this.projectionMatrix = new Matrix4();
  7239. this.projectionMatrixInverse = new Matrix4();
  7240. }
  7241. copy(source, recursive) {
  7242. super.copy(source, recursive);
  7243. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  7244. this.projectionMatrix.copy(source.projectionMatrix);
  7245. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  7246. return this;
  7247. }
  7248. getWorldDirection(target) {
  7249. if (target === undefined) {
  7250. console.warn('THREE.Camera: .getWorldDirection() target is now required');
  7251. target = new Vector3();
  7252. }
  7253. this.updateWorldMatrix(true, false);
  7254. const e = this.matrixWorld.elements;
  7255. return target.set(-e[8], -e[9], -e[10]).normalize();
  7256. }
  7257. updateMatrixWorld(force) {
  7258. super.updateMatrixWorld(force);
  7259. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7260. }
  7261. updateWorldMatrix(updateParents, updateChildren) {
  7262. super.updateWorldMatrix(updateParents, updateChildren);
  7263. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7264. }
  7265. clone() {
  7266. return new this.constructor().copy(this);
  7267. }
  7268. }
  7269. Camera.prototype.isCamera = true;
  7270. class PerspectiveCamera extends Camera {
  7271. constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  7272. super();
  7273. this.type = 'PerspectiveCamera';
  7274. this.fov = fov;
  7275. this.zoom = 1;
  7276. this.near = near;
  7277. this.far = far;
  7278. this.focus = 10;
  7279. this.aspect = aspect;
  7280. this.view = null;
  7281. this.filmGauge = 35; // width of the film (default in millimeters)
  7282. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7283. this.updateProjectionMatrix();
  7284. }
  7285. copy(source, recursive) {
  7286. super.copy(source, recursive);
  7287. this.fov = source.fov;
  7288. this.zoom = source.zoom;
  7289. this.near = source.near;
  7290. this.far = source.far;
  7291. this.focus = source.focus;
  7292. this.aspect = source.aspect;
  7293. this.view = source.view === null ? null : Object.assign({}, source.view);
  7294. this.filmGauge = source.filmGauge;
  7295. this.filmOffset = source.filmOffset;
  7296. return this;
  7297. }
  7298. /**
  7299. * Sets the FOV by focal length in respect to the current .filmGauge.
  7300. *
  7301. * The default film gauge is 35, so that the focal length can be specified for
  7302. * a 35mm (full frame) camera.
  7303. *
  7304. * Values for focal length and film gauge must have the same unit.
  7305. */
  7306. setFocalLength(focalLength) {
  7307. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7308. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7309. this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope);
  7310. this.updateProjectionMatrix();
  7311. }
  7312. /**
  7313. * Calculates the focal length from the current .fov and .filmGauge.
  7314. */
  7315. getFocalLength() {
  7316. const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov);
  7317. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7318. }
  7319. getEffectiveFOV() {
  7320. return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom);
  7321. }
  7322. getFilmWidth() {
  7323. // film not completely covered in portrait format (aspect < 1)
  7324. return this.filmGauge * Math.min(this.aspect, 1);
  7325. }
  7326. getFilmHeight() {
  7327. // film not completely covered in landscape format (aspect > 1)
  7328. return this.filmGauge / Math.max(this.aspect, 1);
  7329. }
  7330. /**
  7331. * Sets an offset in a larger frustum. This is useful for multi-window or
  7332. * multi-monitor/multi-machine setups.
  7333. *
  7334. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7335. * the monitors are in grid like this
  7336. *
  7337. * +---+---+---+
  7338. * | A | B | C |
  7339. * +---+---+---+
  7340. * | D | E | F |
  7341. * +---+---+---+
  7342. *
  7343. * then for each monitor you would call it like this
  7344. *
  7345. * const w = 1920;
  7346. * const h = 1080;
  7347. * const fullWidth = w * 3;
  7348. * const fullHeight = h * 2;
  7349. *
  7350. * --A--
  7351. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7352. * --B--
  7353. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7354. * --C--
  7355. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7356. * --D--
  7357. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7358. * --E--
  7359. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7360. * --F--
  7361. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7362. *
  7363. * Note there is no reason monitors have to be the same size or in a grid.
  7364. */
  7365. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  7366. this.aspect = fullWidth / fullHeight;
  7367. if (this.view === null) {
  7368. this.view = {
  7369. enabled: true,
  7370. fullWidth: 1,
  7371. fullHeight: 1,
  7372. offsetX: 0,
  7373. offsetY: 0,
  7374. width: 1,
  7375. height: 1
  7376. };
  7377. }
  7378. this.view.enabled = true;
  7379. this.view.fullWidth = fullWidth;
  7380. this.view.fullHeight = fullHeight;
  7381. this.view.offsetX = x;
  7382. this.view.offsetY = y;
  7383. this.view.width = width;
  7384. this.view.height = height;
  7385. this.updateProjectionMatrix();
  7386. }
  7387. clearViewOffset() {
  7388. if (this.view !== null) {
  7389. this.view.enabled = false;
  7390. }
  7391. this.updateProjectionMatrix();
  7392. }
  7393. updateProjectionMatrix() {
  7394. const near = this.near;
  7395. let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom;
  7396. let height = 2 * top;
  7397. let width = this.aspect * height;
  7398. let left = -0.5 * width;
  7399. const view = this.view;
  7400. if (this.view !== null && this.view.enabled) {
  7401. const fullWidth = view.fullWidth,
  7402. fullHeight = view.fullHeight;
  7403. left += view.offsetX * width / fullWidth;
  7404. top -= view.offsetY * height / fullHeight;
  7405. width *= view.width / fullWidth;
  7406. height *= view.height / fullHeight;
  7407. }
  7408. const skew = this.filmOffset;
  7409. if (skew !== 0) left += near * skew / this.getFilmWidth();
  7410. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  7411. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  7412. }
  7413. toJSON(meta) {
  7414. const data = super.toJSON(meta);
  7415. data.object.fov = this.fov;
  7416. data.object.zoom = this.zoom;
  7417. data.object.near = this.near;
  7418. data.object.far = this.far;
  7419. data.object.focus = this.focus;
  7420. data.object.aspect = this.aspect;
  7421. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  7422. data.object.filmGauge = this.filmGauge;
  7423. data.object.filmOffset = this.filmOffset;
  7424. return data;
  7425. }
  7426. }
  7427. PerspectiveCamera.prototype.isPerspectiveCamera = true;
  7428. const fov = 90,
  7429. aspect = 1;
  7430. class CubeCamera extends Object3D {
  7431. constructor(near, far, renderTarget) {
  7432. super();
  7433. this.type = 'CubeCamera';
  7434. if (renderTarget.isWebGLCubeRenderTarget !== true) {
  7435. console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
  7436. return;
  7437. }
  7438. this.renderTarget = renderTarget;
  7439. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  7440. cameraPX.layers = this.layers;
  7441. cameraPX.up.set(0, -1, 0);
  7442. cameraPX.lookAt(new Vector3(1, 0, 0));
  7443. this.add(cameraPX);
  7444. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  7445. cameraNX.layers = this.layers;
  7446. cameraNX.up.set(0, -1, 0);
  7447. cameraNX.lookAt(new Vector3(-1, 0, 0));
  7448. this.add(cameraNX);
  7449. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  7450. cameraPY.layers = this.layers;
  7451. cameraPY.up.set(0, 0, 1);
  7452. cameraPY.lookAt(new Vector3(0, 1, 0));
  7453. this.add(cameraPY);
  7454. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  7455. cameraNY.layers = this.layers;
  7456. cameraNY.up.set(0, 0, -1);
  7457. cameraNY.lookAt(new Vector3(0, -1, 0));
  7458. this.add(cameraNY);
  7459. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  7460. cameraPZ.layers = this.layers;
  7461. cameraPZ.up.set(0, -1, 0);
  7462. cameraPZ.lookAt(new Vector3(0, 0, 1));
  7463. this.add(cameraPZ);
  7464. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  7465. cameraNZ.layers = this.layers;
  7466. cameraNZ.up.set(0, -1, 0);
  7467. cameraNZ.lookAt(new Vector3(0, 0, -1));
  7468. this.add(cameraNZ);
  7469. }
  7470. update(renderer, scene) {
  7471. if (this.parent === null) this.updateMatrixWorld();
  7472. const renderTarget = this.renderTarget;
  7473. const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children;
  7474. const currentXrEnabled = renderer.xr.enabled;
  7475. const currentRenderTarget = renderer.getRenderTarget();
  7476. renderer.xr.enabled = false;
  7477. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7478. renderTarget.texture.generateMipmaps = false;
  7479. renderer.setRenderTarget(renderTarget, 0);
  7480. renderer.render(scene, cameraPX);
  7481. renderer.setRenderTarget(renderTarget, 1);
  7482. renderer.render(scene, cameraNX);
  7483. renderer.setRenderTarget(renderTarget, 2);
  7484. renderer.render(scene, cameraPY);
  7485. renderer.setRenderTarget(renderTarget, 3);
  7486. renderer.render(scene, cameraNY);
  7487. renderer.setRenderTarget(renderTarget, 4);
  7488. renderer.render(scene, cameraPZ);
  7489. renderTarget.texture.generateMipmaps = generateMipmaps;
  7490. renderer.setRenderTarget(renderTarget, 5);
  7491. renderer.render(scene, cameraNZ);
  7492. renderer.setRenderTarget(currentRenderTarget);
  7493. renderer.xr.enabled = currentXrEnabled;
  7494. }
  7495. }
  7496. class CubeTexture extends Texture {
  7497. constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  7498. images = images !== undefined ? images : [];
  7499. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7500. format = format !== undefined ? format : RGBFormat;
  7501. super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding); // Why CubeTexture._needsFlipEnvMap is necessary:
  7502. //
  7503. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7504. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7505. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7506. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7507. // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false)
  7508. // when using WebGLCubeRenderTarget.texture as a cube texture.
  7509. this._needsFlipEnvMap = true;
  7510. this.flipY = false;
  7511. }
  7512. get images() {
  7513. return this.image;
  7514. }
  7515. set images(value) {
  7516. this.image = value;
  7517. }
  7518. }
  7519. CubeTexture.prototype.isCubeTexture = true;
  7520. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7521. constructor(size, options, dummy) {
  7522. if (Number.isInteger(options)) {
  7523. console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
  7524. options = dummy;
  7525. }
  7526. super(size, size, options);
  7527. options = options || {};
  7528. this.texture = new CubeTexture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  7529. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7530. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7531. this.texture._needsFlipEnvMap = false;
  7532. }
  7533. fromEquirectangularTexture(renderer, texture) {
  7534. this.texture.type = texture.type;
  7535. this.texture.format = RGBAFormat; // see #18859
  7536. this.texture.encoding = texture.encoding;
  7537. this.texture.generateMipmaps = texture.generateMipmaps;
  7538. this.texture.minFilter = texture.minFilter;
  7539. this.texture.magFilter = texture.magFilter;
  7540. const shader = {
  7541. uniforms: {
  7542. tEquirect: {
  7543. value: null
  7544. }
  7545. },
  7546. vertexShader:
  7547. /* glsl */
  7548. `
  7549. varying vec3 vWorldDirection;
  7550. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7551. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7552. }
  7553. void main() {
  7554. vWorldDirection = transformDirection( position, modelMatrix );
  7555. #include <begin_vertex>
  7556. #include <project_vertex>
  7557. }
  7558. `,
  7559. fragmentShader:
  7560. /* glsl */
  7561. `
  7562. uniform sampler2D tEquirect;
  7563. varying vec3 vWorldDirection;
  7564. #include <common>
  7565. void main() {
  7566. vec3 direction = normalize( vWorldDirection );
  7567. vec2 sampleUV = equirectUv( direction );
  7568. gl_FragColor = texture2D( tEquirect, sampleUV );
  7569. }
  7570. `
  7571. };
  7572. const geometry = new BoxGeometry(5, 5, 5);
  7573. const material = new ShaderMaterial({
  7574. name: 'CubemapFromEquirect',
  7575. uniforms: cloneUniforms(shader.uniforms),
  7576. vertexShader: shader.vertexShader,
  7577. fragmentShader: shader.fragmentShader,
  7578. side: BackSide,
  7579. blending: NoBlending
  7580. });
  7581. material.uniforms.tEquirect.value = texture;
  7582. const mesh = new Mesh(geometry, material);
  7583. const currentMinFilter = texture.minFilter; // Avoid blurred poles
  7584. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  7585. const camera = new CubeCamera(1, 10, this);
  7586. camera.update(renderer, mesh);
  7587. texture.minFilter = currentMinFilter;
  7588. mesh.geometry.dispose();
  7589. mesh.material.dispose();
  7590. return this;
  7591. }
  7592. clear(renderer, color, depth, stencil) {
  7593. const currentRenderTarget = renderer.getRenderTarget();
  7594. for (let i = 0; i < 6; i++) {
  7595. renderer.setRenderTarget(this, i);
  7596. renderer.clear(color, depth, stencil);
  7597. }
  7598. renderer.setRenderTarget(currentRenderTarget);
  7599. }
  7600. }
  7601. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  7602. const _sphere$2 = /*@__PURE__*/new Sphere();
  7603. const _vector$7 = /*@__PURE__*/new Vector3();
  7604. class Frustum {
  7605. constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) {
  7606. this.planes = [p0, p1, p2, p3, p4, p5];
  7607. }
  7608. set(p0, p1, p2, p3, p4, p5) {
  7609. const planes = this.planes;
  7610. planes[0].copy(p0);
  7611. planes[1].copy(p1);
  7612. planes[2].copy(p2);
  7613. planes[3].copy(p3);
  7614. planes[4].copy(p4);
  7615. planes[5].copy(p5);
  7616. return this;
  7617. }
  7618. copy(frustum) {
  7619. const planes = this.planes;
  7620. for (let i = 0; i < 6; i++) {
  7621. planes[i].copy(frustum.planes[i]);
  7622. }
  7623. return this;
  7624. }
  7625. setFromProjectionMatrix(m) {
  7626. const planes = this.planes;
  7627. const me = m.elements;
  7628. const me0 = me[0],
  7629. me1 = me[1],
  7630. me2 = me[2],
  7631. me3 = me[3];
  7632. const me4 = me[4],
  7633. me5 = me[5],
  7634. me6 = me[6],
  7635. me7 = me[7];
  7636. const me8 = me[8],
  7637. me9 = me[9],
  7638. me10 = me[10],
  7639. me11 = me[11];
  7640. const me12 = me[12],
  7641. me13 = me[13],
  7642. me14 = me[14],
  7643. me15 = me[15];
  7644. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  7645. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  7646. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  7647. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  7648. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  7649. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  7650. return this;
  7651. }
  7652. intersectsObject(object) {
  7653. const geometry = object.geometry;
  7654. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7655. _sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  7656. return this.intersectsSphere(_sphere$2);
  7657. }
  7658. intersectsSprite(sprite) {
  7659. _sphere$2.center.set(0, 0, 0);
  7660. _sphere$2.radius = 0.7071067811865476;
  7661. _sphere$2.applyMatrix4(sprite.matrixWorld);
  7662. return this.intersectsSphere(_sphere$2);
  7663. }
  7664. intersectsSphere(sphere) {
  7665. const planes = this.planes;
  7666. const center = sphere.center;
  7667. const negRadius = -sphere.radius;
  7668. for (let i = 0; i < 6; i++) {
  7669. const distance = planes[i].distanceToPoint(center);
  7670. if (distance < negRadius) {
  7671. return false;
  7672. }
  7673. }
  7674. return true;
  7675. }
  7676. intersectsBox(box) {
  7677. const planes = this.planes;
  7678. for (let i = 0; i < 6; i++) {
  7679. const plane = planes[i]; // corner at max distance
  7680. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7681. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7682. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7683. if (plane.distanceToPoint(_vector$7) < 0) {
  7684. return false;
  7685. }
  7686. }
  7687. return true;
  7688. }
  7689. containsPoint(point) {
  7690. const planes = this.planes;
  7691. for (let i = 0; i < 6; i++) {
  7692. if (planes[i].distanceToPoint(point) < 0) {
  7693. return false;
  7694. }
  7695. }
  7696. return true;
  7697. }
  7698. clone() {
  7699. return new this.constructor().copy(this);
  7700. }
  7701. }
  7702. function WebGLAnimation() {
  7703. let context = null;
  7704. let isAnimating = false;
  7705. let animationLoop = null;
  7706. let requestId = null;
  7707. function onAnimationFrame(time, frame) {
  7708. animationLoop(time, frame);
  7709. requestId = context.requestAnimationFrame(onAnimationFrame);
  7710. }
  7711. return {
  7712. start: function () {
  7713. if (isAnimating === true) return;
  7714. if (animationLoop === null) return;
  7715. requestId = context.requestAnimationFrame(onAnimationFrame);
  7716. isAnimating = true;
  7717. },
  7718. stop: function () {
  7719. context.cancelAnimationFrame(requestId);
  7720. isAnimating = false;
  7721. },
  7722. setAnimationLoop: function (callback) {
  7723. animationLoop = callback;
  7724. },
  7725. setContext: function (value) {
  7726. context = value;
  7727. }
  7728. };
  7729. }
  7730. function WebGLAttributes(gl, capabilities) {
  7731. const isWebGL2 = capabilities.isWebGL2;
  7732. const buffers = new WeakMap();
  7733. function createBuffer(attribute, bufferType) {
  7734. const array = attribute.array;
  7735. const usage = attribute.usage;
  7736. const buffer = gl.createBuffer();
  7737. gl.bindBuffer(bufferType, buffer);
  7738. gl.bufferData(bufferType, array, usage);
  7739. attribute.onUploadCallback();
  7740. let type = gl.FLOAT;
  7741. if (array instanceof Float32Array) {
  7742. type = gl.FLOAT;
  7743. } else if (array instanceof Float64Array) {
  7744. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  7745. } else if (array instanceof Uint16Array) {
  7746. if (attribute.isFloat16BufferAttribute) {
  7747. if (isWebGL2) {
  7748. type = gl.HALF_FLOAT;
  7749. } else {
  7750. console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  7751. }
  7752. } else {
  7753. type = gl.UNSIGNED_SHORT;
  7754. }
  7755. } else if (array instanceof Int16Array) {
  7756. type = gl.SHORT;
  7757. } else if (array instanceof Uint32Array) {
  7758. type = gl.UNSIGNED_INT;
  7759. } else if (array instanceof Int32Array) {
  7760. type = gl.INT;
  7761. } else if (array instanceof Int8Array) {
  7762. type = gl.BYTE;
  7763. } else if (array instanceof Uint8Array) {
  7764. type = gl.UNSIGNED_BYTE;
  7765. } else if (array instanceof Uint8ClampedArray) {
  7766. type = gl.UNSIGNED_BYTE;
  7767. }
  7768. return {
  7769. buffer: buffer,
  7770. type: type,
  7771. bytesPerElement: array.BYTES_PER_ELEMENT,
  7772. version: attribute.version
  7773. };
  7774. }
  7775. function updateBuffer(buffer, attribute, bufferType) {
  7776. const array = attribute.array;
  7777. const updateRange = attribute.updateRange;
  7778. gl.bindBuffer(bufferType, buffer);
  7779. if (updateRange.count === -1) {
  7780. // Not using update ranges
  7781. gl.bufferSubData(bufferType, 0, array);
  7782. } else {
  7783. if (isWebGL2) {
  7784. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  7785. } else {
  7786. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  7787. }
  7788. updateRange.count = -1; // reset range
  7789. }
  7790. } //
  7791. function get(attribute) {
  7792. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7793. return buffers.get(attribute);
  7794. }
  7795. function remove(attribute) {
  7796. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7797. const data = buffers.get(attribute);
  7798. if (data) {
  7799. gl.deleteBuffer(data.buffer);
  7800. buffers.delete(attribute);
  7801. }
  7802. }
  7803. function update(attribute, bufferType) {
  7804. if (attribute.isGLBufferAttribute) {
  7805. const cached = buffers.get(attribute);
  7806. if (!cached || cached.version < attribute.version) {
  7807. buffers.set(attribute, {
  7808. buffer: attribute.buffer,
  7809. type: attribute.type,
  7810. bytesPerElement: attribute.elementSize,
  7811. version: attribute.version
  7812. });
  7813. }
  7814. return;
  7815. }
  7816. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7817. const data = buffers.get(attribute);
  7818. if (data === undefined) {
  7819. buffers.set(attribute, createBuffer(attribute, bufferType));
  7820. } else if (data.version < attribute.version) {
  7821. updateBuffer(data.buffer, attribute, bufferType);
  7822. data.version = attribute.version;
  7823. }
  7824. }
  7825. return {
  7826. get: get,
  7827. remove: remove,
  7828. update: update
  7829. };
  7830. }
  7831. class PlaneGeometry extends BufferGeometry {
  7832. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  7833. super();
  7834. this.type = 'PlaneGeometry';
  7835. this.parameters = {
  7836. width: width,
  7837. height: height,
  7838. widthSegments: widthSegments,
  7839. heightSegments: heightSegments
  7840. };
  7841. const width_half = width / 2;
  7842. const height_half = height / 2;
  7843. const gridX = Math.floor(widthSegments);
  7844. const gridY = Math.floor(heightSegments);
  7845. const gridX1 = gridX + 1;
  7846. const gridY1 = gridY + 1;
  7847. const segment_width = width / gridX;
  7848. const segment_height = height / gridY; //
  7849. const indices = [];
  7850. const vertices = [];
  7851. const normals = [];
  7852. const uvs = [];
  7853. for (let iy = 0; iy < gridY1; iy++) {
  7854. const y = iy * segment_height - height_half;
  7855. for (let ix = 0; ix < gridX1; ix++) {
  7856. const x = ix * segment_width - width_half;
  7857. vertices.push(x, -y, 0);
  7858. normals.push(0, 0, 1);
  7859. uvs.push(ix / gridX);
  7860. uvs.push(1 - iy / gridY);
  7861. }
  7862. }
  7863. for (let iy = 0; iy < gridY; iy++) {
  7864. for (let ix = 0; ix < gridX; ix++) {
  7865. const a = ix + gridX1 * iy;
  7866. const b = ix + gridX1 * (iy + 1);
  7867. const c = ix + 1 + gridX1 * (iy + 1);
  7868. const d = ix + 1 + gridX1 * iy;
  7869. indices.push(a, b, d);
  7870. indices.push(b, c, d);
  7871. }
  7872. }
  7873. this.setIndex(indices);
  7874. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7875. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7876. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7877. }
  7878. }
  7879. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7880. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7881. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  7882. 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.specularRoughness );\n\t#endif\n#endif";
  7883. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7884. var begin_vertex = "vec3 transformed = vec3( position );";
  7885. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7886. var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\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\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotVH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_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_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, 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 dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * 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}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.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}\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_Specular_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 dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";
  7887. 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";
  7888. 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";
  7889. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7890. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7891. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7892. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7893. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7894. 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";
  7895. 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";
  7896. 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 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 max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\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 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}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\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}";
  7897. 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";
  7898. 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";
  7899. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7900. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7901. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7902. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7903. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7904. 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}";
  7905. 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#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#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\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";
  7906. 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";
  7907. 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";
  7908. 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";
  7909. 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";
  7910. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif";
  7911. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  7912. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  7913. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\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";
  7914. 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}";
  7915. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  7916. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7917. 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\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * 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\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * 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\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * 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";
  7918. 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\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\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 getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.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 getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.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 getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.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\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif";
  7919. 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 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";
  7920. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7921. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\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\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_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_Diffuse_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)";
  7922. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7923. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\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\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_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_Diffuse_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)";
  7924. 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.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), rawDiffuseColor, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), rawDiffuseColor, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\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.sheenColor = sheen;\n#endif";
  7925. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat specularRoughness;\n\tvec3 specularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\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.specularRoughness;\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#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_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_Diffuse_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 CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * 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}";
  7926. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef 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\tgetPointDirectLightIrradiance( 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\tgetSpotDirectLightIrradiance( 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\tgetDirectionalDirectLightIrradiance( 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";
  7927. 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 += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif";
  7928. 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";
  7929. 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";
  7930. 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";
  7931. 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";
  7932. 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";
  7933. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  7934. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7935. 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";
  7936. 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";
  7937. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7938. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7939. 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";
  7940. 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";
  7941. 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";
  7942. 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;";
  7943. 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";
  7944. 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";
  7945. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7946. 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";
  7947. 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";
  7948. 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}";
  7949. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7950. 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;";
  7951. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7952. 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";
  7953. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7954. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7955. 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";
  7956. 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";
  7957. 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";
  7958. 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}";
  7959. 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";
  7960. 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";
  7961. 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";
  7962. 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";
  7963. 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";
  7964. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7965. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7966. 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; }";
  7967. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\t#ifdef USE_TRANSMISSIONMAP\n\t\ttotalTransmission *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSNMAP\n\t\tthicknessFactor *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition.xyz / vWorldPosition.w;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n\tfloat ior = ( 1.0 + 0.4 * reflectivity ) / ( 1.0 - 0.4 * reflectivity );\n\tvec3 f0 = vec3( pow( ior - 1.0, 2.0 ) / pow( ior + 1.0, 2.0 ) );\n\tvec3 f90 = vec3( 1.0 );\n\tvec3 f_transmission = totalTransmission * getIBLVolumeRefraction(\n\t\tnormal, v, viewDir, roughnessFactor, diffuseColor.rgb, f0, f90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationColor, attenuationDistance);\n\tdiffuseColor.rgb = mix( diffuseColor.rgb, f_transmission, totalTransmission );\n#endif";
  7968. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\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 vec4 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\tvec3 getTransmissionSample(vec2 fragCoord, float roughness, float ior) {\n\t\tfloat framebufferLod = log2(transmissionSamplerSize.x) * applyIorToRoughness(roughness, ior);\n\t\treturn texture2DLodEXT(transmissionSamplerMap, fragCoord.xy, framebufferLod).rgb;\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\tvec3 getIBLVolumeRefraction(vec3 n, vec3 v, vec3 viewDir, float perceptualRoughness, vec3 baseColor, vec3 f0, vec3 f90,\n\t\tvec3 position, mat4 modelMatrix, mat4 viewMatrix, mat4 projMatrix, float ior, float thickness, vec3 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\tvec3 transmittedLight = getTransmissionSample(refractionCoords, perceptualRoughness, ior);\n\t\tvec3 attenuatedColor = applyVolumeAttenuation(transmittedLight, length(transmissionRay), attenuationColor, attenuationDistance);\n\t\tfloat NdotV = saturate(dot(n, viewDir));\n\t\tvec2 brdf = integrateSpecularBRDF(NdotV, perceptualRoughness);\n\t\tvec3 specularColor = f0 * brdf.x + f90 * brdf.y;\n\t\treturn (1.0 - specularColor) * attenuatedColor * baseColor;\n\t}\n#endif";
  7969. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7970. 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";
  7971. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7972. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7973. 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";
  7974. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7975. 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";
  7976. 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}";
  7977. 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}";
  7978. 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}";
  7979. 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}";
  7980. 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 <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}";
  7981. 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}";
  7982. 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 <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}";
  7983. 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}";
  7984. 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}";
  7985. 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}";
  7986. 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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7987. 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}";
  7988. 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 <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\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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\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}";
  7989. 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#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\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 <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  7990. 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 <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_Diffuse_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_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\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}";
  7991. 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}";
  7992. var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\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 <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\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}";
  7993. var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\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 <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#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\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\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  7994. 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 <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 <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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\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}";
  7995. var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\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 <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#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#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\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7996. 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 <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 <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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\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}";
  7997. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\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 <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#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#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\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7998. var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform vec3 attenuationColor;\n\tuniform float attenuationDistance;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#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\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 <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <transmission_pars_fragment>\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 <lights_physical_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#ifdef USE_TRANSMISSION\n\t\tfloat totalTransmission = transmission;\n\t\tfloat thicknessFactor = thickness;\n\t#endif\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\tvec3 rawDiffuseColor = diffuseColor.rgb;\n\t#include <transmission_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 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\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}";
  7999. var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#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\n#ifdef USE_TRANSMISSION\n\tvarying vec4 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 <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#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\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;\n#endif\n}";
  8000. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#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\n#include <packing>\n#include <uv_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}";
  8001. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#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\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 <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#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\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}";
  8002. 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 <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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8003. 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}";
  8004. 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}";
  8005. 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}";
  8006. 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 <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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8007. 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}";
  8008. const ShaderChunk = {
  8009. alphamap_fragment: alphamap_fragment,
  8010. alphamap_pars_fragment: alphamap_pars_fragment,
  8011. alphatest_fragment: alphatest_fragment,
  8012. aomap_fragment: aomap_fragment,
  8013. aomap_pars_fragment: aomap_pars_fragment,
  8014. begin_vertex: begin_vertex,
  8015. beginnormal_vertex: beginnormal_vertex,
  8016. bsdfs: bsdfs,
  8017. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8018. clipping_planes_fragment: clipping_planes_fragment,
  8019. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8020. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8021. clipping_planes_vertex: clipping_planes_vertex,
  8022. color_fragment: color_fragment,
  8023. color_pars_fragment: color_pars_fragment,
  8024. color_pars_vertex: color_pars_vertex,
  8025. color_vertex: color_vertex,
  8026. common: common,
  8027. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8028. defaultnormal_vertex: defaultnormal_vertex,
  8029. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8030. displacementmap_vertex: displacementmap_vertex,
  8031. emissivemap_fragment: emissivemap_fragment,
  8032. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8033. encodings_fragment: encodings_fragment,
  8034. encodings_pars_fragment: encodings_pars_fragment,
  8035. envmap_fragment: envmap_fragment,
  8036. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8037. envmap_pars_fragment: envmap_pars_fragment,
  8038. envmap_pars_vertex: envmap_pars_vertex,
  8039. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8040. envmap_vertex: envmap_vertex,
  8041. fog_vertex: fog_vertex,
  8042. fog_pars_vertex: fog_pars_vertex,
  8043. fog_fragment: fog_fragment,
  8044. fog_pars_fragment: fog_pars_fragment,
  8045. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8046. lightmap_fragment: lightmap_fragment,
  8047. lightmap_pars_fragment: lightmap_pars_fragment,
  8048. lights_lambert_vertex: lights_lambert_vertex,
  8049. lights_pars_begin: lights_pars_begin,
  8050. lights_toon_fragment: lights_toon_fragment,
  8051. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8052. lights_phong_fragment: lights_phong_fragment,
  8053. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8054. lights_physical_fragment: lights_physical_fragment,
  8055. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8056. lights_fragment_begin: lights_fragment_begin,
  8057. lights_fragment_maps: lights_fragment_maps,
  8058. lights_fragment_end: lights_fragment_end,
  8059. logdepthbuf_fragment: logdepthbuf_fragment,
  8060. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8061. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8062. logdepthbuf_vertex: logdepthbuf_vertex,
  8063. map_fragment: map_fragment,
  8064. map_pars_fragment: map_pars_fragment,
  8065. map_particle_fragment: map_particle_fragment,
  8066. map_particle_pars_fragment: map_particle_pars_fragment,
  8067. metalnessmap_fragment: metalnessmap_fragment,
  8068. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8069. morphnormal_vertex: morphnormal_vertex,
  8070. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8071. morphtarget_vertex: morphtarget_vertex,
  8072. normal_fragment_begin: normal_fragment_begin,
  8073. normal_fragment_maps: normal_fragment_maps,
  8074. normalmap_pars_fragment: normalmap_pars_fragment,
  8075. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8076. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8077. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8078. packing: packing,
  8079. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8080. project_vertex: project_vertex,
  8081. dithering_fragment: dithering_fragment,
  8082. dithering_pars_fragment: dithering_pars_fragment,
  8083. roughnessmap_fragment: roughnessmap_fragment,
  8084. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8085. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8086. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8087. shadowmap_vertex: shadowmap_vertex,
  8088. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8089. skinbase_vertex: skinbase_vertex,
  8090. skinning_pars_vertex: skinning_pars_vertex,
  8091. skinning_vertex: skinning_vertex,
  8092. skinnormal_vertex: skinnormal_vertex,
  8093. specularmap_fragment: specularmap_fragment,
  8094. specularmap_pars_fragment: specularmap_pars_fragment,
  8095. tonemapping_fragment: tonemapping_fragment,
  8096. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8097. transmission_fragment: transmission_fragment,
  8098. transmission_pars_fragment: transmission_pars_fragment,
  8099. uv_pars_fragment: uv_pars_fragment,
  8100. uv_pars_vertex: uv_pars_vertex,
  8101. uv_vertex: uv_vertex,
  8102. uv2_pars_fragment: uv2_pars_fragment,
  8103. uv2_pars_vertex: uv2_pars_vertex,
  8104. uv2_vertex: uv2_vertex,
  8105. worldpos_vertex: worldpos_vertex,
  8106. background_frag: background_frag,
  8107. background_vert: background_vert,
  8108. cube_frag: cube_frag,
  8109. cube_vert: cube_vert,
  8110. depth_frag: depth_frag,
  8111. depth_vert: depth_vert,
  8112. distanceRGBA_frag: distanceRGBA_frag,
  8113. distanceRGBA_vert: distanceRGBA_vert,
  8114. equirect_frag: equirect_frag,
  8115. equirect_vert: equirect_vert,
  8116. linedashed_frag: linedashed_frag,
  8117. linedashed_vert: linedashed_vert,
  8118. meshbasic_frag: meshbasic_frag,
  8119. meshbasic_vert: meshbasic_vert,
  8120. meshlambert_frag: meshlambert_frag,
  8121. meshlambert_vert: meshlambert_vert,
  8122. meshmatcap_frag: meshmatcap_frag,
  8123. meshmatcap_vert: meshmatcap_vert,
  8124. meshtoon_frag: meshtoon_frag,
  8125. meshtoon_vert: meshtoon_vert,
  8126. meshphong_frag: meshphong_frag,
  8127. meshphong_vert: meshphong_vert,
  8128. meshphysical_frag: meshphysical_frag,
  8129. meshphysical_vert: meshphysical_vert,
  8130. normal_frag: normal_frag,
  8131. normal_vert: normal_vert,
  8132. points_frag: points_frag,
  8133. points_vert: points_vert,
  8134. shadow_frag: shadow_frag,
  8135. shadow_vert: shadow_vert,
  8136. sprite_frag: sprite_frag,
  8137. sprite_vert: sprite_vert
  8138. };
  8139. /**
  8140. * Uniforms library for shared webgl shaders
  8141. */
  8142. const UniformsLib = {
  8143. common: {
  8144. diffuse: {
  8145. value: new Color(0xffffff)
  8146. },
  8147. opacity: {
  8148. value: 1.0
  8149. },
  8150. map: {
  8151. value: null
  8152. },
  8153. uvTransform: {
  8154. value: new Matrix3()
  8155. },
  8156. uv2Transform: {
  8157. value: new Matrix3()
  8158. },
  8159. alphaMap: {
  8160. value: null
  8161. }
  8162. },
  8163. specularmap: {
  8164. specularMap: {
  8165. value: null
  8166. }
  8167. },
  8168. envmap: {
  8169. envMap: {
  8170. value: null
  8171. },
  8172. flipEnvMap: {
  8173. value: -1
  8174. },
  8175. reflectivity: {
  8176. value: 1.0
  8177. },
  8178. refractionRatio: {
  8179. value: 0.98
  8180. },
  8181. maxMipLevel: {
  8182. value: 0
  8183. }
  8184. },
  8185. aomap: {
  8186. aoMap: {
  8187. value: null
  8188. },
  8189. aoMapIntensity: {
  8190. value: 1
  8191. }
  8192. },
  8193. lightmap: {
  8194. lightMap: {
  8195. value: null
  8196. },
  8197. lightMapIntensity: {
  8198. value: 1
  8199. }
  8200. },
  8201. emissivemap: {
  8202. emissiveMap: {
  8203. value: null
  8204. }
  8205. },
  8206. bumpmap: {
  8207. bumpMap: {
  8208. value: null
  8209. },
  8210. bumpScale: {
  8211. value: 1
  8212. }
  8213. },
  8214. normalmap: {
  8215. normalMap: {
  8216. value: null
  8217. },
  8218. normalScale: {
  8219. value: new Vector2(1, 1)
  8220. }
  8221. },
  8222. displacementmap: {
  8223. displacementMap: {
  8224. value: null
  8225. },
  8226. displacementScale: {
  8227. value: 1
  8228. },
  8229. displacementBias: {
  8230. value: 0
  8231. }
  8232. },
  8233. roughnessmap: {
  8234. roughnessMap: {
  8235. value: null
  8236. }
  8237. },
  8238. metalnessmap: {
  8239. metalnessMap: {
  8240. value: null
  8241. }
  8242. },
  8243. gradientmap: {
  8244. gradientMap: {
  8245. value: null
  8246. }
  8247. },
  8248. fog: {
  8249. fogDensity: {
  8250. value: 0.00025
  8251. },
  8252. fogNear: {
  8253. value: 1
  8254. },
  8255. fogFar: {
  8256. value: 2000
  8257. },
  8258. fogColor: {
  8259. value: new Color(0xffffff)
  8260. }
  8261. },
  8262. lights: {
  8263. ambientLightColor: {
  8264. value: []
  8265. },
  8266. lightProbe: {
  8267. value: []
  8268. },
  8269. directionalLights: {
  8270. value: [],
  8271. properties: {
  8272. direction: {},
  8273. color: {}
  8274. }
  8275. },
  8276. directionalLightShadows: {
  8277. value: [],
  8278. properties: {
  8279. shadowBias: {},
  8280. shadowNormalBias: {},
  8281. shadowRadius: {},
  8282. shadowMapSize: {}
  8283. }
  8284. },
  8285. directionalShadowMap: {
  8286. value: []
  8287. },
  8288. directionalShadowMatrix: {
  8289. value: []
  8290. },
  8291. spotLights: {
  8292. value: [],
  8293. properties: {
  8294. color: {},
  8295. position: {},
  8296. direction: {},
  8297. distance: {},
  8298. coneCos: {},
  8299. penumbraCos: {},
  8300. decay: {}
  8301. }
  8302. },
  8303. spotLightShadows: {
  8304. value: [],
  8305. properties: {
  8306. shadowBias: {},
  8307. shadowNormalBias: {},
  8308. shadowRadius: {},
  8309. shadowMapSize: {}
  8310. }
  8311. },
  8312. spotShadowMap: {
  8313. value: []
  8314. },
  8315. spotShadowMatrix: {
  8316. value: []
  8317. },
  8318. pointLights: {
  8319. value: [],
  8320. properties: {
  8321. color: {},
  8322. position: {},
  8323. decay: {},
  8324. distance: {}
  8325. }
  8326. },
  8327. pointLightShadows: {
  8328. value: [],
  8329. properties: {
  8330. shadowBias: {},
  8331. shadowNormalBias: {},
  8332. shadowRadius: {},
  8333. shadowMapSize: {},
  8334. shadowCameraNear: {},
  8335. shadowCameraFar: {}
  8336. }
  8337. },
  8338. pointShadowMap: {
  8339. value: []
  8340. },
  8341. pointShadowMatrix: {
  8342. value: []
  8343. },
  8344. hemisphereLights: {
  8345. value: [],
  8346. properties: {
  8347. direction: {},
  8348. skyColor: {},
  8349. groundColor: {}
  8350. }
  8351. },
  8352. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8353. rectAreaLights: {
  8354. value: [],
  8355. properties: {
  8356. color: {},
  8357. position: {},
  8358. width: {},
  8359. height: {}
  8360. }
  8361. },
  8362. ltc_1: {
  8363. value: null
  8364. },
  8365. ltc_2: {
  8366. value: null
  8367. }
  8368. },
  8369. points: {
  8370. diffuse: {
  8371. value: new Color(0xffffff)
  8372. },
  8373. opacity: {
  8374. value: 1.0
  8375. },
  8376. size: {
  8377. value: 1.0
  8378. },
  8379. scale: {
  8380. value: 1.0
  8381. },
  8382. map: {
  8383. value: null
  8384. },
  8385. alphaMap: {
  8386. value: null
  8387. },
  8388. uvTransform: {
  8389. value: new Matrix3()
  8390. }
  8391. },
  8392. sprite: {
  8393. diffuse: {
  8394. value: new Color(0xffffff)
  8395. },
  8396. opacity: {
  8397. value: 1.0
  8398. },
  8399. center: {
  8400. value: new Vector2(0.5, 0.5)
  8401. },
  8402. rotation: {
  8403. value: 0.0
  8404. },
  8405. map: {
  8406. value: null
  8407. },
  8408. alphaMap: {
  8409. value: null
  8410. },
  8411. uvTransform: {
  8412. value: new Matrix3()
  8413. }
  8414. }
  8415. };
  8416. const ShaderLib = {
  8417. basic: {
  8418. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  8419. vertexShader: ShaderChunk.meshbasic_vert,
  8420. fragmentShader: ShaderChunk.meshbasic_frag
  8421. },
  8422. lambert: {
  8423. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  8424. emissive: {
  8425. value: new Color(0x000000)
  8426. }
  8427. }]),
  8428. vertexShader: ShaderChunk.meshlambert_vert,
  8429. fragmentShader: ShaderChunk.meshlambert_frag
  8430. },
  8431. phong: {
  8432. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  8433. emissive: {
  8434. value: new Color(0x000000)
  8435. },
  8436. specular: {
  8437. value: new Color(0x111111)
  8438. },
  8439. shininess: {
  8440. value: 30
  8441. }
  8442. }]),
  8443. vertexShader: ShaderChunk.meshphong_vert,
  8444. fragmentShader: ShaderChunk.meshphong_frag
  8445. },
  8446. standard: {
  8447. 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, {
  8448. emissive: {
  8449. value: new Color(0x000000)
  8450. },
  8451. roughness: {
  8452. value: 1.0
  8453. },
  8454. metalness: {
  8455. value: 0.0
  8456. },
  8457. envMapIntensity: {
  8458. value: 1
  8459. } // temporary
  8460. }]),
  8461. vertexShader: ShaderChunk.meshphysical_vert,
  8462. fragmentShader: ShaderChunk.meshphysical_frag
  8463. },
  8464. toon: {
  8465. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  8466. emissive: {
  8467. value: new Color(0x000000)
  8468. }
  8469. }]),
  8470. vertexShader: ShaderChunk.meshtoon_vert,
  8471. fragmentShader: ShaderChunk.meshtoon_frag
  8472. },
  8473. matcap: {
  8474. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  8475. matcap: {
  8476. value: null
  8477. }
  8478. }]),
  8479. vertexShader: ShaderChunk.meshmatcap_vert,
  8480. fragmentShader: ShaderChunk.meshmatcap_frag
  8481. },
  8482. points: {
  8483. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  8484. vertexShader: ShaderChunk.points_vert,
  8485. fragmentShader: ShaderChunk.points_frag
  8486. },
  8487. dashed: {
  8488. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  8489. scale: {
  8490. value: 1
  8491. },
  8492. dashSize: {
  8493. value: 1
  8494. },
  8495. totalSize: {
  8496. value: 2
  8497. }
  8498. }]),
  8499. vertexShader: ShaderChunk.linedashed_vert,
  8500. fragmentShader: ShaderChunk.linedashed_frag
  8501. },
  8502. depth: {
  8503. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  8504. vertexShader: ShaderChunk.depth_vert,
  8505. fragmentShader: ShaderChunk.depth_frag
  8506. },
  8507. normal: {
  8508. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  8509. opacity: {
  8510. value: 1.0
  8511. }
  8512. }]),
  8513. vertexShader: ShaderChunk.normal_vert,
  8514. fragmentShader: ShaderChunk.normal_frag
  8515. },
  8516. sprite: {
  8517. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  8518. vertexShader: ShaderChunk.sprite_vert,
  8519. fragmentShader: ShaderChunk.sprite_frag
  8520. },
  8521. background: {
  8522. uniforms: {
  8523. uvTransform: {
  8524. value: new Matrix3()
  8525. },
  8526. t2D: {
  8527. value: null
  8528. }
  8529. },
  8530. vertexShader: ShaderChunk.background_vert,
  8531. fragmentShader: ShaderChunk.background_frag
  8532. },
  8533. /* -------------------------------------------------------------------------
  8534. // Cube map shader
  8535. ------------------------------------------------------------------------- */
  8536. cube: {
  8537. uniforms: mergeUniforms([UniformsLib.envmap, {
  8538. opacity: {
  8539. value: 1.0
  8540. }
  8541. }]),
  8542. vertexShader: ShaderChunk.cube_vert,
  8543. fragmentShader: ShaderChunk.cube_frag
  8544. },
  8545. equirect: {
  8546. uniforms: {
  8547. tEquirect: {
  8548. value: null
  8549. }
  8550. },
  8551. vertexShader: ShaderChunk.equirect_vert,
  8552. fragmentShader: ShaderChunk.equirect_frag
  8553. },
  8554. distanceRGBA: {
  8555. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  8556. referencePosition: {
  8557. value: new Vector3()
  8558. },
  8559. nearDistance: {
  8560. value: 1
  8561. },
  8562. farDistance: {
  8563. value: 1000
  8564. }
  8565. }]),
  8566. vertexShader: ShaderChunk.distanceRGBA_vert,
  8567. fragmentShader: ShaderChunk.distanceRGBA_frag
  8568. },
  8569. shadow: {
  8570. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  8571. color: {
  8572. value: new Color(0x00000)
  8573. },
  8574. opacity: {
  8575. value: 1.0
  8576. }
  8577. }]),
  8578. vertexShader: ShaderChunk.shadow_vert,
  8579. fragmentShader: ShaderChunk.shadow_frag
  8580. }
  8581. };
  8582. ShaderLib.physical = {
  8583. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  8584. clearcoat: {
  8585. value: 0
  8586. },
  8587. clearcoatMap: {
  8588. value: null
  8589. },
  8590. clearcoatRoughness: {
  8591. value: 0
  8592. },
  8593. clearcoatRoughnessMap: {
  8594. value: null
  8595. },
  8596. clearcoatNormalScale: {
  8597. value: new Vector2(1, 1)
  8598. },
  8599. clearcoatNormalMap: {
  8600. value: null
  8601. },
  8602. sheen: {
  8603. value: new Color(0x000000)
  8604. },
  8605. transmission: {
  8606. value: 0
  8607. },
  8608. transmissionMap: {
  8609. value: null
  8610. },
  8611. transmissionSamplerSize: {
  8612. value: new Vector2()
  8613. },
  8614. transmissionSamplerMap: {
  8615. value: null
  8616. },
  8617. thickness: {
  8618. value: 0
  8619. },
  8620. thicknessMap: {
  8621. value: null
  8622. },
  8623. attenuationDistance: {
  8624. value: 0
  8625. },
  8626. attenuationColor: {
  8627. value: new Color(0x000000)
  8628. }
  8629. }]),
  8630. vertexShader: ShaderChunk.meshphysical_vert,
  8631. fragmentShader: ShaderChunk.meshphysical_frag
  8632. };
  8633. function WebGLBackground(renderer, cubemaps, state, objects, premultipliedAlpha) {
  8634. const clearColor = new Color(0x000000);
  8635. let clearAlpha = 0;
  8636. let planeMesh;
  8637. let boxMesh;
  8638. let currentBackground = null;
  8639. let currentBackgroundVersion = 0;
  8640. let currentTonemapping = null;
  8641. function render(renderList, scene) {
  8642. let forceClear = false;
  8643. let background = scene.isScene === true ? scene.background : null;
  8644. if (background && background.isTexture) {
  8645. background = cubemaps.get(background);
  8646. } // Ignore background in AR
  8647. // TODO: Reconsider this.
  8648. const xr = renderer.xr;
  8649. const session = xr.getSession && xr.getSession();
  8650. if (session && session.environmentBlendMode === 'additive') {
  8651. background = null;
  8652. }
  8653. if (background === null) {
  8654. setClear(clearColor, clearAlpha);
  8655. } else if (background && background.isColor) {
  8656. setClear(background, 1);
  8657. forceClear = true;
  8658. }
  8659. if (renderer.autoClear || forceClear) {
  8660. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  8661. }
  8662. if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
  8663. if (boxMesh === undefined) {
  8664. boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
  8665. name: 'BackgroundCubeMaterial',
  8666. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  8667. vertexShader: ShaderLib.cube.vertexShader,
  8668. fragmentShader: ShaderLib.cube.fragmentShader,
  8669. side: BackSide,
  8670. depthTest: false,
  8671. depthWrite: false,
  8672. fog: false
  8673. }));
  8674. boxMesh.geometry.deleteAttribute('normal');
  8675. boxMesh.geometry.deleteAttribute('uv');
  8676. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  8677. this.matrixWorld.copyPosition(camera.matrixWorld);
  8678. }; // enable code injection for non-built-in material
  8679. Object.defineProperty(boxMesh.material, 'envMap', {
  8680. get: function () {
  8681. return this.uniforms.envMap.value;
  8682. }
  8683. });
  8684. objects.update(boxMesh);
  8685. }
  8686. boxMesh.material.uniforms.envMap.value = background;
  8687. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background._needsFlipEnvMap ? -1 : 1;
  8688. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8689. boxMesh.material.needsUpdate = true;
  8690. currentBackground = background;
  8691. currentBackgroundVersion = background.version;
  8692. currentTonemapping = renderer.toneMapping;
  8693. } // push to the pre-sorted opaque render list
  8694. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  8695. } else if (background && background.isTexture) {
  8696. if (planeMesh === undefined) {
  8697. planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
  8698. name: 'BackgroundMaterial',
  8699. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  8700. vertexShader: ShaderLib.background.vertexShader,
  8701. fragmentShader: ShaderLib.background.fragmentShader,
  8702. side: FrontSide,
  8703. depthTest: false,
  8704. depthWrite: false,
  8705. fog: false
  8706. }));
  8707. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  8708. Object.defineProperty(planeMesh.material, 'map', {
  8709. get: function () {
  8710. return this.uniforms.t2D.value;
  8711. }
  8712. });
  8713. objects.update(planeMesh);
  8714. }
  8715. planeMesh.material.uniforms.t2D.value = background;
  8716. if (background.matrixAutoUpdate === true) {
  8717. background.updateMatrix();
  8718. }
  8719. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  8720. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8721. planeMesh.material.needsUpdate = true;
  8722. currentBackground = background;
  8723. currentBackgroundVersion = background.version;
  8724. currentTonemapping = renderer.toneMapping;
  8725. } // push to the pre-sorted opaque render list
  8726. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  8727. }
  8728. }
  8729. function setClear(color, alpha) {
  8730. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  8731. }
  8732. return {
  8733. getClearColor: function () {
  8734. return clearColor;
  8735. },
  8736. setClearColor: function (color, alpha = 1) {
  8737. clearColor.set(color);
  8738. clearAlpha = alpha;
  8739. setClear(clearColor, clearAlpha);
  8740. },
  8741. getClearAlpha: function () {
  8742. return clearAlpha;
  8743. },
  8744. setClearAlpha: function (alpha) {
  8745. clearAlpha = alpha;
  8746. setClear(clearColor, clearAlpha);
  8747. },
  8748. render: render
  8749. };
  8750. }
  8751. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  8752. const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  8753. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  8754. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8755. const bindingStates = {};
  8756. const defaultState = createBindingState(null);
  8757. let currentState = defaultState;
  8758. function setup(object, material, program, geometry, index) {
  8759. let updateBuffers = false;
  8760. if (vaoAvailable) {
  8761. const state = getBindingState(geometry, program, material);
  8762. if (currentState !== state) {
  8763. currentState = state;
  8764. bindVertexArrayObject(currentState.object);
  8765. }
  8766. updateBuffers = needsUpdate(geometry, index);
  8767. if (updateBuffers) saveCache(geometry, index);
  8768. } else {
  8769. const wireframe = material.wireframe === true;
  8770. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  8771. currentState.geometry = geometry.id;
  8772. currentState.program = program.id;
  8773. currentState.wireframe = wireframe;
  8774. updateBuffers = true;
  8775. }
  8776. }
  8777. if (object.isInstancedMesh === true) {
  8778. updateBuffers = true;
  8779. }
  8780. if (index !== null) {
  8781. attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
  8782. }
  8783. if (updateBuffers) {
  8784. setupVertexAttributes(object, material, program, geometry);
  8785. if (index !== null) {
  8786. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
  8787. }
  8788. }
  8789. }
  8790. function createVertexArrayObject() {
  8791. if (capabilities.isWebGL2) return gl.createVertexArray();
  8792. return extension.createVertexArrayOES();
  8793. }
  8794. function bindVertexArrayObject(vao) {
  8795. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  8796. return extension.bindVertexArrayOES(vao);
  8797. }
  8798. function deleteVertexArrayObject(vao) {
  8799. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  8800. return extension.deleteVertexArrayOES(vao);
  8801. }
  8802. function getBindingState(geometry, program, material) {
  8803. const wireframe = material.wireframe === true;
  8804. let programMap = bindingStates[geometry.id];
  8805. if (programMap === undefined) {
  8806. programMap = {};
  8807. bindingStates[geometry.id] = programMap;
  8808. }
  8809. let stateMap = programMap[program.id];
  8810. if (stateMap === undefined) {
  8811. stateMap = {};
  8812. programMap[program.id] = stateMap;
  8813. }
  8814. let state = stateMap[wireframe];
  8815. if (state === undefined) {
  8816. state = createBindingState(createVertexArrayObject());
  8817. stateMap[wireframe] = state;
  8818. }
  8819. return state;
  8820. }
  8821. function createBindingState(vao) {
  8822. const newAttributes = [];
  8823. const enabledAttributes = [];
  8824. const attributeDivisors = [];
  8825. for (let i = 0; i < maxVertexAttributes; i++) {
  8826. newAttributes[i] = 0;
  8827. enabledAttributes[i] = 0;
  8828. attributeDivisors[i] = 0;
  8829. }
  8830. return {
  8831. // for backward compatibility on non-VAO support browser
  8832. geometry: null,
  8833. program: null,
  8834. wireframe: false,
  8835. newAttributes: newAttributes,
  8836. enabledAttributes: enabledAttributes,
  8837. attributeDivisors: attributeDivisors,
  8838. object: vao,
  8839. attributes: {},
  8840. index: null
  8841. };
  8842. }
  8843. function needsUpdate(geometry, index) {
  8844. const cachedAttributes = currentState.attributes;
  8845. const geometryAttributes = geometry.attributes;
  8846. let attributesNum = 0;
  8847. for (const key in geometryAttributes) {
  8848. const cachedAttribute = cachedAttributes[key];
  8849. const geometryAttribute = geometryAttributes[key];
  8850. if (cachedAttribute === undefined) return true;
  8851. if (cachedAttribute.attribute !== geometryAttribute) return true;
  8852. if (cachedAttribute.data !== geometryAttribute.data) return true;
  8853. attributesNum++;
  8854. }
  8855. if (currentState.attributesNum !== attributesNum) return true;
  8856. if (currentState.index !== index) return true;
  8857. return false;
  8858. }
  8859. function saveCache(geometry, index) {
  8860. const cache = {};
  8861. const attributes = geometry.attributes;
  8862. let attributesNum = 0;
  8863. for (const key in attributes) {
  8864. const attribute = attributes[key];
  8865. const data = {};
  8866. data.attribute = attribute;
  8867. if (attribute.data) {
  8868. data.data = attribute.data;
  8869. }
  8870. cache[key] = data;
  8871. attributesNum++;
  8872. }
  8873. currentState.attributes = cache;
  8874. currentState.attributesNum = attributesNum;
  8875. currentState.index = index;
  8876. }
  8877. function initAttributes() {
  8878. const newAttributes = currentState.newAttributes;
  8879. for (let i = 0, il = newAttributes.length; i < il; i++) {
  8880. newAttributes[i] = 0;
  8881. }
  8882. }
  8883. function enableAttribute(attribute) {
  8884. enableAttributeAndDivisor(attribute, 0);
  8885. }
  8886. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  8887. const newAttributes = currentState.newAttributes;
  8888. const enabledAttributes = currentState.enabledAttributes;
  8889. const attributeDivisors = currentState.attributeDivisors;
  8890. newAttributes[attribute] = 1;
  8891. if (enabledAttributes[attribute] === 0) {
  8892. gl.enableVertexAttribArray(attribute);
  8893. enabledAttributes[attribute] = 1;
  8894. }
  8895. if (attributeDivisors[attribute] !== meshPerAttribute) {
  8896. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  8897. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  8898. attributeDivisors[attribute] = meshPerAttribute;
  8899. }
  8900. }
  8901. function disableUnusedAttributes() {
  8902. const newAttributes = currentState.newAttributes;
  8903. const enabledAttributes = currentState.enabledAttributes;
  8904. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  8905. if (enabledAttributes[i] !== newAttributes[i]) {
  8906. gl.disableVertexAttribArray(i);
  8907. enabledAttributes[i] = 0;
  8908. }
  8909. }
  8910. }
  8911. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  8912. if (capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT)) {
  8913. gl.vertexAttribIPointer(index, size, type, stride, offset);
  8914. } else {
  8915. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  8916. }
  8917. }
  8918. function setupVertexAttributes(object, material, program, geometry) {
  8919. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  8920. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  8921. }
  8922. initAttributes();
  8923. const geometryAttributes = geometry.attributes;
  8924. const programAttributes = program.getAttributes();
  8925. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8926. for (const name in programAttributes) {
  8927. const programAttribute = programAttributes[name];
  8928. if (programAttribute >= 0) {
  8929. const geometryAttribute = geometryAttributes[name];
  8930. if (geometryAttribute !== undefined) {
  8931. const normalized = geometryAttribute.normalized;
  8932. const size = geometryAttribute.itemSize;
  8933. const attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  8934. if (attribute === undefined) continue;
  8935. const buffer = attribute.buffer;
  8936. const type = attribute.type;
  8937. const bytesPerElement = attribute.bytesPerElement;
  8938. if (geometryAttribute.isInterleavedBufferAttribute) {
  8939. const data = geometryAttribute.data;
  8940. const stride = data.stride;
  8941. const offset = geometryAttribute.offset;
  8942. if (data && data.isInstancedInterleavedBuffer) {
  8943. enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  8944. if (geometry._maxInstanceCount === undefined) {
  8945. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8946. }
  8947. } else {
  8948. enableAttribute(programAttribute);
  8949. }
  8950. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8951. vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  8952. } else {
  8953. if (geometryAttribute.isInstancedBufferAttribute) {
  8954. enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  8955. if (geometry._maxInstanceCount === undefined) {
  8956. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8957. }
  8958. } else {
  8959. enableAttribute(programAttribute);
  8960. }
  8961. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8962. vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  8963. }
  8964. } else if (name === 'instanceMatrix') {
  8965. const attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  8966. if (attribute === undefined) continue;
  8967. const buffer = attribute.buffer;
  8968. const type = attribute.type;
  8969. enableAttributeAndDivisor(programAttribute + 0, 1);
  8970. enableAttributeAndDivisor(programAttribute + 1, 1);
  8971. enableAttributeAndDivisor(programAttribute + 2, 1);
  8972. enableAttributeAndDivisor(programAttribute + 3, 1);
  8973. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8974. gl.vertexAttribPointer(programAttribute + 0, 4, type, false, 64, 0);
  8975. gl.vertexAttribPointer(programAttribute + 1, 4, type, false, 64, 16);
  8976. gl.vertexAttribPointer(programAttribute + 2, 4, type, false, 64, 32);
  8977. gl.vertexAttribPointer(programAttribute + 3, 4, type, false, 64, 48);
  8978. } else if (name === 'instanceColor') {
  8979. const attribute = attributes.get(object.instanceColor); // TODO Attribute may not be available on context restore
  8980. if (attribute === undefined) continue;
  8981. const buffer = attribute.buffer;
  8982. const type = attribute.type;
  8983. enableAttributeAndDivisor(programAttribute, 1);
  8984. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8985. gl.vertexAttribPointer(programAttribute, 3, type, false, 12, 0);
  8986. } else if (materialDefaultAttributeValues !== undefined) {
  8987. const value = materialDefaultAttributeValues[name];
  8988. if (value !== undefined) {
  8989. switch (value.length) {
  8990. case 2:
  8991. gl.vertexAttrib2fv(programAttribute, value);
  8992. break;
  8993. case 3:
  8994. gl.vertexAttrib3fv(programAttribute, value);
  8995. break;
  8996. case 4:
  8997. gl.vertexAttrib4fv(programAttribute, value);
  8998. break;
  8999. default:
  9000. gl.vertexAttrib1fv(programAttribute, value);
  9001. }
  9002. }
  9003. }
  9004. }
  9005. }
  9006. disableUnusedAttributes();
  9007. }
  9008. function dispose() {
  9009. reset();
  9010. for (const geometryId in bindingStates) {
  9011. const programMap = bindingStates[geometryId];
  9012. for (const programId in programMap) {
  9013. const stateMap = programMap[programId];
  9014. for (const wireframe in stateMap) {
  9015. deleteVertexArrayObject(stateMap[wireframe].object);
  9016. delete stateMap[wireframe];
  9017. }
  9018. delete programMap[programId];
  9019. }
  9020. delete bindingStates[geometryId];
  9021. }
  9022. }
  9023. function releaseStatesOfGeometry(geometry) {
  9024. if (bindingStates[geometry.id] === undefined) return;
  9025. const programMap = bindingStates[geometry.id];
  9026. for (const programId in programMap) {
  9027. const stateMap = programMap[programId];
  9028. for (const wireframe in stateMap) {
  9029. deleteVertexArrayObject(stateMap[wireframe].object);
  9030. delete stateMap[wireframe];
  9031. }
  9032. delete programMap[programId];
  9033. }
  9034. delete bindingStates[geometry.id];
  9035. }
  9036. function releaseStatesOfProgram(program) {
  9037. for (const geometryId in bindingStates) {
  9038. const programMap = bindingStates[geometryId];
  9039. if (programMap[program.id] === undefined) continue;
  9040. const stateMap = programMap[program.id];
  9041. for (const wireframe in stateMap) {
  9042. deleteVertexArrayObject(stateMap[wireframe].object);
  9043. delete stateMap[wireframe];
  9044. }
  9045. delete programMap[program.id];
  9046. }
  9047. }
  9048. function reset() {
  9049. resetDefaultState();
  9050. if (currentState === defaultState) return;
  9051. currentState = defaultState;
  9052. bindVertexArrayObject(currentState.object);
  9053. } // for backward-compatilibity
  9054. function resetDefaultState() {
  9055. defaultState.geometry = null;
  9056. defaultState.program = null;
  9057. defaultState.wireframe = false;
  9058. }
  9059. return {
  9060. setup: setup,
  9061. reset: reset,
  9062. resetDefaultState: resetDefaultState,
  9063. dispose: dispose,
  9064. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9065. releaseStatesOfProgram: releaseStatesOfProgram,
  9066. initAttributes: initAttributes,
  9067. enableAttribute: enableAttribute,
  9068. disableUnusedAttributes: disableUnusedAttributes
  9069. };
  9070. }
  9071. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  9072. const isWebGL2 = capabilities.isWebGL2;
  9073. let mode;
  9074. function setMode(value) {
  9075. mode = value;
  9076. }
  9077. function render(start, count) {
  9078. gl.drawArrays(mode, start, count);
  9079. info.update(count, mode, 1);
  9080. }
  9081. function renderInstances(start, count, primcount) {
  9082. if (primcount === 0) return;
  9083. let extension, methodName;
  9084. if (isWebGL2) {
  9085. extension = gl;
  9086. methodName = 'drawArraysInstanced';
  9087. } else {
  9088. extension = extensions.get('ANGLE_instanced_arrays');
  9089. methodName = 'drawArraysInstancedANGLE';
  9090. if (extension === null) {
  9091. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9092. return;
  9093. }
  9094. }
  9095. extension[methodName](mode, start, count, primcount);
  9096. info.update(count, mode, primcount);
  9097. } //
  9098. this.setMode = setMode;
  9099. this.render = render;
  9100. this.renderInstances = renderInstances;
  9101. }
  9102. function WebGLCapabilities(gl, extensions, parameters) {
  9103. let maxAnisotropy;
  9104. function getMaxAnisotropy() {
  9105. if (maxAnisotropy !== undefined) return maxAnisotropy;
  9106. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  9107. const extension = extensions.get('EXT_texture_filter_anisotropic');
  9108. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  9109. } else {
  9110. maxAnisotropy = 0;
  9111. }
  9112. return maxAnisotropy;
  9113. }
  9114. function getMaxPrecision(precision) {
  9115. if (precision === 'highp') {
  9116. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
  9117. return 'highp';
  9118. }
  9119. precision = 'mediump';
  9120. }
  9121. if (precision === 'mediump') {
  9122. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
  9123. return 'mediump';
  9124. }
  9125. }
  9126. return 'lowp';
  9127. }
  9128. /* eslint-disable no-undef */
  9129. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  9130. /* eslint-enable no-undef */
  9131. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9132. const maxPrecision = getMaxPrecision(precision);
  9133. if (maxPrecision !== precision) {
  9134. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  9135. precision = maxPrecision;
  9136. }
  9137. const drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers');
  9138. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9139. const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  9140. const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9141. const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  9142. const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9143. const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  9144. const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
  9145. const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
  9146. const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9147. const vertexTextures = maxVertexTextures > 0;
  9148. const floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float');
  9149. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9150. const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
  9151. return {
  9152. isWebGL2: isWebGL2,
  9153. drawBuffers: drawBuffers,
  9154. getMaxAnisotropy: getMaxAnisotropy,
  9155. getMaxPrecision: getMaxPrecision,
  9156. precision: precision,
  9157. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9158. maxTextures: maxTextures,
  9159. maxVertexTextures: maxVertexTextures,
  9160. maxTextureSize: maxTextureSize,
  9161. maxCubemapSize: maxCubemapSize,
  9162. maxAttributes: maxAttributes,
  9163. maxVertexUniforms: maxVertexUniforms,
  9164. maxVaryings: maxVaryings,
  9165. maxFragmentUniforms: maxFragmentUniforms,
  9166. vertexTextures: vertexTextures,
  9167. floatFragmentTextures: floatFragmentTextures,
  9168. floatVertexTextures: floatVertexTextures,
  9169. maxSamples: maxSamples
  9170. };
  9171. }
  9172. function WebGLClipping(properties) {
  9173. const scope = this;
  9174. let globalState = null,
  9175. numGlobalPlanes = 0,
  9176. localClippingEnabled = false,
  9177. renderingShadows = false;
  9178. const plane = new Plane(),
  9179. viewNormalMatrix = new Matrix3(),
  9180. uniform = {
  9181. value: null,
  9182. needsUpdate: false
  9183. };
  9184. this.uniform = uniform;
  9185. this.numPlanes = 0;
  9186. this.numIntersection = 0;
  9187. this.init = function (planes, enableLocalClipping, camera) {
  9188. const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  9189. // run another frame in order to reset the state:
  9190. numGlobalPlanes !== 0 || localClippingEnabled;
  9191. localClippingEnabled = enableLocalClipping;
  9192. globalState = projectPlanes(planes, camera, 0);
  9193. numGlobalPlanes = planes.length;
  9194. return enabled;
  9195. };
  9196. this.beginShadows = function () {
  9197. renderingShadows = true;
  9198. projectPlanes(null);
  9199. };
  9200. this.endShadows = function () {
  9201. renderingShadows = false;
  9202. resetGlobalState();
  9203. };
  9204. this.setState = function (material, camera, useCache) {
  9205. const planes = material.clippingPlanes,
  9206. clipIntersection = material.clipIntersection,
  9207. clipShadows = material.clipShadows;
  9208. const materialProperties = properties.get(material);
  9209. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  9210. // there's no local clipping
  9211. if (renderingShadows) {
  9212. // there's no global clipping
  9213. projectPlanes(null);
  9214. } else {
  9215. resetGlobalState();
  9216. }
  9217. } else {
  9218. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9219. lGlobal = nGlobal * 4;
  9220. let dstArray = materialProperties.clippingState || null;
  9221. uniform.value = dstArray; // ensure unique state
  9222. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  9223. for (let i = 0; i !== lGlobal; ++i) {
  9224. dstArray[i] = globalState[i];
  9225. }
  9226. materialProperties.clippingState = dstArray;
  9227. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9228. this.numPlanes += nGlobal;
  9229. }
  9230. };
  9231. function resetGlobalState() {
  9232. if (uniform.value !== globalState) {
  9233. uniform.value = globalState;
  9234. uniform.needsUpdate = numGlobalPlanes > 0;
  9235. }
  9236. scope.numPlanes = numGlobalPlanes;
  9237. scope.numIntersection = 0;
  9238. }
  9239. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  9240. const nPlanes = planes !== null ? planes.length : 0;
  9241. let dstArray = null;
  9242. if (nPlanes !== 0) {
  9243. dstArray = uniform.value;
  9244. if (skipTransform !== true || dstArray === null) {
  9245. const flatSize = dstOffset + nPlanes * 4,
  9246. viewMatrix = camera.matrixWorldInverse;
  9247. viewNormalMatrix.getNormalMatrix(viewMatrix);
  9248. if (dstArray === null || dstArray.length < flatSize) {
  9249. dstArray = new Float32Array(flatSize);
  9250. }
  9251. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  9252. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  9253. plane.normal.toArray(dstArray, i4);
  9254. dstArray[i4 + 3] = plane.constant;
  9255. }
  9256. }
  9257. uniform.value = dstArray;
  9258. uniform.needsUpdate = true;
  9259. }
  9260. scope.numPlanes = nPlanes;
  9261. scope.numIntersection = 0;
  9262. return dstArray;
  9263. }
  9264. }
  9265. function WebGLCubeMaps(renderer) {
  9266. let cubemaps = new WeakMap();
  9267. function mapTextureMapping(texture, mapping) {
  9268. if (mapping === EquirectangularReflectionMapping) {
  9269. texture.mapping = CubeReflectionMapping;
  9270. } else if (mapping === EquirectangularRefractionMapping) {
  9271. texture.mapping = CubeRefractionMapping;
  9272. }
  9273. return texture;
  9274. }
  9275. function get(texture) {
  9276. if (texture && texture.isTexture) {
  9277. const mapping = texture.mapping;
  9278. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  9279. if (cubemaps.has(texture)) {
  9280. const cubemap = cubemaps.get(texture).texture;
  9281. return mapTextureMapping(cubemap, texture.mapping);
  9282. } else {
  9283. const image = texture.image;
  9284. if (image && image.height > 0) {
  9285. const currentRenderTarget = renderer.getRenderTarget();
  9286. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  9287. renderTarget.fromEquirectangularTexture(renderer, texture);
  9288. cubemaps.set(texture, renderTarget);
  9289. renderer.setRenderTarget(currentRenderTarget);
  9290. texture.addEventListener('dispose', onTextureDispose);
  9291. return mapTextureMapping(renderTarget.texture, texture.mapping);
  9292. } else {
  9293. // image not yet ready. try the conversion next frame
  9294. return null;
  9295. }
  9296. }
  9297. }
  9298. }
  9299. return texture;
  9300. }
  9301. function onTextureDispose(event) {
  9302. const texture = event.target;
  9303. texture.removeEventListener('dispose', onTextureDispose);
  9304. const cubemap = cubemaps.get(texture);
  9305. if (cubemap !== undefined) {
  9306. cubemaps.delete(texture);
  9307. cubemap.dispose();
  9308. }
  9309. }
  9310. function dispose() {
  9311. cubemaps = new WeakMap();
  9312. }
  9313. return {
  9314. get: get,
  9315. dispose: dispose
  9316. };
  9317. }
  9318. function WebGLExtensions(gl) {
  9319. const extensions = {};
  9320. function getExtension(name) {
  9321. if (extensions[name] !== undefined) {
  9322. return extensions[name];
  9323. }
  9324. let extension;
  9325. switch (name) {
  9326. case 'WEBGL_depth_texture':
  9327. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  9328. break;
  9329. case 'EXT_texture_filter_anisotropic':
  9330. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  9331. break;
  9332. case 'WEBGL_compressed_texture_s3tc':
  9333. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  9334. break;
  9335. case 'WEBGL_compressed_texture_pvrtc':
  9336. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  9337. break;
  9338. default:
  9339. extension = gl.getExtension(name);
  9340. }
  9341. extensions[name] = extension;
  9342. return extension;
  9343. }
  9344. return {
  9345. has: function (name) {
  9346. return getExtension(name) !== null;
  9347. },
  9348. init: function (capabilities) {
  9349. if (capabilities.isWebGL2) {
  9350. getExtension('EXT_color_buffer_float');
  9351. } else {
  9352. getExtension('WEBGL_depth_texture');
  9353. getExtension('OES_texture_float');
  9354. getExtension('OES_texture_half_float');
  9355. getExtension('OES_texture_half_float_linear');
  9356. getExtension('OES_standard_derivatives');
  9357. getExtension('OES_element_index_uint');
  9358. getExtension('OES_vertex_array_object');
  9359. getExtension('ANGLE_instanced_arrays');
  9360. }
  9361. getExtension('OES_texture_float_linear');
  9362. getExtension('EXT_color_buffer_half_float');
  9363. },
  9364. get: function (name) {
  9365. const extension = getExtension(name);
  9366. if (extension === null) {
  9367. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  9368. }
  9369. return extension;
  9370. }
  9371. };
  9372. }
  9373. function WebGLGeometries(gl, attributes, info, bindingStates) {
  9374. const geometries = {};
  9375. const wireframeAttributes = new WeakMap();
  9376. function onGeometryDispose(event) {
  9377. const geometry = event.target;
  9378. if (geometry.index !== null) {
  9379. attributes.remove(geometry.index);
  9380. }
  9381. for (const name in geometry.attributes) {
  9382. attributes.remove(geometry.attributes[name]);
  9383. }
  9384. geometry.removeEventListener('dispose', onGeometryDispose);
  9385. delete geometries[geometry.id];
  9386. const attribute = wireframeAttributes.get(geometry);
  9387. if (attribute) {
  9388. attributes.remove(attribute);
  9389. wireframeAttributes.delete(geometry);
  9390. }
  9391. bindingStates.releaseStatesOfGeometry(geometry);
  9392. if (geometry.isInstancedBufferGeometry === true) {
  9393. delete geometry._maxInstanceCount;
  9394. } //
  9395. info.memory.geometries--;
  9396. }
  9397. function get(object, geometry) {
  9398. if (geometries[geometry.id] === true) return geometry;
  9399. geometry.addEventListener('dispose', onGeometryDispose);
  9400. geometries[geometry.id] = true;
  9401. info.memory.geometries++;
  9402. return geometry;
  9403. }
  9404. function update(geometry) {
  9405. const geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  9406. for (const name in geometryAttributes) {
  9407. attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
  9408. } // morph targets
  9409. const morphAttributes = geometry.morphAttributes;
  9410. for (const name in morphAttributes) {
  9411. const array = morphAttributes[name];
  9412. for (let i = 0, l = array.length; i < l; i++) {
  9413. attributes.update(array[i], gl.ARRAY_BUFFER);
  9414. }
  9415. }
  9416. }
  9417. function updateWireframeAttribute(geometry) {
  9418. const indices = [];
  9419. const geometryIndex = geometry.index;
  9420. const geometryPosition = geometry.attributes.position;
  9421. let version = 0;
  9422. if (geometryIndex !== null) {
  9423. const array = geometryIndex.array;
  9424. version = geometryIndex.version;
  9425. for (let i = 0, l = array.length; i < l; i += 3) {
  9426. const a = array[i + 0];
  9427. const b = array[i + 1];
  9428. const c = array[i + 2];
  9429. indices.push(a, b, b, c, c, a);
  9430. }
  9431. } else {
  9432. const array = geometryPosition.array;
  9433. version = geometryPosition.version;
  9434. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  9435. const a = i + 0;
  9436. const b = i + 1;
  9437. const c = i + 2;
  9438. indices.push(a, b, b, c, c, a);
  9439. }
  9440. }
  9441. const attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  9442. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  9443. //
  9444. const previousAttribute = wireframeAttributes.get(geometry);
  9445. if (previousAttribute) attributes.remove(previousAttribute); //
  9446. wireframeAttributes.set(geometry, attribute);
  9447. }
  9448. function getWireframeAttribute(geometry) {
  9449. const currentAttribute = wireframeAttributes.get(geometry);
  9450. if (currentAttribute) {
  9451. const geometryIndex = geometry.index;
  9452. if (geometryIndex !== null) {
  9453. // if the attribute is obsolete, create a new one
  9454. if (currentAttribute.version < geometryIndex.version) {
  9455. updateWireframeAttribute(geometry);
  9456. }
  9457. }
  9458. } else {
  9459. updateWireframeAttribute(geometry);
  9460. }
  9461. return wireframeAttributes.get(geometry);
  9462. }
  9463. return {
  9464. get: get,
  9465. update: update,
  9466. getWireframeAttribute: getWireframeAttribute
  9467. };
  9468. }
  9469. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  9470. const isWebGL2 = capabilities.isWebGL2;
  9471. let mode;
  9472. function setMode(value) {
  9473. mode = value;
  9474. }
  9475. let type, bytesPerElement;
  9476. function setIndex(value) {
  9477. type = value.type;
  9478. bytesPerElement = value.bytesPerElement;
  9479. }
  9480. function render(start, count) {
  9481. gl.drawElements(mode, count, type, start * bytesPerElement);
  9482. info.update(count, mode, 1);
  9483. }
  9484. function renderInstances(start, count, primcount) {
  9485. if (primcount === 0) return;
  9486. let extension, methodName;
  9487. if (isWebGL2) {
  9488. extension = gl;
  9489. methodName = 'drawElementsInstanced';
  9490. } else {
  9491. extension = extensions.get('ANGLE_instanced_arrays');
  9492. methodName = 'drawElementsInstancedANGLE';
  9493. if (extension === null) {
  9494. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9495. return;
  9496. }
  9497. }
  9498. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  9499. info.update(count, mode, primcount);
  9500. } //
  9501. this.setMode = setMode;
  9502. this.setIndex = setIndex;
  9503. this.render = render;
  9504. this.renderInstances = renderInstances;
  9505. }
  9506. function WebGLInfo(gl) {
  9507. const memory = {
  9508. geometries: 0,
  9509. textures: 0
  9510. };
  9511. const render = {
  9512. frame: 0,
  9513. calls: 0,
  9514. triangles: 0,
  9515. points: 0,
  9516. lines: 0
  9517. };
  9518. function update(count, mode, instanceCount) {
  9519. render.calls++;
  9520. switch (mode) {
  9521. case gl.TRIANGLES:
  9522. render.triangles += instanceCount * (count / 3);
  9523. break;
  9524. case gl.LINES:
  9525. render.lines += instanceCount * (count / 2);
  9526. break;
  9527. case gl.LINE_STRIP:
  9528. render.lines += instanceCount * (count - 1);
  9529. break;
  9530. case gl.LINE_LOOP:
  9531. render.lines += instanceCount * count;
  9532. break;
  9533. case gl.POINTS:
  9534. render.points += instanceCount * count;
  9535. break;
  9536. default:
  9537. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  9538. break;
  9539. }
  9540. }
  9541. function reset() {
  9542. render.frame++;
  9543. render.calls = 0;
  9544. render.triangles = 0;
  9545. render.points = 0;
  9546. render.lines = 0;
  9547. }
  9548. return {
  9549. memory: memory,
  9550. render: render,
  9551. programs: null,
  9552. autoReset: true,
  9553. reset: reset,
  9554. update: update
  9555. };
  9556. }
  9557. function numericalSort(a, b) {
  9558. return a[0] - b[0];
  9559. }
  9560. function absNumericalSort(a, b) {
  9561. return Math.abs(b[1]) - Math.abs(a[1]);
  9562. }
  9563. function WebGLMorphtargets(gl) {
  9564. const influencesList = {};
  9565. const morphInfluences = new Float32Array(8);
  9566. const workInfluences = [];
  9567. for (let i = 0; i < 8; i++) {
  9568. workInfluences[i] = [i, 0];
  9569. }
  9570. function update(object, geometry, material, program) {
  9571. const objectInfluences = object.morphTargetInfluences; // When object doesn't have morph target influences defined, we treat it as a 0-length array
  9572. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  9573. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  9574. let influences = influencesList[geometry.id];
  9575. if (influences === undefined) {
  9576. // initialise list
  9577. influences = [];
  9578. for (let i = 0; i < length; i++) {
  9579. influences[i] = [i, 0];
  9580. }
  9581. influencesList[geometry.id] = influences;
  9582. } // Collect influences
  9583. for (let i = 0; i < length; i++) {
  9584. const influence = influences[i];
  9585. influence[0] = i;
  9586. influence[1] = objectInfluences[i];
  9587. }
  9588. influences.sort(absNumericalSort);
  9589. for (let i = 0; i < 8; i++) {
  9590. if (i < length && influences[i][1]) {
  9591. workInfluences[i][0] = influences[i][0];
  9592. workInfluences[i][1] = influences[i][1];
  9593. } else {
  9594. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  9595. workInfluences[i][1] = 0;
  9596. }
  9597. }
  9598. workInfluences.sort(numericalSort);
  9599. const morphTargets = material.morphTargets && geometry.morphAttributes.position;
  9600. const morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  9601. let morphInfluencesSum = 0;
  9602. for (let i = 0; i < 8; i++) {
  9603. const influence = workInfluences[i];
  9604. const index = influence[0];
  9605. const value = influence[1];
  9606. if (index !== Number.MAX_SAFE_INTEGER && value) {
  9607. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  9608. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  9609. }
  9610. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  9611. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  9612. }
  9613. morphInfluences[i] = value;
  9614. morphInfluencesSum += value;
  9615. } else {
  9616. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  9617. geometry.deleteAttribute('morphTarget' + i);
  9618. }
  9619. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  9620. geometry.deleteAttribute('morphNormal' + i);
  9621. }
  9622. morphInfluences[i] = 0;
  9623. }
  9624. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  9625. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  9626. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  9627. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  9628. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  9629. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  9630. }
  9631. return {
  9632. update: update
  9633. };
  9634. }
  9635. function WebGLObjects(gl, geometries, attributes, info) {
  9636. let updateMap = new WeakMap();
  9637. function update(object) {
  9638. const frame = info.render.frame;
  9639. const geometry = object.geometry;
  9640. const buffergeometry = geometries.get(object, geometry); // Update once per frame
  9641. if (updateMap.get(buffergeometry) !== frame) {
  9642. geometries.update(buffergeometry);
  9643. updateMap.set(buffergeometry, frame);
  9644. }
  9645. if (object.isInstancedMesh) {
  9646. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  9647. object.addEventListener('dispose', onInstancedMeshDispose);
  9648. }
  9649. attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
  9650. if (object.instanceColor !== null) {
  9651. attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
  9652. }
  9653. }
  9654. return buffergeometry;
  9655. }
  9656. function dispose() {
  9657. updateMap = new WeakMap();
  9658. }
  9659. function onInstancedMeshDispose(event) {
  9660. const instancedMesh = event.target;
  9661. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  9662. attributes.remove(instancedMesh.instanceMatrix);
  9663. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  9664. }
  9665. return {
  9666. update: update,
  9667. dispose: dispose
  9668. };
  9669. }
  9670. class DataTexture2DArray extends Texture {
  9671. constructor(data = null, width = 1, height = 1, depth = 1) {
  9672. super(null);
  9673. this.image = {
  9674. data,
  9675. width,
  9676. height,
  9677. depth
  9678. };
  9679. this.magFilter = NearestFilter;
  9680. this.minFilter = NearestFilter;
  9681. this.wrapR = ClampToEdgeWrapping;
  9682. this.generateMipmaps = false;
  9683. this.flipY = false;
  9684. this.unpackAlignment = 1;
  9685. this.needsUpdate = true;
  9686. }
  9687. }
  9688. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  9689. class DataTexture3D extends Texture {
  9690. constructor(data = null, width = 1, height = 1, depth = 1) {
  9691. // We're going to add .setXXX() methods for setting properties later.
  9692. // Users can still set in DataTexture3D directly.
  9693. //
  9694. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  9695. // texture.anisotropy = 16;
  9696. //
  9697. // See #14839
  9698. super(null);
  9699. this.image = {
  9700. data,
  9701. width,
  9702. height,
  9703. depth
  9704. };
  9705. this.magFilter = NearestFilter;
  9706. this.minFilter = NearestFilter;
  9707. this.wrapR = ClampToEdgeWrapping;
  9708. this.generateMipmaps = false;
  9709. this.flipY = false;
  9710. this.unpackAlignment = 1;
  9711. this.needsUpdate = true;
  9712. }
  9713. }
  9714. DataTexture3D.prototype.isDataTexture3D = true;
  9715. /**
  9716. * Uniforms of a program.
  9717. * Those form a tree structure with a special top-level container for the root,
  9718. * which you get by calling 'new WebGLUniforms( gl, program )'.
  9719. *
  9720. *
  9721. * Properties of inner nodes including the top-level container:
  9722. *
  9723. * .seq - array of nested uniforms
  9724. * .map - nested uniforms by name
  9725. *
  9726. *
  9727. * Methods of all nodes except the top-level container:
  9728. *
  9729. * .setValue( gl, value, [textures] )
  9730. *
  9731. * uploads a uniform value(s)
  9732. * the 'textures' parameter is needed for sampler uniforms
  9733. *
  9734. *
  9735. * Static methods of the top-level container (textures factorizations):
  9736. *
  9737. * .upload( gl, seq, values, textures )
  9738. *
  9739. * sets uniforms in 'seq' to 'values[id].value'
  9740. *
  9741. * .seqWithValue( seq, values ) : filteredSeq
  9742. *
  9743. * filters 'seq' entries with corresponding entry in values
  9744. *
  9745. *
  9746. * Methods of the top-level container (textures factorizations):
  9747. *
  9748. * .setValue( gl, name, value, textures )
  9749. *
  9750. * sets uniform with name 'name' to 'value'
  9751. *
  9752. * .setOptional( gl, obj, prop )
  9753. *
  9754. * like .set for an optional property of the object
  9755. *
  9756. */
  9757. const emptyTexture = new Texture();
  9758. const emptyTexture2dArray = new DataTexture2DArray();
  9759. const emptyTexture3d = new DataTexture3D();
  9760. const emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  9761. // Array Caches (provide typed arrays for temporary by size)
  9762. const arrayCacheF32 = [];
  9763. const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  9764. const mat4array = new Float32Array(16);
  9765. const mat3array = new Float32Array(9);
  9766. const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  9767. function flatten(array, nBlocks, blockSize) {
  9768. const firstElem = array[0];
  9769. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  9770. // see http://jacksondunstan.com/articles/983
  9771. const n = nBlocks * blockSize;
  9772. let r = arrayCacheF32[n];
  9773. if (r === undefined) {
  9774. r = new Float32Array(n);
  9775. arrayCacheF32[n] = r;
  9776. }
  9777. if (nBlocks !== 0) {
  9778. firstElem.toArray(r, 0);
  9779. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  9780. offset += blockSize;
  9781. array[i].toArray(r, offset);
  9782. }
  9783. }
  9784. return r;
  9785. }
  9786. function arraysEqual(a, b) {
  9787. if (a.length !== b.length) return false;
  9788. for (let i = 0, l = a.length; i < l; i++) {
  9789. if (a[i] !== b[i]) return false;
  9790. }
  9791. return true;
  9792. }
  9793. function copyArray(a, b) {
  9794. for (let i = 0, l = b.length; i < l; i++) {
  9795. a[i] = b[i];
  9796. }
  9797. } // Texture unit allocation
  9798. function allocTexUnits(textures, n) {
  9799. let r = arrayCacheI32[n];
  9800. if (r === undefined) {
  9801. r = new Int32Array(n);
  9802. arrayCacheI32[n] = r;
  9803. }
  9804. for (let i = 0; i !== n; ++i) {
  9805. r[i] = textures.allocateTextureUnit();
  9806. }
  9807. return r;
  9808. } // --- Setters ---
  9809. // Note: Defining these methods externally, because they come in a bunch
  9810. // and this way their names minify.
  9811. // Single scalar
  9812. function setValueV1f(gl, v) {
  9813. const cache = this.cache;
  9814. if (cache[0] === v) return;
  9815. gl.uniform1f(this.addr, v);
  9816. cache[0] = v;
  9817. } // Single float vector (from flat array or THREE.VectorN)
  9818. function setValueV2f(gl, v) {
  9819. const cache = this.cache;
  9820. if (v.x !== undefined) {
  9821. if (cache[0] !== v.x || cache[1] !== v.y) {
  9822. gl.uniform2f(this.addr, v.x, v.y);
  9823. cache[0] = v.x;
  9824. cache[1] = v.y;
  9825. }
  9826. } else {
  9827. if (arraysEqual(cache, v)) return;
  9828. gl.uniform2fv(this.addr, v);
  9829. copyArray(cache, v);
  9830. }
  9831. }
  9832. function setValueV3f(gl, v) {
  9833. const cache = this.cache;
  9834. if (v.x !== undefined) {
  9835. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  9836. gl.uniform3f(this.addr, v.x, v.y, v.z);
  9837. cache[0] = v.x;
  9838. cache[1] = v.y;
  9839. cache[2] = v.z;
  9840. }
  9841. } else if (v.r !== undefined) {
  9842. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  9843. gl.uniform3f(this.addr, v.r, v.g, v.b);
  9844. cache[0] = v.r;
  9845. cache[1] = v.g;
  9846. cache[2] = v.b;
  9847. }
  9848. } else {
  9849. if (arraysEqual(cache, v)) return;
  9850. gl.uniform3fv(this.addr, v);
  9851. copyArray(cache, v);
  9852. }
  9853. }
  9854. function setValueV4f(gl, v) {
  9855. const cache = this.cache;
  9856. if (v.x !== undefined) {
  9857. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  9858. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  9859. cache[0] = v.x;
  9860. cache[1] = v.y;
  9861. cache[2] = v.z;
  9862. cache[3] = v.w;
  9863. }
  9864. } else {
  9865. if (arraysEqual(cache, v)) return;
  9866. gl.uniform4fv(this.addr, v);
  9867. copyArray(cache, v);
  9868. }
  9869. } // Single matrix (from flat array or THREE.MatrixN)
  9870. function setValueM2(gl, v) {
  9871. const cache = this.cache;
  9872. const elements = v.elements;
  9873. if (elements === undefined) {
  9874. if (arraysEqual(cache, v)) return;
  9875. gl.uniformMatrix2fv(this.addr, false, v);
  9876. copyArray(cache, v);
  9877. } else {
  9878. if (arraysEqual(cache, elements)) return;
  9879. mat2array.set(elements);
  9880. gl.uniformMatrix2fv(this.addr, false, mat2array);
  9881. copyArray(cache, elements);
  9882. }
  9883. }
  9884. function setValueM3(gl, v) {
  9885. const cache = this.cache;
  9886. const elements = v.elements;
  9887. if (elements === undefined) {
  9888. if (arraysEqual(cache, v)) return;
  9889. gl.uniformMatrix3fv(this.addr, false, v);
  9890. copyArray(cache, v);
  9891. } else {
  9892. if (arraysEqual(cache, elements)) return;
  9893. mat3array.set(elements);
  9894. gl.uniformMatrix3fv(this.addr, false, mat3array);
  9895. copyArray(cache, elements);
  9896. }
  9897. }
  9898. function setValueM4(gl, v) {
  9899. const cache = this.cache;
  9900. const elements = v.elements;
  9901. if (elements === undefined) {
  9902. if (arraysEqual(cache, v)) return;
  9903. gl.uniformMatrix4fv(this.addr, false, v);
  9904. copyArray(cache, v);
  9905. } else {
  9906. if (arraysEqual(cache, elements)) return;
  9907. mat4array.set(elements);
  9908. gl.uniformMatrix4fv(this.addr, false, mat4array);
  9909. copyArray(cache, elements);
  9910. }
  9911. } // Single integer / boolean
  9912. function setValueV1i(gl, v) {
  9913. const cache = this.cache;
  9914. if (cache[0] === v) return;
  9915. gl.uniform1i(this.addr, v);
  9916. cache[0] = v;
  9917. } // Single integer / boolean vector (from flat array)
  9918. function setValueV2i(gl, v) {
  9919. const cache = this.cache;
  9920. if (arraysEqual(cache, v)) return;
  9921. gl.uniform2iv(this.addr, v);
  9922. copyArray(cache, v);
  9923. }
  9924. function setValueV3i(gl, v) {
  9925. const cache = this.cache;
  9926. if (arraysEqual(cache, v)) return;
  9927. gl.uniform3iv(this.addr, v);
  9928. copyArray(cache, v);
  9929. }
  9930. function setValueV4i(gl, v) {
  9931. const cache = this.cache;
  9932. if (arraysEqual(cache, v)) return;
  9933. gl.uniform4iv(this.addr, v);
  9934. copyArray(cache, v);
  9935. } // Single unsigned integer
  9936. function setValueV1ui(gl, v) {
  9937. const cache = this.cache;
  9938. if (cache[0] === v) return;
  9939. gl.uniform1ui(this.addr, v);
  9940. cache[0] = v;
  9941. } // Single unsigned integer vector (from flat array)
  9942. function setValueV2ui(gl, v) {
  9943. const cache = this.cache;
  9944. if (arraysEqual(cache, v)) return;
  9945. gl.uniform2uiv(this.addr, v);
  9946. copyArray(cache, v);
  9947. }
  9948. function setValueV3ui(gl, v) {
  9949. const cache = this.cache;
  9950. if (arraysEqual(cache, v)) return;
  9951. gl.uniform3uiv(this.addr, v);
  9952. copyArray(cache, v);
  9953. }
  9954. function setValueV4ui(gl, v) {
  9955. const cache = this.cache;
  9956. if (arraysEqual(cache, v)) return;
  9957. gl.uniform4uiv(this.addr, v);
  9958. copyArray(cache, v);
  9959. } // Single texture (2D / Cube)
  9960. function setValueT1(gl, v, textures) {
  9961. const cache = this.cache;
  9962. const unit = textures.allocateTextureUnit();
  9963. if (cache[0] !== unit) {
  9964. gl.uniform1i(this.addr, unit);
  9965. cache[0] = unit;
  9966. }
  9967. textures.safeSetTexture2D(v || emptyTexture, unit);
  9968. }
  9969. function setValueT3D1(gl, v, textures) {
  9970. const cache = this.cache;
  9971. const unit = textures.allocateTextureUnit();
  9972. if (cache[0] !== unit) {
  9973. gl.uniform1i(this.addr, unit);
  9974. cache[0] = unit;
  9975. }
  9976. textures.setTexture3D(v || emptyTexture3d, unit);
  9977. }
  9978. function setValueT6(gl, v, textures) {
  9979. const cache = this.cache;
  9980. const unit = textures.allocateTextureUnit();
  9981. if (cache[0] !== unit) {
  9982. gl.uniform1i(this.addr, unit);
  9983. cache[0] = unit;
  9984. }
  9985. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  9986. }
  9987. function setValueT2DArray1(gl, v, textures) {
  9988. const cache = this.cache;
  9989. const unit = textures.allocateTextureUnit();
  9990. if (cache[0] !== unit) {
  9991. gl.uniform1i(this.addr, unit);
  9992. cache[0] = unit;
  9993. }
  9994. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  9995. } // Helper to pick the right setter for the singular case
  9996. function getSingularSetter(type) {
  9997. switch (type) {
  9998. case 0x1406:
  9999. return setValueV1f;
  10000. // FLOAT
  10001. case 0x8b50:
  10002. return setValueV2f;
  10003. // _VEC2
  10004. case 0x8b51:
  10005. return setValueV3f;
  10006. // _VEC3
  10007. case 0x8b52:
  10008. return setValueV4f;
  10009. // _VEC4
  10010. case 0x8b5a:
  10011. return setValueM2;
  10012. // _MAT2
  10013. case 0x8b5b:
  10014. return setValueM3;
  10015. // _MAT3
  10016. case 0x8b5c:
  10017. return setValueM4;
  10018. // _MAT4
  10019. case 0x1404:
  10020. case 0x8b56:
  10021. return setValueV1i;
  10022. // INT, BOOL
  10023. case 0x8b53:
  10024. case 0x8b57:
  10025. return setValueV2i;
  10026. // _VEC2
  10027. case 0x8b54:
  10028. case 0x8b58:
  10029. return setValueV3i;
  10030. // _VEC3
  10031. case 0x8b55:
  10032. case 0x8b59:
  10033. return setValueV4i;
  10034. // _VEC4
  10035. case 0x1405:
  10036. return setValueV1ui;
  10037. // UINT
  10038. case 0x8dc6:
  10039. return setValueV2ui;
  10040. // _VEC2
  10041. case 0x8dc7:
  10042. return setValueV3ui;
  10043. // _VEC3
  10044. case 0x8dc8:
  10045. return setValueV4ui;
  10046. // _VEC4
  10047. case 0x8b5e: // SAMPLER_2D
  10048. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10049. case 0x8dca: // INT_SAMPLER_2D
  10050. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10051. case 0x8b62:
  10052. // SAMPLER_2D_SHADOW
  10053. return setValueT1;
  10054. case 0x8b5f: // SAMPLER_3D
  10055. case 0x8dcb: // INT_SAMPLER_3D
  10056. case 0x8dd3:
  10057. // UNSIGNED_INT_SAMPLER_3D
  10058. return setValueT3D1;
  10059. case 0x8b60: // SAMPLER_CUBE
  10060. case 0x8dcc: // INT_SAMPLER_CUBE
  10061. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10062. case 0x8dc5:
  10063. // SAMPLER_CUBE_SHADOW
  10064. return setValueT6;
  10065. case 0x8dc1: // SAMPLER_2D_ARRAY
  10066. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10067. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10068. case 0x8dc4:
  10069. // SAMPLER_2D_ARRAY_SHADOW
  10070. return setValueT2DArray1;
  10071. }
  10072. } // Array of scalars
  10073. function setValueV1fArray(gl, v) {
  10074. gl.uniform1fv(this.addr, v);
  10075. } // Array of vectors (from flat array or array of THREE.VectorN)
  10076. function setValueV2fArray(gl, v) {
  10077. const data = flatten(v, this.size, 2);
  10078. gl.uniform2fv(this.addr, data);
  10079. }
  10080. function setValueV3fArray(gl, v) {
  10081. const data = flatten(v, this.size, 3);
  10082. gl.uniform3fv(this.addr, data);
  10083. }
  10084. function setValueV4fArray(gl, v) {
  10085. const data = flatten(v, this.size, 4);
  10086. gl.uniform4fv(this.addr, data);
  10087. } // Array of matrices (from flat array or array of THREE.MatrixN)
  10088. function setValueM2Array(gl, v) {
  10089. const data = flatten(v, this.size, 4);
  10090. gl.uniformMatrix2fv(this.addr, false, data);
  10091. }
  10092. function setValueM3Array(gl, v) {
  10093. const data = flatten(v, this.size, 9);
  10094. gl.uniformMatrix3fv(this.addr, false, data);
  10095. }
  10096. function setValueM4Array(gl, v) {
  10097. const data = flatten(v, this.size, 16);
  10098. gl.uniformMatrix4fv(this.addr, false, data);
  10099. } // Array of integer / boolean
  10100. function setValueV1iArray(gl, v) {
  10101. gl.uniform1iv(this.addr, v);
  10102. } // Array of integer / boolean vectors (from flat array)
  10103. function setValueV2iArray(gl, v) {
  10104. gl.uniform2iv(this.addr, v);
  10105. }
  10106. function setValueV3iArray(gl, v) {
  10107. gl.uniform3iv(this.addr, v);
  10108. }
  10109. function setValueV4iArray(gl, v) {
  10110. gl.uniform4iv(this.addr, v);
  10111. } // Array of unsigned integer
  10112. function setValueV1uiArray(gl, v) {
  10113. gl.uniform1uiv(this.addr, v);
  10114. } // Array of unsigned integer vectors (from flat array)
  10115. function setValueV2uiArray(gl, v) {
  10116. gl.uniform2uiv(this.addr, v);
  10117. }
  10118. function setValueV3uiArray(gl, v) {
  10119. gl.uniform3uiv(this.addr, v);
  10120. }
  10121. function setValueV4uiArray(gl, v) {
  10122. gl.uniform4uiv(this.addr, v);
  10123. } // Array of textures (2D / Cube)
  10124. function setValueT1Array(gl, v, textures) {
  10125. const n = v.length;
  10126. const units = allocTexUnits(textures, n);
  10127. gl.uniform1iv(this.addr, units);
  10128. for (let i = 0; i !== n; ++i) {
  10129. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  10130. }
  10131. }
  10132. function setValueT6Array(gl, v, textures) {
  10133. const n = v.length;
  10134. const units = allocTexUnits(textures, n);
  10135. gl.uniform1iv(this.addr, units);
  10136. for (let i = 0; i !== n; ++i) {
  10137. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  10138. }
  10139. } // Helper to pick the right setter for a pure (bottom-level) array
  10140. function getPureArraySetter(type) {
  10141. switch (type) {
  10142. case 0x1406:
  10143. return setValueV1fArray;
  10144. // FLOAT
  10145. case 0x8b50:
  10146. return setValueV2fArray;
  10147. // _VEC2
  10148. case 0x8b51:
  10149. return setValueV3fArray;
  10150. // _VEC3
  10151. case 0x8b52:
  10152. return setValueV4fArray;
  10153. // _VEC4
  10154. case 0x8b5a:
  10155. return setValueM2Array;
  10156. // _MAT2
  10157. case 0x8b5b:
  10158. return setValueM3Array;
  10159. // _MAT3
  10160. case 0x8b5c:
  10161. return setValueM4Array;
  10162. // _MAT4
  10163. case 0x1404:
  10164. case 0x8b56:
  10165. return setValueV1iArray;
  10166. // INT, BOOL
  10167. case 0x8b53:
  10168. case 0x8b57:
  10169. return setValueV2iArray;
  10170. // _VEC2
  10171. case 0x8b54:
  10172. case 0x8b58:
  10173. return setValueV3iArray;
  10174. // _VEC3
  10175. case 0x8b55:
  10176. case 0x8b59:
  10177. return setValueV4iArray;
  10178. // _VEC4
  10179. case 0x1405:
  10180. return setValueV1uiArray;
  10181. // UINT
  10182. case 0x8dc6:
  10183. return setValueV2uiArray;
  10184. // _VEC2
  10185. case 0x8dc7:
  10186. return setValueV3uiArray;
  10187. // _VEC3
  10188. case 0x8dc8:
  10189. return setValueV4uiArray;
  10190. // _VEC4
  10191. case 0x8b5e: // SAMPLER_2D
  10192. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10193. case 0x8dca: // INT_SAMPLER_2D
  10194. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10195. case 0x8b62:
  10196. // SAMPLER_2D_SHADOW
  10197. return setValueT1Array;
  10198. case 0x8b60: // SAMPLER_CUBE
  10199. case 0x8dcc: // INT_SAMPLER_CUBE
  10200. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10201. case 0x8dc5:
  10202. // SAMPLER_CUBE_SHADOW
  10203. return setValueT6Array;
  10204. }
  10205. } // --- Uniform Classes ---
  10206. function SingleUniform(id, activeInfo, addr) {
  10207. this.id = id;
  10208. this.addr = addr;
  10209. this.cache = [];
  10210. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10211. }
  10212. function PureArrayUniform(id, activeInfo, addr) {
  10213. this.id = id;
  10214. this.addr = addr;
  10215. this.cache = [];
  10216. this.size = activeInfo.size;
  10217. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10218. }
  10219. PureArrayUniform.prototype.updateCache = function (data) {
  10220. const cache = this.cache;
  10221. if (data instanceof Float32Array && cache.length !== data.length) {
  10222. this.cache = new Float32Array(data.length);
  10223. }
  10224. copyArray(cache, data);
  10225. };
  10226. function StructuredUniform(id) {
  10227. this.id = id;
  10228. this.seq = [];
  10229. this.map = {};
  10230. }
  10231. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  10232. const seq = this.seq;
  10233. for (let i = 0, n = seq.length; i !== n; ++i) {
  10234. const u = seq[i];
  10235. u.setValue(gl, value[u.id], textures);
  10236. }
  10237. }; // --- Top-level ---
  10238. // Parser - builds up the property tree from the path strings
  10239. const RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
  10240. // - the identifier (member name or array index)
  10241. // - followed by an optional right bracket (found when array index)
  10242. // - followed by an optional left bracket or dot (type of subscript)
  10243. //
  10244. // Note: These portions can be read in a non-overlapping fashion and
  10245. // allow straightforward parsing of the hierarchy that WebGL encodes
  10246. // in the uniform names.
  10247. function addUniform(container, uniformObject) {
  10248. container.seq.push(uniformObject);
  10249. container.map[uniformObject.id] = uniformObject;
  10250. }
  10251. function parseUniform(activeInfo, addr, container) {
  10252. const path = activeInfo.name,
  10253. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  10254. RePathPart.lastIndex = 0;
  10255. while (true) {
  10256. const match = RePathPart.exec(path),
  10257. matchEnd = RePathPart.lastIndex;
  10258. let id = match[1];
  10259. const idIsIndex = match[2] === ']',
  10260. subscript = match[3];
  10261. if (idIsIndex) id = id | 0; // convert to integer
  10262. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  10263. // bare name or "pure" bottom-level array "[0]" suffix
  10264. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  10265. break;
  10266. } else {
  10267. // step into inner node / create it in case it doesn't exist
  10268. const map = container.map;
  10269. let next = map[id];
  10270. if (next === undefined) {
  10271. next = new StructuredUniform(id);
  10272. addUniform(container, next);
  10273. }
  10274. container = next;
  10275. }
  10276. }
  10277. } // Root Container
  10278. function WebGLUniforms(gl, program) {
  10279. this.seq = [];
  10280. this.map = {};
  10281. const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  10282. for (let i = 0; i < n; ++i) {
  10283. const info = gl.getActiveUniform(program, i),
  10284. addr = gl.getUniformLocation(program, info.name);
  10285. parseUniform(info, addr, this);
  10286. }
  10287. }
  10288. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  10289. const u = this.map[name];
  10290. if (u !== undefined) u.setValue(gl, value, textures);
  10291. };
  10292. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  10293. const v = object[name];
  10294. if (v !== undefined) this.setValue(gl, name, v);
  10295. }; // Static interface
  10296. WebGLUniforms.upload = function (gl, seq, values, textures) {
  10297. for (let i = 0, n = seq.length; i !== n; ++i) {
  10298. const u = seq[i],
  10299. v = values[u.id];
  10300. if (v.needsUpdate !== false) {
  10301. // note: always updating when .needsUpdate is undefined
  10302. u.setValue(gl, v.value, textures);
  10303. }
  10304. }
  10305. };
  10306. WebGLUniforms.seqWithValue = function (seq, values) {
  10307. const r = [];
  10308. for (let i = 0, n = seq.length; i !== n; ++i) {
  10309. const u = seq[i];
  10310. if (u.id in values) r.push(u);
  10311. }
  10312. return r;
  10313. };
  10314. function WebGLShader(gl, type, string) {
  10315. const shader = gl.createShader(type);
  10316. gl.shaderSource(shader, string);
  10317. gl.compileShader(shader);
  10318. return shader;
  10319. }
  10320. let programIdCount = 0;
  10321. function addLineNumbers(string) {
  10322. const lines = string.split('\n');
  10323. for (let i = 0; i < lines.length; i++) {
  10324. lines[i] = i + 1 + ': ' + lines[i];
  10325. }
  10326. return lines.join('\n');
  10327. }
  10328. function getEncodingComponents(encoding) {
  10329. switch (encoding) {
  10330. case LinearEncoding:
  10331. return ['Linear', '( value )'];
  10332. case sRGBEncoding:
  10333. return ['sRGB', '( value )'];
  10334. case RGBEEncoding:
  10335. return ['RGBE', '( value )'];
  10336. case RGBM7Encoding:
  10337. return ['RGBM', '( value, 7.0 )'];
  10338. case RGBM16Encoding:
  10339. return ['RGBM', '( value, 16.0 )'];
  10340. case RGBDEncoding:
  10341. return ['RGBD', '( value, 256.0 )'];
  10342. case GammaEncoding:
  10343. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  10344. case LogLuvEncoding:
  10345. return ['LogLuv', '( value )'];
  10346. default:
  10347. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  10348. return ['Linear', '( value )'];
  10349. }
  10350. }
  10351. function getShaderErrors(gl, shader, type) {
  10352. const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  10353. const log = gl.getShaderInfoLog(shader).trim();
  10354. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  10355. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10356. const source = gl.getShaderSource(shader);
  10357. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  10358. }
  10359. function getTexelDecodingFunction(functionName, encoding) {
  10360. const components = getEncodingComponents(encoding);
  10361. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  10362. }
  10363. function getTexelEncodingFunction(functionName, encoding) {
  10364. const components = getEncodingComponents(encoding);
  10365. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  10366. }
  10367. function getToneMappingFunction(functionName, toneMapping) {
  10368. let toneMappingName;
  10369. switch (toneMapping) {
  10370. case LinearToneMapping:
  10371. toneMappingName = 'Linear';
  10372. break;
  10373. case ReinhardToneMapping:
  10374. toneMappingName = 'Reinhard';
  10375. break;
  10376. case CineonToneMapping:
  10377. toneMappingName = 'OptimizedCineon';
  10378. break;
  10379. case ACESFilmicToneMapping:
  10380. toneMappingName = 'ACESFilmic';
  10381. break;
  10382. case CustomToneMapping:
  10383. toneMappingName = 'Custom';
  10384. break;
  10385. default:
  10386. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  10387. toneMappingName = 'Linear';
  10388. }
  10389. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  10390. }
  10391. function generateExtensions(parameters) {
  10392. 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 > 0.0) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  10393. return chunks.filter(filterEmptyLine).join('\n');
  10394. }
  10395. function generateDefines(defines) {
  10396. const chunks = [];
  10397. for (const name in defines) {
  10398. const value = defines[name];
  10399. if (value === false) continue;
  10400. chunks.push('#define ' + name + ' ' + value);
  10401. }
  10402. return chunks.join('\n');
  10403. }
  10404. function fetchAttributeLocations(gl, program) {
  10405. const attributes = {};
  10406. const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  10407. for (let i = 0; i < n; i++) {
  10408. const info = gl.getActiveAttrib(program, i);
  10409. const name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  10410. attributes[name] = gl.getAttribLocation(program, name);
  10411. }
  10412. return attributes;
  10413. }
  10414. function filterEmptyLine(string) {
  10415. return string !== '';
  10416. }
  10417. function replaceLightNums(string, parameters) {
  10418. 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);
  10419. }
  10420. function replaceClippingPlaneNums(string, parameters) {
  10421. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  10422. } // Resolve Includes
  10423. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  10424. function resolveIncludes(string) {
  10425. return string.replace(includePattern, includeReplacer);
  10426. }
  10427. function includeReplacer(match, include) {
  10428. const string = ShaderChunk[include];
  10429. if (string === undefined) {
  10430. throw new Error('Can not resolve #include <' + include + '>');
  10431. }
  10432. return resolveIncludes(string);
  10433. } // Unroll Loops
  10434. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10435. 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;
  10436. function unrollLoops(string) {
  10437. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  10438. }
  10439. function deprecatedLoopReplacer(match, start, end, snippet) {
  10440. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  10441. return loopReplacer(match, start, end, snippet);
  10442. }
  10443. function loopReplacer(match, start, end, snippet) {
  10444. let string = '';
  10445. for (let i = parseInt(start); i < parseInt(end); i++) {
  10446. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  10447. }
  10448. return string;
  10449. } //
  10450. function generatePrecision(parameters) {
  10451. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  10452. if (parameters.precision === 'highp') {
  10453. precisionstring += '\n#define HIGH_PRECISION';
  10454. } else if (parameters.precision === 'mediump') {
  10455. precisionstring += '\n#define MEDIUM_PRECISION';
  10456. } else if (parameters.precision === 'lowp') {
  10457. precisionstring += '\n#define LOW_PRECISION';
  10458. }
  10459. return precisionstring;
  10460. }
  10461. function generateShadowMapTypeDefine(parameters) {
  10462. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10463. if (parameters.shadowMapType === PCFShadowMap) {
  10464. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10465. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  10466. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10467. } else if (parameters.shadowMapType === VSMShadowMap) {
  10468. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  10469. }
  10470. return shadowMapTypeDefine;
  10471. }
  10472. function generateEnvMapTypeDefine(parameters) {
  10473. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10474. if (parameters.envMap) {
  10475. switch (parameters.envMapMode) {
  10476. case CubeReflectionMapping:
  10477. case CubeRefractionMapping:
  10478. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10479. break;
  10480. case CubeUVReflectionMapping:
  10481. case CubeUVRefractionMapping:
  10482. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10483. break;
  10484. }
  10485. }
  10486. return envMapTypeDefine;
  10487. }
  10488. function generateEnvMapModeDefine(parameters) {
  10489. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10490. if (parameters.envMap) {
  10491. switch (parameters.envMapMode) {
  10492. case CubeRefractionMapping:
  10493. case CubeUVRefractionMapping:
  10494. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10495. break;
  10496. }
  10497. }
  10498. return envMapModeDefine;
  10499. }
  10500. function generateEnvMapBlendingDefine(parameters) {
  10501. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  10502. if (parameters.envMap) {
  10503. switch (parameters.combine) {
  10504. case MultiplyOperation:
  10505. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10506. break;
  10507. case MixOperation:
  10508. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  10509. break;
  10510. case AddOperation:
  10511. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  10512. break;
  10513. }
  10514. }
  10515. return envMapBlendingDefine;
  10516. }
  10517. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  10518. const gl = renderer.getContext();
  10519. const defines = parameters.defines;
  10520. let vertexShader = parameters.vertexShader;
  10521. let fragmentShader = parameters.fragmentShader;
  10522. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  10523. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  10524. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  10525. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  10526. const gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  10527. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  10528. const customDefines = generateDefines(defines);
  10529. const program = gl.createProgram();
  10530. let prefixVertex, prefixFragment;
  10531. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  10532. if (parameters.isRawShaderMaterial) {
  10533. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  10534. if (prefixVertex.length > 0) {
  10535. prefixVertex += '\n';
  10536. }
  10537. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  10538. if (prefixFragment.length > 0) {
  10539. prefixFragment += '\n';
  10540. }
  10541. } else {
  10542. 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.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');
  10543. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  10544. '#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.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', 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
  10545. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
  10546. 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.lightMap ? getTexelDecodingFunction('lightMapTexelToLinear', parameters.lightMapEncoding) : '', getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  10547. }
  10548. vertexShader = resolveIncludes(vertexShader);
  10549. vertexShader = replaceLightNums(vertexShader, parameters);
  10550. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  10551. fragmentShader = resolveIncludes(fragmentShader);
  10552. fragmentShader = replaceLightNums(fragmentShader, parameters);
  10553. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  10554. vertexShader = unrollLoops(vertexShader);
  10555. fragmentShader = unrollLoops(fragmentShader);
  10556. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  10557. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  10558. versionString = '#version 300 es\n';
  10559. prefixVertex = ['#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  10560. 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;
  10561. }
  10562. const vertexGlsl = versionString + prefixVertex + vertexShader;
  10563. const fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  10564. // console.log( '*FRAGMENT*', fragmentGlsl );
  10565. const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl);
  10566. const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl);
  10567. gl.attachShader(program, glVertexShader);
  10568. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  10569. if (parameters.index0AttributeName !== undefined) {
  10570. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  10571. } else if (parameters.morphTargets === true) {
  10572. // programs with morphTargets displace position out of attribute 0
  10573. gl.bindAttribLocation(program, 0, 'position');
  10574. }
  10575. gl.linkProgram(program); // check for link errors
  10576. if (renderer.debug.checkShaderErrors) {
  10577. const programLog = gl.getProgramInfoLog(program).trim();
  10578. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  10579. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  10580. let runnable = true;
  10581. let haveDiagnostics = true;
  10582. if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
  10583. runnable = false;
  10584. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  10585. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  10586. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  10587. } else if (programLog !== '') {
  10588. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  10589. } else if (vertexLog === '' || fragmentLog === '') {
  10590. haveDiagnostics = false;
  10591. }
  10592. if (haveDiagnostics) {
  10593. this.diagnostics = {
  10594. runnable: runnable,
  10595. programLog: programLog,
  10596. vertexShader: {
  10597. log: vertexLog,
  10598. prefix: prefixVertex
  10599. },
  10600. fragmentShader: {
  10601. log: fragmentLog,
  10602. prefix: prefixFragment
  10603. }
  10604. };
  10605. }
  10606. } // Clean up
  10607. // Crashes in iOS9 and iOS10. #18402
  10608. // gl.detachShader( program, glVertexShader );
  10609. // gl.detachShader( program, glFragmentShader );
  10610. gl.deleteShader(glVertexShader);
  10611. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  10612. let cachedUniforms;
  10613. this.getUniforms = function () {
  10614. if (cachedUniforms === undefined) {
  10615. cachedUniforms = new WebGLUniforms(gl, program);
  10616. }
  10617. return cachedUniforms;
  10618. }; // set up caching for attribute locations
  10619. let cachedAttributes;
  10620. this.getAttributes = function () {
  10621. if (cachedAttributes === undefined) {
  10622. cachedAttributes = fetchAttributeLocations(gl, program);
  10623. }
  10624. return cachedAttributes;
  10625. }; // free resource
  10626. this.destroy = function () {
  10627. bindingStates.releaseStatesOfProgram(this);
  10628. gl.deleteProgram(program);
  10629. this.program = undefined;
  10630. }; //
  10631. this.name = parameters.shaderName;
  10632. this.id = programIdCount++;
  10633. this.cacheKey = cacheKey;
  10634. this.usedTimes = 1;
  10635. this.program = program;
  10636. this.vertexShader = glVertexShader;
  10637. this.fragmentShader = glFragmentShader;
  10638. return this;
  10639. }
  10640. function WebGLPrograms(renderer, cubemaps, extensions, capabilities, bindingStates, clipping) {
  10641. const programs = [];
  10642. const isWebGL2 = capabilities.isWebGL2;
  10643. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  10644. const floatVertexTextures = capabilities.floatVertexTextures;
  10645. const maxVertexUniforms = capabilities.maxVertexUniforms;
  10646. const vertexTextures = capabilities.vertexTextures;
  10647. let precision = capabilities.precision;
  10648. const shaderIDs = {
  10649. MeshDepthMaterial: 'depth',
  10650. MeshDistanceMaterial: 'distanceRGBA',
  10651. MeshNormalMaterial: 'normal',
  10652. MeshBasicMaterial: 'basic',
  10653. MeshLambertMaterial: 'lambert',
  10654. MeshPhongMaterial: 'phong',
  10655. MeshToonMaterial: 'toon',
  10656. MeshStandardMaterial: 'physical',
  10657. MeshPhysicalMaterial: 'physical',
  10658. MeshMatcapMaterial: 'matcap',
  10659. LineBasicMaterial: 'basic',
  10660. LineDashedMaterial: 'dashed',
  10661. PointsMaterial: 'points',
  10662. ShadowMaterial: 'shadow',
  10663. SpriteMaterial: 'sprite'
  10664. };
  10665. 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', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap', 'displacementMap', 'specularMap', 'roughnessMap', 'metalnessMap', 'gradientMap', 'alphaMap', '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', 'alphaTest', 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering', 'sheen', 'transmission', 'transmissionMap', 'thicknessMap'];
  10666. function getMaxBones(object) {
  10667. const skeleton = object.skeleton;
  10668. const bones = skeleton.bones;
  10669. if (floatVertexTextures) {
  10670. return 1024;
  10671. } else {
  10672. // default for when object is not specified
  10673. // ( for example when prebuilding shader to be used with multiple objects )
  10674. //
  10675. // - leave some extra space for other uniforms
  10676. // - limit here is ANGLE's 254 max uniform vectors
  10677. // (up to 54 should be safe)
  10678. const nVertexUniforms = maxVertexUniforms;
  10679. const nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  10680. const maxBones = Math.min(nVertexMatrices, bones.length);
  10681. if (maxBones < bones.length) {
  10682. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  10683. return 0;
  10684. }
  10685. return maxBones;
  10686. }
  10687. }
  10688. function getTextureEncodingFromMap(map) {
  10689. let encoding;
  10690. if (map && map.isTexture) {
  10691. encoding = map.encoding;
  10692. } else if (map && map.isWebGLRenderTarget) {
  10693. console.warn('THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.');
  10694. encoding = map.texture.encoding;
  10695. } else {
  10696. encoding = LinearEncoding;
  10697. }
  10698. return encoding;
  10699. }
  10700. function getParameters(material, lights, shadows, scene, object) {
  10701. const fog = scene.fog;
  10702. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  10703. const envMap = cubemaps.get(material.envMap || environment);
  10704. const shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  10705. // (not to blow over maxLights budget)
  10706. const maxBones = object.isSkinnedMesh ? getMaxBones(object) : 0;
  10707. if (material.precision !== null) {
  10708. precision = capabilities.getMaxPrecision(material.precision);
  10709. if (precision !== material.precision) {
  10710. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  10711. }
  10712. }
  10713. let vertexShader, fragmentShader;
  10714. if (shaderID) {
  10715. const shader = ShaderLib[shaderID];
  10716. vertexShader = shader.vertexShader;
  10717. fragmentShader = shader.fragmentShader;
  10718. } else {
  10719. vertexShader = material.vertexShader;
  10720. fragmentShader = material.fragmentShader;
  10721. }
  10722. const currentRenderTarget = renderer.getRenderTarget();
  10723. const parameters = {
  10724. isWebGL2: isWebGL2,
  10725. shaderID: shaderID,
  10726. shaderName: material.type,
  10727. vertexShader: vertexShader,
  10728. fragmentShader: fragmentShader,
  10729. defines: material.defines,
  10730. isRawShaderMaterial: material.isRawShaderMaterial === true,
  10731. glslVersion: material.glslVersion,
  10732. precision: precision,
  10733. instancing: object.isInstancedMesh === true,
  10734. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  10735. supportsVertexTextures: vertexTextures,
  10736. outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
  10737. map: !!material.map,
  10738. mapEncoding: getTextureEncodingFromMap(material.map),
  10739. matcap: !!material.matcap,
  10740. matcapEncoding: getTextureEncodingFromMap(material.matcap),
  10741. envMap: !!envMap,
  10742. envMapMode: envMap && envMap.mapping,
  10743. envMapEncoding: getTextureEncodingFromMap(envMap),
  10744. envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
  10745. lightMap: !!material.lightMap,
  10746. lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
  10747. aoMap: !!material.aoMap,
  10748. emissiveMap: !!material.emissiveMap,
  10749. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
  10750. bumpMap: !!material.bumpMap,
  10751. normalMap: !!material.normalMap,
  10752. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  10753. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  10754. clearcoatMap: !!material.clearcoatMap,
  10755. clearcoatRoughnessMap: !!material.clearcoatRoughnessMap,
  10756. clearcoatNormalMap: !!material.clearcoatNormalMap,
  10757. displacementMap: !!material.displacementMap,
  10758. roughnessMap: !!material.roughnessMap,
  10759. metalnessMap: !!material.metalnessMap,
  10760. specularMap: !!material.specularMap,
  10761. alphaMap: !!material.alphaMap,
  10762. gradientMap: !!material.gradientMap,
  10763. sheen: !!material.sheen,
  10764. transmission: !!material.transmission,
  10765. transmissionMap: !!material.transmissionMap,
  10766. thicknessMap: !!material.thicknessMap,
  10767. combine: material.combine,
  10768. vertexTangents: material.normalMap && material.vertexTangents,
  10769. vertexColors: material.vertexColors,
  10770. vertexAlphas: material.vertexColors === true && object.geometry && object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4,
  10771. 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.transmission || !!material.transmissionMap || !!material.thicknessMap,
  10772. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || !!material.transmission || !!material.transmissionMap || !!material.thicknessMap) && !!material.displacementMap,
  10773. fog: !!fog,
  10774. useFog: material.fog,
  10775. fogExp2: fog && fog.isFogExp2,
  10776. flatShading: !!material.flatShading,
  10777. sizeAttenuation: material.sizeAttenuation,
  10778. logarithmicDepthBuffer: logarithmicDepthBuffer,
  10779. skinning: object.isSkinnedMesh === true && maxBones > 0,
  10780. maxBones: maxBones,
  10781. useVertexTexture: floatVertexTextures,
  10782. morphTargets: material.morphTargets,
  10783. morphNormals: material.morphNormals,
  10784. numDirLights: lights.directional.length,
  10785. numPointLights: lights.point.length,
  10786. numSpotLights: lights.spot.length,
  10787. numRectAreaLights: lights.rectArea.length,
  10788. numHemiLights: lights.hemi.length,
  10789. numDirLightShadows: lights.directionalShadowMap.length,
  10790. numPointLightShadows: lights.pointShadowMap.length,
  10791. numSpotLightShadows: lights.spotShadowMap.length,
  10792. numClippingPlanes: clipping.numPlanes,
  10793. numClipIntersection: clipping.numIntersection,
  10794. dithering: material.dithering,
  10795. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  10796. shadowMapType: renderer.shadowMap.type,
  10797. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  10798. physicallyCorrectLights: renderer.physicallyCorrectLights,
  10799. premultipliedAlpha: material.premultipliedAlpha,
  10800. alphaTest: material.alphaTest,
  10801. doubleSided: material.side === DoubleSide,
  10802. flipSided: material.side === BackSide,
  10803. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
  10804. index0AttributeName: material.index0AttributeName,
  10805. extensionDerivatives: material.extensions && material.extensions.derivatives,
  10806. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  10807. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  10808. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  10809. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  10810. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  10811. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  10812. customProgramCacheKey: material.customProgramCacheKey()
  10813. };
  10814. return parameters;
  10815. }
  10816. function getProgramCacheKey(parameters) {
  10817. const array = [];
  10818. if (parameters.shaderID) {
  10819. array.push(parameters.shaderID);
  10820. } else {
  10821. array.push(parameters.fragmentShader);
  10822. array.push(parameters.vertexShader);
  10823. }
  10824. if (parameters.defines !== undefined) {
  10825. for (const name in parameters.defines) {
  10826. array.push(name);
  10827. array.push(parameters.defines[name]);
  10828. }
  10829. }
  10830. if (parameters.isRawShaderMaterial === false) {
  10831. for (let i = 0; i < parameterNames.length; i++) {
  10832. array.push(parameters[parameterNames[i]]);
  10833. }
  10834. array.push(renderer.outputEncoding);
  10835. array.push(renderer.gammaFactor);
  10836. }
  10837. array.push(parameters.customProgramCacheKey);
  10838. return array.join();
  10839. }
  10840. function getUniforms(material) {
  10841. const shaderID = shaderIDs[material.type];
  10842. let uniforms;
  10843. if (shaderID) {
  10844. const shader = ShaderLib[shaderID];
  10845. uniforms = UniformsUtils.clone(shader.uniforms);
  10846. } else {
  10847. uniforms = material.uniforms;
  10848. }
  10849. return uniforms;
  10850. }
  10851. function acquireProgram(parameters, cacheKey) {
  10852. let program; // Check if code has been already compiled
  10853. for (let p = 0, pl = programs.length; p < pl; p++) {
  10854. const preexistingProgram = programs[p];
  10855. if (preexistingProgram.cacheKey === cacheKey) {
  10856. program = preexistingProgram;
  10857. ++program.usedTimes;
  10858. break;
  10859. }
  10860. }
  10861. if (program === undefined) {
  10862. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  10863. programs.push(program);
  10864. }
  10865. return program;
  10866. }
  10867. function releaseProgram(program) {
  10868. if (--program.usedTimes === 0) {
  10869. // Remove from unordered set
  10870. const i = programs.indexOf(program);
  10871. programs[i] = programs[programs.length - 1];
  10872. programs.pop(); // Free WebGL resources
  10873. program.destroy();
  10874. }
  10875. }
  10876. return {
  10877. getParameters: getParameters,
  10878. getProgramCacheKey: getProgramCacheKey,
  10879. getUniforms: getUniforms,
  10880. acquireProgram: acquireProgram,
  10881. releaseProgram: releaseProgram,
  10882. // Exposed for resource monitoring & error feedback via renderer.info:
  10883. programs: programs
  10884. };
  10885. }
  10886. function WebGLProperties() {
  10887. let properties = new WeakMap();
  10888. function get(object) {
  10889. let map = properties.get(object);
  10890. if (map === undefined) {
  10891. map = {};
  10892. properties.set(object, map);
  10893. }
  10894. return map;
  10895. }
  10896. function remove(object) {
  10897. properties.delete(object);
  10898. }
  10899. function update(object, key, value) {
  10900. properties.get(object)[key] = value;
  10901. }
  10902. function dispose() {
  10903. properties = new WeakMap();
  10904. }
  10905. return {
  10906. get: get,
  10907. remove: remove,
  10908. update: update,
  10909. dispose: dispose
  10910. };
  10911. }
  10912. function painterSortStable(a, b) {
  10913. if (a.groupOrder !== b.groupOrder) {
  10914. return a.groupOrder - b.groupOrder;
  10915. } else if (a.renderOrder !== b.renderOrder) {
  10916. return a.renderOrder - b.renderOrder;
  10917. } else if (a.program !== b.program) {
  10918. return a.program.id - b.program.id;
  10919. } else if (a.material.id !== b.material.id) {
  10920. return a.material.id - b.material.id;
  10921. } else if (a.z !== b.z) {
  10922. return a.z - b.z;
  10923. } else {
  10924. return a.id - b.id;
  10925. }
  10926. }
  10927. function reversePainterSortStable(a, b) {
  10928. if (a.groupOrder !== b.groupOrder) {
  10929. return a.groupOrder - b.groupOrder;
  10930. } else if (a.renderOrder !== b.renderOrder) {
  10931. return a.renderOrder - b.renderOrder;
  10932. } else if (a.z !== b.z) {
  10933. return b.z - a.z;
  10934. } else {
  10935. return a.id - b.id;
  10936. }
  10937. }
  10938. function WebGLRenderList(properties) {
  10939. const renderItems = [];
  10940. let renderItemsIndex = 0;
  10941. const opaque = [];
  10942. const transmissive = [];
  10943. const transparent = [];
  10944. const defaultProgram = {
  10945. id: -1
  10946. };
  10947. function init() {
  10948. renderItemsIndex = 0;
  10949. opaque.length = 0;
  10950. transmissive.length = 0;
  10951. transparent.length = 0;
  10952. }
  10953. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  10954. let renderItem = renderItems[renderItemsIndex];
  10955. const materialProperties = properties.get(material);
  10956. if (renderItem === undefined) {
  10957. renderItem = {
  10958. id: object.id,
  10959. object: object,
  10960. geometry: geometry,
  10961. material: material,
  10962. program: materialProperties.program || defaultProgram,
  10963. groupOrder: groupOrder,
  10964. renderOrder: object.renderOrder,
  10965. z: z,
  10966. group: group
  10967. };
  10968. renderItems[renderItemsIndex] = renderItem;
  10969. } else {
  10970. renderItem.id = object.id;
  10971. renderItem.object = object;
  10972. renderItem.geometry = geometry;
  10973. renderItem.material = material;
  10974. renderItem.program = materialProperties.program || defaultProgram;
  10975. renderItem.groupOrder = groupOrder;
  10976. renderItem.renderOrder = object.renderOrder;
  10977. renderItem.z = z;
  10978. renderItem.group = group;
  10979. }
  10980. renderItemsIndex++;
  10981. return renderItem;
  10982. }
  10983. function push(object, geometry, material, groupOrder, z, group) {
  10984. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  10985. if (material.transmission > 0.0) {
  10986. transmissive.push(renderItem);
  10987. } else if (material.transparent === true) {
  10988. transparent.push(renderItem);
  10989. } else {
  10990. opaque.push(renderItem);
  10991. }
  10992. }
  10993. function unshift(object, geometry, material, groupOrder, z, group) {
  10994. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  10995. if (material.transmission > 0.0) {
  10996. transmissive.unshift(renderItem);
  10997. } else if (material.transparent === true) {
  10998. transparent.unshift(renderItem);
  10999. } else {
  11000. opaque.unshift(renderItem);
  11001. }
  11002. }
  11003. function sort(customOpaqueSort, customTransparentSort) {
  11004. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  11005. if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable);
  11006. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  11007. }
  11008. function finish() {
  11009. // Clear references from inactive renderItems in the list
  11010. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  11011. const renderItem = renderItems[i];
  11012. if (renderItem.id === null) break;
  11013. renderItem.id = null;
  11014. renderItem.object = null;
  11015. renderItem.geometry = null;
  11016. renderItem.material = null;
  11017. renderItem.program = null;
  11018. renderItem.group = null;
  11019. }
  11020. }
  11021. return {
  11022. opaque: opaque,
  11023. transmissive: transmissive,
  11024. transparent: transparent,
  11025. init: init,
  11026. push: push,
  11027. unshift: unshift,
  11028. finish: finish,
  11029. sort: sort
  11030. };
  11031. }
  11032. function WebGLRenderLists(properties) {
  11033. let lists = new WeakMap();
  11034. function get(scene, renderCallDepth) {
  11035. let list;
  11036. if (lists.has(scene) === false) {
  11037. list = new WebGLRenderList(properties);
  11038. lists.set(scene, [list]);
  11039. } else {
  11040. if (renderCallDepth >= lists.get(scene).length) {
  11041. list = new WebGLRenderList(properties);
  11042. lists.get(scene).push(list);
  11043. } else {
  11044. list = lists.get(scene)[renderCallDepth];
  11045. }
  11046. }
  11047. return list;
  11048. }
  11049. function dispose() {
  11050. lists = new WeakMap();
  11051. }
  11052. return {
  11053. get: get,
  11054. dispose: dispose
  11055. };
  11056. }
  11057. function UniformsCache() {
  11058. const lights = {};
  11059. return {
  11060. get: function (light) {
  11061. if (lights[light.id] !== undefined) {
  11062. return lights[light.id];
  11063. }
  11064. let uniforms;
  11065. switch (light.type) {
  11066. case 'DirectionalLight':
  11067. uniforms = {
  11068. direction: new Vector3(),
  11069. color: new Color()
  11070. };
  11071. break;
  11072. case 'SpotLight':
  11073. uniforms = {
  11074. position: new Vector3(),
  11075. direction: new Vector3(),
  11076. color: new Color(),
  11077. distance: 0,
  11078. coneCos: 0,
  11079. penumbraCos: 0,
  11080. decay: 0
  11081. };
  11082. break;
  11083. case 'PointLight':
  11084. uniforms = {
  11085. position: new Vector3(),
  11086. color: new Color(),
  11087. distance: 0,
  11088. decay: 0
  11089. };
  11090. break;
  11091. case 'HemisphereLight':
  11092. uniforms = {
  11093. direction: new Vector3(),
  11094. skyColor: new Color(),
  11095. groundColor: new Color()
  11096. };
  11097. break;
  11098. case 'RectAreaLight':
  11099. uniforms = {
  11100. color: new Color(),
  11101. position: new Vector3(),
  11102. halfWidth: new Vector3(),
  11103. halfHeight: new Vector3()
  11104. };
  11105. break;
  11106. }
  11107. lights[light.id] = uniforms;
  11108. return uniforms;
  11109. }
  11110. };
  11111. }
  11112. function ShadowUniformsCache() {
  11113. const lights = {};
  11114. return {
  11115. get: function (light) {
  11116. if (lights[light.id] !== undefined) {
  11117. return lights[light.id];
  11118. }
  11119. let uniforms;
  11120. switch (light.type) {
  11121. case 'DirectionalLight':
  11122. uniforms = {
  11123. shadowBias: 0,
  11124. shadowNormalBias: 0,
  11125. shadowRadius: 1,
  11126. shadowMapSize: new Vector2()
  11127. };
  11128. break;
  11129. case 'SpotLight':
  11130. uniforms = {
  11131. shadowBias: 0,
  11132. shadowNormalBias: 0,
  11133. shadowRadius: 1,
  11134. shadowMapSize: new Vector2()
  11135. };
  11136. break;
  11137. case 'PointLight':
  11138. uniforms = {
  11139. shadowBias: 0,
  11140. shadowNormalBias: 0,
  11141. shadowRadius: 1,
  11142. shadowMapSize: new Vector2(),
  11143. shadowCameraNear: 1,
  11144. shadowCameraFar: 1000
  11145. };
  11146. break;
  11147. // TODO (abelnation): set RectAreaLight shadow uniforms
  11148. }
  11149. lights[light.id] = uniforms;
  11150. return uniforms;
  11151. }
  11152. };
  11153. }
  11154. let nextVersion = 0;
  11155. function shadowCastingLightsFirst(lightA, lightB) {
  11156. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  11157. }
  11158. function WebGLLights(extensions, capabilities) {
  11159. const cache = new UniformsCache();
  11160. const shadowCache = ShadowUniformsCache();
  11161. const state = {
  11162. version: 0,
  11163. hash: {
  11164. directionalLength: -1,
  11165. pointLength: -1,
  11166. spotLength: -1,
  11167. rectAreaLength: -1,
  11168. hemiLength: -1,
  11169. numDirectionalShadows: -1,
  11170. numPointShadows: -1,
  11171. numSpotShadows: -1
  11172. },
  11173. ambient: [0, 0, 0],
  11174. probe: [],
  11175. directional: [],
  11176. directionalShadow: [],
  11177. directionalShadowMap: [],
  11178. directionalShadowMatrix: [],
  11179. spot: [],
  11180. spotShadow: [],
  11181. spotShadowMap: [],
  11182. spotShadowMatrix: [],
  11183. rectArea: [],
  11184. rectAreaLTC1: null,
  11185. rectAreaLTC2: null,
  11186. point: [],
  11187. pointShadow: [],
  11188. pointShadowMap: [],
  11189. pointShadowMatrix: [],
  11190. hemi: []
  11191. };
  11192. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  11193. const vector3 = new Vector3();
  11194. const matrix4 = new Matrix4();
  11195. const matrix42 = new Matrix4();
  11196. function setup(lights) {
  11197. let r = 0,
  11198. g = 0,
  11199. b = 0;
  11200. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  11201. let directionalLength = 0;
  11202. let pointLength = 0;
  11203. let spotLength = 0;
  11204. let rectAreaLength = 0;
  11205. let hemiLength = 0;
  11206. let numDirectionalShadows = 0;
  11207. let numPointShadows = 0;
  11208. let numSpotShadows = 0;
  11209. lights.sort(shadowCastingLightsFirst);
  11210. for (let i = 0, l = lights.length; i < l; i++) {
  11211. const light = lights[i];
  11212. const color = light.color;
  11213. const intensity = light.intensity;
  11214. const distance = light.distance;
  11215. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  11216. if (light.isAmbientLight) {
  11217. r += color.r * intensity;
  11218. g += color.g * intensity;
  11219. b += color.b * intensity;
  11220. } else if (light.isLightProbe) {
  11221. for (let j = 0; j < 9; j++) {
  11222. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  11223. }
  11224. } else if (light.isDirectionalLight) {
  11225. const uniforms = cache.get(light);
  11226. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  11227. if (light.castShadow) {
  11228. const shadow = light.shadow;
  11229. const shadowUniforms = shadowCache.get(light);
  11230. shadowUniforms.shadowBias = shadow.bias;
  11231. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11232. shadowUniforms.shadowRadius = shadow.radius;
  11233. shadowUniforms.shadowMapSize = shadow.mapSize;
  11234. state.directionalShadow[directionalLength] = shadowUniforms;
  11235. state.directionalShadowMap[directionalLength] = shadowMap;
  11236. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  11237. numDirectionalShadows++;
  11238. }
  11239. state.directional[directionalLength] = uniforms;
  11240. directionalLength++;
  11241. } else if (light.isSpotLight) {
  11242. const uniforms = cache.get(light);
  11243. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11244. uniforms.color.copy(color).multiplyScalar(intensity);
  11245. uniforms.distance = distance;
  11246. uniforms.coneCos = Math.cos(light.angle);
  11247. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  11248. uniforms.decay = light.decay;
  11249. if (light.castShadow) {
  11250. const shadow = light.shadow;
  11251. const shadowUniforms = shadowCache.get(light);
  11252. shadowUniforms.shadowBias = shadow.bias;
  11253. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11254. shadowUniforms.shadowRadius = shadow.radius;
  11255. shadowUniforms.shadowMapSize = shadow.mapSize;
  11256. state.spotShadow[spotLength] = shadowUniforms;
  11257. state.spotShadowMap[spotLength] = shadowMap;
  11258. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  11259. numSpotShadows++;
  11260. }
  11261. state.spot[spotLength] = uniforms;
  11262. spotLength++;
  11263. } else if (light.isRectAreaLight) {
  11264. const uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  11265. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  11266. // (b) intensity is the brightness of the light
  11267. uniforms.color.copy(color).multiplyScalar(intensity);
  11268. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  11269. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  11270. state.rectArea[rectAreaLength] = uniforms;
  11271. rectAreaLength++;
  11272. } else if (light.isPointLight) {
  11273. const uniforms = cache.get(light);
  11274. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  11275. uniforms.distance = light.distance;
  11276. uniforms.decay = light.decay;
  11277. if (light.castShadow) {
  11278. const shadow = light.shadow;
  11279. const shadowUniforms = shadowCache.get(light);
  11280. shadowUniforms.shadowBias = shadow.bias;
  11281. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11282. shadowUniforms.shadowRadius = shadow.radius;
  11283. shadowUniforms.shadowMapSize = shadow.mapSize;
  11284. shadowUniforms.shadowCameraNear = shadow.camera.near;
  11285. shadowUniforms.shadowCameraFar = shadow.camera.far;
  11286. state.pointShadow[pointLength] = shadowUniforms;
  11287. state.pointShadowMap[pointLength] = shadowMap;
  11288. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  11289. numPointShadows++;
  11290. }
  11291. state.point[pointLength] = uniforms;
  11292. pointLength++;
  11293. } else if (light.isHemisphereLight) {
  11294. const uniforms = cache.get(light);
  11295. uniforms.skyColor.copy(light.color).multiplyScalar(intensity);
  11296. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  11297. state.hemi[hemiLength] = uniforms;
  11298. hemiLength++;
  11299. }
  11300. }
  11301. if (rectAreaLength > 0) {
  11302. if (capabilities.isWebGL2) {
  11303. // WebGL 2
  11304. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11305. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11306. } else {
  11307. // WebGL 1
  11308. if (extensions.has('OES_texture_float_linear') === true) {
  11309. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11310. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11311. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  11312. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  11313. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  11314. } else {
  11315. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  11316. }
  11317. }
  11318. }
  11319. state.ambient[0] = r;
  11320. state.ambient[1] = g;
  11321. state.ambient[2] = b;
  11322. const hash = state.hash;
  11323. 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) {
  11324. state.directional.length = directionalLength;
  11325. state.spot.length = spotLength;
  11326. state.rectArea.length = rectAreaLength;
  11327. state.point.length = pointLength;
  11328. state.hemi.length = hemiLength;
  11329. state.directionalShadow.length = numDirectionalShadows;
  11330. state.directionalShadowMap.length = numDirectionalShadows;
  11331. state.pointShadow.length = numPointShadows;
  11332. state.pointShadowMap.length = numPointShadows;
  11333. state.spotShadow.length = numSpotShadows;
  11334. state.spotShadowMap.length = numSpotShadows;
  11335. state.directionalShadowMatrix.length = numDirectionalShadows;
  11336. state.pointShadowMatrix.length = numPointShadows;
  11337. state.spotShadowMatrix.length = numSpotShadows;
  11338. hash.directionalLength = directionalLength;
  11339. hash.pointLength = pointLength;
  11340. hash.spotLength = spotLength;
  11341. hash.rectAreaLength = rectAreaLength;
  11342. hash.hemiLength = hemiLength;
  11343. hash.numDirectionalShadows = numDirectionalShadows;
  11344. hash.numPointShadows = numPointShadows;
  11345. hash.numSpotShadows = numSpotShadows;
  11346. state.version = nextVersion++;
  11347. }
  11348. }
  11349. function setupView(lights, camera) {
  11350. let directionalLength = 0;
  11351. let pointLength = 0;
  11352. let spotLength = 0;
  11353. let rectAreaLength = 0;
  11354. let hemiLength = 0;
  11355. const viewMatrix = camera.matrixWorldInverse;
  11356. for (let i = 0, l = lights.length; i < l; i++) {
  11357. const light = lights[i];
  11358. if (light.isDirectionalLight) {
  11359. const uniforms = state.directional[directionalLength];
  11360. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11361. vector3.setFromMatrixPosition(light.target.matrixWorld);
  11362. uniforms.direction.sub(vector3);
  11363. uniforms.direction.transformDirection(viewMatrix);
  11364. directionalLength++;
  11365. } else if (light.isSpotLight) {
  11366. const uniforms = state.spot[spotLength];
  11367. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11368. uniforms.position.applyMatrix4(viewMatrix);
  11369. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11370. vector3.setFromMatrixPosition(light.target.matrixWorld);
  11371. uniforms.direction.sub(vector3);
  11372. uniforms.direction.transformDirection(viewMatrix);
  11373. spotLength++;
  11374. } else if (light.isRectAreaLight) {
  11375. const uniforms = state.rectArea[rectAreaLength];
  11376. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11377. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  11378. matrix42.identity();
  11379. matrix4.copy(light.matrixWorld);
  11380. matrix4.premultiply(viewMatrix);
  11381. matrix42.extractRotation(matrix4);
  11382. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  11383. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  11384. uniforms.halfWidth.applyMatrix4(matrix42);
  11385. uniforms.halfHeight.applyMatrix4(matrix42);
  11386. rectAreaLength++;
  11387. } else if (light.isPointLight) {
  11388. const uniforms = state.point[pointLength];
  11389. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11390. uniforms.position.applyMatrix4(viewMatrix);
  11391. pointLength++;
  11392. } else if (light.isHemisphereLight) {
  11393. const uniforms = state.hemi[hemiLength];
  11394. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11395. uniforms.direction.transformDirection(viewMatrix);
  11396. uniforms.direction.normalize();
  11397. hemiLength++;
  11398. }
  11399. }
  11400. }
  11401. return {
  11402. setup: setup,
  11403. setupView: setupView,
  11404. state: state
  11405. };
  11406. }
  11407. function WebGLRenderState(extensions, capabilities) {
  11408. const lights = new WebGLLights(extensions, capabilities);
  11409. const lightsArray = [];
  11410. const shadowsArray = [];
  11411. function init() {
  11412. lightsArray.length = 0;
  11413. shadowsArray.length = 0;
  11414. }
  11415. function pushLight(light) {
  11416. lightsArray.push(light);
  11417. }
  11418. function pushShadow(shadowLight) {
  11419. shadowsArray.push(shadowLight);
  11420. }
  11421. function setupLights() {
  11422. lights.setup(lightsArray);
  11423. }
  11424. function setupLightsView(camera) {
  11425. lights.setupView(lightsArray, camera);
  11426. }
  11427. const state = {
  11428. lightsArray: lightsArray,
  11429. shadowsArray: shadowsArray,
  11430. lights: lights
  11431. };
  11432. return {
  11433. init: init,
  11434. state: state,
  11435. setupLights: setupLights,
  11436. setupLightsView: setupLightsView,
  11437. pushLight: pushLight,
  11438. pushShadow: pushShadow
  11439. };
  11440. }
  11441. function WebGLRenderStates(extensions, capabilities) {
  11442. let renderStates = new WeakMap();
  11443. function get(scene, renderCallDepth = 0) {
  11444. let renderState;
  11445. if (renderStates.has(scene) === false) {
  11446. renderState = new WebGLRenderState(extensions, capabilities);
  11447. renderStates.set(scene, [renderState]);
  11448. } else {
  11449. if (renderCallDepth >= renderStates.get(scene).length) {
  11450. renderState = new WebGLRenderState(extensions, capabilities);
  11451. renderStates.get(scene).push(renderState);
  11452. } else {
  11453. renderState = renderStates.get(scene)[renderCallDepth];
  11454. }
  11455. }
  11456. return renderState;
  11457. }
  11458. function dispose() {
  11459. renderStates = new WeakMap();
  11460. }
  11461. return {
  11462. get: get,
  11463. dispose: dispose
  11464. };
  11465. }
  11466. /**
  11467. * parameters = {
  11468. *
  11469. * opacity: <float>,
  11470. *
  11471. * map: new THREE.Texture( <Image> ),
  11472. *
  11473. * alphaMap: new THREE.Texture( <Image> ),
  11474. *
  11475. * displacementMap: new THREE.Texture( <Image> ),
  11476. * displacementScale: <float>,
  11477. * displacementBias: <float>,
  11478. *
  11479. * wireframe: <boolean>,
  11480. * wireframeLinewidth: <float>
  11481. * }
  11482. */
  11483. class MeshDepthMaterial extends Material {
  11484. constructor(parameters) {
  11485. super();
  11486. this.type = 'MeshDepthMaterial';
  11487. this.depthPacking = BasicDepthPacking;
  11488. this.morphTargets = false;
  11489. this.map = null;
  11490. this.alphaMap = null;
  11491. this.displacementMap = null;
  11492. this.displacementScale = 1;
  11493. this.displacementBias = 0;
  11494. this.wireframe = false;
  11495. this.wireframeLinewidth = 1;
  11496. this.fog = false;
  11497. this.setValues(parameters);
  11498. }
  11499. copy(source) {
  11500. super.copy(source);
  11501. this.depthPacking = source.depthPacking;
  11502. this.morphTargets = source.morphTargets;
  11503. this.map = source.map;
  11504. this.alphaMap = source.alphaMap;
  11505. this.displacementMap = source.displacementMap;
  11506. this.displacementScale = source.displacementScale;
  11507. this.displacementBias = source.displacementBias;
  11508. this.wireframe = source.wireframe;
  11509. this.wireframeLinewidth = source.wireframeLinewidth;
  11510. return this;
  11511. }
  11512. }
  11513. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  11514. /**
  11515. * parameters = {
  11516. *
  11517. * referencePosition: <float>,
  11518. * nearDistance: <float>,
  11519. * farDistance: <float>,
  11520. *
  11521. * morphTargets: <bool>,
  11522. *
  11523. * map: new THREE.Texture( <Image> ),
  11524. *
  11525. * alphaMap: new THREE.Texture( <Image> ),
  11526. *
  11527. * displacementMap: new THREE.Texture( <Image> ),
  11528. * displacementScale: <float>,
  11529. * displacementBias: <float>
  11530. *
  11531. * }
  11532. */
  11533. class MeshDistanceMaterial extends Material {
  11534. constructor(parameters) {
  11535. super();
  11536. this.type = 'MeshDistanceMaterial';
  11537. this.referencePosition = new Vector3();
  11538. this.nearDistance = 1;
  11539. this.farDistance = 1000;
  11540. this.morphTargets = false;
  11541. this.map = null;
  11542. this.alphaMap = null;
  11543. this.displacementMap = null;
  11544. this.displacementScale = 1;
  11545. this.displacementBias = 0;
  11546. this.fog = false;
  11547. this.setValues(parameters);
  11548. }
  11549. copy(source) {
  11550. super.copy(source);
  11551. this.referencePosition.copy(source.referencePosition);
  11552. this.nearDistance = source.nearDistance;
  11553. this.farDistance = source.farDistance;
  11554. this.morphTargets = source.morphTargets;
  11555. this.map = source.map;
  11556. this.alphaMap = source.alphaMap;
  11557. this.displacementMap = source.displacementMap;
  11558. this.displacementScale = source.displacementScale;
  11559. this.displacementBias = source.displacementBias;
  11560. return this;
  11561. }
  11562. }
  11563. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  11564. var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n\tfor ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 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, i ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean * HALF_SAMPLE_RATE;\n\tsquared_mean = squared_mean * HALF_SAMPLE_RATE;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  11565. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  11566. function WebGLShadowMap(_renderer, _objects, _capabilities) {
  11567. let _frustum = new Frustum();
  11568. const _shadowMapSize = new Vector2(),
  11569. _viewportSize = new Vector2(),
  11570. _viewport = new Vector4(),
  11571. _depthMaterials = [],
  11572. _distanceMaterials = [],
  11573. _materialCache = {},
  11574. _maxTextureSize = _capabilities.maxTextureSize;
  11575. const shadowSide = {
  11576. 0: BackSide,
  11577. 1: FrontSide,
  11578. 2: DoubleSide
  11579. };
  11580. const shadowMaterialVertical = new ShaderMaterial({
  11581. defines: {
  11582. SAMPLE_RATE: 2.0 / 8.0,
  11583. HALF_SAMPLE_RATE: 1.0 / 8.0
  11584. },
  11585. uniforms: {
  11586. shadow_pass: {
  11587. value: null
  11588. },
  11589. resolution: {
  11590. value: new Vector2()
  11591. },
  11592. radius: {
  11593. value: 4.0
  11594. }
  11595. },
  11596. vertexShader: vsm_vert,
  11597. fragmentShader: vsm_frag
  11598. });
  11599. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  11600. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  11601. const fullScreenTri = new BufferGeometry();
  11602. fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  11603. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  11604. const scope = this;
  11605. this.enabled = false;
  11606. this.autoUpdate = true;
  11607. this.needsUpdate = false;
  11608. this.type = PCFShadowMap;
  11609. this.render = function (lights, scene, camera) {
  11610. if (scope.enabled === false) return;
  11611. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  11612. if (lights.length === 0) return;
  11613. const currentRenderTarget = _renderer.getRenderTarget();
  11614. const activeCubeFace = _renderer.getActiveCubeFace();
  11615. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  11616. const _state = _renderer.state; // Set GL state for depth map.
  11617. _state.setBlending(NoBlending);
  11618. _state.buffers.color.setClear(1, 1, 1, 1);
  11619. _state.buffers.depth.setTest(true);
  11620. _state.setScissorTest(false); // render depth map
  11621. for (let i = 0, il = lights.length; i < il; i++) {
  11622. const light = lights[i];
  11623. const shadow = light.shadow;
  11624. if (shadow === undefined) {
  11625. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  11626. continue;
  11627. }
  11628. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  11629. _shadowMapSize.copy(shadow.mapSize);
  11630. const shadowFrameExtents = shadow.getFrameExtents();
  11631. _shadowMapSize.multiply(shadowFrameExtents);
  11632. _viewportSize.copy(shadow.mapSize);
  11633. if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) {
  11634. if (_shadowMapSize.x > _maxTextureSize) {
  11635. _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x);
  11636. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  11637. shadow.mapSize.x = _viewportSize.x;
  11638. }
  11639. if (_shadowMapSize.y > _maxTextureSize) {
  11640. _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y);
  11641. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  11642. shadow.mapSize.y = _viewportSize.y;
  11643. }
  11644. }
  11645. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  11646. const pars = {
  11647. minFilter: LinearFilter,
  11648. magFilter: LinearFilter,
  11649. format: RGBAFormat
  11650. };
  11651. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  11652. shadow.map.texture.name = light.name + '.shadowMap';
  11653. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  11654. shadow.camera.updateProjectionMatrix();
  11655. }
  11656. if (shadow.map === null) {
  11657. const pars = {
  11658. minFilter: NearestFilter,
  11659. magFilter: NearestFilter,
  11660. format: RGBAFormat
  11661. };
  11662. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  11663. shadow.map.texture.name = light.name + '.shadowMap';
  11664. shadow.camera.updateProjectionMatrix();
  11665. }
  11666. _renderer.setRenderTarget(shadow.map);
  11667. _renderer.clear();
  11668. const viewportCount = shadow.getViewportCount();
  11669. for (let vp = 0; vp < viewportCount; vp++) {
  11670. const viewport = shadow.getViewport(vp);
  11671. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  11672. _state.viewport(_viewport);
  11673. shadow.updateMatrices(light, vp);
  11674. _frustum = shadow.getFrustum();
  11675. renderObject(scene, camera, shadow.camera, light, this.type);
  11676. } // do blur pass for VSM
  11677. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  11678. VSMPass(shadow, camera);
  11679. }
  11680. shadow.needsUpdate = false;
  11681. }
  11682. scope.needsUpdate = false;
  11683. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  11684. };
  11685. function VSMPass(shadow, camera) {
  11686. const geometry = _objects.update(fullScreenMesh); // vertical pass
  11687. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  11688. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  11689. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  11690. _renderer.setRenderTarget(shadow.mapPass);
  11691. _renderer.clear();
  11692. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizontal pass
  11693. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  11694. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  11695. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  11696. _renderer.setRenderTarget(shadow.map);
  11697. _renderer.clear();
  11698. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  11699. }
  11700. function getDepthMaterialVariant(useMorphing) {
  11701. const index = useMorphing << 0;
  11702. let material = _depthMaterials[index];
  11703. if (material === undefined) {
  11704. material = new MeshDepthMaterial({
  11705. depthPacking: RGBADepthPacking,
  11706. morphTargets: useMorphing
  11707. });
  11708. _depthMaterials[index] = material;
  11709. }
  11710. return material;
  11711. }
  11712. function getDistanceMaterialVariant(useMorphing) {
  11713. const index = useMorphing << 0;
  11714. let material = _distanceMaterials[index];
  11715. if (material === undefined) {
  11716. material = new MeshDistanceMaterial({
  11717. morphTargets: useMorphing
  11718. });
  11719. _distanceMaterials[index] = material;
  11720. }
  11721. return material;
  11722. }
  11723. function getDepthMaterial(object, geometry, material, light, shadowCameraNear, shadowCameraFar, type) {
  11724. let result = null;
  11725. let getMaterialVariant = getDepthMaterialVariant;
  11726. let customMaterial = object.customDepthMaterial;
  11727. if (light.isPointLight === true) {
  11728. getMaterialVariant = getDistanceMaterialVariant;
  11729. customMaterial = object.customDistanceMaterial;
  11730. }
  11731. if (customMaterial === undefined) {
  11732. let useMorphing = false;
  11733. if (material.morphTargets === true) {
  11734. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  11735. }
  11736. result = getMaterialVariant(useMorphing);
  11737. } else {
  11738. result = customMaterial;
  11739. }
  11740. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  11741. // in this case we need a unique material instance reflecting the
  11742. // appropriate state
  11743. const keyA = result.uuid,
  11744. keyB = material.uuid;
  11745. let materialsForVariant = _materialCache[keyA];
  11746. if (materialsForVariant === undefined) {
  11747. materialsForVariant = {};
  11748. _materialCache[keyA] = materialsForVariant;
  11749. }
  11750. let cachedMaterial = materialsForVariant[keyB];
  11751. if (cachedMaterial === undefined) {
  11752. cachedMaterial = result.clone();
  11753. materialsForVariant[keyB] = cachedMaterial;
  11754. }
  11755. result = cachedMaterial;
  11756. }
  11757. result.visible = material.visible;
  11758. result.wireframe = material.wireframe;
  11759. if (type === VSMShadowMap) {
  11760. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  11761. } else {
  11762. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  11763. }
  11764. result.clipShadows = material.clipShadows;
  11765. result.clippingPlanes = material.clippingPlanes;
  11766. result.clipIntersection = material.clipIntersection;
  11767. result.wireframeLinewidth = material.wireframeLinewidth;
  11768. result.linewidth = material.linewidth;
  11769. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  11770. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  11771. result.nearDistance = shadowCameraNear;
  11772. result.farDistance = shadowCameraFar;
  11773. }
  11774. return result;
  11775. }
  11776. function renderObject(object, camera, shadowCamera, light, type) {
  11777. if (object.visible === false) return;
  11778. const visible = object.layers.test(camera.layers);
  11779. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  11780. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  11781. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  11782. const geometry = _objects.update(object);
  11783. const material = object.material;
  11784. if (Array.isArray(material)) {
  11785. const groups = geometry.groups;
  11786. for (let k = 0, kl = groups.length; k < kl; k++) {
  11787. const group = groups[k];
  11788. const groupMaterial = material[group.materialIndex];
  11789. if (groupMaterial && groupMaterial.visible) {
  11790. const depthMaterial = getDepthMaterial(object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  11791. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  11792. }
  11793. }
  11794. } else if (material.visible) {
  11795. const depthMaterial = getDepthMaterial(object, geometry, material, light, shadowCamera.near, shadowCamera.far, type);
  11796. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  11797. }
  11798. }
  11799. }
  11800. const children = object.children;
  11801. for (let i = 0, l = children.length; i < l; i++) {
  11802. renderObject(children[i], camera, shadowCamera, light, type);
  11803. }
  11804. }
  11805. }
  11806. function WebGLState(gl, extensions, capabilities) {
  11807. const isWebGL2 = capabilities.isWebGL2;
  11808. function ColorBuffer() {
  11809. let locked = false;
  11810. const color = new Vector4();
  11811. let currentColorMask = null;
  11812. const currentColorClear = new Vector4(0, 0, 0, 0);
  11813. return {
  11814. setMask: function (colorMask) {
  11815. if (currentColorMask !== colorMask && !locked) {
  11816. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  11817. currentColorMask = colorMask;
  11818. }
  11819. },
  11820. setLocked: function (lock) {
  11821. locked = lock;
  11822. },
  11823. setClear: function (r, g, b, a, premultipliedAlpha) {
  11824. if (premultipliedAlpha === true) {
  11825. r *= a;
  11826. g *= a;
  11827. b *= a;
  11828. }
  11829. color.set(r, g, b, a);
  11830. if (currentColorClear.equals(color) === false) {
  11831. gl.clearColor(r, g, b, a);
  11832. currentColorClear.copy(color);
  11833. }
  11834. },
  11835. reset: function () {
  11836. locked = false;
  11837. currentColorMask = null;
  11838. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  11839. }
  11840. };
  11841. }
  11842. function DepthBuffer() {
  11843. let locked = false;
  11844. let currentDepthMask = null;
  11845. let currentDepthFunc = null;
  11846. let currentDepthClear = null;
  11847. return {
  11848. setTest: function (depthTest) {
  11849. if (depthTest) {
  11850. enable(gl.DEPTH_TEST);
  11851. } else {
  11852. disable(gl.DEPTH_TEST);
  11853. }
  11854. },
  11855. setMask: function (depthMask) {
  11856. if (currentDepthMask !== depthMask && !locked) {
  11857. gl.depthMask(depthMask);
  11858. currentDepthMask = depthMask;
  11859. }
  11860. },
  11861. setFunc: function (depthFunc) {
  11862. if (currentDepthFunc !== depthFunc) {
  11863. if (depthFunc) {
  11864. switch (depthFunc) {
  11865. case NeverDepth:
  11866. gl.depthFunc(gl.NEVER);
  11867. break;
  11868. case AlwaysDepth:
  11869. gl.depthFunc(gl.ALWAYS);
  11870. break;
  11871. case LessDepth:
  11872. gl.depthFunc(gl.LESS);
  11873. break;
  11874. case LessEqualDepth:
  11875. gl.depthFunc(gl.LEQUAL);
  11876. break;
  11877. case EqualDepth:
  11878. gl.depthFunc(gl.EQUAL);
  11879. break;
  11880. case GreaterEqualDepth:
  11881. gl.depthFunc(gl.GEQUAL);
  11882. break;
  11883. case GreaterDepth:
  11884. gl.depthFunc(gl.GREATER);
  11885. break;
  11886. case NotEqualDepth:
  11887. gl.depthFunc(gl.NOTEQUAL);
  11888. break;
  11889. default:
  11890. gl.depthFunc(gl.LEQUAL);
  11891. }
  11892. } else {
  11893. gl.depthFunc(gl.LEQUAL);
  11894. }
  11895. currentDepthFunc = depthFunc;
  11896. }
  11897. },
  11898. setLocked: function (lock) {
  11899. locked = lock;
  11900. },
  11901. setClear: function (depth) {
  11902. if (currentDepthClear !== depth) {
  11903. gl.clearDepth(depth);
  11904. currentDepthClear = depth;
  11905. }
  11906. },
  11907. reset: function () {
  11908. locked = false;
  11909. currentDepthMask = null;
  11910. currentDepthFunc = null;
  11911. currentDepthClear = null;
  11912. }
  11913. };
  11914. }
  11915. function StencilBuffer() {
  11916. let locked = false;
  11917. let currentStencilMask = null;
  11918. let currentStencilFunc = null;
  11919. let currentStencilRef = null;
  11920. let currentStencilFuncMask = null;
  11921. let currentStencilFail = null;
  11922. let currentStencilZFail = null;
  11923. let currentStencilZPass = null;
  11924. let currentStencilClear = null;
  11925. return {
  11926. setTest: function (stencilTest) {
  11927. if (!locked) {
  11928. if (stencilTest) {
  11929. enable(gl.STENCIL_TEST);
  11930. } else {
  11931. disable(gl.STENCIL_TEST);
  11932. }
  11933. }
  11934. },
  11935. setMask: function (stencilMask) {
  11936. if (currentStencilMask !== stencilMask && !locked) {
  11937. gl.stencilMask(stencilMask);
  11938. currentStencilMask = stencilMask;
  11939. }
  11940. },
  11941. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  11942. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  11943. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  11944. currentStencilFunc = stencilFunc;
  11945. currentStencilRef = stencilRef;
  11946. currentStencilFuncMask = stencilMask;
  11947. }
  11948. },
  11949. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  11950. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  11951. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  11952. currentStencilFail = stencilFail;
  11953. currentStencilZFail = stencilZFail;
  11954. currentStencilZPass = stencilZPass;
  11955. }
  11956. },
  11957. setLocked: function (lock) {
  11958. locked = lock;
  11959. },
  11960. setClear: function (stencil) {
  11961. if (currentStencilClear !== stencil) {
  11962. gl.clearStencil(stencil);
  11963. currentStencilClear = stencil;
  11964. }
  11965. },
  11966. reset: function () {
  11967. locked = false;
  11968. currentStencilMask = null;
  11969. currentStencilFunc = null;
  11970. currentStencilRef = null;
  11971. currentStencilFuncMask = null;
  11972. currentStencilFail = null;
  11973. currentStencilZFail = null;
  11974. currentStencilZPass = null;
  11975. currentStencilClear = null;
  11976. }
  11977. };
  11978. } //
  11979. const colorBuffer = new ColorBuffer();
  11980. const depthBuffer = new DepthBuffer();
  11981. const stencilBuffer = new StencilBuffer();
  11982. let enabledCapabilities = {};
  11983. let xrFramebuffer = null;
  11984. let currentBoundFramebuffers = {};
  11985. let currentProgram = null;
  11986. let currentBlendingEnabled = false;
  11987. let currentBlending = null;
  11988. let currentBlendEquation = null;
  11989. let currentBlendSrc = null;
  11990. let currentBlendDst = null;
  11991. let currentBlendEquationAlpha = null;
  11992. let currentBlendSrcAlpha = null;
  11993. let currentBlendDstAlpha = null;
  11994. let currentPremultipledAlpha = false;
  11995. let currentFlipSided = null;
  11996. let currentCullFace = null;
  11997. let currentLineWidth = null;
  11998. let currentPolygonOffsetFactor = null;
  11999. let currentPolygonOffsetUnits = null;
  12000. const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12001. let lineWidthAvailable = false;
  12002. let version = 0;
  12003. const glVersion = gl.getParameter(gl.VERSION);
  12004. if (glVersion.indexOf('WebGL') !== -1) {
  12005. version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
  12006. lineWidthAvailable = version >= 1.0;
  12007. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  12008. version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
  12009. lineWidthAvailable = version >= 2.0;
  12010. }
  12011. let currentTextureSlot = null;
  12012. let currentBoundTextures = {};
  12013. const scissorParam = gl.getParameter(gl.SCISSOR_BOX);
  12014. const viewportParam = gl.getParameter(gl.VIEWPORT);
  12015. const currentScissor = new Vector4().fromArray(scissorParam);
  12016. const currentViewport = new Vector4().fromArray(viewportParam);
  12017. function createTexture(type, target, count) {
  12018. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  12019. const texture = gl.createTexture();
  12020. gl.bindTexture(type, texture);
  12021. gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12022. gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12023. for (let i = 0; i < count; i++) {
  12024. gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
  12025. }
  12026. return texture;
  12027. }
  12028. const emptyTextures = {};
  12029. emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1);
  12030. emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); // init
  12031. colorBuffer.setClear(0, 0, 0, 1);
  12032. depthBuffer.setClear(1);
  12033. stencilBuffer.setClear(0);
  12034. enable(gl.DEPTH_TEST);
  12035. depthBuffer.setFunc(LessEqualDepth);
  12036. setFlipSided(false);
  12037. setCullFace(CullFaceBack);
  12038. enable(gl.CULL_FACE);
  12039. setBlending(NoBlending); //
  12040. function enable(id) {
  12041. if (enabledCapabilities[id] !== true) {
  12042. gl.enable(id);
  12043. enabledCapabilities[id] = true;
  12044. }
  12045. }
  12046. function disable(id) {
  12047. if (enabledCapabilities[id] !== false) {
  12048. gl.disable(id);
  12049. enabledCapabilities[id] = false;
  12050. }
  12051. }
  12052. function bindXRFramebuffer(framebuffer) {
  12053. if (framebuffer !== xrFramebuffer) {
  12054. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  12055. xrFramebuffer = framebuffer;
  12056. }
  12057. }
  12058. function bindFramebuffer(target, framebuffer) {
  12059. if (framebuffer === null && xrFramebuffer !== null) framebuffer = xrFramebuffer; // use active XR framebuffer if available
  12060. if (currentBoundFramebuffers[target] !== framebuffer) {
  12061. gl.bindFramebuffer(target, framebuffer);
  12062. currentBoundFramebuffers[target] = framebuffer;
  12063. if (isWebGL2) {
  12064. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  12065. if (target === gl.DRAW_FRAMEBUFFER) {
  12066. currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer;
  12067. }
  12068. if (target === gl.FRAMEBUFFER) {
  12069. currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer;
  12070. }
  12071. }
  12072. return true;
  12073. }
  12074. return false;
  12075. }
  12076. function useProgram(program) {
  12077. if (currentProgram !== program) {
  12078. gl.useProgram(program);
  12079. currentProgram = program;
  12080. return true;
  12081. }
  12082. return false;
  12083. }
  12084. const equationToGL = {
  12085. [AddEquation]: gl.FUNC_ADD,
  12086. [SubtractEquation]: gl.FUNC_SUBTRACT,
  12087. [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT
  12088. };
  12089. if (isWebGL2) {
  12090. equationToGL[MinEquation] = gl.MIN;
  12091. equationToGL[MaxEquation] = gl.MAX;
  12092. } else {
  12093. const extension = extensions.get('EXT_blend_minmax');
  12094. if (extension !== null) {
  12095. equationToGL[MinEquation] = extension.MIN_EXT;
  12096. equationToGL[MaxEquation] = extension.MAX_EXT;
  12097. }
  12098. }
  12099. const factorToGL = {
  12100. [ZeroFactor]: gl.ZERO,
  12101. [OneFactor]: gl.ONE,
  12102. [SrcColorFactor]: gl.SRC_COLOR,
  12103. [SrcAlphaFactor]: gl.SRC_ALPHA,
  12104. [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE,
  12105. [DstColorFactor]: gl.DST_COLOR,
  12106. [DstAlphaFactor]: gl.DST_ALPHA,
  12107. [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR,
  12108. [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA,
  12109. [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR,
  12110. [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA
  12111. };
  12112. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  12113. if (blending === NoBlending) {
  12114. if (currentBlendingEnabled === true) {
  12115. disable(gl.BLEND);
  12116. currentBlendingEnabled = false;
  12117. }
  12118. return;
  12119. }
  12120. if (currentBlendingEnabled === false) {
  12121. enable(gl.BLEND);
  12122. currentBlendingEnabled = true;
  12123. }
  12124. if (blending !== CustomBlending) {
  12125. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  12126. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  12127. gl.blendEquation(gl.FUNC_ADD);
  12128. currentBlendEquation = AddEquation;
  12129. currentBlendEquationAlpha = AddEquation;
  12130. }
  12131. if (premultipliedAlpha) {
  12132. switch (blending) {
  12133. case NormalBlending:
  12134. gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  12135. break;
  12136. case AdditiveBlending:
  12137. gl.blendFunc(gl.ONE, gl.ONE);
  12138. break;
  12139. case SubtractiveBlending:
  12140. gl.blendFuncSeparate(gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA);
  12141. break;
  12142. case MultiplyBlending:
  12143. gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA);
  12144. break;
  12145. default:
  12146. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12147. break;
  12148. }
  12149. } else {
  12150. switch (blending) {
  12151. case NormalBlending:
  12152. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  12153. break;
  12154. case AdditiveBlending:
  12155. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  12156. break;
  12157. case SubtractiveBlending:
  12158. gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_COLOR);
  12159. break;
  12160. case MultiplyBlending:
  12161. gl.blendFunc(gl.ZERO, gl.SRC_COLOR);
  12162. break;
  12163. default:
  12164. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12165. break;
  12166. }
  12167. }
  12168. currentBlendSrc = null;
  12169. currentBlendDst = null;
  12170. currentBlendSrcAlpha = null;
  12171. currentBlendDstAlpha = null;
  12172. currentBlending = blending;
  12173. currentPremultipledAlpha = premultipliedAlpha;
  12174. }
  12175. return;
  12176. } // custom blending
  12177. blendEquationAlpha = blendEquationAlpha || blendEquation;
  12178. blendSrcAlpha = blendSrcAlpha || blendSrc;
  12179. blendDstAlpha = blendDstAlpha || blendDst;
  12180. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  12181. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  12182. currentBlendEquation = blendEquation;
  12183. currentBlendEquationAlpha = blendEquationAlpha;
  12184. }
  12185. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  12186. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  12187. currentBlendSrc = blendSrc;
  12188. currentBlendDst = blendDst;
  12189. currentBlendSrcAlpha = blendSrcAlpha;
  12190. currentBlendDstAlpha = blendDstAlpha;
  12191. }
  12192. currentBlending = blending;
  12193. currentPremultipledAlpha = null;
  12194. }
  12195. function setMaterial(material, frontFaceCW) {
  12196. material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE);
  12197. let flipSided = material.side === BackSide;
  12198. if (frontFaceCW) flipSided = !flipSided;
  12199. setFlipSided(flipSided);
  12200. 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);
  12201. depthBuffer.setFunc(material.depthFunc);
  12202. depthBuffer.setTest(material.depthTest);
  12203. depthBuffer.setMask(material.depthWrite);
  12204. colorBuffer.setMask(material.colorWrite);
  12205. const stencilWrite = material.stencilWrite;
  12206. stencilBuffer.setTest(stencilWrite);
  12207. if (stencilWrite) {
  12208. stencilBuffer.setMask(material.stencilWriteMask);
  12209. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  12210. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  12211. }
  12212. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  12213. material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  12214. } //
  12215. function setFlipSided(flipSided) {
  12216. if (currentFlipSided !== flipSided) {
  12217. if (flipSided) {
  12218. gl.frontFace(gl.CW);
  12219. } else {
  12220. gl.frontFace(gl.CCW);
  12221. }
  12222. currentFlipSided = flipSided;
  12223. }
  12224. }
  12225. function setCullFace(cullFace) {
  12226. if (cullFace !== CullFaceNone) {
  12227. enable(gl.CULL_FACE);
  12228. if (cullFace !== currentCullFace) {
  12229. if (cullFace === CullFaceBack) {
  12230. gl.cullFace(gl.BACK);
  12231. } else if (cullFace === CullFaceFront) {
  12232. gl.cullFace(gl.FRONT);
  12233. } else {
  12234. gl.cullFace(gl.FRONT_AND_BACK);
  12235. }
  12236. }
  12237. } else {
  12238. disable(gl.CULL_FACE);
  12239. }
  12240. currentCullFace = cullFace;
  12241. }
  12242. function setLineWidth(width) {
  12243. if (width !== currentLineWidth) {
  12244. if (lineWidthAvailable) gl.lineWidth(width);
  12245. currentLineWidth = width;
  12246. }
  12247. }
  12248. function setPolygonOffset(polygonOffset, factor, units) {
  12249. if (polygonOffset) {
  12250. enable(gl.POLYGON_OFFSET_FILL);
  12251. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  12252. gl.polygonOffset(factor, units);
  12253. currentPolygonOffsetFactor = factor;
  12254. currentPolygonOffsetUnits = units;
  12255. }
  12256. } else {
  12257. disable(gl.POLYGON_OFFSET_FILL);
  12258. }
  12259. }
  12260. function setScissorTest(scissorTest) {
  12261. if (scissorTest) {
  12262. enable(gl.SCISSOR_TEST);
  12263. } else {
  12264. disable(gl.SCISSOR_TEST);
  12265. }
  12266. } // texture
  12267. function activeTexture(webglSlot) {
  12268. if (webglSlot === undefined) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  12269. if (currentTextureSlot !== webglSlot) {
  12270. gl.activeTexture(webglSlot);
  12271. currentTextureSlot = webglSlot;
  12272. }
  12273. }
  12274. function bindTexture(webglType, webglTexture) {
  12275. if (currentTextureSlot === null) {
  12276. activeTexture();
  12277. }
  12278. let boundTexture = currentBoundTextures[currentTextureSlot];
  12279. if (boundTexture === undefined) {
  12280. boundTexture = {
  12281. type: undefined,
  12282. texture: undefined
  12283. };
  12284. currentBoundTextures[currentTextureSlot] = boundTexture;
  12285. }
  12286. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  12287. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  12288. boundTexture.type = webglType;
  12289. boundTexture.texture = webglTexture;
  12290. }
  12291. }
  12292. function unbindTexture() {
  12293. const boundTexture = currentBoundTextures[currentTextureSlot];
  12294. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  12295. gl.bindTexture(boundTexture.type, null);
  12296. boundTexture.type = undefined;
  12297. boundTexture.texture = undefined;
  12298. }
  12299. }
  12300. function compressedTexImage2D() {
  12301. try {
  12302. gl.compressedTexImage2D.apply(gl, arguments);
  12303. } catch (error) {
  12304. console.error('THREE.WebGLState:', error);
  12305. }
  12306. }
  12307. function texImage2D() {
  12308. try {
  12309. gl.texImage2D.apply(gl, arguments);
  12310. } catch (error) {
  12311. console.error('THREE.WebGLState:', error);
  12312. }
  12313. }
  12314. function texImage3D() {
  12315. try {
  12316. gl.texImage3D.apply(gl, arguments);
  12317. } catch (error) {
  12318. console.error('THREE.WebGLState:', error);
  12319. }
  12320. } //
  12321. function scissor(scissor) {
  12322. if (currentScissor.equals(scissor) === false) {
  12323. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  12324. currentScissor.copy(scissor);
  12325. }
  12326. }
  12327. function viewport(viewport) {
  12328. if (currentViewport.equals(viewport) === false) {
  12329. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  12330. currentViewport.copy(viewport);
  12331. }
  12332. } //
  12333. function reset() {
  12334. // reset state
  12335. gl.disable(gl.BLEND);
  12336. gl.disable(gl.CULL_FACE);
  12337. gl.disable(gl.DEPTH_TEST);
  12338. gl.disable(gl.POLYGON_OFFSET_FILL);
  12339. gl.disable(gl.SCISSOR_TEST);
  12340. gl.disable(gl.STENCIL_TEST);
  12341. gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  12342. gl.blendEquation(gl.FUNC_ADD);
  12343. gl.blendFunc(gl.ONE, gl.ZERO);
  12344. gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
  12345. gl.colorMask(true, true, true, true);
  12346. gl.clearColor(0, 0, 0, 0);
  12347. gl.depthMask(true);
  12348. gl.depthFunc(gl.LESS);
  12349. gl.clearDepth(1);
  12350. gl.stencilMask(0xffffffff);
  12351. gl.stencilFunc(gl.ALWAYS, 0, 0xffffffff);
  12352. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  12353. gl.clearStencil(0);
  12354. gl.cullFace(gl.BACK);
  12355. gl.frontFace(gl.CCW);
  12356. gl.polygonOffset(0, 0);
  12357. gl.activeTexture(gl.TEXTURE0);
  12358. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12359. if (isWebGL2 === true) {
  12360. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  12361. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  12362. }
  12363. gl.useProgram(null);
  12364. gl.lineWidth(1);
  12365. gl.scissor(0, 0, gl.canvas.width, gl.canvas.height);
  12366. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); // reset internals
  12367. enabledCapabilities = {};
  12368. currentTextureSlot = null;
  12369. currentBoundTextures = {};
  12370. xrFramebuffer = null;
  12371. currentBoundFramebuffers = {};
  12372. currentProgram = null;
  12373. currentBlendingEnabled = false;
  12374. currentBlending = null;
  12375. currentBlendEquation = null;
  12376. currentBlendSrc = null;
  12377. currentBlendDst = null;
  12378. currentBlendEquationAlpha = null;
  12379. currentBlendSrcAlpha = null;
  12380. currentBlendDstAlpha = null;
  12381. currentPremultipledAlpha = false;
  12382. currentFlipSided = null;
  12383. currentCullFace = null;
  12384. currentLineWidth = null;
  12385. currentPolygonOffsetFactor = null;
  12386. currentPolygonOffsetUnits = null;
  12387. currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height);
  12388. currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height);
  12389. colorBuffer.reset();
  12390. depthBuffer.reset();
  12391. stencilBuffer.reset();
  12392. }
  12393. return {
  12394. buffers: {
  12395. color: colorBuffer,
  12396. depth: depthBuffer,
  12397. stencil: stencilBuffer
  12398. },
  12399. enable: enable,
  12400. disable: disable,
  12401. bindFramebuffer: bindFramebuffer,
  12402. bindXRFramebuffer: bindXRFramebuffer,
  12403. useProgram: useProgram,
  12404. setBlending: setBlending,
  12405. setMaterial: setMaterial,
  12406. setFlipSided: setFlipSided,
  12407. setCullFace: setCullFace,
  12408. setLineWidth: setLineWidth,
  12409. setPolygonOffset: setPolygonOffset,
  12410. setScissorTest: setScissorTest,
  12411. activeTexture: activeTexture,
  12412. bindTexture: bindTexture,
  12413. unbindTexture: unbindTexture,
  12414. compressedTexImage2D: compressedTexImage2D,
  12415. texImage2D: texImage2D,
  12416. texImage3D: texImage3D,
  12417. scissor: scissor,
  12418. viewport: viewport,
  12419. reset: reset
  12420. };
  12421. }
  12422. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  12423. const isWebGL2 = capabilities.isWebGL2;
  12424. const maxTextures = capabilities.maxTextures;
  12425. const maxCubemapSize = capabilities.maxCubemapSize;
  12426. const maxTextureSize = capabilities.maxTextureSize;
  12427. const maxSamples = capabilities.maxSamples;
  12428. const _videoTextures = new WeakMap();
  12429. let _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  12430. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  12431. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  12432. let useOffscreenCanvas = false;
  12433. try {
  12434. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext('2d') !== null;
  12435. } catch (err) {// Ignore any errors
  12436. }
  12437. function createCanvas(width, height) {
  12438. // Use OffscreenCanvas when available. Specially needed in web workers
  12439. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  12440. }
  12441. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  12442. let scale = 1; // handle case if texture exceeds max size
  12443. if (image.width > maxSize || image.height > maxSize) {
  12444. scale = maxSize / Math.max(image.width, image.height);
  12445. } // only perform resize if necessary
  12446. if (scale < 1 || needsPowerOfTwo === true) {
  12447. // only perform resize for certain image types
  12448. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  12449. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  12450. const width = floor(scale * image.width);
  12451. const height = floor(scale * image.height);
  12452. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  12453. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  12454. canvas.width = width;
  12455. canvas.height = height;
  12456. const context = canvas.getContext('2d');
  12457. context.drawImage(image, 0, 0, width, height);
  12458. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  12459. return canvas;
  12460. } else {
  12461. if ('data' in image) {
  12462. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  12463. }
  12464. return image;
  12465. }
  12466. }
  12467. return image;
  12468. }
  12469. function isPowerOfTwo$1(image) {
  12470. return isPowerOfTwo(image.width) && isPowerOfTwo(image.height);
  12471. }
  12472. function textureNeedsPowerOfTwo(texture) {
  12473. if (isWebGL2) return false;
  12474. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  12475. }
  12476. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  12477. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  12478. }
  12479. function generateMipmap(target, texture, width, height) {
  12480. _gl.generateMipmap(target);
  12481. const textureProperties = properties.get(texture);
  12482. textureProperties.__maxMipLevel = Math.log2(Math.max(width, height));
  12483. }
  12484. function getInternalFormat(internalFormatName, glFormat, glType) {
  12485. if (isWebGL2 === false) return glFormat;
  12486. if (internalFormatName !== null) {
  12487. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  12488. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  12489. }
  12490. let internalFormat = glFormat;
  12491. if (glFormat === _gl.RED) {
  12492. if (glType === _gl.FLOAT) internalFormat = _gl.R32F;
  12493. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F;
  12494. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8;
  12495. }
  12496. if (glFormat === _gl.RGB) {
  12497. if (glType === _gl.FLOAT) internalFormat = _gl.RGB32F;
  12498. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGB16F;
  12499. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGB8;
  12500. }
  12501. if (glFormat === _gl.RGBA) {
  12502. if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
  12503. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
  12504. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGBA8;
  12505. }
  12506. if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) {
  12507. extensions.get('EXT_color_buffer_float');
  12508. }
  12509. return internalFormat;
  12510. } // Fallback filters for non-power-of-2 textures
  12511. function filterFallback(f) {
  12512. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  12513. return _gl.NEAREST;
  12514. }
  12515. return _gl.LINEAR;
  12516. } //
  12517. function onTextureDispose(event) {
  12518. const texture = event.target;
  12519. texture.removeEventListener('dispose', onTextureDispose);
  12520. deallocateTexture(texture);
  12521. if (texture.isVideoTexture) {
  12522. _videoTextures.delete(texture);
  12523. }
  12524. info.memory.textures--;
  12525. }
  12526. function onRenderTargetDispose(event) {
  12527. const renderTarget = event.target;
  12528. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  12529. deallocateRenderTarget(renderTarget);
  12530. } //
  12531. function deallocateTexture(texture) {
  12532. const textureProperties = properties.get(texture);
  12533. if (textureProperties.__webglInit === undefined) return;
  12534. _gl.deleteTexture(textureProperties.__webglTexture);
  12535. properties.remove(texture);
  12536. }
  12537. function deallocateRenderTarget(renderTarget) {
  12538. const texture = renderTarget.texture;
  12539. const renderTargetProperties = properties.get(renderTarget);
  12540. const textureProperties = properties.get(texture);
  12541. if (!renderTarget) return;
  12542. if (textureProperties.__webglTexture !== undefined) {
  12543. _gl.deleteTexture(textureProperties.__webglTexture);
  12544. info.memory.textures--;
  12545. }
  12546. if (renderTarget.depthTexture) {
  12547. renderTarget.depthTexture.dispose();
  12548. }
  12549. if (renderTarget.isWebGLCubeRenderTarget) {
  12550. for (let i = 0; i < 6; i++) {
  12551. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  12552. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  12553. }
  12554. } else {
  12555. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  12556. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  12557. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  12558. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  12559. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  12560. }
  12561. if (renderTarget.isWebGLMultipleRenderTargets) {
  12562. for (let i = 0, il = texture.length; i < il; i++) {
  12563. const attachmentProperties = properties.get(texture[i]);
  12564. if (attachmentProperties.__webglTexture) {
  12565. _gl.deleteTexture(attachmentProperties.__webglTexture);
  12566. info.memory.textures--;
  12567. }
  12568. properties.remove(texture[i]);
  12569. }
  12570. }
  12571. properties.remove(texture);
  12572. properties.remove(renderTarget);
  12573. } //
  12574. let textureUnits = 0;
  12575. function resetTextureUnits() {
  12576. textureUnits = 0;
  12577. }
  12578. function allocateTextureUnit() {
  12579. const textureUnit = textureUnits;
  12580. if (textureUnit >= maxTextures) {
  12581. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  12582. }
  12583. textureUnits += 1;
  12584. return textureUnit;
  12585. } //
  12586. function setTexture2D(texture, slot) {
  12587. const textureProperties = properties.get(texture);
  12588. if (texture.isVideoTexture) updateVideoTexture(texture);
  12589. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12590. const image = texture.image;
  12591. if (image === undefined) {
  12592. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  12593. } else if (image.complete === false) {
  12594. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  12595. } else {
  12596. uploadTexture(textureProperties, texture, slot);
  12597. return;
  12598. }
  12599. }
  12600. state.activeTexture(_gl.TEXTURE0 + slot);
  12601. state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture);
  12602. }
  12603. function setTexture2DArray(texture, slot) {
  12604. const textureProperties = properties.get(texture);
  12605. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12606. uploadTexture(textureProperties, texture, slot);
  12607. return;
  12608. }
  12609. state.activeTexture(_gl.TEXTURE0 + slot);
  12610. state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture);
  12611. }
  12612. function setTexture3D(texture, slot) {
  12613. const textureProperties = properties.get(texture);
  12614. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12615. uploadTexture(textureProperties, texture, slot);
  12616. return;
  12617. }
  12618. state.activeTexture(_gl.TEXTURE0 + slot);
  12619. state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture);
  12620. }
  12621. function setTextureCube(texture, slot) {
  12622. const textureProperties = properties.get(texture);
  12623. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12624. uploadCubeTexture(textureProperties, texture, slot);
  12625. return;
  12626. }
  12627. state.activeTexture(_gl.TEXTURE0 + slot);
  12628. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  12629. }
  12630. const wrappingToGL = {
  12631. [RepeatWrapping]: _gl.REPEAT,
  12632. [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE,
  12633. [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT
  12634. };
  12635. const filterToGL = {
  12636. [NearestFilter]: _gl.NEAREST,
  12637. [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST,
  12638. [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR,
  12639. [LinearFilter]: _gl.LINEAR,
  12640. [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST,
  12641. [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR
  12642. };
  12643. function setTextureParameters(textureType, texture, supportsMips) {
  12644. if (supportsMips) {
  12645. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]);
  12646. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]);
  12647. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  12648. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]);
  12649. }
  12650. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]);
  12651. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]);
  12652. } else {
  12653. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE);
  12654. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE);
  12655. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  12656. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE);
  12657. }
  12658. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  12659. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  12660. }
  12661. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter));
  12662. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter));
  12663. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  12664. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  12665. }
  12666. }
  12667. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  12668. const extension = extensions.get('EXT_texture_filter_anisotropic');
  12669. if (texture.type === FloatType && extensions.has('OES_texture_float_linear') === false) return; // verify extension for WebGL 1 and WebGL 2
  12670. if (isWebGL2 === false && texture.type === HalfFloatType && extensions.has('OES_texture_half_float_linear') === false) return; // verify extension for WebGL 1 only
  12671. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  12672. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  12673. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  12674. }
  12675. }
  12676. }
  12677. function initTexture(textureProperties, texture) {
  12678. if (textureProperties.__webglInit === undefined) {
  12679. textureProperties.__webglInit = true;
  12680. texture.addEventListener('dispose', onTextureDispose);
  12681. textureProperties.__webglTexture = _gl.createTexture();
  12682. info.memory.textures++;
  12683. }
  12684. }
  12685. function uploadTexture(textureProperties, texture, slot) {
  12686. let textureType = _gl.TEXTURE_2D;
  12687. if (texture.isDataTexture2DArray) textureType = _gl.TEXTURE_2D_ARRAY;
  12688. if (texture.isDataTexture3D) textureType = _gl.TEXTURE_3D;
  12689. initTexture(textureProperties, texture);
  12690. state.activeTexture(_gl.TEXTURE0 + slot);
  12691. state.bindTexture(textureType, textureProperties.__webglTexture);
  12692. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  12693. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  12694. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  12695. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  12696. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false;
  12697. const image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  12698. const supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  12699. glFormat = utils.convert(texture.format);
  12700. let glType = utils.convert(texture.type),
  12701. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12702. setTextureParameters(textureType, texture, supportsMips);
  12703. let mipmap;
  12704. const mipmaps = texture.mipmaps;
  12705. if (texture.isDepthTexture) {
  12706. // populate depth texture with dummy data
  12707. glInternalFormat = _gl.DEPTH_COMPONENT;
  12708. if (isWebGL2) {
  12709. if (texture.type === FloatType) {
  12710. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  12711. } else if (texture.type === UnsignedIntType) {
  12712. glInternalFormat = _gl.DEPTH_COMPONENT24;
  12713. } else if (texture.type === UnsignedInt248Type) {
  12714. glInternalFormat = _gl.DEPTH24_STENCIL8;
  12715. } else {
  12716. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  12717. }
  12718. } else {
  12719. if (texture.type === FloatType) {
  12720. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  12721. }
  12722. } // validation checks for WebGL 1
  12723. if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  12724. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  12725. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  12726. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12727. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  12728. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  12729. texture.type = UnsignedShortType;
  12730. glType = utils.convert(texture.type);
  12731. }
  12732. }
  12733. if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  12734. // Depth stencil textures need the DEPTH_STENCIL internal format
  12735. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12736. glInternalFormat = _gl.DEPTH_STENCIL; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  12737. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  12738. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12739. if (texture.type !== UnsignedInt248Type) {
  12740. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  12741. texture.type = UnsignedInt248Type;
  12742. glType = utils.convert(texture.type);
  12743. }
  12744. } //
  12745. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  12746. } else if (texture.isDataTexture) {
  12747. // use manually created mipmaps if available
  12748. // if there are no manual mipmaps
  12749. // set 0 level mipmap and then use GL to generate other mipmap levels
  12750. if (mipmaps.length > 0 && supportsMips) {
  12751. for (let i = 0, il = mipmaps.length; i < il; i++) {
  12752. mipmap = mipmaps[i];
  12753. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  12754. }
  12755. texture.generateMipmaps = false;
  12756. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12757. } else {
  12758. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  12759. textureProperties.__maxMipLevel = 0;
  12760. }
  12761. } else if (texture.isCompressedTexture) {
  12762. for (let i = 0, il = mipmaps.length; i < il; i++) {
  12763. mipmap = mipmaps[i];
  12764. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  12765. if (glFormat !== null) {
  12766. state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  12767. } else {
  12768. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  12769. }
  12770. } else {
  12771. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  12772. }
  12773. }
  12774. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12775. } else if (texture.isDataTexture2DArray) {
  12776. state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  12777. textureProperties.__maxMipLevel = 0;
  12778. } else if (texture.isDataTexture3D) {
  12779. state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  12780. textureProperties.__maxMipLevel = 0;
  12781. } else {
  12782. // regular Texture (image, video, canvas)
  12783. // use manually created mipmaps if available
  12784. // if there are no manual mipmaps
  12785. // set 0 level mipmap and then use GL to generate other mipmap levels
  12786. if (mipmaps.length > 0 && supportsMips) {
  12787. for (let i = 0, il = mipmaps.length; i < il; i++) {
  12788. mipmap = mipmaps[i];
  12789. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap);
  12790. }
  12791. texture.generateMipmaps = false;
  12792. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12793. } else {
  12794. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image);
  12795. textureProperties.__maxMipLevel = 0;
  12796. }
  12797. }
  12798. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  12799. generateMipmap(textureType, texture, image.width, image.height);
  12800. }
  12801. textureProperties.__version = texture.version;
  12802. if (texture.onUpdate) texture.onUpdate(texture);
  12803. }
  12804. function uploadCubeTexture(textureProperties, texture, slot) {
  12805. if (texture.image.length !== 6) return;
  12806. initTexture(textureProperties, texture);
  12807. state.activeTexture(_gl.TEXTURE0 + slot);
  12808. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  12809. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  12810. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  12811. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  12812. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  12813. const isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
  12814. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  12815. const cubeImage = [];
  12816. for (let i = 0; i < 6; i++) {
  12817. if (!isCompressed && !isDataTexture) {
  12818. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  12819. } else {
  12820. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  12821. }
  12822. }
  12823. const image = cubeImage[0],
  12824. supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  12825. glFormat = utils.convert(texture.format),
  12826. glType = utils.convert(texture.type),
  12827. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12828. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  12829. let mipmaps;
  12830. if (isCompressed) {
  12831. for (let i = 0; i < 6; i++) {
  12832. mipmaps = cubeImage[i].mipmaps;
  12833. for (let j = 0; j < mipmaps.length; j++) {
  12834. const mipmap = mipmaps[j];
  12835. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  12836. if (glFormat !== null) {
  12837. state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  12838. } else {
  12839. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  12840. }
  12841. } else {
  12842. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  12843. }
  12844. }
  12845. }
  12846. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12847. } else {
  12848. mipmaps = texture.mipmaps;
  12849. for (let i = 0; i < 6; i++) {
  12850. if (isDataTexture) {
  12851. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  12852. for (let j = 0; j < mipmaps.length; j++) {
  12853. const mipmap = mipmaps[j];
  12854. const mipmapImage = mipmap.image[i].image;
  12855. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  12856. }
  12857. } else {
  12858. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  12859. for (let j = 0; j < mipmaps.length; j++) {
  12860. const mipmap = mipmaps[j];
  12861. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  12862. }
  12863. }
  12864. }
  12865. textureProperties.__maxMipLevel = mipmaps.length;
  12866. }
  12867. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  12868. // We assume images for cube map have the same size.
  12869. generateMipmap(_gl.TEXTURE_CUBE_MAP, texture, image.width, image.height);
  12870. }
  12871. textureProperties.__version = texture.version;
  12872. if (texture.onUpdate) texture.onUpdate(texture);
  12873. } // Render targets
  12874. // Setup storage for target texture and bind it to correct framebuffer
  12875. function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) {
  12876. const glFormat = utils.convert(texture.format);
  12877. const glType = utils.convert(texture.type);
  12878. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12879. if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) {
  12880. state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null);
  12881. } else {
  12882. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  12883. }
  12884. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  12885. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0);
  12886. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  12887. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  12888. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  12889. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
  12890. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  12891. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  12892. if (isMultisample) {
  12893. const depthTexture = renderTarget.depthTexture;
  12894. if (depthTexture && depthTexture.isDepthTexture) {
  12895. if (depthTexture.type === FloatType) {
  12896. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  12897. } else if (depthTexture.type === UnsignedIntType) {
  12898. glInternalFormat = _gl.DEPTH_COMPONENT24;
  12899. }
  12900. }
  12901. const samples = getRenderTargetSamples(renderTarget);
  12902. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  12903. } else {
  12904. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  12905. }
  12906. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  12907. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  12908. if (isMultisample) {
  12909. const samples = getRenderTargetSamples(renderTarget);
  12910. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  12911. } else {
  12912. _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height);
  12913. }
  12914. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  12915. } else {
  12916. // Use the first texture for MRT so far
  12917. const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[0] : renderTarget.texture;
  12918. const glFormat = utils.convert(texture.format);
  12919. const glType = utils.convert(texture.type);
  12920. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12921. if (isMultisample) {
  12922. const samples = getRenderTargetSamples(renderTarget);
  12923. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  12924. } else {
  12925. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  12926. }
  12927. }
  12928. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  12929. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  12930. function setupDepthTexture(framebuffer, renderTarget) {
  12931. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  12932. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  12933. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  12934. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  12935. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  12936. } // upload an empty depth texture with framebuffer size
  12937. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  12938. renderTarget.depthTexture.image.width = renderTarget.width;
  12939. renderTarget.depthTexture.image.height = renderTarget.height;
  12940. renderTarget.depthTexture.needsUpdate = true;
  12941. }
  12942. setTexture2D(renderTarget.depthTexture, 0);
  12943. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  12944. if (renderTarget.depthTexture.format === DepthFormat) {
  12945. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  12946. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  12947. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  12948. } else {
  12949. throw new Error('Unknown depthTexture format');
  12950. }
  12951. } // Setup GL resources for a non-texture depth buffer
  12952. function setupDepthRenderbuffer(renderTarget) {
  12953. const renderTargetProperties = properties.get(renderTarget);
  12954. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  12955. if (renderTarget.depthTexture) {
  12956. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  12957. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  12958. } else {
  12959. if (isCube) {
  12960. renderTargetProperties.__webglDepthbuffer = [];
  12961. for (let i = 0; i < 6; i++) {
  12962. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]);
  12963. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  12964. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  12965. }
  12966. } else {
  12967. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  12968. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  12969. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  12970. }
  12971. }
  12972. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  12973. } // Set up GL resources for the render target
  12974. function setupRenderTarget(renderTarget) {
  12975. const texture = renderTarget.texture;
  12976. const renderTargetProperties = properties.get(renderTarget);
  12977. const textureProperties = properties.get(texture);
  12978. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  12979. if (renderTarget.isWebGLMultipleRenderTargets !== true) {
  12980. textureProperties.__webglTexture = _gl.createTexture();
  12981. textureProperties.__version = texture.version;
  12982. info.memory.textures++;
  12983. }
  12984. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  12985. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
  12986. const isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  12987. const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
  12988. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
  12989. if (isWebGL2 && texture.format === RGBFormat && (texture.type === FloatType || texture.type === HalfFloatType)) {
  12990. texture.format = RGBAFormat;
  12991. console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
  12992. } // Setup framebuffer
  12993. if (isCube) {
  12994. renderTargetProperties.__webglFramebuffer = [];
  12995. for (let i = 0; i < 6; i++) {
  12996. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  12997. }
  12998. } else {
  12999. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  13000. if (isMultipleRenderTargets) {
  13001. if (capabilities.drawBuffers) {
  13002. const textures = renderTarget.texture;
  13003. for (let i = 0, il = textures.length; i < il; i++) {
  13004. const attachmentProperties = properties.get(textures[i]);
  13005. if (attachmentProperties.__webglTexture === undefined) {
  13006. attachmentProperties.__webglTexture = _gl.createTexture();
  13007. info.memory.textures++;
  13008. }
  13009. }
  13010. } else {
  13011. console.warn('THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.');
  13012. }
  13013. } else if (isMultisample) {
  13014. if (isWebGL2) {
  13015. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  13016. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  13017. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  13018. const glFormat = utils.convert(texture.format);
  13019. const glType = utils.convert(texture.type);
  13020. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13021. const samples = getRenderTargetSamples(renderTarget);
  13022. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13023. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13024. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  13025. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  13026. if (renderTarget.depthBuffer) {
  13027. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  13028. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  13029. }
  13030. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  13031. } else {
  13032. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13033. }
  13034. }
  13035. } // Setup color buffer
  13036. if (isCube) {
  13037. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13038. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  13039. for (let i = 0; i < 6; i++) {
  13040. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i);
  13041. }
  13042. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13043. generateMipmap(_gl.TEXTURE_CUBE_MAP, texture, renderTarget.width, renderTarget.height);
  13044. }
  13045. state.bindTexture(_gl.TEXTURE_CUBE_MAP, null);
  13046. } else if (isMultipleRenderTargets) {
  13047. const textures = renderTarget.texture;
  13048. for (let i = 0, il = textures.length; i < il; i++) {
  13049. const attachment = textures[i];
  13050. const attachmentProperties = properties.get(attachment);
  13051. state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture);
  13052. setTextureParameters(_gl.TEXTURE_2D, attachment, supportsMips);
  13053. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D);
  13054. if (textureNeedsGenerateMipmaps(attachment, supportsMips)) {
  13055. generateMipmap(_gl.TEXTURE_2D, attachment, renderTarget.width, renderTarget.height);
  13056. }
  13057. }
  13058. state.bindTexture(_gl.TEXTURE_2D, null);
  13059. } else {
  13060. let glTextureType = _gl.TEXTURE_2D;
  13061. if (isRenderTarget3D) {
  13062. // Render targets containing layers, i.e: Texture 3D and 2d arrays
  13063. if (isWebGL2) {
  13064. const isTexture3D = texture.isDataTexture3D;
  13065. glTextureType = isTexture3D ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  13066. } else {
  13067. console.warn('THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.');
  13068. }
  13069. }
  13070. state.bindTexture(glTextureType, textureProperties.__webglTexture);
  13071. setTextureParameters(glTextureType, texture, supportsMips);
  13072. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType);
  13073. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13074. generateMipmap(_gl.TEXTURE_2D, texture, renderTarget.width, renderTarget.height);
  13075. }
  13076. state.bindTexture(_gl.TEXTURE_2D, null);
  13077. } // Setup depth and stencil buffers
  13078. if (renderTarget.depthBuffer) {
  13079. setupDepthRenderbuffer(renderTarget);
  13080. }
  13081. }
  13082. function updateRenderTargetMipmap(renderTarget) {
  13083. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
  13084. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  13085. for (let i = 0, il = textures.length; i < il; i++) {
  13086. const texture = textures[i];
  13087. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13088. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  13089. const webglTexture = properties.get(texture).__webglTexture;
  13090. state.bindTexture(target, webglTexture);
  13091. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  13092. state.bindTexture(target, null);
  13093. }
  13094. }
  13095. }
  13096. function updateMultisampleRenderTarget(renderTarget) {
  13097. if (renderTarget.isWebGLMultisampleRenderTarget) {
  13098. if (isWebGL2) {
  13099. const width = renderTarget.width;
  13100. const height = renderTarget.height;
  13101. let mask = _gl.COLOR_BUFFER_BIT;
  13102. if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT;
  13103. if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT;
  13104. const renderTargetProperties = properties.get(renderTarget);
  13105. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13106. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  13107. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST);
  13108. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
  13109. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13110. } else {
  13111. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13112. }
  13113. }
  13114. }
  13115. function getRenderTargetSamples(renderTarget) {
  13116. return isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(maxSamples, renderTarget.samples) : 0;
  13117. }
  13118. function updateVideoTexture(texture) {
  13119. const frame = info.render.frame; // Check the last frame we updated the VideoTexture
  13120. if (_videoTextures.get(texture) !== frame) {
  13121. _videoTextures.set(texture, frame);
  13122. texture.update();
  13123. }
  13124. } // backwards compatibility
  13125. let warnedTexture2D = false;
  13126. let warnedTextureCube = false;
  13127. function safeSetTexture2D(texture, slot) {
  13128. if (texture && texture.isWebGLRenderTarget) {
  13129. if (warnedTexture2D === false) {
  13130. console.warn('THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.');
  13131. warnedTexture2D = true;
  13132. }
  13133. texture = texture.texture;
  13134. }
  13135. setTexture2D(texture, slot);
  13136. }
  13137. function safeSetTextureCube(texture, slot) {
  13138. if (texture && texture.isWebGLCubeRenderTarget) {
  13139. if (warnedTextureCube === false) {
  13140. console.warn('THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.');
  13141. warnedTextureCube = true;
  13142. }
  13143. texture = texture.texture;
  13144. }
  13145. setTextureCube(texture, slot);
  13146. } //
  13147. this.allocateTextureUnit = allocateTextureUnit;
  13148. this.resetTextureUnits = resetTextureUnits;
  13149. this.setTexture2D = setTexture2D;
  13150. this.setTexture2DArray = setTexture2DArray;
  13151. this.setTexture3D = setTexture3D;
  13152. this.setTextureCube = setTextureCube;
  13153. this.setupRenderTarget = setupRenderTarget;
  13154. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  13155. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  13156. this.safeSetTexture2D = safeSetTexture2D;
  13157. this.safeSetTextureCube = safeSetTextureCube;
  13158. }
  13159. function WebGLUtils(gl, extensions, capabilities) {
  13160. const isWebGL2 = capabilities.isWebGL2;
  13161. function convert(p) {
  13162. let extension;
  13163. if (p === UnsignedByteType) return gl.UNSIGNED_BYTE;
  13164. if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4;
  13165. if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1;
  13166. if (p === UnsignedShort565Type) return gl.UNSIGNED_SHORT_5_6_5;
  13167. if (p === ByteType) return gl.BYTE;
  13168. if (p === ShortType) return gl.SHORT;
  13169. if (p === UnsignedShortType) return gl.UNSIGNED_SHORT;
  13170. if (p === IntType) return gl.INT;
  13171. if (p === UnsignedIntType) return gl.UNSIGNED_INT;
  13172. if (p === FloatType) return gl.FLOAT;
  13173. if (p === HalfFloatType) {
  13174. if (isWebGL2) return gl.HALF_FLOAT;
  13175. extension = extensions.get('OES_texture_half_float');
  13176. if (extension !== null) {
  13177. return extension.HALF_FLOAT_OES;
  13178. } else {
  13179. return null;
  13180. }
  13181. }
  13182. if (p === AlphaFormat) return gl.ALPHA;
  13183. if (p === RGBFormat) return gl.RGB;
  13184. if (p === RGBAFormat) return gl.RGBA;
  13185. if (p === LuminanceFormat) return gl.LUMINANCE;
  13186. if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
  13187. if (p === DepthFormat) return gl.DEPTH_COMPONENT;
  13188. if (p === DepthStencilFormat) return gl.DEPTH_STENCIL;
  13189. if (p === RedFormat) return gl.RED; // WebGL2 formats.
  13190. if (p === RedIntegerFormat) return gl.RED_INTEGER;
  13191. if (p === RGFormat) return gl.RG;
  13192. if (p === RGIntegerFormat) return gl.RG_INTEGER;
  13193. if (p === RGBIntegerFormat) return gl.RGB_INTEGER;
  13194. if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER;
  13195. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  13196. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  13197. if (extension !== null) {
  13198. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13199. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13200. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13201. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13202. } else {
  13203. return null;
  13204. }
  13205. }
  13206. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  13207. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  13208. if (extension !== null) {
  13209. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13210. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13211. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13212. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13213. } else {
  13214. return null;
  13215. }
  13216. }
  13217. if (p === RGB_ETC1_Format) {
  13218. extension = extensions.get('WEBGL_compressed_texture_etc1');
  13219. if (extension !== null) {
  13220. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13221. } else {
  13222. return null;
  13223. }
  13224. }
  13225. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  13226. extension = extensions.get('WEBGL_compressed_texture_etc');
  13227. if (extension !== null) {
  13228. if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
  13229. if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  13230. }
  13231. }
  13232. 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) {
  13233. extension = extensions.get('WEBGL_compressed_texture_astc');
  13234. if (extension !== null) {
  13235. // TODO Complete?
  13236. return p;
  13237. } else {
  13238. return null;
  13239. }
  13240. }
  13241. if (p === RGBA_BPTC_Format) {
  13242. extension = extensions.get('EXT_texture_compression_bptc');
  13243. if (extension !== null) {
  13244. // TODO Complete?
  13245. return p;
  13246. } else {
  13247. return null;
  13248. }
  13249. }
  13250. if (p === UnsignedInt248Type) {
  13251. if (isWebGL2) return gl.UNSIGNED_INT_24_8;
  13252. extension = extensions.get('WEBGL_depth_texture');
  13253. if (extension !== null) {
  13254. return extension.UNSIGNED_INT_24_8_WEBGL;
  13255. } else {
  13256. return null;
  13257. }
  13258. }
  13259. }
  13260. return {
  13261. convert: convert
  13262. };
  13263. }
  13264. class ArrayCamera extends PerspectiveCamera {
  13265. constructor(array = []) {
  13266. super();
  13267. this.cameras = array;
  13268. }
  13269. }
  13270. ArrayCamera.prototype.isArrayCamera = true;
  13271. class Group extends Object3D {
  13272. constructor() {
  13273. super();
  13274. this.type = 'Group';
  13275. }
  13276. }
  13277. Group.prototype.isGroup = true;
  13278. const _moveEvent = {
  13279. type: 'move'
  13280. };
  13281. class WebXRController {
  13282. constructor() {
  13283. this._targetRay = null;
  13284. this._grip = null;
  13285. this._hand = null;
  13286. }
  13287. getHandSpace() {
  13288. if (this._hand === null) {
  13289. this._hand = new Group();
  13290. this._hand.matrixAutoUpdate = false;
  13291. this._hand.visible = false;
  13292. this._hand.joints = {};
  13293. this._hand.inputState = {
  13294. pinching: false
  13295. };
  13296. }
  13297. return this._hand;
  13298. }
  13299. getTargetRaySpace() {
  13300. if (this._targetRay === null) {
  13301. this._targetRay = new Group();
  13302. this._targetRay.matrixAutoUpdate = false;
  13303. this._targetRay.visible = false;
  13304. this._targetRay.hasLinearVelocity = false;
  13305. this._targetRay.linearVelocity = new Vector3();
  13306. this._targetRay.hasAngularVelocity = false;
  13307. this._targetRay.angularVelocity = new Vector3();
  13308. }
  13309. return this._targetRay;
  13310. }
  13311. getGripSpace() {
  13312. if (this._grip === null) {
  13313. this._grip = new Group();
  13314. this._grip.matrixAutoUpdate = false;
  13315. this._grip.visible = false;
  13316. this._grip.hasLinearVelocity = false;
  13317. this._grip.linearVelocity = new Vector3();
  13318. this._grip.hasAngularVelocity = false;
  13319. this._grip.angularVelocity = new Vector3();
  13320. }
  13321. return this._grip;
  13322. }
  13323. dispatchEvent(event) {
  13324. if (this._targetRay !== null) {
  13325. this._targetRay.dispatchEvent(event);
  13326. }
  13327. if (this._grip !== null) {
  13328. this._grip.dispatchEvent(event);
  13329. }
  13330. if (this._hand !== null) {
  13331. this._hand.dispatchEvent(event);
  13332. }
  13333. return this;
  13334. }
  13335. disconnect(inputSource) {
  13336. this.dispatchEvent({
  13337. type: 'disconnected',
  13338. data: inputSource
  13339. });
  13340. if (this._targetRay !== null) {
  13341. this._targetRay.visible = false;
  13342. }
  13343. if (this._grip !== null) {
  13344. this._grip.visible = false;
  13345. }
  13346. if (this._hand !== null) {
  13347. this._hand.visible = false;
  13348. }
  13349. return this;
  13350. }
  13351. update(inputSource, frame, referenceSpace) {
  13352. let inputPose = null;
  13353. let gripPose = null;
  13354. let handPose = null;
  13355. const targetRay = this._targetRay;
  13356. const grip = this._grip;
  13357. const hand = this._hand;
  13358. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  13359. if (targetRay !== null) {
  13360. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  13361. if (inputPose !== null) {
  13362. targetRay.matrix.fromArray(inputPose.transform.matrix);
  13363. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  13364. if (inputPose.linearVelocity) {
  13365. targetRay.hasLinearVelocity = true;
  13366. targetRay.linearVelocity.copy(inputPose.linearVelocity);
  13367. } else {
  13368. targetRay.hasLinearVelocity = false;
  13369. }
  13370. if (inputPose.angularVelocity) {
  13371. targetRay.hasAngularVelocity = true;
  13372. targetRay.angularVelocity.copy(inputPose.angularVelocity);
  13373. } else {
  13374. targetRay.hasAngularVelocity = false;
  13375. }
  13376. this.dispatchEvent(_moveEvent);
  13377. }
  13378. }
  13379. if (hand && inputSource.hand) {
  13380. handPose = true;
  13381. for (const inputjoint of inputSource.hand.values()) {
  13382. // Update the joints groups with the XRJoint poses
  13383. const jointPose = frame.getJointPose(inputjoint, referenceSpace);
  13384. if (hand.joints[inputjoint.jointName] === undefined) {
  13385. // The transform of this joint will be updated with the joint pose on each frame
  13386. const joint = new Group();
  13387. joint.matrixAutoUpdate = false;
  13388. joint.visible = false;
  13389. hand.joints[inputjoint.jointName] = joint; // ??
  13390. hand.add(joint);
  13391. }
  13392. const joint = hand.joints[inputjoint.jointName];
  13393. if (jointPose !== null) {
  13394. joint.matrix.fromArray(jointPose.transform.matrix);
  13395. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  13396. joint.jointRadius = jointPose.radius;
  13397. }
  13398. joint.visible = jointPose !== null;
  13399. } // Custom events
  13400. // Check pinchz
  13401. const indexTip = hand.joints['index-finger-tip'];
  13402. const thumbTip = hand.joints['thumb-tip'];
  13403. const distance = indexTip.position.distanceTo(thumbTip.position);
  13404. const distanceToPinch = 0.02;
  13405. const threshold = 0.005;
  13406. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  13407. hand.inputState.pinching = false;
  13408. this.dispatchEvent({
  13409. type: 'pinchend',
  13410. handedness: inputSource.handedness,
  13411. target: this
  13412. });
  13413. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  13414. hand.inputState.pinching = true;
  13415. this.dispatchEvent({
  13416. type: 'pinchstart',
  13417. handedness: inputSource.handedness,
  13418. target: this
  13419. });
  13420. }
  13421. } else {
  13422. if (grip !== null && inputSource.gripSpace) {
  13423. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  13424. if (gripPose !== null) {
  13425. grip.matrix.fromArray(gripPose.transform.matrix);
  13426. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  13427. if (gripPose.linearVelocity) {
  13428. grip.hasLinearVelocity = true;
  13429. grip.linearVelocity.copy(gripPose.linearVelocity);
  13430. } else {
  13431. grip.hasLinearVelocity = false;
  13432. }
  13433. if (gripPose.angularVelocity) {
  13434. grip.hasAngularVelocity = true;
  13435. grip.angularVelocity.copy(gripPose.angularVelocity);
  13436. } else {
  13437. grip.hasAngularVelocity = false;
  13438. }
  13439. }
  13440. }
  13441. }
  13442. }
  13443. if (targetRay !== null) {
  13444. targetRay.visible = inputPose !== null;
  13445. }
  13446. if (grip !== null) {
  13447. grip.visible = gripPose !== null;
  13448. }
  13449. if (hand !== null) {
  13450. hand.visible = handPose !== null;
  13451. }
  13452. return this;
  13453. }
  13454. }
  13455. class WebXRManager extends EventDispatcher {
  13456. constructor(renderer, gl) {
  13457. super();
  13458. const scope = this;
  13459. const state = renderer.state;
  13460. let session = null;
  13461. let framebufferScaleFactor = 1.0;
  13462. let referenceSpace = null;
  13463. let referenceSpaceType = 'local-floor';
  13464. let pose = null;
  13465. const controllers = [];
  13466. const inputSourcesMap = new Map(); //
  13467. const cameraL = new PerspectiveCamera();
  13468. cameraL.layers.enable(1);
  13469. cameraL.viewport = new Vector4();
  13470. const cameraR = new PerspectiveCamera();
  13471. cameraR.layers.enable(2);
  13472. cameraR.viewport = new Vector4();
  13473. const cameras = [cameraL, cameraR];
  13474. const cameraVR = new ArrayCamera();
  13475. cameraVR.layers.enable(1);
  13476. cameraVR.layers.enable(2);
  13477. let _currentDepthNear = null;
  13478. let _currentDepthFar = null; //
  13479. this.cameraAutoUpdate = true;
  13480. this.enabled = false;
  13481. this.isPresenting = false;
  13482. this.getController = function (index) {
  13483. let controller = controllers[index];
  13484. if (controller === undefined) {
  13485. controller = new WebXRController();
  13486. controllers[index] = controller;
  13487. }
  13488. return controller.getTargetRaySpace();
  13489. };
  13490. this.getControllerGrip = function (index) {
  13491. let controller = controllers[index];
  13492. if (controller === undefined) {
  13493. controller = new WebXRController();
  13494. controllers[index] = controller;
  13495. }
  13496. return controller.getGripSpace();
  13497. };
  13498. this.getHand = function (index) {
  13499. let controller = controllers[index];
  13500. if (controller === undefined) {
  13501. controller = new WebXRController();
  13502. controllers[index] = controller;
  13503. }
  13504. return controller.getHandSpace();
  13505. }; //
  13506. function onSessionEvent(event) {
  13507. const controller = inputSourcesMap.get(event.inputSource);
  13508. if (controller) {
  13509. controller.dispatchEvent({
  13510. type: event.type,
  13511. data: event.inputSource
  13512. });
  13513. }
  13514. }
  13515. function onSessionEnd() {
  13516. inputSourcesMap.forEach(function (controller, inputSource) {
  13517. controller.disconnect(inputSource);
  13518. });
  13519. inputSourcesMap.clear();
  13520. _currentDepthNear = null;
  13521. _currentDepthFar = null; // restore framebuffer/rendering state
  13522. state.bindXRFramebuffer(null);
  13523. renderer.setRenderTarget(renderer.getRenderTarget()); //
  13524. animation.stop();
  13525. scope.isPresenting = false;
  13526. scope.dispatchEvent({
  13527. type: 'sessionend'
  13528. });
  13529. }
  13530. this.setFramebufferScaleFactor = function (value) {
  13531. framebufferScaleFactor = value;
  13532. if (scope.isPresenting === true) {
  13533. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  13534. }
  13535. };
  13536. this.setReferenceSpaceType = function (value) {
  13537. referenceSpaceType = value;
  13538. if (scope.isPresenting === true) {
  13539. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  13540. }
  13541. };
  13542. this.getReferenceSpace = function () {
  13543. return referenceSpace;
  13544. };
  13545. this.getSession = function () {
  13546. return session;
  13547. };
  13548. this.setSession = async function (value) {
  13549. session = value;
  13550. if (session !== null) {
  13551. session.addEventListener('select', onSessionEvent);
  13552. session.addEventListener('selectstart', onSessionEvent);
  13553. session.addEventListener('selectend', onSessionEvent);
  13554. session.addEventListener('squeeze', onSessionEvent);
  13555. session.addEventListener('squeezestart', onSessionEvent);
  13556. session.addEventListener('squeezeend', onSessionEvent);
  13557. session.addEventListener('end', onSessionEnd);
  13558. session.addEventListener('inputsourceschange', onInputSourcesChange);
  13559. const attributes = gl.getContextAttributes();
  13560. if (attributes.xrCompatible !== true) {
  13561. await gl.makeXRCompatible();
  13562. }
  13563. const layerInit = {
  13564. antialias: attributes.antialias,
  13565. alpha: attributes.alpha,
  13566. depth: attributes.depth,
  13567. stencil: attributes.stencil,
  13568. framebufferScaleFactor: framebufferScaleFactor
  13569. }; // eslint-disable-next-line no-undef
  13570. const baseLayer = new XRWebGLLayer(session, gl, layerInit);
  13571. session.updateRenderState({
  13572. baseLayer: baseLayer
  13573. });
  13574. referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
  13575. animation.setContext(session);
  13576. animation.start();
  13577. scope.isPresenting = true;
  13578. scope.dispatchEvent({
  13579. type: 'sessionstart'
  13580. });
  13581. }
  13582. };
  13583. function onInputSourcesChange(event) {
  13584. const inputSources = session.inputSources; // Assign inputSources to available controllers
  13585. for (let i = 0; i < controllers.length; i++) {
  13586. inputSourcesMap.set(inputSources[i], controllers[i]);
  13587. } // Notify disconnected
  13588. for (let i = 0; i < event.removed.length; i++) {
  13589. const inputSource = event.removed[i];
  13590. const controller = inputSourcesMap.get(inputSource);
  13591. if (controller) {
  13592. controller.dispatchEvent({
  13593. type: 'disconnected',
  13594. data: inputSource
  13595. });
  13596. inputSourcesMap.delete(inputSource);
  13597. }
  13598. } // Notify connected
  13599. for (let i = 0; i < event.added.length; i++) {
  13600. const inputSource = event.added[i];
  13601. const controller = inputSourcesMap.get(inputSource);
  13602. if (controller) {
  13603. controller.dispatchEvent({
  13604. type: 'connected',
  13605. data: inputSource
  13606. });
  13607. }
  13608. }
  13609. } //
  13610. const cameraLPos = new Vector3();
  13611. const cameraRPos = new Vector3();
  13612. /**
  13613. * Assumes 2 cameras that are parallel and share an X-axis, and that
  13614. * the cameras' projection and world matrices have already been set.
  13615. * And that near and far planes are identical for both cameras.
  13616. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  13617. */
  13618. function setProjectionFromUnion(camera, cameraL, cameraR) {
  13619. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  13620. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  13621. const ipd = cameraLPos.distanceTo(cameraRPos);
  13622. const projL = cameraL.projectionMatrix.elements;
  13623. const projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  13624. // most likely identical top and bottom frustum extents.
  13625. // Use the left camera for these values.
  13626. const near = projL[14] / (projL[10] - 1);
  13627. const far = projL[14] / (projL[10] + 1);
  13628. const topFov = (projL[9] + 1) / projL[5];
  13629. const bottomFov = (projL[9] - 1) / projL[5];
  13630. const leftFov = (projL[8] - 1) / projL[0];
  13631. const rightFov = (projR[8] + 1) / projR[0];
  13632. const left = near * leftFov;
  13633. const right = near * rightFov; // Calculate the new camera's position offset from the
  13634. // left camera. xOffset should be roughly half `ipd`.
  13635. const zOffset = ipd / (-leftFov + rightFov);
  13636. const xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  13637. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  13638. camera.translateX(xOffset);
  13639. camera.translateZ(zOffset);
  13640. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  13641. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  13642. // the values so that the near plane's position does not change in world space,
  13643. // although must now be relative to the new union camera.
  13644. const near2 = near + zOffset;
  13645. const far2 = far + zOffset;
  13646. const left2 = left - xOffset;
  13647. const right2 = right + (ipd - xOffset);
  13648. const top2 = topFov * far / far2 * near2;
  13649. const bottom2 = bottomFov * far / far2 * near2;
  13650. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  13651. }
  13652. function updateCamera(camera, parent) {
  13653. if (parent === null) {
  13654. camera.matrixWorld.copy(camera.matrix);
  13655. } else {
  13656. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  13657. }
  13658. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  13659. }
  13660. this.updateCamera = function (camera) {
  13661. if (session === null) return;
  13662. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  13663. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  13664. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  13665. // Note that the new renderState won't apply until the next frame. See #18320
  13666. session.updateRenderState({
  13667. depthNear: cameraVR.near,
  13668. depthFar: cameraVR.far
  13669. });
  13670. _currentDepthNear = cameraVR.near;
  13671. _currentDepthFar = cameraVR.far;
  13672. }
  13673. const parent = camera.parent;
  13674. const cameras = cameraVR.cameras;
  13675. updateCamera(cameraVR, parent);
  13676. for (let i = 0; i < cameras.length; i++) {
  13677. updateCamera(cameras[i], parent);
  13678. } // update camera and its children
  13679. camera.matrixWorld.copy(cameraVR.matrixWorld);
  13680. camera.matrix.copy(cameraVR.matrix);
  13681. camera.matrix.decompose(camera.position, camera.quaternion, camera.scale);
  13682. const children = camera.children;
  13683. for (let i = 0, l = children.length; i < l; i++) {
  13684. children[i].updateMatrixWorld(true);
  13685. } // update projection matrix for proper view frustum culling
  13686. if (cameras.length === 2) {
  13687. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  13688. } else {
  13689. // assume single camera setup (AR)
  13690. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  13691. }
  13692. };
  13693. this.getCamera = function () {
  13694. return cameraVR;
  13695. }; // Animation Loop
  13696. let onAnimationFrameCallback = null;
  13697. function onAnimationFrame(time, frame) {
  13698. pose = frame.getViewerPose(referenceSpace);
  13699. if (pose !== null) {
  13700. const views = pose.views;
  13701. const baseLayer = session.renderState.baseLayer;
  13702. state.bindXRFramebuffer(baseLayer.framebuffer);
  13703. let cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  13704. if (views.length !== cameraVR.cameras.length) {
  13705. cameraVR.cameras.length = 0;
  13706. cameraVRNeedsUpdate = true;
  13707. }
  13708. for (let i = 0; i < views.length; i++) {
  13709. const view = views[i];
  13710. const viewport = baseLayer.getViewport(view);
  13711. const camera = cameras[i];
  13712. camera.matrix.fromArray(view.transform.matrix);
  13713. camera.projectionMatrix.fromArray(view.projectionMatrix);
  13714. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  13715. if (i === 0) {
  13716. cameraVR.matrix.copy(camera.matrix);
  13717. }
  13718. if (cameraVRNeedsUpdate === true) {
  13719. cameraVR.cameras.push(camera);
  13720. }
  13721. }
  13722. } //
  13723. const inputSources = session.inputSources;
  13724. for (let i = 0; i < controllers.length; i++) {
  13725. const controller = controllers[i];
  13726. const inputSource = inputSources[i];
  13727. controller.update(inputSource, frame, referenceSpace);
  13728. }
  13729. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  13730. }
  13731. const animation = new WebGLAnimation();
  13732. animation.setAnimationLoop(onAnimationFrame);
  13733. this.setAnimationLoop = function (callback) {
  13734. onAnimationFrameCallback = callback;
  13735. };
  13736. this.dispose = function () {};
  13737. }
  13738. }
  13739. function WebGLMaterials(properties) {
  13740. function refreshFogUniforms(uniforms, fog) {
  13741. uniforms.fogColor.value.copy(fog.color);
  13742. if (fog.isFog) {
  13743. uniforms.fogNear.value = fog.near;
  13744. uniforms.fogFar.value = fog.far;
  13745. } else if (fog.isFogExp2) {
  13746. uniforms.fogDensity.value = fog.density;
  13747. }
  13748. }
  13749. function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) {
  13750. if (material.isMeshBasicMaterial) {
  13751. refreshUniformsCommon(uniforms, material);
  13752. } else if (material.isMeshLambertMaterial) {
  13753. refreshUniformsCommon(uniforms, material);
  13754. refreshUniformsLambert(uniforms, material);
  13755. } else if (material.isMeshToonMaterial) {
  13756. refreshUniformsCommon(uniforms, material);
  13757. refreshUniformsToon(uniforms, material);
  13758. } else if (material.isMeshPhongMaterial) {
  13759. refreshUniformsCommon(uniforms, material);
  13760. refreshUniformsPhong(uniforms, material);
  13761. } else if (material.isMeshStandardMaterial) {
  13762. refreshUniformsCommon(uniforms, material);
  13763. if (material.isMeshPhysicalMaterial) {
  13764. refreshUniformsPhysical(uniforms, material, transmissionRenderTarget);
  13765. } else {
  13766. refreshUniformsStandard(uniforms, material);
  13767. }
  13768. } else if (material.isMeshMatcapMaterial) {
  13769. refreshUniformsCommon(uniforms, material);
  13770. refreshUniformsMatcap(uniforms, material);
  13771. } else if (material.isMeshDepthMaterial) {
  13772. refreshUniformsCommon(uniforms, material);
  13773. refreshUniformsDepth(uniforms, material);
  13774. } else if (material.isMeshDistanceMaterial) {
  13775. refreshUniformsCommon(uniforms, material);
  13776. refreshUniformsDistance(uniforms, material);
  13777. } else if (material.isMeshNormalMaterial) {
  13778. refreshUniformsCommon(uniforms, material);
  13779. refreshUniformsNormal(uniforms, material);
  13780. } else if (material.isLineBasicMaterial) {
  13781. refreshUniformsLine(uniforms, material);
  13782. if (material.isLineDashedMaterial) {
  13783. refreshUniformsDash(uniforms, material);
  13784. }
  13785. } else if (material.isPointsMaterial) {
  13786. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  13787. } else if (material.isSpriteMaterial) {
  13788. refreshUniformsSprites(uniforms, material);
  13789. } else if (material.isShadowMaterial) {
  13790. uniforms.color.value.copy(material.color);
  13791. uniforms.opacity.value = material.opacity;
  13792. } else if (material.isShaderMaterial) {
  13793. material.uniformsNeedUpdate = false; // #15581
  13794. }
  13795. }
  13796. function refreshUniformsCommon(uniforms, material) {
  13797. uniforms.opacity.value = material.opacity;
  13798. if (material.color) {
  13799. uniforms.diffuse.value.copy(material.color);
  13800. }
  13801. if (material.emissive) {
  13802. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  13803. }
  13804. if (material.map) {
  13805. uniforms.map.value = material.map;
  13806. }
  13807. if (material.alphaMap) {
  13808. uniforms.alphaMap.value = material.alphaMap;
  13809. }
  13810. if (material.specularMap) {
  13811. uniforms.specularMap.value = material.specularMap;
  13812. }
  13813. const envMap = properties.get(material).envMap;
  13814. if (envMap) {
  13815. uniforms.envMap.value = envMap;
  13816. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap._needsFlipEnvMap ? -1 : 1;
  13817. uniforms.reflectivity.value = material.reflectivity;
  13818. uniforms.refractionRatio.value = material.refractionRatio;
  13819. const maxMipLevel = properties.get(envMap).__maxMipLevel;
  13820. if (maxMipLevel !== undefined) {
  13821. uniforms.maxMipLevel.value = maxMipLevel;
  13822. }
  13823. }
  13824. if (material.lightMap) {
  13825. uniforms.lightMap.value = material.lightMap;
  13826. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  13827. }
  13828. if (material.aoMap) {
  13829. uniforms.aoMap.value = material.aoMap;
  13830. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  13831. } // uv repeat and offset setting priorities
  13832. // 1. color map
  13833. // 2. specular map
  13834. // 3. displacementMap map
  13835. // 4. normal map
  13836. // 5. bump map
  13837. // 6. roughnessMap map
  13838. // 7. metalnessMap map
  13839. // 8. alphaMap map
  13840. // 9. emissiveMap map
  13841. // 10. clearcoat map
  13842. // 11. clearcoat normal map
  13843. // 12. clearcoat roughnessMap map
  13844. let uvScaleMap;
  13845. if (material.map) {
  13846. uvScaleMap = material.map;
  13847. } else if (material.specularMap) {
  13848. uvScaleMap = material.specularMap;
  13849. } else if (material.displacementMap) {
  13850. uvScaleMap = material.displacementMap;
  13851. } else if (material.normalMap) {
  13852. uvScaleMap = material.normalMap;
  13853. } else if (material.bumpMap) {
  13854. uvScaleMap = material.bumpMap;
  13855. } else if (material.roughnessMap) {
  13856. uvScaleMap = material.roughnessMap;
  13857. } else if (material.metalnessMap) {
  13858. uvScaleMap = material.metalnessMap;
  13859. } else if (material.alphaMap) {
  13860. uvScaleMap = material.alphaMap;
  13861. } else if (material.emissiveMap) {
  13862. uvScaleMap = material.emissiveMap;
  13863. } else if (material.clearcoatMap) {
  13864. uvScaleMap = material.clearcoatMap;
  13865. } else if (material.clearcoatNormalMap) {
  13866. uvScaleMap = material.clearcoatNormalMap;
  13867. } else if (material.clearcoatRoughnessMap) {
  13868. uvScaleMap = material.clearcoatRoughnessMap;
  13869. }
  13870. if (uvScaleMap !== undefined) {
  13871. // backwards compatibility
  13872. if (uvScaleMap.isWebGLRenderTarget) {
  13873. uvScaleMap = uvScaleMap.texture;
  13874. }
  13875. if (uvScaleMap.matrixAutoUpdate === true) {
  13876. uvScaleMap.updateMatrix();
  13877. }
  13878. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  13879. } // uv repeat and offset setting priorities for uv2
  13880. // 1. ao map
  13881. // 2. light map
  13882. let uv2ScaleMap;
  13883. if (material.aoMap) {
  13884. uv2ScaleMap = material.aoMap;
  13885. } else if (material.lightMap) {
  13886. uv2ScaleMap = material.lightMap;
  13887. }
  13888. if (uv2ScaleMap !== undefined) {
  13889. // backwards compatibility
  13890. if (uv2ScaleMap.isWebGLRenderTarget) {
  13891. uv2ScaleMap = uv2ScaleMap.texture;
  13892. }
  13893. if (uv2ScaleMap.matrixAutoUpdate === true) {
  13894. uv2ScaleMap.updateMatrix();
  13895. }
  13896. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  13897. }
  13898. }
  13899. function refreshUniformsLine(uniforms, material) {
  13900. uniforms.diffuse.value.copy(material.color);
  13901. uniforms.opacity.value = material.opacity;
  13902. }
  13903. function refreshUniformsDash(uniforms, material) {
  13904. uniforms.dashSize.value = material.dashSize;
  13905. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13906. uniforms.scale.value = material.scale;
  13907. }
  13908. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  13909. uniforms.diffuse.value.copy(material.color);
  13910. uniforms.opacity.value = material.opacity;
  13911. uniforms.size.value = material.size * pixelRatio;
  13912. uniforms.scale.value = height * 0.5;
  13913. if (material.map) {
  13914. uniforms.map.value = material.map;
  13915. }
  13916. if (material.alphaMap) {
  13917. uniforms.alphaMap.value = material.alphaMap;
  13918. } // uv repeat and offset setting priorities
  13919. // 1. color map
  13920. // 2. alpha map
  13921. let uvScaleMap;
  13922. if (material.map) {
  13923. uvScaleMap = material.map;
  13924. } else if (material.alphaMap) {
  13925. uvScaleMap = material.alphaMap;
  13926. }
  13927. if (uvScaleMap !== undefined) {
  13928. if (uvScaleMap.matrixAutoUpdate === true) {
  13929. uvScaleMap.updateMatrix();
  13930. }
  13931. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  13932. }
  13933. }
  13934. function refreshUniformsSprites(uniforms, material) {
  13935. uniforms.diffuse.value.copy(material.color);
  13936. uniforms.opacity.value = material.opacity;
  13937. uniforms.rotation.value = material.rotation;
  13938. if (material.map) {
  13939. uniforms.map.value = material.map;
  13940. }
  13941. if (material.alphaMap) {
  13942. uniforms.alphaMap.value = material.alphaMap;
  13943. } // uv repeat and offset setting priorities
  13944. // 1. color map
  13945. // 2. alpha map
  13946. let uvScaleMap;
  13947. if (material.map) {
  13948. uvScaleMap = material.map;
  13949. } else if (material.alphaMap) {
  13950. uvScaleMap = material.alphaMap;
  13951. }
  13952. if (uvScaleMap !== undefined) {
  13953. if (uvScaleMap.matrixAutoUpdate === true) {
  13954. uvScaleMap.updateMatrix();
  13955. }
  13956. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  13957. }
  13958. }
  13959. function refreshUniformsLambert(uniforms, material) {
  13960. if (material.emissiveMap) {
  13961. uniforms.emissiveMap.value = material.emissiveMap;
  13962. }
  13963. }
  13964. function refreshUniformsPhong(uniforms, material) {
  13965. uniforms.specular.value.copy(material.specular);
  13966. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  13967. if (material.emissiveMap) {
  13968. uniforms.emissiveMap.value = material.emissiveMap;
  13969. }
  13970. if (material.bumpMap) {
  13971. uniforms.bumpMap.value = material.bumpMap;
  13972. uniforms.bumpScale.value = material.bumpScale;
  13973. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  13974. }
  13975. if (material.normalMap) {
  13976. uniforms.normalMap.value = material.normalMap;
  13977. uniforms.normalScale.value.copy(material.normalScale);
  13978. if (material.side === BackSide) uniforms.normalScale.value.negate();
  13979. }
  13980. if (material.displacementMap) {
  13981. uniforms.displacementMap.value = material.displacementMap;
  13982. uniforms.displacementScale.value = material.displacementScale;
  13983. uniforms.displacementBias.value = material.displacementBias;
  13984. }
  13985. }
  13986. function refreshUniformsToon(uniforms, material) {
  13987. if (material.gradientMap) {
  13988. uniforms.gradientMap.value = material.gradientMap;
  13989. }
  13990. if (material.emissiveMap) {
  13991. uniforms.emissiveMap.value = material.emissiveMap;
  13992. }
  13993. if (material.bumpMap) {
  13994. uniforms.bumpMap.value = material.bumpMap;
  13995. uniforms.bumpScale.value = material.bumpScale;
  13996. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  13997. }
  13998. if (material.normalMap) {
  13999. uniforms.normalMap.value = material.normalMap;
  14000. uniforms.normalScale.value.copy(material.normalScale);
  14001. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14002. }
  14003. if (material.displacementMap) {
  14004. uniforms.displacementMap.value = material.displacementMap;
  14005. uniforms.displacementScale.value = material.displacementScale;
  14006. uniforms.displacementBias.value = material.displacementBias;
  14007. }
  14008. }
  14009. function refreshUniformsStandard(uniforms, material) {
  14010. uniforms.roughness.value = material.roughness;
  14011. uniforms.metalness.value = material.metalness;
  14012. if (material.roughnessMap) {
  14013. uniforms.roughnessMap.value = material.roughnessMap;
  14014. }
  14015. if (material.metalnessMap) {
  14016. uniforms.metalnessMap.value = material.metalnessMap;
  14017. }
  14018. if (material.emissiveMap) {
  14019. uniforms.emissiveMap.value = material.emissiveMap;
  14020. }
  14021. if (material.bumpMap) {
  14022. uniforms.bumpMap.value = material.bumpMap;
  14023. uniforms.bumpScale.value = material.bumpScale;
  14024. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14025. }
  14026. if (material.normalMap) {
  14027. uniforms.normalMap.value = material.normalMap;
  14028. uniforms.normalScale.value.copy(material.normalScale);
  14029. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14030. }
  14031. if (material.displacementMap) {
  14032. uniforms.displacementMap.value = material.displacementMap;
  14033. uniforms.displacementScale.value = material.displacementScale;
  14034. uniforms.displacementBias.value = material.displacementBias;
  14035. }
  14036. const envMap = properties.get(material).envMap;
  14037. if (envMap) {
  14038. //uniforms.envMap.value = material.envMap; // part of uniforms common
  14039. uniforms.envMapIntensity.value = material.envMapIntensity;
  14040. }
  14041. }
  14042. function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) {
  14043. refreshUniformsStandard(uniforms, material);
  14044. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  14045. uniforms.clearcoat.value = material.clearcoat;
  14046. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  14047. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  14048. if (material.clearcoatMap) {
  14049. uniforms.clearcoatMap.value = material.clearcoatMap;
  14050. }
  14051. if (material.clearcoatRoughnessMap) {
  14052. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  14053. }
  14054. if (material.clearcoatNormalMap) {
  14055. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  14056. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  14057. if (material.side === BackSide) {
  14058. uniforms.clearcoatNormalScale.value.negate();
  14059. }
  14060. }
  14061. uniforms.transmission.value = material.transmission;
  14062. if (material.transmissionMap) {
  14063. uniforms.transmissionMap.value = material.transmissionMap;
  14064. }
  14065. if (material.transmission > 0.0) {
  14066. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  14067. uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height);
  14068. }
  14069. uniforms.thickness.value = material.thickness;
  14070. if (material.thicknessMap) {
  14071. uniforms.thicknessMap.value = material.thicknessMap;
  14072. }
  14073. uniforms.attenuationDistance.value = material.attenuationDistance;
  14074. uniforms.attenuationColor.value.copy(material.attenuationColor);
  14075. }
  14076. function refreshUniformsMatcap(uniforms, material) {
  14077. if (material.matcap) {
  14078. uniforms.matcap.value = material.matcap;
  14079. }
  14080. if (material.bumpMap) {
  14081. uniforms.bumpMap.value = material.bumpMap;
  14082. uniforms.bumpScale.value = material.bumpScale;
  14083. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14084. }
  14085. if (material.normalMap) {
  14086. uniforms.normalMap.value = material.normalMap;
  14087. uniforms.normalScale.value.copy(material.normalScale);
  14088. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14089. }
  14090. if (material.displacementMap) {
  14091. uniforms.displacementMap.value = material.displacementMap;
  14092. uniforms.displacementScale.value = material.displacementScale;
  14093. uniforms.displacementBias.value = material.displacementBias;
  14094. }
  14095. }
  14096. function refreshUniformsDepth(uniforms, material) {
  14097. if (material.displacementMap) {
  14098. uniforms.displacementMap.value = material.displacementMap;
  14099. uniforms.displacementScale.value = material.displacementScale;
  14100. uniforms.displacementBias.value = material.displacementBias;
  14101. }
  14102. }
  14103. function refreshUniformsDistance(uniforms, material) {
  14104. if (material.displacementMap) {
  14105. uniforms.displacementMap.value = material.displacementMap;
  14106. uniforms.displacementScale.value = material.displacementScale;
  14107. uniforms.displacementBias.value = material.displacementBias;
  14108. }
  14109. uniforms.referencePosition.value.copy(material.referencePosition);
  14110. uniforms.nearDistance.value = material.nearDistance;
  14111. uniforms.farDistance.value = material.farDistance;
  14112. }
  14113. function refreshUniformsNormal(uniforms, material) {
  14114. if (material.bumpMap) {
  14115. uniforms.bumpMap.value = material.bumpMap;
  14116. uniforms.bumpScale.value = material.bumpScale;
  14117. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14118. }
  14119. if (material.normalMap) {
  14120. uniforms.normalMap.value = material.normalMap;
  14121. uniforms.normalScale.value.copy(material.normalScale);
  14122. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14123. }
  14124. if (material.displacementMap) {
  14125. uniforms.displacementMap.value = material.displacementMap;
  14126. uniforms.displacementScale.value = material.displacementScale;
  14127. uniforms.displacementBias.value = material.displacementBias;
  14128. }
  14129. }
  14130. return {
  14131. refreshFogUniforms: refreshFogUniforms,
  14132. refreshMaterialUniforms: refreshMaterialUniforms
  14133. };
  14134. }
  14135. function createCanvasElement() {
  14136. const canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  14137. canvas.style.display = 'block';
  14138. return canvas;
  14139. }
  14140. function WebGLRenderer(parameters) {
  14141. parameters = parameters || {};
  14142. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  14143. _context = parameters.context !== undefined ? parameters.context : null,
  14144. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14145. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14146. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14147. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14148. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14149. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14150. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  14151. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  14152. let currentRenderList = null;
  14153. let currentRenderState = null; // render() can be called from within a callback triggered by another render.
  14154. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  14155. const renderListStack = [];
  14156. const renderStateStack = []; // public properties
  14157. this.domElement = _canvas; // Debug configuration container
  14158. this.debug = {
  14159. /**
  14160. * Enables error checking and reporting when shader programs are being compiled
  14161. * @type {boolean}
  14162. */
  14163. checkShaderErrors: true
  14164. }; // clearing
  14165. this.autoClear = true;
  14166. this.autoClearColor = true;
  14167. this.autoClearDepth = true;
  14168. this.autoClearStencil = true; // scene graph
  14169. this.sortObjects = true; // user-defined clipping
  14170. this.clippingPlanes = [];
  14171. this.localClippingEnabled = false; // physically based shading
  14172. this.gammaFactor = 2.0; // for backwards compatibility
  14173. this.outputEncoding = LinearEncoding; // physical lights
  14174. this.physicallyCorrectLights = false; // tone mapping
  14175. this.toneMapping = NoToneMapping;
  14176. this.toneMappingExposure = 1.0; // internal properties
  14177. const _this = this;
  14178. let _isContextLost = false; // internal state cache
  14179. let _currentActiveCubeFace = 0;
  14180. let _currentActiveMipmapLevel = 0;
  14181. let _currentRenderTarget = null;
  14182. let _currentMaterialId = -1;
  14183. let _currentCamera = null;
  14184. const _currentViewport = new Vector4();
  14185. const _currentScissor = new Vector4();
  14186. let _currentScissorTest = null; //
  14187. let _width = _canvas.width;
  14188. let _height = _canvas.height;
  14189. let _pixelRatio = 1;
  14190. let _opaqueSort = null;
  14191. let _transparentSort = null;
  14192. const _viewport = new Vector4(0, 0, _width, _height);
  14193. const _scissor = new Vector4(0, 0, _width, _height);
  14194. let _scissorTest = false; //
  14195. const _currentDrawBuffers = []; // frustum
  14196. const _frustum = new Frustum(); // clipping
  14197. let _clippingEnabled = false;
  14198. let _localClippingEnabled = false; // transmission
  14199. let _transmissionRenderTarget = null; // camera matrices cache
  14200. const _projScreenMatrix = new Matrix4();
  14201. const _vector3 = new Vector3();
  14202. const _emptyScene = {
  14203. background: null,
  14204. fog: null,
  14205. environment: null,
  14206. overrideMaterial: null,
  14207. isScene: true
  14208. };
  14209. function getTargetPixelRatio() {
  14210. return _currentRenderTarget === null ? _pixelRatio : 1;
  14211. } // initialize
  14212. let _gl = _context;
  14213. function getContext(contextNames, contextAttributes) {
  14214. for (let i = 0; i < contextNames.length; i++) {
  14215. const contextName = contextNames[i];
  14216. const context = _canvas.getContext(contextName, contextAttributes);
  14217. if (context !== null) return context;
  14218. }
  14219. return null;
  14220. }
  14221. try {
  14222. const contextAttributes = {
  14223. alpha: _alpha,
  14224. depth: _depth,
  14225. stencil: _stencil,
  14226. antialias: _antialias,
  14227. premultipliedAlpha: _premultipliedAlpha,
  14228. preserveDrawingBuffer: _preserveDrawingBuffer,
  14229. powerPreference: _powerPreference,
  14230. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  14231. }; // event listeners must be registered before WebGL context is created, see #12753
  14232. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  14233. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  14234. if (_gl === null) {
  14235. const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  14236. if (_this.isWebGL1Renderer === true) {
  14237. contextNames.shift();
  14238. }
  14239. _gl = getContext(contextNames, contextAttributes);
  14240. if (_gl === null) {
  14241. if (getContext(contextNames)) {
  14242. throw new Error('Error creating WebGL context with your selected attributes.');
  14243. } else {
  14244. throw new Error('Error creating WebGL context.');
  14245. }
  14246. }
  14247. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14248. if (_gl.getShaderPrecisionFormat === undefined) {
  14249. _gl.getShaderPrecisionFormat = function () {
  14250. return {
  14251. 'rangeMin': 1,
  14252. 'rangeMax': 1,
  14253. 'precision': 1
  14254. };
  14255. };
  14256. }
  14257. } catch (error) {
  14258. console.error('THREE.WebGLRenderer: ' + error.message);
  14259. throw error;
  14260. }
  14261. let extensions, capabilities, state, info;
  14262. let properties, textures, cubemaps, attributes, geometries, objects;
  14263. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  14264. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  14265. let utils, bindingStates;
  14266. function initGLContext() {
  14267. extensions = new WebGLExtensions(_gl);
  14268. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  14269. extensions.init(capabilities);
  14270. utils = new WebGLUtils(_gl, extensions, capabilities);
  14271. state = new WebGLState(_gl, extensions, capabilities);
  14272. _currentDrawBuffers[0] = _gl.BACK;
  14273. info = new WebGLInfo(_gl);
  14274. properties = new WebGLProperties();
  14275. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  14276. cubemaps = new WebGLCubeMaps(_this);
  14277. attributes = new WebGLAttributes(_gl, capabilities);
  14278. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  14279. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  14280. objects = new WebGLObjects(_gl, geometries, attributes, info);
  14281. morphtargets = new WebGLMorphtargets(_gl);
  14282. clipping = new WebGLClipping(properties);
  14283. programCache = new WebGLPrograms(_this, cubemaps, extensions, capabilities, bindingStates, clipping);
  14284. materials = new WebGLMaterials(properties);
  14285. renderLists = new WebGLRenderLists(properties);
  14286. renderStates = new WebGLRenderStates(extensions, capabilities);
  14287. background = new WebGLBackground(_this, cubemaps, state, objects, _premultipliedAlpha);
  14288. shadowMap = new WebGLShadowMap(_this, objects, capabilities);
  14289. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  14290. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  14291. info.programs = programCache.programs;
  14292. _this.capabilities = capabilities;
  14293. _this.extensions = extensions;
  14294. _this.properties = properties;
  14295. _this.renderLists = renderLists;
  14296. _this.shadowMap = shadowMap;
  14297. _this.state = state;
  14298. _this.info = info;
  14299. }
  14300. initGLContext(); // xr
  14301. const xr = new WebXRManager(_this, _gl);
  14302. this.xr = xr; // API
  14303. this.getContext = function () {
  14304. return _gl;
  14305. };
  14306. this.getContextAttributes = function () {
  14307. return _gl.getContextAttributes();
  14308. };
  14309. this.forceContextLoss = function () {
  14310. const extension = extensions.get('WEBGL_lose_context');
  14311. if (extension) extension.loseContext();
  14312. };
  14313. this.forceContextRestore = function () {
  14314. const extension = extensions.get('WEBGL_lose_context');
  14315. if (extension) extension.restoreContext();
  14316. };
  14317. this.getPixelRatio = function () {
  14318. return _pixelRatio;
  14319. };
  14320. this.setPixelRatio = function (value) {
  14321. if (value === undefined) return;
  14322. _pixelRatio = value;
  14323. this.setSize(_width, _height, false);
  14324. };
  14325. this.getSize = function (target) {
  14326. if (target === undefined) {
  14327. console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');
  14328. target = new Vector2();
  14329. }
  14330. return target.set(_width, _height);
  14331. };
  14332. this.setSize = function (width, height, updateStyle) {
  14333. if (xr.isPresenting) {
  14334. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  14335. return;
  14336. }
  14337. _width = width;
  14338. _height = height;
  14339. _canvas.width = Math.floor(width * _pixelRatio);
  14340. _canvas.height = Math.floor(height * _pixelRatio);
  14341. if (updateStyle !== false) {
  14342. _canvas.style.width = width + 'px';
  14343. _canvas.style.height = height + 'px';
  14344. }
  14345. this.setViewport(0, 0, width, height);
  14346. };
  14347. this.getDrawingBufferSize = function (target) {
  14348. if (target === undefined) {
  14349. console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');
  14350. target = new Vector2();
  14351. }
  14352. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  14353. };
  14354. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  14355. _width = width;
  14356. _height = height;
  14357. _pixelRatio = pixelRatio;
  14358. _canvas.width = Math.floor(width * pixelRatio);
  14359. _canvas.height = Math.floor(height * pixelRatio);
  14360. this.setViewport(0, 0, width, height);
  14361. };
  14362. this.getCurrentViewport = function (target) {
  14363. if (target === undefined) {
  14364. console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');
  14365. target = new Vector4();
  14366. }
  14367. return target.copy(_currentViewport);
  14368. };
  14369. this.getViewport = function (target) {
  14370. return target.copy(_viewport);
  14371. };
  14372. this.setViewport = function (x, y, width, height) {
  14373. if (x.isVector4) {
  14374. _viewport.set(x.x, x.y, x.z, x.w);
  14375. } else {
  14376. _viewport.set(x, y, width, height);
  14377. }
  14378. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  14379. };
  14380. this.getScissor = function (target) {
  14381. return target.copy(_scissor);
  14382. };
  14383. this.setScissor = function (x, y, width, height) {
  14384. if (x.isVector4) {
  14385. _scissor.set(x.x, x.y, x.z, x.w);
  14386. } else {
  14387. _scissor.set(x, y, width, height);
  14388. }
  14389. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  14390. };
  14391. this.getScissorTest = function () {
  14392. return _scissorTest;
  14393. };
  14394. this.setScissorTest = function (boolean) {
  14395. state.setScissorTest(_scissorTest = boolean);
  14396. };
  14397. this.setOpaqueSort = function (method) {
  14398. _opaqueSort = method;
  14399. };
  14400. this.setTransparentSort = function (method) {
  14401. _transparentSort = method;
  14402. }; // Clearing
  14403. this.getClearColor = function (target) {
  14404. if (target === undefined) {
  14405. console.warn('WebGLRenderer: .getClearColor() now requires a Color as an argument');
  14406. target = new Color();
  14407. }
  14408. return target.copy(background.getClearColor());
  14409. };
  14410. this.setClearColor = function () {
  14411. background.setClearColor.apply(background, arguments);
  14412. };
  14413. this.getClearAlpha = function () {
  14414. return background.getClearAlpha();
  14415. };
  14416. this.setClearAlpha = function () {
  14417. background.setClearAlpha.apply(background, arguments);
  14418. };
  14419. this.clear = function (color, depth, stencil) {
  14420. let bits = 0;
  14421. if (color === undefined || color) bits |= _gl.COLOR_BUFFER_BIT;
  14422. if (depth === undefined || depth) bits |= _gl.DEPTH_BUFFER_BIT;
  14423. if (stencil === undefined || stencil) bits |= _gl.STENCIL_BUFFER_BIT;
  14424. _gl.clear(bits);
  14425. };
  14426. this.clearColor = function () {
  14427. this.clear(true, false, false);
  14428. };
  14429. this.clearDepth = function () {
  14430. this.clear(false, true, false);
  14431. };
  14432. this.clearStencil = function () {
  14433. this.clear(false, false, true);
  14434. }; //
  14435. this.dispose = function () {
  14436. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  14437. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  14438. renderLists.dispose();
  14439. renderStates.dispose();
  14440. properties.dispose();
  14441. cubemaps.dispose();
  14442. objects.dispose();
  14443. bindingStates.dispose();
  14444. xr.dispose();
  14445. xr.removeEventListener('sessionstart', onXRSessionStart);
  14446. xr.removeEventListener('sessionend', onXRSessionEnd);
  14447. if (_transmissionRenderTarget) {
  14448. _transmissionRenderTarget.dispose();
  14449. _transmissionRenderTarget = null;
  14450. }
  14451. animation.stop();
  14452. }; // Events
  14453. function onContextLost(event) {
  14454. event.preventDefault();
  14455. console.log('THREE.WebGLRenderer: Context Lost.');
  14456. _isContextLost = true;
  14457. }
  14458. function onContextRestore()
  14459. /* event */
  14460. {
  14461. console.log('THREE.WebGLRenderer: Context Restored.');
  14462. _isContextLost = false;
  14463. const infoAutoReset = info.autoReset;
  14464. const shadowMapEnabled = shadowMap.enabled;
  14465. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  14466. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  14467. const shadowMapType = shadowMap.type;
  14468. initGLContext();
  14469. info.autoReset = infoAutoReset;
  14470. shadowMap.enabled = shadowMapEnabled;
  14471. shadowMap.autoUpdate = shadowMapAutoUpdate;
  14472. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  14473. shadowMap.type = shadowMapType;
  14474. }
  14475. function onMaterialDispose(event) {
  14476. const material = event.target;
  14477. material.removeEventListener('dispose', onMaterialDispose);
  14478. deallocateMaterial(material);
  14479. } // Buffer deallocation
  14480. function deallocateMaterial(material) {
  14481. releaseMaterialProgramReferences(material);
  14482. properties.remove(material);
  14483. }
  14484. function releaseMaterialProgramReferences(material) {
  14485. const programs = properties.get(material).programs;
  14486. if (programs !== undefined) {
  14487. programs.forEach(function (program) {
  14488. programCache.releaseProgram(program);
  14489. });
  14490. }
  14491. } // Buffer rendering
  14492. function renderObjectImmediate(object, program) {
  14493. object.render(function (object) {
  14494. _this.renderBufferImmediate(object, program);
  14495. });
  14496. }
  14497. this.renderBufferImmediate = function (object, program) {
  14498. bindingStates.initAttributes();
  14499. const buffers = properties.get(object);
  14500. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  14501. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  14502. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  14503. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  14504. const programAttributes = program.getAttributes();
  14505. if (object.hasPositions) {
  14506. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.position);
  14507. _gl.bufferData(_gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW);
  14508. bindingStates.enableAttribute(programAttributes.position);
  14509. _gl.vertexAttribPointer(programAttributes.position, 3, _gl.FLOAT, false, 0, 0);
  14510. }
  14511. if (object.hasNormals) {
  14512. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.normal);
  14513. _gl.bufferData(_gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW);
  14514. bindingStates.enableAttribute(programAttributes.normal);
  14515. _gl.vertexAttribPointer(programAttributes.normal, 3, _gl.FLOAT, false, 0, 0);
  14516. }
  14517. if (object.hasUvs) {
  14518. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.uv);
  14519. _gl.bufferData(_gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW);
  14520. bindingStates.enableAttribute(programAttributes.uv);
  14521. _gl.vertexAttribPointer(programAttributes.uv, 2, _gl.FLOAT, false, 0, 0);
  14522. }
  14523. if (object.hasColors) {
  14524. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.color);
  14525. _gl.bufferData(_gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW);
  14526. bindingStates.enableAttribute(programAttributes.color);
  14527. _gl.vertexAttribPointer(programAttributes.color, 3, _gl.FLOAT, false, 0, 0);
  14528. }
  14529. bindingStates.disableUnusedAttributes();
  14530. _gl.drawArrays(_gl.TRIANGLES, 0, object.count);
  14531. object.count = 0;
  14532. };
  14533. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  14534. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  14535. const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  14536. const program = setProgram(camera, scene, material, object);
  14537. state.setMaterial(material, frontFaceCW); //
  14538. let index = geometry.index;
  14539. const position = geometry.attributes.position; //
  14540. if (index === null) {
  14541. if (position === undefined || position.count === 0) return;
  14542. } else if (index.count === 0) {
  14543. return;
  14544. } //
  14545. let rangeFactor = 1;
  14546. if (material.wireframe === true) {
  14547. index = geometries.getWireframeAttribute(geometry);
  14548. rangeFactor = 2;
  14549. }
  14550. if (material.morphTargets || material.morphNormals) {
  14551. morphtargets.update(object, geometry, material, program);
  14552. }
  14553. bindingStates.setup(object, material, program, geometry, index);
  14554. let attribute;
  14555. let renderer = bufferRenderer;
  14556. if (index !== null) {
  14557. attribute = attributes.get(index);
  14558. renderer = indexedBufferRenderer;
  14559. renderer.setIndex(attribute);
  14560. } //
  14561. const dataCount = index !== null ? index.count : position.count;
  14562. const rangeStart = geometry.drawRange.start * rangeFactor;
  14563. const rangeCount = geometry.drawRange.count * rangeFactor;
  14564. const groupStart = group !== null ? group.start * rangeFactor : 0;
  14565. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  14566. const drawStart = Math.max(rangeStart, groupStart);
  14567. const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  14568. const drawCount = Math.max(0, drawEnd - drawStart + 1);
  14569. if (drawCount === 0) return; //
  14570. if (object.isMesh) {
  14571. if (material.wireframe === true) {
  14572. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  14573. renderer.setMode(_gl.LINES);
  14574. } else {
  14575. renderer.setMode(_gl.TRIANGLES);
  14576. }
  14577. } else if (object.isLine) {
  14578. let lineWidth = material.linewidth;
  14579. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  14580. state.setLineWidth(lineWidth * getTargetPixelRatio());
  14581. if (object.isLineSegments) {
  14582. renderer.setMode(_gl.LINES);
  14583. } else if (object.isLineLoop) {
  14584. renderer.setMode(_gl.LINE_LOOP);
  14585. } else {
  14586. renderer.setMode(_gl.LINE_STRIP);
  14587. }
  14588. } else if (object.isPoints) {
  14589. renderer.setMode(_gl.POINTS);
  14590. } else if (object.isSprite) {
  14591. renderer.setMode(_gl.TRIANGLES);
  14592. }
  14593. if (object.isInstancedMesh) {
  14594. renderer.renderInstances(drawStart, drawCount, object.count);
  14595. } else if (geometry.isInstancedBufferGeometry) {
  14596. const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  14597. renderer.renderInstances(drawStart, drawCount, instanceCount);
  14598. } else {
  14599. renderer.render(drawStart, drawCount);
  14600. }
  14601. }; // Compile
  14602. this.compile = function (scene, camera) {
  14603. currentRenderState = renderStates.get(scene);
  14604. currentRenderState.init();
  14605. scene.traverseVisible(function (object) {
  14606. if (object.isLight && object.layers.test(camera.layers)) {
  14607. currentRenderState.pushLight(object);
  14608. if (object.castShadow) {
  14609. currentRenderState.pushShadow(object);
  14610. }
  14611. }
  14612. });
  14613. currentRenderState.setupLights();
  14614. scene.traverse(function (object) {
  14615. const material = object.material;
  14616. if (material) {
  14617. if (Array.isArray(material)) {
  14618. for (let i = 0; i < material.length; i++) {
  14619. const material2 = material[i];
  14620. getProgram(material2, scene, object);
  14621. }
  14622. } else {
  14623. getProgram(material, scene, object);
  14624. }
  14625. }
  14626. });
  14627. }; // Animation Loop
  14628. let onAnimationFrameCallback = null;
  14629. function onAnimationFrame(time) {
  14630. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  14631. }
  14632. function onXRSessionStart() {
  14633. animation.stop();
  14634. }
  14635. function onXRSessionEnd() {
  14636. animation.start();
  14637. }
  14638. const animation = new WebGLAnimation();
  14639. animation.setAnimationLoop(onAnimationFrame);
  14640. if (typeof window !== 'undefined') animation.setContext(window);
  14641. this.setAnimationLoop = function (callback) {
  14642. onAnimationFrameCallback = callback;
  14643. xr.setAnimationLoop(callback);
  14644. callback === null ? animation.stop() : animation.start();
  14645. };
  14646. xr.addEventListener('sessionstart', onXRSessionStart);
  14647. xr.addEventListener('sessionend', onXRSessionEnd); // Rendering
  14648. this.render = function (scene, camera) {
  14649. if (camera !== undefined && camera.isCamera !== true) {
  14650. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  14651. return;
  14652. }
  14653. if (_isContextLost === true) return; // update scene graph
  14654. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  14655. if (camera.parent === null) camera.updateMatrixWorld();
  14656. if (xr.enabled === true && xr.isPresenting === true) {
  14657. if (xr.cameraAutoUpdate === true) xr.updateCamera(camera);
  14658. camera = xr.getCamera(); // use XR camera for rendering
  14659. } //
  14660. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget);
  14661. currentRenderState = renderStates.get(scene, renderStateStack.length);
  14662. currentRenderState.init();
  14663. renderStateStack.push(currentRenderState);
  14664. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  14665. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  14666. _localClippingEnabled = this.localClippingEnabled;
  14667. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  14668. currentRenderList = renderLists.get(scene, renderListStack.length);
  14669. currentRenderList.init();
  14670. renderListStack.push(currentRenderList);
  14671. projectObject(scene, camera, 0, _this.sortObjects);
  14672. currentRenderList.finish();
  14673. if (_this.sortObjects === true) {
  14674. currentRenderList.sort(_opaqueSort, _transparentSort);
  14675. } //
  14676. if (_clippingEnabled === true) clipping.beginShadows();
  14677. const shadowsArray = currentRenderState.state.shadowsArray;
  14678. shadowMap.render(shadowsArray, scene, camera);
  14679. currentRenderState.setupLights();
  14680. currentRenderState.setupLightsView(camera);
  14681. if (_clippingEnabled === true) clipping.endShadows(); //
  14682. if (this.info.autoReset === true) this.info.reset(); //
  14683. background.render(currentRenderList, scene); // render scene
  14684. const opaqueObjects = currentRenderList.opaque;
  14685. const transmissiveObjects = currentRenderList.transmissive;
  14686. const transparentObjects = currentRenderList.transparent;
  14687. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  14688. if (transmissiveObjects.length > 0) renderTransmissiveObjects(opaqueObjects, transmissiveObjects, scene, camera);
  14689. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera); //
  14690. if (_currentRenderTarget !== null) {
  14691. // Generate mipmap if we're using any kind of mipmap filtering
  14692. textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessary
  14693. textures.updateMultisampleRenderTarget(_currentRenderTarget);
  14694. } //
  14695. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); // Ensure depth buffer writing is enabled so it can be cleared on next render
  14696. state.buffers.depth.setTest(true);
  14697. state.buffers.depth.setMask(true);
  14698. state.buffers.color.setMask(true);
  14699. state.setPolygonOffset(false); // _gl.finish();
  14700. bindingStates.resetDefaultState();
  14701. _currentMaterialId = -1;
  14702. _currentCamera = null;
  14703. renderStateStack.pop();
  14704. if (renderStateStack.length > 0) {
  14705. currentRenderState = renderStateStack[renderStateStack.length - 1];
  14706. } else {
  14707. currentRenderState = null;
  14708. }
  14709. renderListStack.pop();
  14710. if (renderListStack.length > 0) {
  14711. currentRenderList = renderListStack[renderListStack.length - 1];
  14712. } else {
  14713. currentRenderList = null;
  14714. }
  14715. };
  14716. function projectObject(object, camera, groupOrder, sortObjects) {
  14717. if (object.visible === false) return;
  14718. const visible = object.layers.test(camera.layers);
  14719. if (visible) {
  14720. if (object.isGroup) {
  14721. groupOrder = object.renderOrder;
  14722. } else if (object.isLOD) {
  14723. if (object.autoUpdate === true) object.update(camera);
  14724. } else if (object.isLight) {
  14725. currentRenderState.pushLight(object);
  14726. if (object.castShadow) {
  14727. currentRenderState.pushShadow(object);
  14728. }
  14729. } else if (object.isSprite) {
  14730. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  14731. if (sortObjects) {
  14732. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  14733. }
  14734. const geometry = objects.update(object);
  14735. const material = object.material;
  14736. if (material.visible) {
  14737. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  14738. }
  14739. }
  14740. } else if (object.isImmediateRenderObject) {
  14741. if (sortObjects) {
  14742. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  14743. }
  14744. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  14745. } else if (object.isMesh || object.isLine || object.isPoints) {
  14746. if (object.isSkinnedMesh) {
  14747. // update skeleton only once in a frame
  14748. if (object.skeleton.frame !== info.render.frame) {
  14749. object.skeleton.update();
  14750. object.skeleton.frame = info.render.frame;
  14751. }
  14752. }
  14753. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  14754. if (sortObjects) {
  14755. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  14756. }
  14757. const geometry = objects.update(object);
  14758. const material = object.material;
  14759. if (Array.isArray(material)) {
  14760. const groups = geometry.groups;
  14761. for (let i = 0, l = groups.length; i < l; i++) {
  14762. const group = groups[i];
  14763. const groupMaterial = material[group.materialIndex];
  14764. if (groupMaterial && groupMaterial.visible) {
  14765. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  14766. }
  14767. }
  14768. } else if (material.visible) {
  14769. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  14770. }
  14771. }
  14772. }
  14773. }
  14774. const children = object.children;
  14775. for (let i = 0, l = children.length; i < l; i++) {
  14776. projectObject(children[i], camera, groupOrder, sortObjects);
  14777. }
  14778. }
  14779. function renderTransmissiveObjects(opaqueObjects, transmissiveObjects, scene, camera) {
  14780. if (_transmissionRenderTarget === null) {
  14781. const needsAntialias = _antialias === true && capabilities.isWebGL2 === true;
  14782. const renderTargetType = needsAntialias ? WebGLMultisampleRenderTarget : WebGLRenderTarget;
  14783. _transmissionRenderTarget = new renderTargetType(1024, 1024, {
  14784. generateMipmaps: true,
  14785. minFilter: LinearMipmapLinearFilter,
  14786. magFilter: NearestFilter,
  14787. wrapS: ClampToEdgeWrapping,
  14788. wrapT: ClampToEdgeWrapping
  14789. });
  14790. }
  14791. const currentRenderTarget = _this.getRenderTarget();
  14792. _this.setRenderTarget(_transmissionRenderTarget);
  14793. _this.clear();
  14794. renderObjects(opaqueObjects, scene, camera);
  14795. textures.updateMultisampleRenderTarget(_transmissionRenderTarget);
  14796. textures.updateRenderTargetMipmap(_transmissionRenderTarget);
  14797. _this.setRenderTarget(currentRenderTarget);
  14798. renderObjects(transmissiveObjects, scene, camera);
  14799. }
  14800. function renderObjects(renderList, scene, camera) {
  14801. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  14802. for (let i = 0, l = renderList.length; i < l; i++) {
  14803. const renderItem = renderList[i];
  14804. const object = renderItem.object;
  14805. const geometry = renderItem.geometry;
  14806. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  14807. const group = renderItem.group;
  14808. if (camera.isArrayCamera) {
  14809. const cameras = camera.cameras;
  14810. for (let j = 0, jl = cameras.length; j < jl; j++) {
  14811. const camera2 = cameras[j];
  14812. if (object.layers.test(camera2.layers)) {
  14813. state.viewport(_currentViewport.copy(camera2.viewport));
  14814. currentRenderState.setupLightsView(camera2);
  14815. renderObject(object, scene, camera2, geometry, material, group);
  14816. }
  14817. }
  14818. } else {
  14819. renderObject(object, scene, camera, geometry, material, group);
  14820. }
  14821. }
  14822. }
  14823. function renderObject(object, scene, camera, geometry, material, group) {
  14824. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  14825. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  14826. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  14827. if (object.isImmediateRenderObject) {
  14828. const program = setProgram(camera, scene, material, object);
  14829. state.setMaterial(material);
  14830. bindingStates.reset();
  14831. renderObjectImmediate(object, program);
  14832. } else {
  14833. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  14834. }
  14835. object.onAfterRender(_this, scene, camera, geometry, material, group);
  14836. }
  14837. function getProgram(material, scene, object) {
  14838. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  14839. const materialProperties = properties.get(material);
  14840. const lights = currentRenderState.state.lights;
  14841. const shadowsArray = currentRenderState.state.shadowsArray;
  14842. const lightsStateVersion = lights.state.version;
  14843. const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  14844. const programCacheKey = programCache.getProgramCacheKey(parameters);
  14845. 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
  14846. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  14847. materialProperties.fog = scene.fog;
  14848. materialProperties.envMap = cubemaps.get(material.envMap || materialProperties.environment);
  14849. if (programs === undefined) {
  14850. // new material
  14851. material.addEventListener('dispose', onMaterialDispose);
  14852. programs = new Map();
  14853. materialProperties.programs = programs;
  14854. }
  14855. let program = programs.get(programCacheKey);
  14856. if (program !== undefined) {
  14857. // early out if program and light state is identical
  14858. if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) {
  14859. updateCommonMaterialProperties(material, parameters);
  14860. return program;
  14861. }
  14862. } else {
  14863. parameters.uniforms = programCache.getUniforms(material);
  14864. material.onBuild(parameters, _this);
  14865. material.onBeforeCompile(parameters, _this);
  14866. program = programCache.acquireProgram(parameters, programCacheKey);
  14867. programs.set(programCacheKey, program);
  14868. materialProperties.uniforms = parameters.uniforms;
  14869. }
  14870. const uniforms = materialProperties.uniforms;
  14871. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  14872. uniforms.clippingPlanes = clipping.uniform;
  14873. }
  14874. updateCommonMaterialProperties(material, parameters); // store the light setup it was created for
  14875. materialProperties.needsLights = materialNeedsLights(material);
  14876. materialProperties.lightsStateVersion = lightsStateVersion;
  14877. if (materialProperties.needsLights) {
  14878. // wire up the material to this renderer's lighting state
  14879. uniforms.ambientLightColor.value = lights.state.ambient;
  14880. uniforms.lightProbe.value = lights.state.probe;
  14881. uniforms.directionalLights.value = lights.state.directional;
  14882. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  14883. uniforms.spotLights.value = lights.state.spot;
  14884. uniforms.spotLightShadows.value = lights.state.spotShadow;
  14885. uniforms.rectAreaLights.value = lights.state.rectArea;
  14886. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  14887. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  14888. uniforms.pointLights.value = lights.state.point;
  14889. uniforms.pointLightShadows.value = lights.state.pointShadow;
  14890. uniforms.hemisphereLights.value = lights.state.hemi;
  14891. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  14892. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  14893. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  14894. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  14895. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  14896. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  14897. }
  14898. const progUniforms = program.getUniforms();
  14899. const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  14900. materialProperties.currentProgram = program;
  14901. materialProperties.uniformsList = uniformsList;
  14902. return program;
  14903. }
  14904. function updateCommonMaterialProperties(material, parameters) {
  14905. const materialProperties = properties.get(material);
  14906. materialProperties.outputEncoding = parameters.outputEncoding;
  14907. materialProperties.instancing = parameters.instancing;
  14908. materialProperties.skinning = parameters.skinning;
  14909. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  14910. materialProperties.numIntersection = parameters.numClipIntersection;
  14911. materialProperties.vertexAlphas = parameters.vertexAlphas;
  14912. }
  14913. function setProgram(camera, scene, material, object) {
  14914. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  14915. textures.resetTextureUnits();
  14916. const fog = scene.fog;
  14917. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  14918. const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  14919. const envMap = cubemaps.get(material.envMap || environment);
  14920. const vertexAlphas = material.vertexColors === true && object.geometry && object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4;
  14921. const materialProperties = properties.get(material);
  14922. const lights = currentRenderState.state.lights;
  14923. if (_clippingEnabled === true) {
  14924. if (_localClippingEnabled === true || camera !== _currentCamera) {
  14925. const useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  14926. // object instead of the material, once it becomes feasible
  14927. // (#8465, #8379)
  14928. clipping.setState(material, camera, useCache);
  14929. }
  14930. } //
  14931. let needsProgramChange = false;
  14932. if (material.version === materialProperties.__version) {
  14933. if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  14934. needsProgramChange = true;
  14935. } else if (materialProperties.outputEncoding !== encoding) {
  14936. needsProgramChange = true;
  14937. } else if (object.isInstancedMesh && materialProperties.instancing === false) {
  14938. needsProgramChange = true;
  14939. } else if (!object.isInstancedMesh && materialProperties.instancing === true) {
  14940. needsProgramChange = true;
  14941. } else if (object.isSkinnedMesh && materialProperties.skinning === false) {
  14942. needsProgramChange = true;
  14943. } else if (!object.isSkinnedMesh && materialProperties.skinning === true) {
  14944. needsProgramChange = true;
  14945. } else if (materialProperties.envMap !== envMap) {
  14946. needsProgramChange = true;
  14947. } else if (material.fog && materialProperties.fog !== fog) {
  14948. needsProgramChange = true;
  14949. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  14950. needsProgramChange = true;
  14951. } else if (materialProperties.vertexAlphas !== vertexAlphas) {
  14952. needsProgramChange = true;
  14953. }
  14954. } else {
  14955. needsProgramChange = true;
  14956. materialProperties.__version = material.version;
  14957. } //
  14958. let program = materialProperties.currentProgram;
  14959. if (needsProgramChange === true) {
  14960. program = getProgram(material, scene, object);
  14961. }
  14962. let refreshProgram = false;
  14963. let refreshMaterial = false;
  14964. let refreshLights = false;
  14965. const p_uniforms = program.getUniforms(),
  14966. m_uniforms = materialProperties.uniforms;
  14967. if (state.useProgram(program.program)) {
  14968. refreshProgram = true;
  14969. refreshMaterial = true;
  14970. refreshLights = true;
  14971. }
  14972. if (material.id !== _currentMaterialId) {
  14973. _currentMaterialId = material.id;
  14974. refreshMaterial = true;
  14975. }
  14976. if (refreshProgram || _currentCamera !== camera) {
  14977. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  14978. if (capabilities.logarithmicDepthBuffer) {
  14979. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  14980. }
  14981. if (_currentCamera !== camera) {
  14982. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  14983. // now, in case this material supports lights - or later, when
  14984. // the next material that does gets activated:
  14985. refreshMaterial = true; // set to true on material change
  14986. refreshLights = true; // remains set until update done
  14987. } // load material specific uniforms
  14988. // (shader material also gets them for the sake of genericity)
  14989. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  14990. const uCamPos = p_uniforms.map.cameraPosition;
  14991. if (uCamPos !== undefined) {
  14992. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  14993. }
  14994. }
  14995. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  14996. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  14997. }
  14998. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || object.isSkinnedMesh) {
  14999. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  15000. }
  15001. } // skinning uniforms must be set even if material didn't change
  15002. // auto-setting of texture unit for bone texture must go before other textures
  15003. // otherwise textures used for skinning can take over texture units reserved for other material textures
  15004. if (object.isSkinnedMesh) {
  15005. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  15006. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  15007. const skeleton = object.skeleton;
  15008. if (skeleton) {
  15009. if (capabilities.floatVertexTextures) {
  15010. if (skeleton.boneTexture === null) skeleton.computeBoneTexture();
  15011. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  15012. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  15013. } else {
  15014. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  15015. }
  15016. }
  15017. }
  15018. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  15019. materialProperties.receiveShadow = object.receiveShadow;
  15020. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  15021. }
  15022. if (refreshMaterial) {
  15023. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  15024. if (materialProperties.needsLights) {
  15025. // the current material requires lighting info
  15026. // note: all lighting uniforms are always set correctly
  15027. // they simply reference the renderer's state for their
  15028. // values
  15029. //
  15030. // use the current material's .needsUpdate flags to set
  15031. // the GL state when required
  15032. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  15033. } // refresh uniforms common to several materials
  15034. if (fog && material.fog) {
  15035. materials.refreshFogUniforms(m_uniforms, fog);
  15036. }
  15037. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget);
  15038. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15039. }
  15040. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  15041. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15042. material.uniformsNeedUpdate = false;
  15043. }
  15044. if (material.isSpriteMaterial) {
  15045. p_uniforms.setValue(_gl, 'center', object.center);
  15046. } // common matrices
  15047. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  15048. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  15049. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  15050. return program;
  15051. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15052. function markUniformsLightsNeedsUpdate(uniforms, value) {
  15053. uniforms.ambientLightColor.needsUpdate = value;
  15054. uniforms.lightProbe.needsUpdate = value;
  15055. uniforms.directionalLights.needsUpdate = value;
  15056. uniforms.directionalLightShadows.needsUpdate = value;
  15057. uniforms.pointLights.needsUpdate = value;
  15058. uniforms.pointLightShadows.needsUpdate = value;
  15059. uniforms.spotLights.needsUpdate = value;
  15060. uniforms.spotLightShadows.needsUpdate = value;
  15061. uniforms.rectAreaLights.needsUpdate = value;
  15062. uniforms.hemisphereLights.needsUpdate = value;
  15063. }
  15064. function materialNeedsLights(material) {
  15065. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  15066. }
  15067. this.getActiveCubeFace = function () {
  15068. return _currentActiveCubeFace;
  15069. };
  15070. this.getActiveMipmapLevel = function () {
  15071. return _currentActiveMipmapLevel;
  15072. };
  15073. this.getRenderTarget = function () {
  15074. return _currentRenderTarget;
  15075. };
  15076. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  15077. _currentRenderTarget = renderTarget;
  15078. _currentActiveCubeFace = activeCubeFace;
  15079. _currentActiveMipmapLevel = activeMipmapLevel;
  15080. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  15081. textures.setupRenderTarget(renderTarget);
  15082. }
  15083. let framebuffer = null;
  15084. let isCube = false;
  15085. let isRenderTarget3D = false;
  15086. if (renderTarget) {
  15087. const texture = renderTarget.texture;
  15088. if (texture.isDataTexture3D || texture.isDataTexture2DArray) {
  15089. isRenderTarget3D = true;
  15090. }
  15091. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  15092. if (renderTarget.isWebGLCubeRenderTarget) {
  15093. framebuffer = __webglFramebuffer[activeCubeFace];
  15094. isCube = true;
  15095. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  15096. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  15097. } else {
  15098. framebuffer = __webglFramebuffer;
  15099. }
  15100. _currentViewport.copy(renderTarget.viewport);
  15101. _currentScissor.copy(renderTarget.scissor);
  15102. _currentScissorTest = renderTarget.scissorTest;
  15103. } else {
  15104. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  15105. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  15106. _currentScissorTest = _scissorTest;
  15107. }
  15108. const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  15109. if (framebufferBound && capabilities.drawBuffers) {
  15110. let needsUpdate = false;
  15111. if (renderTarget) {
  15112. if (renderTarget.isWebGLMultipleRenderTargets) {
  15113. const textures = renderTarget.texture;
  15114. if (_currentDrawBuffers.length !== textures.length || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  15115. for (let i = 0, il = textures.length; i < il; i++) {
  15116. _currentDrawBuffers[i] = _gl.COLOR_ATTACHMENT0 + i;
  15117. }
  15118. _currentDrawBuffers.length = textures.length;
  15119. needsUpdate = true;
  15120. }
  15121. } else {
  15122. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  15123. _currentDrawBuffers[0] = _gl.COLOR_ATTACHMENT0;
  15124. _currentDrawBuffers.length = 1;
  15125. needsUpdate = true;
  15126. }
  15127. }
  15128. } else {
  15129. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.BACK) {
  15130. _currentDrawBuffers[0] = _gl.BACK;
  15131. _currentDrawBuffers.length = 1;
  15132. needsUpdate = true;
  15133. }
  15134. }
  15135. if (needsUpdate) {
  15136. if (capabilities.isWebGL2) {
  15137. _gl.drawBuffers(_currentDrawBuffers);
  15138. } else {
  15139. extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(_currentDrawBuffers);
  15140. }
  15141. }
  15142. }
  15143. state.viewport(_currentViewport);
  15144. state.scissor(_currentScissor);
  15145. state.setScissorTest(_currentScissorTest);
  15146. if (isCube) {
  15147. const textureProperties = properties.get(renderTarget.texture);
  15148. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  15149. } else if (isRenderTarget3D) {
  15150. const textureProperties = properties.get(renderTarget.texture);
  15151. const layer = activeCubeFace || 0;
  15152. _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer);
  15153. }
  15154. };
  15155. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  15156. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  15157. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  15158. return;
  15159. }
  15160. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  15161. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  15162. framebuffer = framebuffer[activeCubeFaceIndex];
  15163. }
  15164. if (framebuffer) {
  15165. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  15166. try {
  15167. const texture = renderTarget.texture;
  15168. const textureFormat = texture.format;
  15169. const textureType = texture.type;
  15170. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) {
  15171. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  15172. return;
  15173. }
  15174. const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
  15175. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513)
  15176. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  15177. !halfFloatSupportedByExt) {
  15178. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  15179. return;
  15180. }
  15181. if (_gl.checkFramebufferStatus(_gl.FRAMEBUFFER) === _gl.FRAMEBUFFER_COMPLETE) {
  15182. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  15183. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  15184. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  15185. }
  15186. } else {
  15187. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  15188. }
  15189. } finally {
  15190. // restore framebuffer of current render target if necessary
  15191. const framebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
  15192. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  15193. }
  15194. }
  15195. };
  15196. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  15197. const levelScale = Math.pow(2, -level);
  15198. const width = Math.floor(texture.image.width * levelScale);
  15199. const height = Math.floor(texture.image.height * levelScale);
  15200. let glFormat = utils.convert(texture.format);
  15201. if (capabilities.isWebGL2) {
  15202. // Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=1120100
  15203. if (glFormat === _gl.RGB) glFormat = _gl.RGB8;
  15204. if (glFormat === _gl.RGBA) glFormat = _gl.RGBA8;
  15205. }
  15206. textures.setTexture2D(texture, 0);
  15207. _gl.copyTexImage2D(_gl.TEXTURE_2D, level, glFormat, position.x, position.y, width, height, 0);
  15208. state.unbindTexture();
  15209. };
  15210. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  15211. const width = srcTexture.image.width;
  15212. const height = srcTexture.image.height;
  15213. const glFormat = utils.convert(dstTexture.format);
  15214. const glType = utils.convert(dstTexture.type);
  15215. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  15216. // parameters, make sure they are correct for the dstTexture
  15217. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  15218. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  15219. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  15220. if (srcTexture.isDataTexture) {
  15221. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  15222. } else {
  15223. if (srcTexture.isCompressedTexture) {
  15224. _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  15225. } else {
  15226. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image);
  15227. }
  15228. } // Generate mipmaps only when copying level 0
  15229. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D);
  15230. state.unbindTexture();
  15231. };
  15232. this.copyTextureToTexture3D = function (sourceBox, position, srcTexture, dstTexture, level = 0) {
  15233. if (_this.isWebGL1Renderer) {
  15234. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.');
  15235. return;
  15236. }
  15237. const {
  15238. width,
  15239. height,
  15240. data
  15241. } = srcTexture.image;
  15242. const glFormat = utils.convert(dstTexture.format);
  15243. const glType = utils.convert(dstTexture.type);
  15244. let glTarget;
  15245. if (dstTexture.isDataTexture3D) {
  15246. textures.setTexture3D(dstTexture, 0);
  15247. glTarget = _gl.TEXTURE_3D;
  15248. } else if (dstTexture.isDataTexture2DArray) {
  15249. textures.setTexture2DArray(dstTexture, 0);
  15250. glTarget = _gl.TEXTURE_2D_ARRAY;
  15251. } else {
  15252. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.');
  15253. return;
  15254. }
  15255. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  15256. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  15257. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  15258. const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH);
  15259. const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT);
  15260. const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS);
  15261. const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS);
  15262. const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES);
  15263. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, width);
  15264. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, height);
  15265. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x);
  15266. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y);
  15267. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z);
  15268. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, sourceBox.max.x - sourceBox.min.x + 1, sourceBox.max.y - sourceBox.min.y + 1, sourceBox.max.z - sourceBox.min.z + 1, glFormat, glType, data);
  15269. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen);
  15270. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight);
  15271. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels);
  15272. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows);
  15273. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages); // Generate mipmaps only when copying level 0
  15274. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget);
  15275. state.unbindTexture();
  15276. };
  15277. this.initTexture = function (texture) {
  15278. textures.setTexture2D(texture, 0);
  15279. state.unbindTexture();
  15280. };
  15281. this.resetState = function () {
  15282. _currentActiveCubeFace = 0;
  15283. _currentActiveMipmapLevel = 0;
  15284. _currentRenderTarget = null;
  15285. state.reset();
  15286. bindingStates.reset();
  15287. };
  15288. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  15289. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  15290. detail: this
  15291. })); // eslint-disable-line no-undef
  15292. }
  15293. }
  15294. class WebGL1Renderer extends WebGLRenderer {}
  15295. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  15296. class FogExp2 {
  15297. constructor(color, density = 0.00025) {
  15298. this.name = '';
  15299. this.color = new Color(color);
  15300. this.density = density;
  15301. }
  15302. clone() {
  15303. return new FogExp2(this.color, this.density);
  15304. }
  15305. toJSON()
  15306. /* meta */
  15307. {
  15308. return {
  15309. type: 'FogExp2',
  15310. color: this.color.getHex(),
  15311. density: this.density
  15312. };
  15313. }
  15314. }
  15315. FogExp2.prototype.isFogExp2 = true;
  15316. class Fog {
  15317. constructor(color, near = 1, far = 1000) {
  15318. this.name = '';
  15319. this.color = new Color(color);
  15320. this.near = near;
  15321. this.far = far;
  15322. }
  15323. clone() {
  15324. return new Fog(this.color, this.near, this.far);
  15325. }
  15326. toJSON()
  15327. /* meta */
  15328. {
  15329. return {
  15330. type: 'Fog',
  15331. color: this.color.getHex(),
  15332. near: this.near,
  15333. far: this.far
  15334. };
  15335. }
  15336. }
  15337. Fog.prototype.isFog = true;
  15338. class Scene extends Object3D {
  15339. constructor() {
  15340. super();
  15341. this.type = 'Scene';
  15342. this.background = null;
  15343. this.environment = null;
  15344. this.fog = null;
  15345. this.overrideMaterial = null;
  15346. this.autoUpdate = true; // checked by the renderer
  15347. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  15348. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  15349. detail: this
  15350. })); // eslint-disable-line no-undef
  15351. }
  15352. }
  15353. copy(source, recursive) {
  15354. super.copy(source, recursive);
  15355. if (source.background !== null) this.background = source.background.clone();
  15356. if (source.environment !== null) this.environment = source.environment.clone();
  15357. if (source.fog !== null) this.fog = source.fog.clone();
  15358. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  15359. this.autoUpdate = source.autoUpdate;
  15360. this.matrixAutoUpdate = source.matrixAutoUpdate;
  15361. return this;
  15362. }
  15363. toJSON(meta) {
  15364. const data = super.toJSON(meta);
  15365. if (this.background !== null) data.object.background = this.background.toJSON(meta);
  15366. if (this.environment !== null) data.object.environment = this.environment.toJSON(meta);
  15367. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  15368. return data;
  15369. }
  15370. }
  15371. Scene.prototype.isScene = true;
  15372. class InterleavedBuffer {
  15373. constructor(array, stride) {
  15374. this.array = array;
  15375. this.stride = stride;
  15376. this.count = array !== undefined ? array.length / stride : 0;
  15377. this.usage = StaticDrawUsage;
  15378. this.updateRange = {
  15379. offset: 0,
  15380. count: -1
  15381. };
  15382. this.version = 0;
  15383. this.uuid = generateUUID();
  15384. }
  15385. onUploadCallback() {}
  15386. set needsUpdate(value) {
  15387. if (value === true) this.version++;
  15388. }
  15389. setUsage(value) {
  15390. this.usage = value;
  15391. return this;
  15392. }
  15393. copy(source) {
  15394. this.array = new source.array.constructor(source.array);
  15395. this.count = source.count;
  15396. this.stride = source.stride;
  15397. this.usage = source.usage;
  15398. return this;
  15399. }
  15400. copyAt(index1, attribute, index2) {
  15401. index1 *= this.stride;
  15402. index2 *= attribute.stride;
  15403. for (let i = 0, l = this.stride; i < l; i++) {
  15404. this.array[index1 + i] = attribute.array[index2 + i];
  15405. }
  15406. return this;
  15407. }
  15408. set(value, offset = 0) {
  15409. this.array.set(value, offset);
  15410. return this;
  15411. }
  15412. clone(data) {
  15413. if (data.arrayBuffers === undefined) {
  15414. data.arrayBuffers = {};
  15415. }
  15416. if (this.array.buffer._uuid === undefined) {
  15417. this.array.buffer._uuid = generateUUID();
  15418. }
  15419. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  15420. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  15421. }
  15422. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  15423. const ib = new this.constructor(array, this.stride);
  15424. ib.setUsage(this.usage);
  15425. return ib;
  15426. }
  15427. onUpload(callback) {
  15428. this.onUploadCallback = callback;
  15429. return this;
  15430. }
  15431. toJSON(data) {
  15432. if (data.arrayBuffers === undefined) {
  15433. data.arrayBuffers = {};
  15434. } // generate UUID for array buffer if necessary
  15435. if (this.array.buffer._uuid === undefined) {
  15436. this.array.buffer._uuid = generateUUID();
  15437. }
  15438. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  15439. data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
  15440. } //
  15441. return {
  15442. uuid: this.uuid,
  15443. buffer: this.array.buffer._uuid,
  15444. type: this.array.constructor.name,
  15445. stride: this.stride
  15446. };
  15447. }
  15448. }
  15449. InterleavedBuffer.prototype.isInterleavedBuffer = true;
  15450. const _vector$6 = /*@__PURE__*/new Vector3();
  15451. class InterleavedBufferAttribute {
  15452. constructor(interleavedBuffer, itemSize, offset, normalized) {
  15453. this.name = '';
  15454. this.data = interleavedBuffer;
  15455. this.itemSize = itemSize;
  15456. this.offset = offset;
  15457. this.normalized = normalized === true;
  15458. }
  15459. get count() {
  15460. return this.data.count;
  15461. }
  15462. get array() {
  15463. return this.data.array;
  15464. }
  15465. set needsUpdate(value) {
  15466. this.data.needsUpdate = value;
  15467. }
  15468. applyMatrix4(m) {
  15469. for (let i = 0, l = this.data.count; i < l; i++) {
  15470. _vector$6.x = this.getX(i);
  15471. _vector$6.y = this.getY(i);
  15472. _vector$6.z = this.getZ(i);
  15473. _vector$6.applyMatrix4(m);
  15474. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  15475. }
  15476. return this;
  15477. }
  15478. applyNormalMatrix(m) {
  15479. for (let i = 0, l = this.count; i < l; i++) {
  15480. _vector$6.x = this.getX(i);
  15481. _vector$6.y = this.getY(i);
  15482. _vector$6.z = this.getZ(i);
  15483. _vector$6.applyNormalMatrix(m);
  15484. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  15485. }
  15486. return this;
  15487. }
  15488. transformDirection(m) {
  15489. for (let i = 0, l = this.count; i < l; i++) {
  15490. _vector$6.x = this.getX(i);
  15491. _vector$6.y = this.getY(i);
  15492. _vector$6.z = this.getZ(i);
  15493. _vector$6.transformDirection(m);
  15494. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  15495. }
  15496. return this;
  15497. }
  15498. setX(index, x) {
  15499. this.data.array[index * this.data.stride + this.offset] = x;
  15500. return this;
  15501. }
  15502. setY(index, y) {
  15503. this.data.array[index * this.data.stride + this.offset + 1] = y;
  15504. return this;
  15505. }
  15506. setZ(index, z) {
  15507. this.data.array[index * this.data.stride + this.offset + 2] = z;
  15508. return this;
  15509. }
  15510. setW(index, w) {
  15511. this.data.array[index * this.data.stride + this.offset + 3] = w;
  15512. return this;
  15513. }
  15514. getX(index) {
  15515. return this.data.array[index * this.data.stride + this.offset];
  15516. }
  15517. getY(index) {
  15518. return this.data.array[index * this.data.stride + this.offset + 1];
  15519. }
  15520. getZ(index) {
  15521. return this.data.array[index * this.data.stride + this.offset + 2];
  15522. }
  15523. getW(index) {
  15524. return this.data.array[index * this.data.stride + this.offset + 3];
  15525. }
  15526. setXY(index, x, y) {
  15527. index = index * this.data.stride + this.offset;
  15528. this.data.array[index + 0] = x;
  15529. this.data.array[index + 1] = y;
  15530. return this;
  15531. }
  15532. setXYZ(index, x, y, z) {
  15533. index = index * this.data.stride + this.offset;
  15534. this.data.array[index + 0] = x;
  15535. this.data.array[index + 1] = y;
  15536. this.data.array[index + 2] = z;
  15537. return this;
  15538. }
  15539. setXYZW(index, x, y, z, w) {
  15540. index = index * this.data.stride + this.offset;
  15541. this.data.array[index + 0] = x;
  15542. this.data.array[index + 1] = y;
  15543. this.data.array[index + 2] = z;
  15544. this.data.array[index + 3] = w;
  15545. return this;
  15546. }
  15547. clone(data) {
  15548. if (data === undefined) {
  15549. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');
  15550. const array = [];
  15551. for (let i = 0; i < this.count; i++) {
  15552. const index = i * this.data.stride + this.offset;
  15553. for (let j = 0; j < this.itemSize; j++) {
  15554. array.push(this.data.array[index + j]);
  15555. }
  15556. }
  15557. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  15558. } else {
  15559. if (data.interleavedBuffers === undefined) {
  15560. data.interleavedBuffers = {};
  15561. }
  15562. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  15563. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  15564. }
  15565. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  15566. }
  15567. }
  15568. toJSON(data) {
  15569. if (data === undefined) {
  15570. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');
  15571. const array = [];
  15572. for (let i = 0; i < this.count; i++) {
  15573. const index = i * this.data.stride + this.offset;
  15574. for (let j = 0; j < this.itemSize; j++) {
  15575. array.push(this.data.array[index + j]);
  15576. }
  15577. } // deinterleave data and save it as an ordinary buffer attribute for now
  15578. return {
  15579. itemSize: this.itemSize,
  15580. type: this.array.constructor.name,
  15581. array: array,
  15582. normalized: this.normalized
  15583. };
  15584. } else {
  15585. // save as true interlaved attribtue
  15586. if (data.interleavedBuffers === undefined) {
  15587. data.interleavedBuffers = {};
  15588. }
  15589. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  15590. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  15591. }
  15592. return {
  15593. isInterleavedBufferAttribute: true,
  15594. itemSize: this.itemSize,
  15595. data: this.data.uuid,
  15596. offset: this.offset,
  15597. normalized: this.normalized
  15598. };
  15599. }
  15600. }
  15601. }
  15602. InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
  15603. /**
  15604. * parameters = {
  15605. * color: <hex>,
  15606. * map: new THREE.Texture( <Image> ),
  15607. * alphaMap: new THREE.Texture( <Image> ),
  15608. * rotation: <float>,
  15609. * sizeAttenuation: <bool>
  15610. * }
  15611. */
  15612. class SpriteMaterial extends Material {
  15613. constructor(parameters) {
  15614. super();
  15615. this.type = 'SpriteMaterial';
  15616. this.color = new Color(0xffffff);
  15617. this.map = null;
  15618. this.alphaMap = null;
  15619. this.rotation = 0;
  15620. this.sizeAttenuation = true;
  15621. this.transparent = true;
  15622. this.setValues(parameters);
  15623. }
  15624. copy(source) {
  15625. super.copy(source);
  15626. this.color.copy(source.color);
  15627. this.map = source.map;
  15628. this.alphaMap = source.alphaMap;
  15629. this.rotation = source.rotation;
  15630. this.sizeAttenuation = source.sizeAttenuation;
  15631. return this;
  15632. }
  15633. }
  15634. SpriteMaterial.prototype.isSpriteMaterial = true;
  15635. let _geometry;
  15636. const _intersectPoint = /*@__PURE__*/new Vector3();
  15637. const _worldScale = /*@__PURE__*/new Vector3();
  15638. const _mvPosition = /*@__PURE__*/new Vector3();
  15639. const _alignedPosition = /*@__PURE__*/new Vector2();
  15640. const _rotatedPosition = /*@__PURE__*/new Vector2();
  15641. const _viewWorldMatrix = /*@__PURE__*/new Matrix4();
  15642. const _vA = /*@__PURE__*/new Vector3();
  15643. const _vB = /*@__PURE__*/new Vector3();
  15644. const _vC = /*@__PURE__*/new Vector3();
  15645. const _uvA = /*@__PURE__*/new Vector2();
  15646. const _uvB = /*@__PURE__*/new Vector2();
  15647. const _uvC = /*@__PURE__*/new Vector2();
  15648. class Sprite extends Object3D {
  15649. constructor(material) {
  15650. super();
  15651. this.type = 'Sprite';
  15652. if (_geometry === undefined) {
  15653. _geometry = new BufferGeometry();
  15654. 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]);
  15655. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  15656. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  15657. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  15658. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  15659. }
  15660. this.geometry = _geometry;
  15661. this.material = material !== undefined ? material : new SpriteMaterial();
  15662. this.center = new Vector2(0.5, 0.5);
  15663. }
  15664. raycast(raycaster, intersects) {
  15665. if (raycaster.camera === null) {
  15666. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  15667. }
  15668. _worldScale.setFromMatrixScale(this.matrixWorld);
  15669. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  15670. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  15671. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  15672. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  15673. _worldScale.multiplyScalar(-_mvPosition.z);
  15674. }
  15675. const rotation = this.material.rotation;
  15676. let sin, cos;
  15677. if (rotation !== 0) {
  15678. cos = Math.cos(rotation);
  15679. sin = Math.sin(rotation);
  15680. }
  15681. const center = this.center;
  15682. transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15683. transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15684. transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15685. _uvA.set(0, 0);
  15686. _uvB.set(1, 0);
  15687. _uvC.set(1, 1); // check first triangle
  15688. let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
  15689. if (intersect === null) {
  15690. // check second triangle
  15691. transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15692. _uvB.set(0, 1);
  15693. intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
  15694. if (intersect === null) {
  15695. return;
  15696. }
  15697. }
  15698. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  15699. if (distance < raycaster.near || distance > raycaster.far) return;
  15700. intersects.push({
  15701. distance: distance,
  15702. point: _intersectPoint.clone(),
  15703. uv: Triangle.getUV(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()),
  15704. face: null,
  15705. object: this
  15706. });
  15707. }
  15708. copy(source) {
  15709. super.copy(source);
  15710. if (source.center !== undefined) this.center.copy(source.center);
  15711. this.material = source.material;
  15712. return this;
  15713. }
  15714. }
  15715. Sprite.prototype.isSprite = true;
  15716. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  15717. // compute position in camera space
  15718. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  15719. if (sin !== undefined) {
  15720. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  15721. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  15722. } else {
  15723. _rotatedPosition.copy(_alignedPosition);
  15724. }
  15725. vertexPosition.copy(mvPosition);
  15726. vertexPosition.x += _rotatedPosition.x;
  15727. vertexPosition.y += _rotatedPosition.y; // transform to world space
  15728. vertexPosition.applyMatrix4(_viewWorldMatrix);
  15729. }
  15730. const _v1$2 = /*@__PURE__*/new Vector3();
  15731. const _v2$1 = /*@__PURE__*/new Vector3();
  15732. class LOD extends Object3D {
  15733. constructor() {
  15734. super();
  15735. this._currentLevel = 0;
  15736. this.type = 'LOD';
  15737. Object.defineProperties(this, {
  15738. levels: {
  15739. enumerable: true,
  15740. value: []
  15741. },
  15742. isLOD: {
  15743. value: true
  15744. }
  15745. });
  15746. this.autoUpdate = true;
  15747. }
  15748. copy(source) {
  15749. super.copy(source, false);
  15750. const levels = source.levels;
  15751. for (let i = 0, l = levels.length; i < l; i++) {
  15752. const level = levels[i];
  15753. this.addLevel(level.object.clone(), level.distance);
  15754. }
  15755. this.autoUpdate = source.autoUpdate;
  15756. return this;
  15757. }
  15758. addLevel(object, distance = 0) {
  15759. distance = Math.abs(distance);
  15760. const levels = this.levels;
  15761. let l;
  15762. for (l = 0; l < levels.length; l++) {
  15763. if (distance < levels[l].distance) {
  15764. break;
  15765. }
  15766. }
  15767. levels.splice(l, 0, {
  15768. distance: distance,
  15769. object: object
  15770. });
  15771. this.add(object);
  15772. return this;
  15773. }
  15774. getCurrentLevel() {
  15775. return this._currentLevel;
  15776. }
  15777. getObjectForDistance(distance) {
  15778. const levels = this.levels;
  15779. if (levels.length > 0) {
  15780. let i, l;
  15781. for (i = 1, l = levels.length; i < l; i++) {
  15782. if (distance < levels[i].distance) {
  15783. break;
  15784. }
  15785. }
  15786. return levels[i - 1].object;
  15787. }
  15788. return null;
  15789. }
  15790. raycast(raycaster, intersects) {
  15791. const levels = this.levels;
  15792. if (levels.length > 0) {
  15793. _v1$2.setFromMatrixPosition(this.matrixWorld);
  15794. const distance = raycaster.ray.origin.distanceTo(_v1$2);
  15795. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  15796. }
  15797. }
  15798. update(camera) {
  15799. const levels = this.levels;
  15800. if (levels.length > 1) {
  15801. _v1$2.setFromMatrixPosition(camera.matrixWorld);
  15802. _v2$1.setFromMatrixPosition(this.matrixWorld);
  15803. const distance = _v1$2.distanceTo(_v2$1) / camera.zoom;
  15804. levels[0].object.visible = true;
  15805. let i, l;
  15806. for (i = 1, l = levels.length; i < l; i++) {
  15807. if (distance >= levels[i].distance) {
  15808. levels[i - 1].object.visible = false;
  15809. levels[i].object.visible = true;
  15810. } else {
  15811. break;
  15812. }
  15813. }
  15814. this._currentLevel = i - 1;
  15815. for (; i < l; i++) {
  15816. levels[i].object.visible = false;
  15817. }
  15818. }
  15819. }
  15820. toJSON(meta) {
  15821. const data = super.toJSON(meta);
  15822. if (this.autoUpdate === false) data.object.autoUpdate = false;
  15823. data.object.levels = [];
  15824. const levels = this.levels;
  15825. for (let i = 0, l = levels.length; i < l; i++) {
  15826. const level = levels[i];
  15827. data.object.levels.push({
  15828. object: level.object.uuid,
  15829. distance: level.distance
  15830. });
  15831. }
  15832. return data;
  15833. }
  15834. }
  15835. const _basePosition = /*@__PURE__*/new Vector3();
  15836. const _skinIndex = /*@__PURE__*/new Vector4();
  15837. const _skinWeight = /*@__PURE__*/new Vector4();
  15838. const _vector$5 = /*@__PURE__*/new Vector3();
  15839. const _matrix = /*@__PURE__*/new Matrix4();
  15840. class SkinnedMesh extends Mesh {
  15841. constructor(geometry, material) {
  15842. super(geometry, material);
  15843. this.type = 'SkinnedMesh';
  15844. this.bindMode = 'attached';
  15845. this.bindMatrix = new Matrix4();
  15846. this.bindMatrixInverse = new Matrix4();
  15847. }
  15848. copy(source) {
  15849. super.copy(source);
  15850. this.bindMode = source.bindMode;
  15851. this.bindMatrix.copy(source.bindMatrix);
  15852. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  15853. this.skeleton = source.skeleton;
  15854. return this;
  15855. }
  15856. bind(skeleton, bindMatrix) {
  15857. this.skeleton = skeleton;
  15858. if (bindMatrix === undefined) {
  15859. this.updateMatrixWorld(true);
  15860. this.skeleton.calculateInverses();
  15861. bindMatrix = this.matrixWorld;
  15862. }
  15863. this.bindMatrix.copy(bindMatrix);
  15864. this.bindMatrixInverse.copy(bindMatrix).invert();
  15865. }
  15866. pose() {
  15867. this.skeleton.pose();
  15868. }
  15869. normalizeSkinWeights() {
  15870. const vector = new Vector4();
  15871. const skinWeight = this.geometry.attributes.skinWeight;
  15872. for (let i = 0, l = skinWeight.count; i < l; i++) {
  15873. vector.x = skinWeight.getX(i);
  15874. vector.y = skinWeight.getY(i);
  15875. vector.z = skinWeight.getZ(i);
  15876. vector.w = skinWeight.getW(i);
  15877. const scale = 1.0 / vector.manhattanLength();
  15878. if (scale !== Infinity) {
  15879. vector.multiplyScalar(scale);
  15880. } else {
  15881. vector.set(1, 0, 0, 0); // do something reasonable
  15882. }
  15883. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  15884. }
  15885. }
  15886. updateMatrixWorld(force) {
  15887. super.updateMatrixWorld(force);
  15888. if (this.bindMode === 'attached') {
  15889. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  15890. } else if (this.bindMode === 'detached') {
  15891. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  15892. } else {
  15893. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  15894. }
  15895. }
  15896. boneTransform(index, target) {
  15897. const skeleton = this.skeleton;
  15898. const geometry = this.geometry;
  15899. _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  15900. _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  15901. _basePosition.fromBufferAttribute(geometry.attributes.position, index).applyMatrix4(this.bindMatrix);
  15902. target.set(0, 0, 0);
  15903. for (let i = 0; i < 4; i++) {
  15904. const weight = _skinWeight.getComponent(i);
  15905. if (weight !== 0) {
  15906. const boneIndex = _skinIndex.getComponent(i);
  15907. _matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  15908. target.addScaledVector(_vector$5.copy(_basePosition).applyMatrix4(_matrix), weight);
  15909. }
  15910. }
  15911. return target.applyMatrix4(this.bindMatrixInverse);
  15912. }
  15913. }
  15914. SkinnedMesh.prototype.isSkinnedMesh = true;
  15915. class Bone extends Object3D {
  15916. constructor() {
  15917. super();
  15918. this.type = 'Bone';
  15919. }
  15920. }
  15921. Bone.prototype.isBone = true;
  15922. class DataTexture extends Texture {
  15923. constructor(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  15924. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  15925. this.image = {
  15926. data: data || null,
  15927. width: width || 1,
  15928. height: height || 1
  15929. };
  15930. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  15931. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  15932. this.generateMipmaps = false;
  15933. this.flipY = false;
  15934. this.unpackAlignment = 1;
  15935. this.needsUpdate = true;
  15936. }
  15937. }
  15938. DataTexture.prototype.isDataTexture = true;
  15939. const _offsetMatrix = /*@__PURE__*/new Matrix4();
  15940. const _identityMatrix = /*@__PURE__*/new Matrix4();
  15941. class Skeleton {
  15942. constructor(bones = [], boneInverses = []) {
  15943. this.uuid = generateUUID();
  15944. this.bones = bones.slice(0);
  15945. this.boneInverses = boneInverses;
  15946. this.boneMatrices = null;
  15947. this.boneTexture = null;
  15948. this.boneTextureSize = 0;
  15949. this.frame = -1;
  15950. this.init();
  15951. }
  15952. init() {
  15953. const bones = this.bones;
  15954. const boneInverses = this.boneInverses;
  15955. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  15956. if (boneInverses.length === 0) {
  15957. this.calculateInverses();
  15958. } else {
  15959. // handle special case
  15960. if (bones.length !== boneInverses.length) {
  15961. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  15962. this.boneInverses = [];
  15963. for (let i = 0, il = this.bones.length; i < il; i++) {
  15964. this.boneInverses.push(new Matrix4());
  15965. }
  15966. }
  15967. }
  15968. }
  15969. calculateInverses() {
  15970. this.boneInverses.length = 0;
  15971. for (let i = 0, il = this.bones.length; i < il; i++) {
  15972. const inverse = new Matrix4();
  15973. if (this.bones[i]) {
  15974. inverse.copy(this.bones[i].matrixWorld).invert();
  15975. }
  15976. this.boneInverses.push(inverse);
  15977. }
  15978. }
  15979. pose() {
  15980. // recover the bind-time world matrices
  15981. for (let i = 0, il = this.bones.length; i < il; i++) {
  15982. const bone = this.bones[i];
  15983. if (bone) {
  15984. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  15985. }
  15986. } // compute the local matrices, positions, rotations and scales
  15987. for (let i = 0, il = this.bones.length; i < il; i++) {
  15988. const bone = this.bones[i];
  15989. if (bone) {
  15990. if (bone.parent && bone.parent.isBone) {
  15991. bone.matrix.copy(bone.parent.matrixWorld).invert();
  15992. bone.matrix.multiply(bone.matrixWorld);
  15993. } else {
  15994. bone.matrix.copy(bone.matrixWorld);
  15995. }
  15996. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  15997. }
  15998. }
  15999. }
  16000. update() {
  16001. const bones = this.bones;
  16002. const boneInverses = this.boneInverses;
  16003. const boneMatrices = this.boneMatrices;
  16004. const boneTexture = this.boneTexture; // flatten bone matrices to array
  16005. for (let i = 0, il = bones.length; i < il; i++) {
  16006. // compute the offset between the current and the original transform
  16007. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  16008. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  16009. _offsetMatrix.toArray(boneMatrices, i * 16);
  16010. }
  16011. if (boneTexture !== null) {
  16012. boneTexture.needsUpdate = true;
  16013. }
  16014. }
  16015. clone() {
  16016. return new Skeleton(this.bones, this.boneInverses);
  16017. }
  16018. computeBoneTexture() {
  16019. // layout (1 matrix = 4 pixels)
  16020. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  16021. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  16022. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  16023. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  16024. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  16025. let size = Math.sqrt(this.bones.length * 4); // 4 pixels needed for 1 matrix
  16026. size = ceilPowerOfTwo(size);
  16027. size = Math.max(size, 4);
  16028. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  16029. boneMatrices.set(this.boneMatrices); // copy current values
  16030. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  16031. this.boneMatrices = boneMatrices;
  16032. this.boneTexture = boneTexture;
  16033. this.boneTextureSize = size;
  16034. return this;
  16035. }
  16036. getBoneByName(name) {
  16037. for (let i = 0, il = this.bones.length; i < il; i++) {
  16038. const bone = this.bones[i];
  16039. if (bone.name === name) {
  16040. return bone;
  16041. }
  16042. }
  16043. return undefined;
  16044. }
  16045. dispose() {
  16046. if (this.boneTexture !== null) {
  16047. this.boneTexture.dispose();
  16048. this.boneTexture = null;
  16049. }
  16050. }
  16051. fromJSON(json, bones) {
  16052. this.uuid = json.uuid;
  16053. for (let i = 0, l = json.bones.length; i < l; i++) {
  16054. const uuid = json.bones[i];
  16055. let bone = bones[uuid];
  16056. if (bone === undefined) {
  16057. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  16058. bone = new Bone();
  16059. }
  16060. this.bones.push(bone);
  16061. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  16062. }
  16063. this.init();
  16064. return this;
  16065. }
  16066. toJSON() {
  16067. const data = {
  16068. metadata: {
  16069. version: 4.5,
  16070. type: 'Skeleton',
  16071. generator: 'Skeleton.toJSON'
  16072. },
  16073. bones: [],
  16074. boneInverses: []
  16075. };
  16076. data.uuid = this.uuid;
  16077. const bones = this.bones;
  16078. const boneInverses = this.boneInverses;
  16079. for (let i = 0, l = bones.length; i < l; i++) {
  16080. const bone = bones[i];
  16081. data.bones.push(bone.uuid);
  16082. const boneInverse = boneInverses[i];
  16083. data.boneInverses.push(boneInverse.toArray());
  16084. }
  16085. return data;
  16086. }
  16087. }
  16088. const _instanceLocalMatrix = /*@__PURE__*/new Matrix4();
  16089. const _instanceWorldMatrix = /*@__PURE__*/new Matrix4();
  16090. const _instanceIntersects = [];
  16091. const _mesh = /*@__PURE__*/new Mesh();
  16092. class InstancedMesh extends Mesh {
  16093. constructor(geometry, material, count) {
  16094. super(geometry, material);
  16095. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  16096. this.instanceColor = null;
  16097. this.count = count;
  16098. this.frustumCulled = false;
  16099. }
  16100. copy(source) {
  16101. super.copy(source);
  16102. this.instanceMatrix.copy(source.instanceMatrix);
  16103. if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
  16104. this.count = source.count;
  16105. return this;
  16106. }
  16107. getColorAt(index, color) {
  16108. color.fromArray(this.instanceColor.array, index * 3);
  16109. }
  16110. getMatrixAt(index, matrix) {
  16111. matrix.fromArray(this.instanceMatrix.array, index * 16);
  16112. }
  16113. raycast(raycaster, intersects) {
  16114. const matrixWorld = this.matrixWorld;
  16115. const raycastTimes = this.count;
  16116. _mesh.geometry = this.geometry;
  16117. _mesh.material = this.material;
  16118. if (_mesh.material === undefined) return;
  16119. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  16120. // calculate the world matrix for each instance
  16121. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  16122. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  16123. _mesh.matrixWorld = _instanceWorldMatrix;
  16124. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  16125. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  16126. const intersect = _instanceIntersects[i];
  16127. intersect.instanceId = instanceId;
  16128. intersect.object = this;
  16129. intersects.push(intersect);
  16130. }
  16131. _instanceIntersects.length = 0;
  16132. }
  16133. }
  16134. setColorAt(index, color) {
  16135. if (this.instanceColor === null) {
  16136. this.instanceColor = new BufferAttribute(new Float32Array(this.count * 3), 3);
  16137. }
  16138. color.toArray(this.instanceColor.array, index * 3);
  16139. }
  16140. setMatrixAt(index, matrix) {
  16141. matrix.toArray(this.instanceMatrix.array, index * 16);
  16142. }
  16143. updateMorphTargets() {}
  16144. dispose() {
  16145. this.dispatchEvent({
  16146. type: 'dispose'
  16147. });
  16148. }
  16149. }
  16150. InstancedMesh.prototype.isInstancedMesh = true;
  16151. /**
  16152. * parameters = {
  16153. * color: <hex>,
  16154. * opacity: <float>,
  16155. *
  16156. * linewidth: <float>,
  16157. * linecap: "round",
  16158. * linejoin: "round"
  16159. * }
  16160. */
  16161. class LineBasicMaterial extends Material {
  16162. constructor(parameters) {
  16163. super();
  16164. this.type = 'LineBasicMaterial';
  16165. this.color = new Color(0xffffff);
  16166. this.linewidth = 1;
  16167. this.linecap = 'round';
  16168. this.linejoin = 'round';
  16169. this.morphTargets = false;
  16170. this.setValues(parameters);
  16171. }
  16172. copy(source) {
  16173. super.copy(source);
  16174. this.color.copy(source.color);
  16175. this.linewidth = source.linewidth;
  16176. this.linecap = source.linecap;
  16177. this.linejoin = source.linejoin;
  16178. this.morphTargets = source.morphTargets;
  16179. return this;
  16180. }
  16181. }
  16182. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  16183. const _start$1 = /*@__PURE__*/new Vector3();
  16184. const _end$1 = /*@__PURE__*/new Vector3();
  16185. const _inverseMatrix$1 = /*@__PURE__*/new Matrix4();
  16186. const _ray$1 = /*@__PURE__*/new Ray();
  16187. const _sphere$1 = /*@__PURE__*/new Sphere();
  16188. class Line extends Object3D {
  16189. constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) {
  16190. super();
  16191. this.type = 'Line';
  16192. this.geometry = geometry;
  16193. this.material = material;
  16194. this.updateMorphTargets();
  16195. }
  16196. copy(source) {
  16197. super.copy(source);
  16198. this.material = source.material;
  16199. this.geometry = source.geometry;
  16200. return this;
  16201. }
  16202. computeLineDistances() {
  16203. const geometry = this.geometry;
  16204. if (geometry.isBufferGeometry) {
  16205. // we assume non-indexed geometry
  16206. if (geometry.index === null) {
  16207. const positionAttribute = geometry.attributes.position;
  16208. const lineDistances = [0];
  16209. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  16210. _start$1.fromBufferAttribute(positionAttribute, i - 1);
  16211. _end$1.fromBufferAttribute(positionAttribute, i);
  16212. lineDistances[i] = lineDistances[i - 1];
  16213. lineDistances[i] += _start$1.distanceTo(_end$1);
  16214. }
  16215. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16216. } else {
  16217. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16218. }
  16219. } else if (geometry.isGeometry) {
  16220. console.error('THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16221. }
  16222. return this;
  16223. }
  16224. raycast(raycaster, intersects) {
  16225. const geometry = this.geometry;
  16226. const matrixWorld = this.matrixWorld;
  16227. const threshold = raycaster.params.Line.threshold;
  16228. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  16229. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16230. _sphere$1.copy(geometry.boundingSphere);
  16231. _sphere$1.applyMatrix4(matrixWorld);
  16232. _sphere$1.radius += threshold;
  16233. if (raycaster.ray.intersectsSphere(_sphere$1) === false) return; //
  16234. _inverseMatrix$1.copy(matrixWorld).invert();
  16235. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  16236. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16237. const localThresholdSq = localThreshold * localThreshold;
  16238. const vStart = new Vector3();
  16239. const vEnd = new Vector3();
  16240. const interSegment = new Vector3();
  16241. const interRay = new Vector3();
  16242. const step = this.isLineSegments ? 2 : 1;
  16243. if (geometry.isBufferGeometry) {
  16244. const index = geometry.index;
  16245. const attributes = geometry.attributes;
  16246. const positionAttribute = attributes.position;
  16247. if (index !== null) {
  16248. const start = Math.max(0, drawRange.start);
  16249. const end = Math.min(index.count, drawRange.start + drawRange.count);
  16250. for (let i = start, l = end - 1; i < l; i += step) {
  16251. const a = index.getX(i);
  16252. const b = index.getX(i + 1);
  16253. vStart.fromBufferAttribute(positionAttribute, a);
  16254. vEnd.fromBufferAttribute(positionAttribute, b);
  16255. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16256. if (distSq > localThresholdSq) continue;
  16257. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16258. const distance = raycaster.ray.origin.distanceTo(interRay);
  16259. if (distance < raycaster.near || distance > raycaster.far) continue;
  16260. intersects.push({
  16261. distance: distance,
  16262. // What do we want? intersection point on the ray or on the segment??
  16263. // point: raycaster.ray.at( distance ),
  16264. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16265. index: i,
  16266. face: null,
  16267. faceIndex: null,
  16268. object: this
  16269. });
  16270. }
  16271. } else {
  16272. const start = Math.max(0, drawRange.start);
  16273. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  16274. for (let i = start, l = end - 1; i < l; i += step) {
  16275. vStart.fromBufferAttribute(positionAttribute, i);
  16276. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  16277. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16278. if (distSq > localThresholdSq) continue;
  16279. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16280. const distance = raycaster.ray.origin.distanceTo(interRay);
  16281. if (distance < raycaster.near || distance > raycaster.far) continue;
  16282. intersects.push({
  16283. distance: distance,
  16284. // What do we want? intersection point on the ray or on the segment??
  16285. // point: raycaster.ray.at( distance ),
  16286. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16287. index: i,
  16288. face: null,
  16289. faceIndex: null,
  16290. object: this
  16291. });
  16292. }
  16293. }
  16294. } else if (geometry.isGeometry) {
  16295. console.error('THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16296. }
  16297. }
  16298. updateMorphTargets() {
  16299. const geometry = this.geometry;
  16300. if (geometry.isBufferGeometry) {
  16301. const morphAttributes = geometry.morphAttributes;
  16302. const keys = Object.keys(morphAttributes);
  16303. if (keys.length > 0) {
  16304. const morphAttribute = morphAttributes[keys[0]];
  16305. if (morphAttribute !== undefined) {
  16306. this.morphTargetInfluences = [];
  16307. this.morphTargetDictionary = {};
  16308. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  16309. const name = morphAttribute[m].name || String(m);
  16310. this.morphTargetInfluences.push(0);
  16311. this.morphTargetDictionary[name] = m;
  16312. }
  16313. }
  16314. }
  16315. } else {
  16316. const morphTargets = geometry.morphTargets;
  16317. if (morphTargets !== undefined && morphTargets.length > 0) {
  16318. console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  16319. }
  16320. }
  16321. }
  16322. }
  16323. Line.prototype.isLine = true;
  16324. const _start = /*@__PURE__*/new Vector3();
  16325. const _end = /*@__PURE__*/new Vector3();
  16326. class LineSegments extends Line {
  16327. constructor(geometry, material) {
  16328. super(geometry, material);
  16329. this.type = 'LineSegments';
  16330. }
  16331. computeLineDistances() {
  16332. const geometry = this.geometry;
  16333. if (geometry.isBufferGeometry) {
  16334. // we assume non-indexed geometry
  16335. if (geometry.index === null) {
  16336. const positionAttribute = geometry.attributes.position;
  16337. const lineDistances = [];
  16338. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  16339. _start.fromBufferAttribute(positionAttribute, i);
  16340. _end.fromBufferAttribute(positionAttribute, i + 1);
  16341. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  16342. lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end);
  16343. }
  16344. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16345. } else {
  16346. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16347. }
  16348. } else if (geometry.isGeometry) {
  16349. console.error('THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16350. }
  16351. return this;
  16352. }
  16353. }
  16354. LineSegments.prototype.isLineSegments = true;
  16355. class LineLoop extends Line {
  16356. constructor(geometry, material) {
  16357. super(geometry, material);
  16358. this.type = 'LineLoop';
  16359. }
  16360. }
  16361. LineLoop.prototype.isLineLoop = true;
  16362. /**
  16363. * parameters = {
  16364. * color: <hex>,
  16365. * opacity: <float>,
  16366. * map: new THREE.Texture( <Image> ),
  16367. * alphaMap: new THREE.Texture( <Image> ),
  16368. *
  16369. * size: <float>,
  16370. * sizeAttenuation: <bool>
  16371. *
  16372. * morphTargets: <bool>
  16373. * }
  16374. */
  16375. class PointsMaterial extends Material {
  16376. constructor(parameters) {
  16377. super();
  16378. this.type = 'PointsMaterial';
  16379. this.color = new Color(0xffffff);
  16380. this.map = null;
  16381. this.alphaMap = null;
  16382. this.size = 1;
  16383. this.sizeAttenuation = true;
  16384. this.morphTargets = false;
  16385. this.setValues(parameters);
  16386. }
  16387. copy(source) {
  16388. super.copy(source);
  16389. this.color.copy(source.color);
  16390. this.map = source.map;
  16391. this.alphaMap = source.alphaMap;
  16392. this.size = source.size;
  16393. this.sizeAttenuation = source.sizeAttenuation;
  16394. this.morphTargets = source.morphTargets;
  16395. return this;
  16396. }
  16397. }
  16398. PointsMaterial.prototype.isPointsMaterial = true;
  16399. const _inverseMatrix = /*@__PURE__*/new Matrix4();
  16400. const _ray = /*@__PURE__*/new Ray();
  16401. const _sphere = /*@__PURE__*/new Sphere();
  16402. const _position$2 = /*@__PURE__*/new Vector3();
  16403. class Points extends Object3D {
  16404. constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) {
  16405. super();
  16406. this.type = 'Points';
  16407. this.geometry = geometry;
  16408. this.material = material;
  16409. this.updateMorphTargets();
  16410. }
  16411. copy(source) {
  16412. super.copy(source);
  16413. this.material = source.material;
  16414. this.geometry = source.geometry;
  16415. return this;
  16416. }
  16417. raycast(raycaster, intersects) {
  16418. const geometry = this.geometry;
  16419. const matrixWorld = this.matrixWorld;
  16420. const threshold = raycaster.params.Points.threshold;
  16421. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  16422. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16423. _sphere.copy(geometry.boundingSphere);
  16424. _sphere.applyMatrix4(matrixWorld);
  16425. _sphere.radius += threshold;
  16426. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  16427. _inverseMatrix.copy(matrixWorld).invert();
  16428. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);
  16429. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16430. const localThresholdSq = localThreshold * localThreshold;
  16431. if (geometry.isBufferGeometry) {
  16432. const index = geometry.index;
  16433. const attributes = geometry.attributes;
  16434. const positionAttribute = attributes.position;
  16435. if (index !== null) {
  16436. const start = Math.max(0, drawRange.start);
  16437. const end = Math.min(index.count, drawRange.start + drawRange.count);
  16438. for (let i = start, il = end; i < il; i++) {
  16439. const a = index.getX(i);
  16440. _position$2.fromBufferAttribute(positionAttribute, a);
  16441. testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16442. }
  16443. } else {
  16444. const start = Math.max(0, drawRange.start);
  16445. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  16446. for (let i = start, l = end; i < l; i++) {
  16447. _position$2.fromBufferAttribute(positionAttribute, i);
  16448. testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16449. }
  16450. }
  16451. } else {
  16452. console.error('THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16453. }
  16454. }
  16455. updateMorphTargets() {
  16456. const geometry = this.geometry;
  16457. if (geometry.isBufferGeometry) {
  16458. const morphAttributes = geometry.morphAttributes;
  16459. const keys = Object.keys(morphAttributes);
  16460. if (keys.length > 0) {
  16461. const morphAttribute = morphAttributes[keys[0]];
  16462. if (morphAttribute !== undefined) {
  16463. this.morphTargetInfluences = [];
  16464. this.morphTargetDictionary = {};
  16465. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  16466. const name = morphAttribute[m].name || String(m);
  16467. this.morphTargetInfluences.push(0);
  16468. this.morphTargetDictionary[name] = m;
  16469. }
  16470. }
  16471. }
  16472. } else {
  16473. const morphTargets = geometry.morphTargets;
  16474. if (morphTargets !== undefined && morphTargets.length > 0) {
  16475. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  16476. }
  16477. }
  16478. }
  16479. }
  16480. Points.prototype.isPoints = true;
  16481. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  16482. const rayPointDistanceSq = _ray.distanceSqToPoint(point);
  16483. if (rayPointDistanceSq < localThresholdSq) {
  16484. const intersectPoint = new Vector3();
  16485. _ray.closestPointToPoint(point, intersectPoint);
  16486. intersectPoint.applyMatrix4(matrixWorld);
  16487. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  16488. if (distance < raycaster.near || distance > raycaster.far) return;
  16489. intersects.push({
  16490. distance: distance,
  16491. distanceToRay: Math.sqrt(rayPointDistanceSq),
  16492. point: intersectPoint,
  16493. index: index,
  16494. face: null,
  16495. object: object
  16496. });
  16497. }
  16498. }
  16499. class VideoTexture extends Texture {
  16500. constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  16501. super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16502. this.format = format !== undefined ? format : RGBFormat;
  16503. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  16504. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  16505. this.generateMipmaps = false;
  16506. const scope = this;
  16507. function updateVideo() {
  16508. scope.needsUpdate = true;
  16509. video.requestVideoFrameCallback(updateVideo);
  16510. }
  16511. if ('requestVideoFrameCallback' in video) {
  16512. video.requestVideoFrameCallback(updateVideo);
  16513. }
  16514. }
  16515. clone() {
  16516. return new this.constructor(this.image).copy(this);
  16517. }
  16518. update() {
  16519. const video = this.image;
  16520. const hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  16521. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  16522. this.needsUpdate = true;
  16523. }
  16524. }
  16525. }
  16526. VideoTexture.prototype.isVideoTexture = true;
  16527. class CompressedTexture extends Texture {
  16528. constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  16529. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  16530. this.image = {
  16531. width: width,
  16532. height: height
  16533. };
  16534. this.mipmaps = mipmaps; // no flipping for cube textures
  16535. // (also flipping doesn't work for compressed textures )
  16536. this.flipY = false; // can't generate mipmaps for compressed textures
  16537. // mips must be embedded in DDS files
  16538. this.generateMipmaps = false;
  16539. }
  16540. }
  16541. CompressedTexture.prototype.isCompressedTexture = true;
  16542. class CanvasTexture extends Texture {
  16543. constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  16544. super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16545. this.needsUpdate = true;
  16546. }
  16547. }
  16548. CanvasTexture.prototype.isCanvasTexture = true;
  16549. class DepthTexture extends Texture {
  16550. constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  16551. format = format !== undefined ? format : DepthFormat;
  16552. if (format !== DepthFormat && format !== DepthStencilFormat) {
  16553. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  16554. }
  16555. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  16556. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  16557. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16558. this.image = {
  16559. width: width,
  16560. height: height
  16561. };
  16562. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  16563. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  16564. this.flipY = false;
  16565. this.generateMipmaps = false;
  16566. }
  16567. }
  16568. DepthTexture.prototype.isDepthTexture = true;
  16569. class CircleGeometry extends BufferGeometry {
  16570. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  16571. super();
  16572. this.type = 'CircleGeometry';
  16573. this.parameters = {
  16574. radius: radius,
  16575. segments: segments,
  16576. thetaStart: thetaStart,
  16577. thetaLength: thetaLength
  16578. };
  16579. segments = Math.max(3, segments); // buffers
  16580. const indices = [];
  16581. const vertices = [];
  16582. const normals = [];
  16583. const uvs = []; // helper variables
  16584. const vertex = new Vector3();
  16585. const uv = new Vector2(); // center point
  16586. vertices.push(0, 0, 0);
  16587. normals.push(0, 0, 1);
  16588. uvs.push(0.5, 0.5);
  16589. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  16590. const segment = thetaStart + s / segments * thetaLength; // vertex
  16591. vertex.x = radius * Math.cos(segment);
  16592. vertex.y = radius * Math.sin(segment);
  16593. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  16594. normals.push(0, 0, 1); // uvs
  16595. uv.x = (vertices[i] / radius + 1) / 2;
  16596. uv.y = (vertices[i + 1] / radius + 1) / 2;
  16597. uvs.push(uv.x, uv.y);
  16598. } // indices
  16599. for (let i = 1; i <= segments; i++) {
  16600. indices.push(i, i + 1, 0);
  16601. } // build geometry
  16602. this.setIndex(indices);
  16603. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  16604. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  16605. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  16606. }
  16607. }
  16608. class CylinderGeometry extends BufferGeometry {
  16609. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  16610. super();
  16611. this.type = 'CylinderGeometry';
  16612. this.parameters = {
  16613. radiusTop: radiusTop,
  16614. radiusBottom: radiusBottom,
  16615. height: height,
  16616. radialSegments: radialSegments,
  16617. heightSegments: heightSegments,
  16618. openEnded: openEnded,
  16619. thetaStart: thetaStart,
  16620. thetaLength: thetaLength
  16621. };
  16622. const scope = this;
  16623. radialSegments = Math.floor(radialSegments);
  16624. heightSegments = Math.floor(heightSegments); // buffers
  16625. const indices = [];
  16626. const vertices = [];
  16627. const normals = [];
  16628. const uvs = []; // helper variables
  16629. let index = 0;
  16630. const indexArray = [];
  16631. const halfHeight = height / 2;
  16632. let groupStart = 0; // generate geometry
  16633. generateTorso();
  16634. if (openEnded === false) {
  16635. if (radiusTop > 0) generateCap(true);
  16636. if (radiusBottom > 0) generateCap(false);
  16637. } // build geometry
  16638. this.setIndex(indices);
  16639. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  16640. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  16641. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  16642. function generateTorso() {
  16643. const normal = new Vector3();
  16644. const vertex = new Vector3();
  16645. let groupCount = 0; // this will be used to calculate the normal
  16646. const slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  16647. for (let y = 0; y <= heightSegments; y++) {
  16648. const indexRow = [];
  16649. const v = y / heightSegments; // calculate the radius of the current row
  16650. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  16651. for (let x = 0; x <= radialSegments; x++) {
  16652. const u = x / radialSegments;
  16653. const theta = u * thetaLength + thetaStart;
  16654. const sinTheta = Math.sin(theta);
  16655. const cosTheta = Math.cos(theta); // vertex
  16656. vertex.x = radius * sinTheta;
  16657. vertex.y = -v * height + halfHeight;
  16658. vertex.z = radius * cosTheta;
  16659. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  16660. normal.set(sinTheta, slope, cosTheta).normalize();
  16661. normals.push(normal.x, normal.y, normal.z); // uv
  16662. uvs.push(u, 1 - v); // save index of vertex in respective row
  16663. indexRow.push(index++);
  16664. } // now save vertices of the row in our index array
  16665. indexArray.push(indexRow);
  16666. } // generate indices
  16667. for (let x = 0; x < radialSegments; x++) {
  16668. for (let y = 0; y < heightSegments; y++) {
  16669. // we use the index array to access the correct indices
  16670. const a = indexArray[y][x];
  16671. const b = indexArray[y + 1][x];
  16672. const c = indexArray[y + 1][x + 1];
  16673. const d = indexArray[y][x + 1]; // faces
  16674. indices.push(a, b, d);
  16675. indices.push(b, c, d); // update group counter
  16676. groupCount += 6;
  16677. }
  16678. } // add a group to the geometry. this will ensure multi material support
  16679. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  16680. groupStart += groupCount;
  16681. }
  16682. function generateCap(top) {
  16683. // save the index of the first center vertex
  16684. const centerIndexStart = index;
  16685. const uv = new Vector2();
  16686. const vertex = new Vector3();
  16687. let groupCount = 0;
  16688. const radius = top === true ? radiusTop : radiusBottom;
  16689. const sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  16690. // because the geometry needs one set of uvs per face,
  16691. // we must generate a center vertex per face/segment
  16692. for (let x = 1; x <= radialSegments; x++) {
  16693. // vertex
  16694. vertices.push(0, halfHeight * sign, 0); // normal
  16695. normals.push(0, sign, 0); // uv
  16696. uvs.push(0.5, 0.5); // increase index
  16697. index++;
  16698. } // save the index of the last center vertex
  16699. const centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  16700. for (let x = 0; x <= radialSegments; x++) {
  16701. const u = x / radialSegments;
  16702. const theta = u * thetaLength + thetaStart;
  16703. const cosTheta = Math.cos(theta);
  16704. const sinTheta = Math.sin(theta); // vertex
  16705. vertex.x = radius * sinTheta;
  16706. vertex.y = halfHeight * sign;
  16707. vertex.z = radius * cosTheta;
  16708. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  16709. normals.push(0, sign, 0); // uv
  16710. uv.x = cosTheta * 0.5 + 0.5;
  16711. uv.y = sinTheta * 0.5 * sign + 0.5;
  16712. uvs.push(uv.x, uv.y); // increase index
  16713. index++;
  16714. } // generate indices
  16715. for (let x = 0; x < radialSegments; x++) {
  16716. const c = centerIndexStart + x;
  16717. const i = centerIndexEnd + x;
  16718. if (top === true) {
  16719. // face top
  16720. indices.push(i, i + 1, c);
  16721. } else {
  16722. // face bottom
  16723. indices.push(i + 1, i, c);
  16724. }
  16725. groupCount += 3;
  16726. } // add a group to the geometry. this will ensure multi material support
  16727. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  16728. groupStart += groupCount;
  16729. }
  16730. }
  16731. }
  16732. class ConeGeometry extends CylinderGeometry {
  16733. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  16734. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  16735. this.type = 'ConeGeometry';
  16736. this.parameters = {
  16737. radius: radius,
  16738. height: height,
  16739. radialSegments: radialSegments,
  16740. heightSegments: heightSegments,
  16741. openEnded: openEnded,
  16742. thetaStart: thetaStart,
  16743. thetaLength: thetaLength
  16744. };
  16745. }
  16746. }
  16747. class PolyhedronGeometry extends BufferGeometry {
  16748. constructor(vertices, indices, radius = 1, detail = 0) {
  16749. super();
  16750. this.type = 'PolyhedronGeometry';
  16751. this.parameters = {
  16752. vertices: vertices,
  16753. indices: indices,
  16754. radius: radius,
  16755. detail: detail
  16756. }; // default buffer data
  16757. const vertexBuffer = [];
  16758. const uvBuffer = []; // the subdivision creates the vertex buffer data
  16759. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  16760. applyRadius(radius); // finally, create the uv data
  16761. generateUVs(); // build non-indexed geometry
  16762. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  16763. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  16764. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  16765. if (detail === 0) {
  16766. this.computeVertexNormals(); // flat normals
  16767. } else {
  16768. this.normalizeNormals(); // smooth normals
  16769. } // helper functions
  16770. function subdivide(detail) {
  16771. const a = new Vector3();
  16772. const b = new Vector3();
  16773. const c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  16774. for (let i = 0; i < indices.length; i += 3) {
  16775. // get the vertices of the face
  16776. getVertexByIndex(indices[i + 0], a);
  16777. getVertexByIndex(indices[i + 1], b);
  16778. getVertexByIndex(indices[i + 2], c); // perform subdivision
  16779. subdivideFace(a, b, c, detail);
  16780. }
  16781. }
  16782. function subdivideFace(a, b, c, detail) {
  16783. const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  16784. const v = []; // construct all of the vertices for this subdivision
  16785. for (let i = 0; i <= cols; i++) {
  16786. v[i] = [];
  16787. const aj = a.clone().lerp(c, i / cols);
  16788. const bj = b.clone().lerp(c, i / cols);
  16789. const rows = cols - i;
  16790. for (let j = 0; j <= rows; j++) {
  16791. if (j === 0 && i === cols) {
  16792. v[i][j] = aj;
  16793. } else {
  16794. v[i][j] = aj.clone().lerp(bj, j / rows);
  16795. }
  16796. }
  16797. } // construct all of the faces
  16798. for (let i = 0; i < cols; i++) {
  16799. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  16800. const k = Math.floor(j / 2);
  16801. if (j % 2 === 0) {
  16802. pushVertex(v[i][k + 1]);
  16803. pushVertex(v[i + 1][k]);
  16804. pushVertex(v[i][k]);
  16805. } else {
  16806. pushVertex(v[i][k + 1]);
  16807. pushVertex(v[i + 1][k + 1]);
  16808. pushVertex(v[i + 1][k]);
  16809. }
  16810. }
  16811. }
  16812. }
  16813. function applyRadius(radius) {
  16814. const vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  16815. for (let i = 0; i < vertexBuffer.length; i += 3) {
  16816. vertex.x = vertexBuffer[i + 0];
  16817. vertex.y = vertexBuffer[i + 1];
  16818. vertex.z = vertexBuffer[i + 2];
  16819. vertex.normalize().multiplyScalar(radius);
  16820. vertexBuffer[i + 0] = vertex.x;
  16821. vertexBuffer[i + 1] = vertex.y;
  16822. vertexBuffer[i + 2] = vertex.z;
  16823. }
  16824. }
  16825. function generateUVs() {
  16826. const vertex = new Vector3();
  16827. for (let i = 0; i < vertexBuffer.length; i += 3) {
  16828. vertex.x = vertexBuffer[i + 0];
  16829. vertex.y = vertexBuffer[i + 1];
  16830. vertex.z = vertexBuffer[i + 2];
  16831. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  16832. const v = inclination(vertex) / Math.PI + 0.5;
  16833. uvBuffer.push(u, 1 - v);
  16834. }
  16835. correctUVs();
  16836. correctSeam();
  16837. }
  16838. function correctSeam() {
  16839. // handle case when face straddles the seam, see #3269
  16840. for (let i = 0; i < uvBuffer.length; i += 6) {
  16841. // uv data of a single face
  16842. const x0 = uvBuffer[i + 0];
  16843. const x1 = uvBuffer[i + 2];
  16844. const x2 = uvBuffer[i + 4];
  16845. const max = Math.max(x0, x1, x2);
  16846. const min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  16847. if (max > 0.9 && min < 0.1) {
  16848. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  16849. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  16850. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  16851. }
  16852. }
  16853. }
  16854. function pushVertex(vertex) {
  16855. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  16856. }
  16857. function getVertexByIndex(index, vertex) {
  16858. const stride = index * 3;
  16859. vertex.x = vertices[stride + 0];
  16860. vertex.y = vertices[stride + 1];
  16861. vertex.z = vertices[stride + 2];
  16862. }
  16863. function correctUVs() {
  16864. const a = new Vector3();
  16865. const b = new Vector3();
  16866. const c = new Vector3();
  16867. const centroid = new Vector3();
  16868. const uvA = new Vector2();
  16869. const uvB = new Vector2();
  16870. const uvC = new Vector2();
  16871. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  16872. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  16873. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  16874. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  16875. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  16876. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  16877. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  16878. centroid.copy(a).add(b).add(c).divideScalar(3);
  16879. const azi = azimuth(centroid);
  16880. correctUV(uvA, j + 0, a, azi);
  16881. correctUV(uvB, j + 2, b, azi);
  16882. correctUV(uvC, j + 4, c, azi);
  16883. }
  16884. }
  16885. function correctUV(uv, stride, vector, azimuth) {
  16886. if (azimuth < 0 && uv.x === 1) {
  16887. uvBuffer[stride] = uv.x - 1;
  16888. }
  16889. if (vector.x === 0 && vector.z === 0) {
  16890. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  16891. }
  16892. } // Angle around the Y axis, counter-clockwise when looking from above.
  16893. function azimuth(vector) {
  16894. return Math.atan2(vector.z, -vector.x);
  16895. } // Angle above the XZ plane.
  16896. function inclination(vector) {
  16897. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  16898. }
  16899. }
  16900. }
  16901. class DodecahedronGeometry extends PolyhedronGeometry {
  16902. constructor(radius = 1, detail = 0) {
  16903. const t = (1 + Math.sqrt(5)) / 2;
  16904. const r = 1 / t;
  16905. const vertices = [// (±1, ±1, ±1)
  16906. -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/φ, ±φ)
  16907. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  16908. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  16909. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  16910. 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];
  16911. super(vertices, indices, radius, detail);
  16912. this.type = 'DodecahedronGeometry';
  16913. this.parameters = {
  16914. radius: radius,
  16915. detail: detail
  16916. };
  16917. }
  16918. }
  16919. const _v0 = new Vector3();
  16920. const _v1$1 = new Vector3();
  16921. const _normal = new Vector3();
  16922. const _triangle = new Triangle();
  16923. class EdgesGeometry extends BufferGeometry {
  16924. constructor(geometry, thresholdAngle) {
  16925. super();
  16926. this.type = 'EdgesGeometry';
  16927. this.parameters = {
  16928. thresholdAngle: thresholdAngle
  16929. };
  16930. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1;
  16931. if (geometry.isGeometry === true) {
  16932. console.error('THREE.EdgesGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16933. return;
  16934. }
  16935. const precisionPoints = 4;
  16936. const precision = Math.pow(10, precisionPoints);
  16937. const thresholdDot = Math.cos(DEG2RAD * thresholdAngle);
  16938. const indexAttr = geometry.getIndex();
  16939. const positionAttr = geometry.getAttribute('position');
  16940. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  16941. const indexArr = [0, 0, 0];
  16942. const vertKeys = ['a', 'b', 'c'];
  16943. const hashes = new Array(3);
  16944. const edgeData = {};
  16945. const vertices = [];
  16946. for (let i = 0; i < indexCount; i += 3) {
  16947. if (indexAttr) {
  16948. indexArr[0] = indexAttr.getX(i);
  16949. indexArr[1] = indexAttr.getX(i + 1);
  16950. indexArr[2] = indexAttr.getX(i + 2);
  16951. } else {
  16952. indexArr[0] = i;
  16953. indexArr[1] = i + 1;
  16954. indexArr[2] = i + 2;
  16955. }
  16956. const {
  16957. a,
  16958. b,
  16959. c
  16960. } = _triangle;
  16961. a.fromBufferAttribute(positionAttr, indexArr[0]);
  16962. b.fromBufferAttribute(positionAttr, indexArr[1]);
  16963. c.fromBufferAttribute(positionAttr, indexArr[2]);
  16964. _triangle.getNormal(_normal); // create hashes for the edge from the vertices
  16965. hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`;
  16966. hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`;
  16967. hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; // skip degenerate triangles
  16968. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  16969. continue;
  16970. } // iterate over every edge
  16971. for (let j = 0; j < 3; j++) {
  16972. // get the first and next vertex making up the edge
  16973. const jNext = (j + 1) % 3;
  16974. const vecHash0 = hashes[j];
  16975. const vecHash1 = hashes[jNext];
  16976. const v0 = _triangle[vertKeys[j]];
  16977. const v1 = _triangle[vertKeys[jNext]];
  16978. const hash = `${vecHash0}_${vecHash1}`;
  16979. const reverseHash = `${vecHash1}_${vecHash0}`;
  16980. if (reverseHash in edgeData && edgeData[reverseHash]) {
  16981. // if we found a sibling edge add it into the vertex array if
  16982. // it meets the angle threshold and delete the edge from the map.
  16983. if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  16984. vertices.push(v0.x, v0.y, v0.z);
  16985. vertices.push(v1.x, v1.y, v1.z);
  16986. }
  16987. edgeData[reverseHash] = null;
  16988. } else if (!(hash in edgeData)) {
  16989. // if we've already got an edge here then skip adding a new one
  16990. edgeData[hash] = {
  16991. index0: indexArr[j],
  16992. index1: indexArr[jNext],
  16993. normal: _normal.clone()
  16994. };
  16995. }
  16996. }
  16997. } // iterate over all remaining, unmatched edges and add them to the vertex array
  16998. for (const key in edgeData) {
  16999. if (edgeData[key]) {
  17000. const {
  17001. index0,
  17002. index1
  17003. } = edgeData[key];
  17004. _v0.fromBufferAttribute(positionAttr, index0);
  17005. _v1$1.fromBufferAttribute(positionAttr, index1);
  17006. vertices.push(_v0.x, _v0.y, _v0.z);
  17007. vertices.push(_v1$1.x, _v1$1.y, _v1$1.z);
  17008. }
  17009. }
  17010. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17011. }
  17012. }
  17013. /**
  17014. * Port from https://github.com/mapbox/earcut (v2.2.2)
  17015. */
  17016. const Earcut = {
  17017. triangulate: function (data, holeIndices, dim) {
  17018. dim = dim || 2;
  17019. const hasHoles = holeIndices && holeIndices.length;
  17020. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  17021. let outerNode = linkedList(data, 0, outerLen, dim, true);
  17022. const triangles = [];
  17023. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  17024. let minX, minY, maxX, maxY, x, y, invSize;
  17025. 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
  17026. if (data.length > 80 * dim) {
  17027. minX = maxX = data[0];
  17028. minY = maxY = data[1];
  17029. for (let i = dim; i < outerLen; i += dim) {
  17030. x = data[i];
  17031. y = data[i + 1];
  17032. if (x < minX) minX = x;
  17033. if (y < minY) minY = y;
  17034. if (x > maxX) maxX = x;
  17035. if (y > maxY) maxY = y;
  17036. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  17037. invSize = Math.max(maxX - minX, maxY - minY);
  17038. invSize = invSize !== 0 ? 1 / invSize : 0;
  17039. }
  17040. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  17041. return triangles;
  17042. }
  17043. }; // create a circular doubly linked list from polygon points in the specified winding order
  17044. function linkedList(data, start, end, dim, clockwise) {
  17045. let i, last;
  17046. if (clockwise === signedArea(data, start, end, dim) > 0) {
  17047. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  17048. } else {
  17049. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  17050. }
  17051. if (last && equals(last, last.next)) {
  17052. removeNode(last);
  17053. last = last.next;
  17054. }
  17055. return last;
  17056. } // eliminate colinear or duplicate points
  17057. function filterPoints(start, end) {
  17058. if (!start) return start;
  17059. if (!end) end = start;
  17060. let p = start,
  17061. again;
  17062. do {
  17063. again = false;
  17064. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  17065. removeNode(p);
  17066. p = end = p.prev;
  17067. if (p === p.next) break;
  17068. again = true;
  17069. } else {
  17070. p = p.next;
  17071. }
  17072. } while (again || p !== end);
  17073. return end;
  17074. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  17075. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  17076. if (!ear) return; // interlink polygon nodes in z-order
  17077. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  17078. let stop = ear,
  17079. prev,
  17080. next; // iterate through ears, slicing them one by one
  17081. while (ear.prev !== ear.next) {
  17082. prev = ear.prev;
  17083. next = ear.next;
  17084. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  17085. // cut off the triangle
  17086. triangles.push(prev.i / dim);
  17087. triangles.push(ear.i / dim);
  17088. triangles.push(next.i / dim);
  17089. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  17090. ear = next.next;
  17091. stop = next.next;
  17092. continue;
  17093. }
  17094. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  17095. if (ear === stop) {
  17096. // try filtering points and slicing again
  17097. if (!pass) {
  17098. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  17099. } else if (pass === 1) {
  17100. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  17101. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  17102. } else if (pass === 2) {
  17103. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  17104. }
  17105. break;
  17106. }
  17107. }
  17108. } // check whether a polygon node forms a valid ear with adjacent nodes
  17109. function isEar(ear) {
  17110. const a = ear.prev,
  17111. b = ear,
  17112. c = ear.next;
  17113. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  17114. // now make sure we don't have other points inside the potential ear
  17115. let p = ear.next.next;
  17116. while (p !== ear.prev) {
  17117. 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;
  17118. p = p.next;
  17119. }
  17120. return true;
  17121. }
  17122. function isEarHashed(ear, minX, minY, invSize) {
  17123. const a = ear.prev,
  17124. b = ear,
  17125. c = ear.next;
  17126. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  17127. // triangle bbox; min & max are calculated like this for speed
  17128. const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  17129. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  17130. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  17131. 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;
  17132. const minZ = zOrder(minTX, minTY, minX, minY, invSize),
  17133. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  17134. let p = ear.prevZ,
  17135. n = ear.nextZ; // look for points inside the triangle in both directions
  17136. while (p && p.z >= minZ && n && n.z <= maxZ) {
  17137. 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;
  17138. p = p.prevZ;
  17139. 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;
  17140. n = n.nextZ;
  17141. } // look for remaining points in decreasing z-order
  17142. while (p && p.z >= minZ) {
  17143. 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;
  17144. p = p.prevZ;
  17145. } // look for remaining points in increasing z-order
  17146. while (n && n.z <= maxZ) {
  17147. 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;
  17148. n = n.nextZ;
  17149. }
  17150. return true;
  17151. } // go through all polygon nodes and cure small local self-intersections
  17152. function cureLocalIntersections(start, triangles, dim) {
  17153. let p = start;
  17154. do {
  17155. const a = p.prev,
  17156. b = p.next.next;
  17157. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  17158. triangles.push(a.i / dim);
  17159. triangles.push(p.i / dim);
  17160. triangles.push(b.i / dim); // remove two nodes involved
  17161. removeNode(p);
  17162. removeNode(p.next);
  17163. p = start = b;
  17164. }
  17165. p = p.next;
  17166. } while (p !== start);
  17167. return filterPoints(p);
  17168. } // try splitting polygon into two and triangulate them independently
  17169. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  17170. // look for a valid diagonal that divides the polygon into two
  17171. let a = start;
  17172. do {
  17173. let b = a.next.next;
  17174. while (b !== a.prev) {
  17175. if (a.i !== b.i && isValidDiagonal(a, b)) {
  17176. // split the polygon in two by the diagonal
  17177. let c = splitPolygon(a, b); // filter colinear points around the cuts
  17178. a = filterPoints(a, a.next);
  17179. c = filterPoints(c, c.next); // run earcut on each half
  17180. earcutLinked(a, triangles, dim, minX, minY, invSize);
  17181. earcutLinked(c, triangles, dim, minX, minY, invSize);
  17182. return;
  17183. }
  17184. b = b.next;
  17185. }
  17186. a = a.next;
  17187. } while (a !== start);
  17188. } // link every hole into the outer loop, producing a single-ring polygon without holes
  17189. function eliminateHoles(data, holeIndices, outerNode, dim) {
  17190. const queue = [];
  17191. let i, len, start, end, list;
  17192. for (i = 0, len = holeIndices.length; i < len; i++) {
  17193. start = holeIndices[i] * dim;
  17194. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  17195. list = linkedList(data, start, end, dim, false);
  17196. if (list === list.next) list.steiner = true;
  17197. queue.push(getLeftmost(list));
  17198. }
  17199. queue.sort(compareX); // process holes from left to right
  17200. for (i = 0; i < queue.length; i++) {
  17201. eliminateHole(queue[i], outerNode);
  17202. outerNode = filterPoints(outerNode, outerNode.next);
  17203. }
  17204. return outerNode;
  17205. }
  17206. function compareX(a, b) {
  17207. return a.x - b.x;
  17208. } // find a bridge between vertices that connects hole with an outer ring and and link it
  17209. function eliminateHole(hole, outerNode) {
  17210. outerNode = findHoleBridge(hole, outerNode);
  17211. if (outerNode) {
  17212. const b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  17213. filterPoints(outerNode, outerNode.next);
  17214. filterPoints(b, b.next);
  17215. }
  17216. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  17217. function findHoleBridge(hole, outerNode) {
  17218. let p = outerNode;
  17219. const hx = hole.x;
  17220. const hy = hole.y;
  17221. let qx = -Infinity,
  17222. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  17223. // segment's endpoint with lesser x will be potential connection point
  17224. do {
  17225. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  17226. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  17227. if (x <= hx && x > qx) {
  17228. qx = x;
  17229. if (x === hx) {
  17230. if (hy === p.y) return p;
  17231. if (hy === p.next.y) return p.next;
  17232. }
  17233. m = p.x < p.next.x ? p : p.next;
  17234. }
  17235. }
  17236. p = p.next;
  17237. } while (p !== outerNode);
  17238. if (!m) return null;
  17239. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  17240. // look for points inside the triangle of hole point, segment intersection and endpoint;
  17241. // if there are no points found, we have a valid connection;
  17242. // otherwise choose the point of the minimum angle with the ray as connection point
  17243. const stop = m,
  17244. mx = m.x,
  17245. my = m.y;
  17246. let tanMin = Infinity,
  17247. tan;
  17248. p = m;
  17249. do {
  17250. 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)) {
  17251. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  17252. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  17253. m = p;
  17254. tanMin = tan;
  17255. }
  17256. }
  17257. p = p.next;
  17258. } while (p !== stop);
  17259. return m;
  17260. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  17261. function sectorContainsSector(m, p) {
  17262. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  17263. } // interlink polygon nodes in z-order
  17264. function indexCurve(start, minX, minY, invSize) {
  17265. let p = start;
  17266. do {
  17267. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  17268. p.prevZ = p.prev;
  17269. p.nextZ = p.next;
  17270. p = p.next;
  17271. } while (p !== start);
  17272. p.prevZ.nextZ = null;
  17273. p.prevZ = null;
  17274. sortLinked(p);
  17275. } // Simon Tatham's linked list merge sort algorithm
  17276. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  17277. function sortLinked(list) {
  17278. let i,
  17279. p,
  17280. q,
  17281. e,
  17282. tail,
  17283. numMerges,
  17284. pSize,
  17285. qSize,
  17286. inSize = 1;
  17287. do {
  17288. p = list;
  17289. list = null;
  17290. tail = null;
  17291. numMerges = 0;
  17292. while (p) {
  17293. numMerges++;
  17294. q = p;
  17295. pSize = 0;
  17296. for (i = 0; i < inSize; i++) {
  17297. pSize++;
  17298. q = q.nextZ;
  17299. if (!q) break;
  17300. }
  17301. qSize = inSize;
  17302. while (pSize > 0 || qSize > 0 && q) {
  17303. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  17304. e = p;
  17305. p = p.nextZ;
  17306. pSize--;
  17307. } else {
  17308. e = q;
  17309. q = q.nextZ;
  17310. qSize--;
  17311. }
  17312. if (tail) tail.nextZ = e;else list = e;
  17313. e.prevZ = tail;
  17314. tail = e;
  17315. }
  17316. p = q;
  17317. }
  17318. tail.nextZ = null;
  17319. inSize *= 2;
  17320. } while (numMerges > 1);
  17321. return list;
  17322. } // z-order of a point given coords and inverse of the longer side of data bbox
  17323. function zOrder(x, y, minX, minY, invSize) {
  17324. // coords are transformed into non-negative 15-bit integer range
  17325. x = 32767 * (x - minX) * invSize;
  17326. y = 32767 * (y - minY) * invSize;
  17327. x = (x | x << 8) & 0x00FF00FF;
  17328. x = (x | x << 4) & 0x0F0F0F0F;
  17329. x = (x | x << 2) & 0x33333333;
  17330. x = (x | x << 1) & 0x55555555;
  17331. y = (y | y << 8) & 0x00FF00FF;
  17332. y = (y | y << 4) & 0x0F0F0F0F;
  17333. y = (y | y << 2) & 0x33333333;
  17334. y = (y | y << 1) & 0x55555555;
  17335. return x | y << 1;
  17336. } // find the leftmost node of a polygon ring
  17337. function getLeftmost(start) {
  17338. let p = start,
  17339. leftmost = start;
  17340. do {
  17341. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  17342. p = p.next;
  17343. } while (p !== start);
  17344. return leftmost;
  17345. } // check if a point lies within a convex triangle
  17346. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  17347. 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;
  17348. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  17349. function isValidDiagonal(a, b) {
  17350. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( // dones't intersect other edges
  17351. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && ( // locally visible
  17352. area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  17353. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  17354. } // signed area of a triangle
  17355. function area(p, q, r) {
  17356. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  17357. } // check if two points are equal
  17358. function equals(p1, p2) {
  17359. return p1.x === p2.x && p1.y === p2.y;
  17360. } // check if two segments intersect
  17361. function intersects(p1, q1, p2, q2) {
  17362. const o1 = sign(area(p1, q1, p2));
  17363. const o2 = sign(area(p1, q1, q2));
  17364. const o3 = sign(area(p2, q2, p1));
  17365. const o4 = sign(area(p2, q2, q1));
  17366. if (o1 !== o2 && o3 !== o4) return true; // general case
  17367. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  17368. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  17369. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  17370. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  17371. return false;
  17372. } // for collinear points p, q, r, check if point q lies on segment pr
  17373. function onSegment(p, q, r) {
  17374. 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);
  17375. }
  17376. function sign(num) {
  17377. return num > 0 ? 1 : num < 0 ? -1 : 0;
  17378. } // check if a polygon diagonal intersects any polygon segments
  17379. function intersectsPolygon(a, b) {
  17380. let p = a;
  17381. do {
  17382. 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;
  17383. p = p.next;
  17384. } while (p !== a);
  17385. return false;
  17386. } // check if a polygon diagonal is locally inside the polygon
  17387. function locallyInside(a, b) {
  17388. 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;
  17389. } // check if the middle point of a polygon diagonal is inside the polygon
  17390. function middleInside(a, b) {
  17391. let p = a,
  17392. inside = false;
  17393. const px = (a.x + b.x) / 2,
  17394. py = (a.y + b.y) / 2;
  17395. do {
  17396. 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;
  17397. p = p.next;
  17398. } while (p !== a);
  17399. return inside;
  17400. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  17401. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  17402. function splitPolygon(a, b) {
  17403. const a2 = new Node(a.i, a.x, a.y),
  17404. b2 = new Node(b.i, b.x, b.y),
  17405. an = a.next,
  17406. bp = b.prev;
  17407. a.next = b;
  17408. b.prev = a;
  17409. a2.next = an;
  17410. an.prev = a2;
  17411. b2.next = a2;
  17412. a2.prev = b2;
  17413. bp.next = b2;
  17414. b2.prev = bp;
  17415. return b2;
  17416. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  17417. function insertNode(i, x, y, last) {
  17418. const p = new Node(i, x, y);
  17419. if (!last) {
  17420. p.prev = p;
  17421. p.next = p;
  17422. } else {
  17423. p.next = last.next;
  17424. p.prev = last;
  17425. last.next.prev = p;
  17426. last.next = p;
  17427. }
  17428. return p;
  17429. }
  17430. function removeNode(p) {
  17431. p.next.prev = p.prev;
  17432. p.prev.next = p.next;
  17433. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  17434. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  17435. }
  17436. function Node(i, x, y) {
  17437. // vertex index in coordinates array
  17438. this.i = i; // vertex coordinates
  17439. this.x = x;
  17440. this.y = y; // previous and next vertex nodes in a polygon ring
  17441. this.prev = null;
  17442. this.next = null; // z-order curve value
  17443. this.z = null; // previous and next nodes in z-order
  17444. this.prevZ = null;
  17445. this.nextZ = null; // indicates whether this is a steiner point
  17446. this.steiner = false;
  17447. }
  17448. function signedArea(data, start, end, dim) {
  17449. let sum = 0;
  17450. for (let i = start, j = end - dim; i < end; i += dim) {
  17451. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  17452. j = i;
  17453. }
  17454. return sum;
  17455. }
  17456. class ShapeUtils {
  17457. // calculate area of the contour polygon
  17458. static area(contour) {
  17459. const n = contour.length;
  17460. let a = 0.0;
  17461. for (let p = n - 1, q = 0; q < n; p = q++) {
  17462. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  17463. }
  17464. return a * 0.5;
  17465. }
  17466. static isClockWise(pts) {
  17467. return ShapeUtils.area(pts) < 0;
  17468. }
  17469. static triangulateShape(contour, holes) {
  17470. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  17471. const holeIndices = []; // array of hole indices
  17472. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  17473. removeDupEndPts(contour);
  17474. addContour(vertices, contour); //
  17475. let holeIndex = contour.length;
  17476. holes.forEach(removeDupEndPts);
  17477. for (let i = 0; i < holes.length; i++) {
  17478. holeIndices.push(holeIndex);
  17479. holeIndex += holes[i].length;
  17480. addContour(vertices, holes[i]);
  17481. } //
  17482. const triangles = Earcut.triangulate(vertices, holeIndices); //
  17483. for (let i = 0; i < triangles.length; i += 3) {
  17484. faces.push(triangles.slice(i, i + 3));
  17485. }
  17486. return faces;
  17487. }
  17488. }
  17489. function removeDupEndPts(points) {
  17490. const l = points.length;
  17491. if (l > 2 && points[l - 1].equals(points[0])) {
  17492. points.pop();
  17493. }
  17494. }
  17495. function addContour(vertices, contour) {
  17496. for (let i = 0; i < contour.length; i++) {
  17497. vertices.push(contour[i].x);
  17498. vertices.push(contour[i].y);
  17499. }
  17500. }
  17501. /**
  17502. * Creates extruded geometry from a path shape.
  17503. *
  17504. * parameters = {
  17505. *
  17506. * curveSegments: <int>, // number of points on the curves
  17507. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  17508. * depth: <float>, // Depth to extrude the shape
  17509. *
  17510. * bevelEnabled: <bool>, // turn on bevel
  17511. * bevelThickness: <float>, // how deep into the original shape bevel goes
  17512. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  17513. * bevelOffset: <float>, // how far from shape outline does bevel start
  17514. * bevelSegments: <int>, // number of bevel layers
  17515. *
  17516. * extrudePath: <THREE.Curve> // curve to extrude shape along
  17517. *
  17518. * UVGenerator: <Object> // object that provides UV generator functions
  17519. *
  17520. * }
  17521. */
  17522. class ExtrudeGeometry extends BufferGeometry {
  17523. constructor(shapes, options) {
  17524. super();
  17525. this.type = 'ExtrudeGeometry';
  17526. this.parameters = {
  17527. shapes: shapes,
  17528. options: options
  17529. };
  17530. shapes = Array.isArray(shapes) ? shapes : [shapes];
  17531. const scope = this;
  17532. const verticesArray = [];
  17533. const uvArray = [];
  17534. for (let i = 0, l = shapes.length; i < l; i++) {
  17535. const shape = shapes[i];
  17536. addShape(shape);
  17537. } // build geometry
  17538. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  17539. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  17540. this.computeVertexNormals(); // functions
  17541. function addShape(shape) {
  17542. const placeholder = []; // options
  17543. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  17544. const steps = options.steps !== undefined ? options.steps : 1;
  17545. let depth = options.depth !== undefined ? options.depth : 100;
  17546. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  17547. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  17548. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  17549. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  17550. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  17551. const extrudePath = options.extrudePath;
  17552. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  17553. if (options.amount !== undefined) {
  17554. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  17555. depth = options.amount;
  17556. } //
  17557. let extrudePts,
  17558. extrudeByPath = false;
  17559. let splineTube, binormal, normal, position2;
  17560. if (extrudePath) {
  17561. extrudePts = extrudePath.getSpacedPoints(steps);
  17562. extrudeByPath = true;
  17563. bevelEnabled = false; // bevels not supported for path extrusion
  17564. // SETUP TNB variables
  17565. // TODO1 - have a .isClosed in spline?
  17566. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  17567. binormal = new Vector3();
  17568. normal = new Vector3();
  17569. position2 = new Vector3();
  17570. } // Safeguards if bevels are not enabled
  17571. if (!bevelEnabled) {
  17572. bevelSegments = 0;
  17573. bevelThickness = 0;
  17574. bevelSize = 0;
  17575. bevelOffset = 0;
  17576. } // Variables initialization
  17577. const shapePoints = shape.extractPoints(curveSegments);
  17578. let vertices = shapePoints.shape;
  17579. const holes = shapePoints.holes;
  17580. const reverse = !ShapeUtils.isClockWise(vertices);
  17581. if (reverse) {
  17582. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  17583. for (let h = 0, hl = holes.length; h < hl; h++) {
  17584. const ahole = holes[h];
  17585. if (ShapeUtils.isClockWise(ahole)) {
  17586. holes[h] = ahole.reverse();
  17587. }
  17588. }
  17589. }
  17590. const faces = ShapeUtils.triangulateShape(vertices, holes);
  17591. /* Vertices */
  17592. const contour = vertices; // vertices has all points but contour has only points of circumference
  17593. for (let h = 0, hl = holes.length; h < hl; h++) {
  17594. const ahole = holes[h];
  17595. vertices = vertices.concat(ahole);
  17596. }
  17597. function scalePt2(pt, vec, size) {
  17598. if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
  17599. return vec.clone().multiplyScalar(size).add(pt);
  17600. }
  17601. const vlen = vertices.length,
  17602. flen = faces.length; // Find directions for point movement
  17603. function getBevelVec(inPt, inPrev, inNext) {
  17604. // computes for inPt the corresponding point inPt' on a new contour
  17605. // shifted by 1 unit (length of normalized vector) to the left
  17606. // if we walk along contour clockwise, this new contour is outside the old one
  17607. //
  17608. // inPt' is the intersection of the two lines parallel to the two
  17609. // adjacent edges of inPt at a distance of 1 unit on the left side.
  17610. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  17611. // good reading for geometry algorithms (here: line-line intersection)
  17612. // http://geomalgorithms.com/a05-_intersect-1.html
  17613. const v_prev_x = inPt.x - inPrev.x,
  17614. v_prev_y = inPt.y - inPrev.y;
  17615. const v_next_x = inNext.x - inPt.x,
  17616. v_next_y = inNext.y - inPt.y;
  17617. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  17618. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  17619. if (Math.abs(collinear0) > Number.EPSILON) {
  17620. // not collinear
  17621. // length of vectors for normalizing
  17622. const v_prev_len = Math.sqrt(v_prev_lensq);
  17623. 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
  17624. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  17625. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  17626. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  17627. const ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  17628. 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
  17629. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  17630. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  17631. // but prevent crazy spikes
  17632. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  17633. if (v_trans_lensq <= 2) {
  17634. return new Vector2(v_trans_x, v_trans_y);
  17635. } else {
  17636. shrink_by = Math.sqrt(v_trans_lensq / 2);
  17637. }
  17638. } else {
  17639. // handle special case of collinear edges
  17640. let direction_eq = false; // assumes: opposite
  17641. if (v_prev_x > Number.EPSILON) {
  17642. if (v_next_x > Number.EPSILON) {
  17643. direction_eq = true;
  17644. }
  17645. } else {
  17646. if (v_prev_x < -Number.EPSILON) {
  17647. if (v_next_x < -Number.EPSILON) {
  17648. direction_eq = true;
  17649. }
  17650. } else {
  17651. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  17652. direction_eq = true;
  17653. }
  17654. }
  17655. }
  17656. if (direction_eq) {
  17657. // console.log("Warning: lines are a straight sequence");
  17658. v_trans_x = -v_prev_y;
  17659. v_trans_y = v_prev_x;
  17660. shrink_by = Math.sqrt(v_prev_lensq);
  17661. } else {
  17662. // console.log("Warning: lines are a straight spike");
  17663. v_trans_x = v_prev_x;
  17664. v_trans_y = v_prev_y;
  17665. shrink_by = Math.sqrt(v_prev_lensq / 2);
  17666. }
  17667. }
  17668. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  17669. }
  17670. const contourMovements = [];
  17671. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  17672. if (j === il) j = 0;
  17673. if (k === il) k = 0; // (j)---(i)---(k)
  17674. // console.log('i,j,k', i, j , k)
  17675. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  17676. }
  17677. const holesMovements = [];
  17678. let oneHoleMovements,
  17679. verticesMovements = contourMovements.concat();
  17680. for (let h = 0, hl = holes.length; h < hl; h++) {
  17681. const ahole = holes[h];
  17682. oneHoleMovements = [];
  17683. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  17684. if (j === il) j = 0;
  17685. if (k === il) k = 0; // (j)---(i)---(k)
  17686. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  17687. }
  17688. holesMovements.push(oneHoleMovements);
  17689. verticesMovements = verticesMovements.concat(oneHoleMovements);
  17690. } // Loop bevelSegments, 1 for the front, 1 for the back
  17691. for (let b = 0; b < bevelSegments; b++) {
  17692. //for ( b = bevelSegments; b > 0; b -- ) {
  17693. const t = b / bevelSegments;
  17694. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  17695. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  17696. for (let i = 0, il = contour.length; i < il; i++) {
  17697. const vert = scalePt2(contour[i], contourMovements[i], bs);
  17698. v(vert.x, vert.y, -z);
  17699. } // expand holes
  17700. for (let h = 0, hl = holes.length; h < hl; h++) {
  17701. const ahole = holes[h];
  17702. oneHoleMovements = holesMovements[h];
  17703. for (let i = 0, il = ahole.length; i < il; i++) {
  17704. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  17705. v(vert.x, vert.y, -z);
  17706. }
  17707. }
  17708. }
  17709. const bs = bevelSize + bevelOffset; // Back facing vertices
  17710. for (let i = 0; i < vlen; i++) {
  17711. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  17712. if (!extrudeByPath) {
  17713. v(vert.x, vert.y, 0);
  17714. } else {
  17715. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  17716. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  17717. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  17718. position2.copy(extrudePts[0]).add(normal).add(binormal);
  17719. v(position2.x, position2.y, position2.z);
  17720. }
  17721. } // Add stepped vertices...
  17722. // Including front facing vertices
  17723. for (let s = 1; s <= steps; s++) {
  17724. for (let i = 0; i < vlen; i++) {
  17725. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  17726. if (!extrudeByPath) {
  17727. v(vert.x, vert.y, depth / steps * s);
  17728. } else {
  17729. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  17730. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  17731. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  17732. position2.copy(extrudePts[s]).add(normal).add(binormal);
  17733. v(position2.x, position2.y, position2.z);
  17734. }
  17735. }
  17736. } // Add bevel segments planes
  17737. //for ( b = 1; b <= bevelSegments; b ++ ) {
  17738. for (let b = bevelSegments - 1; b >= 0; b--) {
  17739. const t = b / bevelSegments;
  17740. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  17741. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  17742. for (let i = 0, il = contour.length; i < il; i++) {
  17743. const vert = scalePt2(contour[i], contourMovements[i], bs);
  17744. v(vert.x, vert.y, depth + z);
  17745. } // expand holes
  17746. for (let h = 0, hl = holes.length; h < hl; h++) {
  17747. const ahole = holes[h];
  17748. oneHoleMovements = holesMovements[h];
  17749. for (let i = 0, il = ahole.length; i < il; i++) {
  17750. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  17751. if (!extrudeByPath) {
  17752. v(vert.x, vert.y, depth + z);
  17753. } else {
  17754. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  17755. }
  17756. }
  17757. }
  17758. }
  17759. /* Faces */
  17760. // Top and bottom faces
  17761. buildLidFaces(); // Sides faces
  17762. buildSideFaces(); ///// Internal functions
  17763. function buildLidFaces() {
  17764. const start = verticesArray.length / 3;
  17765. if (bevelEnabled) {
  17766. let layer = 0; // steps + 1
  17767. let offset = vlen * layer; // Bottom faces
  17768. for (let i = 0; i < flen; i++) {
  17769. const face = faces[i];
  17770. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  17771. }
  17772. layer = steps + bevelSegments * 2;
  17773. offset = vlen * layer; // Top faces
  17774. for (let i = 0; i < flen; i++) {
  17775. const face = faces[i];
  17776. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  17777. }
  17778. } else {
  17779. // Bottom faces
  17780. for (let i = 0; i < flen; i++) {
  17781. const face = faces[i];
  17782. f3(face[2], face[1], face[0]);
  17783. } // Top faces
  17784. for (let i = 0; i < flen; i++) {
  17785. const face = faces[i];
  17786. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  17787. }
  17788. }
  17789. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  17790. } // Create faces for the z-sides of the shape
  17791. function buildSideFaces() {
  17792. const start = verticesArray.length / 3;
  17793. let layeroffset = 0;
  17794. sidewalls(contour, layeroffset);
  17795. layeroffset += contour.length;
  17796. for (let h = 0, hl = holes.length; h < hl; h++) {
  17797. const ahole = holes[h];
  17798. sidewalls(ahole, layeroffset); //, true
  17799. layeroffset += ahole.length;
  17800. }
  17801. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  17802. }
  17803. function sidewalls(contour, layeroffset) {
  17804. let i = contour.length;
  17805. while (--i >= 0) {
  17806. const j = i;
  17807. let k = i - 1;
  17808. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  17809. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  17810. const slen1 = vlen * s;
  17811. const slen2 = vlen * (s + 1);
  17812. const a = layeroffset + j + slen1,
  17813. b = layeroffset + k + slen1,
  17814. c = layeroffset + k + slen2,
  17815. d = layeroffset + j + slen2;
  17816. f4(a, b, c, d);
  17817. }
  17818. }
  17819. }
  17820. function v(x, y, z) {
  17821. placeholder.push(x);
  17822. placeholder.push(y);
  17823. placeholder.push(z);
  17824. }
  17825. function f3(a, b, c) {
  17826. addVertex(a);
  17827. addVertex(b);
  17828. addVertex(c);
  17829. const nextIndex = verticesArray.length / 3;
  17830. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  17831. addUV(uvs[0]);
  17832. addUV(uvs[1]);
  17833. addUV(uvs[2]);
  17834. }
  17835. function f4(a, b, c, d) {
  17836. addVertex(a);
  17837. addVertex(b);
  17838. addVertex(d);
  17839. addVertex(b);
  17840. addVertex(c);
  17841. addVertex(d);
  17842. const nextIndex = verticesArray.length / 3;
  17843. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  17844. addUV(uvs[0]);
  17845. addUV(uvs[1]);
  17846. addUV(uvs[3]);
  17847. addUV(uvs[1]);
  17848. addUV(uvs[2]);
  17849. addUV(uvs[3]);
  17850. }
  17851. function addVertex(index) {
  17852. verticesArray.push(placeholder[index * 3 + 0]);
  17853. verticesArray.push(placeholder[index * 3 + 1]);
  17854. verticesArray.push(placeholder[index * 3 + 2]);
  17855. }
  17856. function addUV(vector2) {
  17857. uvArray.push(vector2.x);
  17858. uvArray.push(vector2.y);
  17859. }
  17860. }
  17861. }
  17862. toJSON() {
  17863. const data = super.toJSON();
  17864. const shapes = this.parameters.shapes;
  17865. const options = this.parameters.options;
  17866. return toJSON$1(shapes, options, data);
  17867. }
  17868. }
  17869. const WorldUVGenerator = {
  17870. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  17871. const a_x = vertices[indexA * 3];
  17872. const a_y = vertices[indexA * 3 + 1];
  17873. const b_x = vertices[indexB * 3];
  17874. const b_y = vertices[indexB * 3 + 1];
  17875. const c_x = vertices[indexC * 3];
  17876. const c_y = vertices[indexC * 3 + 1];
  17877. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  17878. },
  17879. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  17880. const a_x = vertices[indexA * 3];
  17881. const a_y = vertices[indexA * 3 + 1];
  17882. const a_z = vertices[indexA * 3 + 2];
  17883. const b_x = vertices[indexB * 3];
  17884. const b_y = vertices[indexB * 3 + 1];
  17885. const b_z = vertices[indexB * 3 + 2];
  17886. const c_x = vertices[indexC * 3];
  17887. const c_y = vertices[indexC * 3 + 1];
  17888. const c_z = vertices[indexC * 3 + 2];
  17889. const d_x = vertices[indexD * 3];
  17890. const d_y = vertices[indexD * 3 + 1];
  17891. const d_z = vertices[indexD * 3 + 2];
  17892. if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) {
  17893. 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)];
  17894. } else {
  17895. 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)];
  17896. }
  17897. }
  17898. };
  17899. function toJSON$1(shapes, options, data) {
  17900. data.shapes = [];
  17901. if (Array.isArray(shapes)) {
  17902. for (let i = 0, l = shapes.length; i < l; i++) {
  17903. const shape = shapes[i];
  17904. data.shapes.push(shape.uuid);
  17905. }
  17906. } else {
  17907. data.shapes.push(shapes.uuid);
  17908. }
  17909. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  17910. return data;
  17911. }
  17912. class IcosahedronGeometry extends PolyhedronGeometry {
  17913. constructor(radius = 1, detail = 0) {
  17914. const t = (1 + Math.sqrt(5)) / 2;
  17915. 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];
  17916. 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];
  17917. super(vertices, indices, radius, detail);
  17918. this.type = 'IcosahedronGeometry';
  17919. this.parameters = {
  17920. radius: radius,
  17921. detail: detail
  17922. };
  17923. }
  17924. }
  17925. class LatheGeometry extends BufferGeometry {
  17926. constructor(points, segments = 12, phiStart = 0, phiLength = Math.PI * 2) {
  17927. super();
  17928. this.type = 'LatheGeometry';
  17929. this.parameters = {
  17930. points: points,
  17931. segments: segments,
  17932. phiStart: phiStart,
  17933. phiLength: phiLength
  17934. };
  17935. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  17936. phiLength = clamp(phiLength, 0, Math.PI * 2); // buffers
  17937. const indices = [];
  17938. const vertices = [];
  17939. const uvs = []; // helper variables
  17940. const inverseSegments = 1.0 / segments;
  17941. const vertex = new Vector3();
  17942. const uv = new Vector2(); // generate vertices and uvs
  17943. for (let i = 0; i <= segments; i++) {
  17944. const phi = phiStart + i * inverseSegments * phiLength;
  17945. const sin = Math.sin(phi);
  17946. const cos = Math.cos(phi);
  17947. for (let j = 0; j <= points.length - 1; j++) {
  17948. // vertex
  17949. vertex.x = points[j].x * sin;
  17950. vertex.y = points[j].y;
  17951. vertex.z = points[j].x * cos;
  17952. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  17953. uv.x = i / segments;
  17954. uv.y = j / (points.length - 1);
  17955. uvs.push(uv.x, uv.y);
  17956. }
  17957. } // indices
  17958. for (let i = 0; i < segments; i++) {
  17959. for (let j = 0; j < points.length - 1; j++) {
  17960. const base = j + i * points.length;
  17961. const a = base;
  17962. const b = base + points.length;
  17963. const c = base + points.length + 1;
  17964. const d = base + 1; // faces
  17965. indices.push(a, b, d);
  17966. indices.push(b, c, d);
  17967. }
  17968. } // build geometry
  17969. this.setIndex(indices);
  17970. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17971. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  17972. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  17973. // because the corresponding vertices are identical (but still have different UVs).
  17974. if (phiLength === Math.PI * 2) {
  17975. const normals = this.attributes.normal.array;
  17976. const n1 = new Vector3();
  17977. const n2 = new Vector3();
  17978. const n = new Vector3(); // this is the buffer offset for the last line of vertices
  17979. const base = segments * points.length * 3;
  17980. for (let i = 0, j = 0; i < points.length; i++, j += 3) {
  17981. // select the normal of the vertex in the first line
  17982. n1.x = normals[j + 0];
  17983. n1.y = normals[j + 1];
  17984. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  17985. n2.x = normals[base + j + 0];
  17986. n2.y = normals[base + j + 1];
  17987. n2.z = normals[base + j + 2]; // average normals
  17988. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  17989. normals[j + 0] = normals[base + j + 0] = n.x;
  17990. normals[j + 1] = normals[base + j + 1] = n.y;
  17991. normals[j + 2] = normals[base + j + 2] = n.z;
  17992. }
  17993. }
  17994. }
  17995. }
  17996. class OctahedronGeometry extends PolyhedronGeometry {
  17997. constructor(radius = 1, detail = 0) {
  17998. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  17999. 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];
  18000. super(vertices, indices, radius, detail);
  18001. this.type = 'OctahedronGeometry';
  18002. this.parameters = {
  18003. radius: radius,
  18004. detail: detail
  18005. };
  18006. }
  18007. }
  18008. /**
  18009. * Parametric Surfaces Geometry
  18010. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  18011. */
  18012. class ParametricGeometry extends BufferGeometry {
  18013. constructor(func, slices, stacks) {
  18014. super();
  18015. this.type = 'ParametricGeometry';
  18016. this.parameters = {
  18017. func: func,
  18018. slices: slices,
  18019. stacks: stacks
  18020. }; // buffers
  18021. const indices = [];
  18022. const vertices = [];
  18023. const normals = [];
  18024. const uvs = [];
  18025. const EPS = 0.00001;
  18026. const normal = new Vector3();
  18027. const p0 = new Vector3(),
  18028. p1 = new Vector3();
  18029. const pu = new Vector3(),
  18030. pv = new Vector3();
  18031. if (func.length < 3) {
  18032. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  18033. } // generate vertices, normals and uvs
  18034. const sliceCount = slices + 1;
  18035. for (let i = 0; i <= stacks; i++) {
  18036. const v = i / stacks;
  18037. for (let j = 0; j <= slices; j++) {
  18038. const u = j / slices; // vertex
  18039. func(u, v, p0);
  18040. vertices.push(p0.x, p0.y, p0.z); // normal
  18041. // approximate tangent vectors via finite differences
  18042. if (u - EPS >= 0) {
  18043. func(u - EPS, v, p1);
  18044. pu.subVectors(p0, p1);
  18045. } else {
  18046. func(u + EPS, v, p1);
  18047. pu.subVectors(p1, p0);
  18048. }
  18049. if (v - EPS >= 0) {
  18050. func(u, v - EPS, p1);
  18051. pv.subVectors(p0, p1);
  18052. } else {
  18053. func(u, v + EPS, p1);
  18054. pv.subVectors(p1, p0);
  18055. } // cross product of tangent vectors returns surface normal
  18056. normal.crossVectors(pu, pv).normalize();
  18057. normals.push(normal.x, normal.y, normal.z); // uv
  18058. uvs.push(u, v);
  18059. }
  18060. } // generate indices
  18061. for (let i = 0; i < stacks; i++) {
  18062. for (let j = 0; j < slices; j++) {
  18063. const a = i * sliceCount + j;
  18064. const b = i * sliceCount + j + 1;
  18065. const c = (i + 1) * sliceCount + j + 1;
  18066. const d = (i + 1) * sliceCount + j; // faces one and two
  18067. indices.push(a, b, d);
  18068. indices.push(b, c, d);
  18069. }
  18070. } // build geometry
  18071. this.setIndex(indices);
  18072. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18073. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18074. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18075. }
  18076. }
  18077. class RingGeometry extends BufferGeometry {
  18078. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  18079. super();
  18080. this.type = 'RingGeometry';
  18081. this.parameters = {
  18082. innerRadius: innerRadius,
  18083. outerRadius: outerRadius,
  18084. thetaSegments: thetaSegments,
  18085. phiSegments: phiSegments,
  18086. thetaStart: thetaStart,
  18087. thetaLength: thetaLength
  18088. };
  18089. thetaSegments = Math.max(3, thetaSegments);
  18090. phiSegments = Math.max(1, phiSegments); // buffers
  18091. const indices = [];
  18092. const vertices = [];
  18093. const normals = [];
  18094. const uvs = []; // some helper variables
  18095. let radius = innerRadius;
  18096. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  18097. const vertex = new Vector3();
  18098. const uv = new Vector2(); // generate vertices, normals and uvs
  18099. for (let j = 0; j <= phiSegments; j++) {
  18100. for (let i = 0; i <= thetaSegments; i++) {
  18101. // values are generate from the inside of the ring to the outside
  18102. const segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  18103. vertex.x = radius * Math.cos(segment);
  18104. vertex.y = radius * Math.sin(segment);
  18105. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18106. normals.push(0, 0, 1); // uv
  18107. uv.x = (vertex.x / outerRadius + 1) / 2;
  18108. uv.y = (vertex.y / outerRadius + 1) / 2;
  18109. uvs.push(uv.x, uv.y);
  18110. } // increase the radius for next row of vertices
  18111. radius += radiusStep;
  18112. } // indices
  18113. for (let j = 0; j < phiSegments; j++) {
  18114. const thetaSegmentLevel = j * (thetaSegments + 1);
  18115. for (let i = 0; i < thetaSegments; i++) {
  18116. const segment = i + thetaSegmentLevel;
  18117. const a = segment;
  18118. const b = segment + thetaSegments + 1;
  18119. const c = segment + thetaSegments + 2;
  18120. const d = segment + 1; // faces
  18121. indices.push(a, b, d);
  18122. indices.push(b, c, d);
  18123. }
  18124. } // build geometry
  18125. this.setIndex(indices);
  18126. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18127. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18128. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18129. }
  18130. }
  18131. class ShapeGeometry extends BufferGeometry {
  18132. constructor(shapes, curveSegments = 12) {
  18133. super();
  18134. this.type = 'ShapeGeometry';
  18135. this.parameters = {
  18136. shapes: shapes,
  18137. curveSegments: curveSegments
  18138. }; // buffers
  18139. const indices = [];
  18140. const vertices = [];
  18141. const normals = [];
  18142. const uvs = []; // helper variables
  18143. let groupStart = 0;
  18144. let groupCount = 0; // allow single and array values for "shapes" parameter
  18145. if (Array.isArray(shapes) === false) {
  18146. addShape(shapes);
  18147. } else {
  18148. for (let i = 0; i < shapes.length; i++) {
  18149. addShape(shapes[i]);
  18150. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  18151. groupStart += groupCount;
  18152. groupCount = 0;
  18153. }
  18154. } // build geometry
  18155. this.setIndex(indices);
  18156. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18157. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18158. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  18159. function addShape(shape) {
  18160. const indexOffset = vertices.length / 3;
  18161. const points = shape.extractPoints(curveSegments);
  18162. let shapeVertices = points.shape;
  18163. const shapeHoles = points.holes; // check direction of vertices
  18164. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  18165. shapeVertices = shapeVertices.reverse();
  18166. }
  18167. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  18168. const shapeHole = shapeHoles[i];
  18169. if (ShapeUtils.isClockWise(shapeHole) === true) {
  18170. shapeHoles[i] = shapeHole.reverse();
  18171. }
  18172. }
  18173. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  18174. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  18175. const shapeHole = shapeHoles[i];
  18176. shapeVertices = shapeVertices.concat(shapeHole);
  18177. } // vertices, normals, uvs
  18178. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  18179. const vertex = shapeVertices[i];
  18180. vertices.push(vertex.x, vertex.y, 0);
  18181. normals.push(0, 0, 1);
  18182. uvs.push(vertex.x, vertex.y); // world uvs
  18183. } // incides
  18184. for (let i = 0, l = faces.length; i < l; i++) {
  18185. const face = faces[i];
  18186. const a = face[0] + indexOffset;
  18187. const b = face[1] + indexOffset;
  18188. const c = face[2] + indexOffset;
  18189. indices.push(a, b, c);
  18190. groupCount += 3;
  18191. }
  18192. }
  18193. }
  18194. toJSON() {
  18195. const data = super.toJSON();
  18196. const shapes = this.parameters.shapes;
  18197. return toJSON(shapes, data);
  18198. }
  18199. }
  18200. function toJSON(shapes, data) {
  18201. data.shapes = [];
  18202. if (Array.isArray(shapes)) {
  18203. for (let i = 0, l = shapes.length; i < l; i++) {
  18204. const shape = shapes[i];
  18205. data.shapes.push(shape.uuid);
  18206. }
  18207. } else {
  18208. data.shapes.push(shapes.uuid);
  18209. }
  18210. return data;
  18211. }
  18212. class SphereGeometry extends BufferGeometry {
  18213. constructor(radius = 1, widthSegments = 8, heightSegments = 6, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  18214. super();
  18215. this.type = 'SphereGeometry';
  18216. this.parameters = {
  18217. radius: radius,
  18218. widthSegments: widthSegments,
  18219. heightSegments: heightSegments,
  18220. phiStart: phiStart,
  18221. phiLength: phiLength,
  18222. thetaStart: thetaStart,
  18223. thetaLength: thetaLength
  18224. };
  18225. widthSegments = Math.max(3, Math.floor(widthSegments));
  18226. heightSegments = Math.max(2, Math.floor(heightSegments));
  18227. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  18228. let index = 0;
  18229. const grid = [];
  18230. const vertex = new Vector3();
  18231. const normal = new Vector3(); // buffers
  18232. const indices = [];
  18233. const vertices = [];
  18234. const normals = [];
  18235. const uvs = []; // generate vertices, normals and uvs
  18236. for (let iy = 0; iy <= heightSegments; iy++) {
  18237. const verticesRow = [];
  18238. const v = iy / heightSegments; // special case for the poles
  18239. let uOffset = 0;
  18240. if (iy == 0 && thetaStart == 0) {
  18241. uOffset = 0.5 / widthSegments;
  18242. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  18243. uOffset = -0.5 / widthSegments;
  18244. }
  18245. for (let ix = 0; ix <= widthSegments; ix++) {
  18246. const u = ix / widthSegments; // vertex
  18247. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  18248. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  18249. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  18250. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18251. normal.copy(vertex).normalize();
  18252. normals.push(normal.x, normal.y, normal.z); // uv
  18253. uvs.push(u + uOffset, 1 - v);
  18254. verticesRow.push(index++);
  18255. }
  18256. grid.push(verticesRow);
  18257. } // indices
  18258. for (let iy = 0; iy < heightSegments; iy++) {
  18259. for (let ix = 0; ix < widthSegments; ix++) {
  18260. const a = grid[iy][ix + 1];
  18261. const b = grid[iy][ix];
  18262. const c = grid[iy + 1][ix];
  18263. const d = grid[iy + 1][ix + 1];
  18264. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  18265. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  18266. }
  18267. } // build geometry
  18268. this.setIndex(indices);
  18269. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18270. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18271. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18272. }
  18273. }
  18274. class TetrahedronGeometry extends PolyhedronGeometry {
  18275. constructor(radius = 1, detail = 0) {
  18276. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  18277. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  18278. super(vertices, indices, radius, detail);
  18279. this.type = 'TetrahedronGeometry';
  18280. this.parameters = {
  18281. radius: radius,
  18282. detail: detail
  18283. };
  18284. }
  18285. }
  18286. /**
  18287. * Text = 3D Text
  18288. *
  18289. * parameters = {
  18290. * font: <THREE.Font>, // font
  18291. *
  18292. * size: <float>, // size of the text
  18293. * height: <float>, // thickness to extrude text
  18294. * curveSegments: <int>, // number of points on the curves
  18295. *
  18296. * bevelEnabled: <bool>, // turn on bevel
  18297. * bevelThickness: <float>, // how deep into text bevel goes
  18298. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  18299. * bevelOffset: <float> // how far from text outline does bevel start
  18300. * }
  18301. */
  18302. class TextGeometry extends ExtrudeGeometry {
  18303. constructor(text, parameters = {}) {
  18304. const font = parameters.font;
  18305. if (!(font && font.isFont)) {
  18306. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  18307. return new BufferGeometry();
  18308. }
  18309. const shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  18310. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  18311. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  18312. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  18313. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  18314. super(shapes, parameters);
  18315. this.type = 'TextGeometry';
  18316. }
  18317. }
  18318. class TorusGeometry extends BufferGeometry {
  18319. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  18320. super();
  18321. this.type = 'TorusGeometry';
  18322. this.parameters = {
  18323. radius: radius,
  18324. tube: tube,
  18325. radialSegments: radialSegments,
  18326. tubularSegments: tubularSegments,
  18327. arc: arc
  18328. };
  18329. radialSegments = Math.floor(radialSegments);
  18330. tubularSegments = Math.floor(tubularSegments); // buffers
  18331. const indices = [];
  18332. const vertices = [];
  18333. const normals = [];
  18334. const uvs = []; // helper variables
  18335. const center = new Vector3();
  18336. const vertex = new Vector3();
  18337. const normal = new Vector3(); // generate vertices, normals and uvs
  18338. for (let j = 0; j <= radialSegments; j++) {
  18339. for (let i = 0; i <= tubularSegments; i++) {
  18340. const u = i / tubularSegments * arc;
  18341. const v = j / radialSegments * Math.PI * 2; // vertex
  18342. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  18343. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  18344. vertex.z = tube * Math.sin(v);
  18345. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18346. center.x = radius * Math.cos(u);
  18347. center.y = radius * Math.sin(u);
  18348. normal.subVectors(vertex, center).normalize();
  18349. normals.push(normal.x, normal.y, normal.z); // uv
  18350. uvs.push(i / tubularSegments);
  18351. uvs.push(j / radialSegments);
  18352. }
  18353. } // generate indices
  18354. for (let j = 1; j <= radialSegments; j++) {
  18355. for (let i = 1; i <= tubularSegments; i++) {
  18356. // indices
  18357. const a = (tubularSegments + 1) * j + i - 1;
  18358. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  18359. const c = (tubularSegments + 1) * (j - 1) + i;
  18360. const d = (tubularSegments + 1) * j + i; // faces
  18361. indices.push(a, b, d);
  18362. indices.push(b, c, d);
  18363. }
  18364. } // build geometry
  18365. this.setIndex(indices);
  18366. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18367. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18368. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18369. }
  18370. }
  18371. class TorusKnotGeometry extends BufferGeometry {
  18372. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  18373. super();
  18374. this.type = 'TorusKnotGeometry';
  18375. this.parameters = {
  18376. radius: radius,
  18377. tube: tube,
  18378. tubularSegments: tubularSegments,
  18379. radialSegments: radialSegments,
  18380. p: p,
  18381. q: q
  18382. };
  18383. tubularSegments = Math.floor(tubularSegments);
  18384. radialSegments = Math.floor(radialSegments); // buffers
  18385. const indices = [];
  18386. const vertices = [];
  18387. const normals = [];
  18388. const uvs = []; // helper variables
  18389. const vertex = new Vector3();
  18390. const normal = new Vector3();
  18391. const P1 = new Vector3();
  18392. const P2 = new Vector3();
  18393. const B = new Vector3();
  18394. const T = new Vector3();
  18395. const N = new Vector3(); // generate vertices, normals and uvs
  18396. for (let i = 0; i <= tubularSegments; ++i) {
  18397. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  18398. 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.
  18399. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  18400. calculatePositionOnCurve(u, p, q, radius, P1);
  18401. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  18402. T.subVectors(P2, P1);
  18403. N.addVectors(P2, P1);
  18404. B.crossVectors(T, N);
  18405. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  18406. B.normalize();
  18407. N.normalize();
  18408. for (let j = 0; j <= radialSegments; ++j) {
  18409. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  18410. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  18411. const v = j / radialSegments * Math.PI * 2;
  18412. const cx = -tube * Math.cos(v);
  18413. const cy = tube * Math.sin(v); // now calculate the final vertex position.
  18414. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  18415. vertex.x = P1.x + (cx * N.x + cy * B.x);
  18416. vertex.y = P1.y + (cx * N.y + cy * B.y);
  18417. vertex.z = P1.z + (cx * N.z + cy * B.z);
  18418. 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)
  18419. normal.subVectors(vertex, P1).normalize();
  18420. normals.push(normal.x, normal.y, normal.z); // uv
  18421. uvs.push(i / tubularSegments);
  18422. uvs.push(j / radialSegments);
  18423. }
  18424. } // generate indices
  18425. for (let j = 1; j <= tubularSegments; j++) {
  18426. for (let i = 1; i <= radialSegments; i++) {
  18427. // indices
  18428. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  18429. const b = (radialSegments + 1) * j + (i - 1);
  18430. const c = (radialSegments + 1) * j + i;
  18431. const d = (radialSegments + 1) * (j - 1) + i; // faces
  18432. indices.push(a, b, d);
  18433. indices.push(b, c, d);
  18434. }
  18435. } // build geometry
  18436. this.setIndex(indices);
  18437. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18438. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18439. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  18440. function calculatePositionOnCurve(u, p, q, radius, position) {
  18441. const cu = Math.cos(u);
  18442. const su = Math.sin(u);
  18443. const quOverP = q / p * u;
  18444. const cs = Math.cos(quOverP);
  18445. position.x = radius * (2 + cs) * 0.5 * cu;
  18446. position.y = radius * (2 + cs) * su * 0.5;
  18447. position.z = radius * Math.sin(quOverP) * 0.5;
  18448. }
  18449. }
  18450. }
  18451. class TubeGeometry extends BufferGeometry {
  18452. constructor(path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) {
  18453. super();
  18454. this.type = 'TubeGeometry';
  18455. this.parameters = {
  18456. path: path,
  18457. tubularSegments: tubularSegments,
  18458. radius: radius,
  18459. radialSegments: radialSegments,
  18460. closed: closed
  18461. };
  18462. const frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  18463. this.tangents = frames.tangents;
  18464. this.normals = frames.normals;
  18465. this.binormals = frames.binormals; // helper variables
  18466. const vertex = new Vector3();
  18467. const normal = new Vector3();
  18468. const uv = new Vector2();
  18469. let P = new Vector3(); // buffer
  18470. const vertices = [];
  18471. const normals = [];
  18472. const uvs = [];
  18473. const indices = []; // create buffer data
  18474. generateBufferData(); // build geometry
  18475. this.setIndex(indices);
  18476. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18477. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18478. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  18479. function generateBufferData() {
  18480. for (let i = 0; i < tubularSegments; i++) {
  18481. generateSegment(i);
  18482. } // if the geometry is not closed, generate the last row of vertices and normals
  18483. // at the regular position on the given path
  18484. //
  18485. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  18486. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  18487. // this makes it easy compute correct values for closed geometries
  18488. generateUVs(); // finally create faces
  18489. generateIndices();
  18490. }
  18491. function generateSegment(i) {
  18492. // we use getPointAt to sample evenly distributed points from the given path
  18493. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  18494. const N = frames.normals[i];
  18495. const B = frames.binormals[i]; // generate normals and vertices for the current segment
  18496. for (let j = 0; j <= radialSegments; j++) {
  18497. const v = j / radialSegments * Math.PI * 2;
  18498. const sin = Math.sin(v);
  18499. const cos = -Math.cos(v); // normal
  18500. normal.x = cos * N.x + sin * B.x;
  18501. normal.y = cos * N.y + sin * B.y;
  18502. normal.z = cos * N.z + sin * B.z;
  18503. normal.normalize();
  18504. normals.push(normal.x, normal.y, normal.z); // vertex
  18505. vertex.x = P.x + radius * normal.x;
  18506. vertex.y = P.y + radius * normal.y;
  18507. vertex.z = P.z + radius * normal.z;
  18508. vertices.push(vertex.x, vertex.y, vertex.z);
  18509. }
  18510. }
  18511. function generateIndices() {
  18512. for (let j = 1; j <= tubularSegments; j++) {
  18513. for (let i = 1; i <= radialSegments; i++) {
  18514. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  18515. const b = (radialSegments + 1) * j + (i - 1);
  18516. const c = (radialSegments + 1) * j + i;
  18517. const d = (radialSegments + 1) * (j - 1) + i; // faces
  18518. indices.push(a, b, d);
  18519. indices.push(b, c, d);
  18520. }
  18521. }
  18522. }
  18523. function generateUVs() {
  18524. for (let i = 0; i <= tubularSegments; i++) {
  18525. for (let j = 0; j <= radialSegments; j++) {
  18526. uv.x = i / tubularSegments;
  18527. uv.y = j / radialSegments;
  18528. uvs.push(uv.x, uv.y);
  18529. }
  18530. }
  18531. }
  18532. }
  18533. toJSON() {
  18534. const data = super.toJSON();
  18535. data.path = this.parameters.path.toJSON();
  18536. return data;
  18537. }
  18538. }
  18539. class WireframeGeometry extends BufferGeometry {
  18540. constructor(geometry) {
  18541. super();
  18542. this.type = 'WireframeGeometry';
  18543. if (geometry.isGeometry === true) {
  18544. console.error('THREE.WireframeGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  18545. return;
  18546. } // buffer
  18547. const vertices = []; // helper variables
  18548. const edge = [0, 0],
  18549. edges = {};
  18550. const vertex = new Vector3();
  18551. if (geometry.index !== null) {
  18552. // indexed BufferGeometry
  18553. const position = geometry.attributes.position;
  18554. const indices = geometry.index;
  18555. let groups = geometry.groups;
  18556. if (groups.length === 0) {
  18557. groups = [{
  18558. start: 0,
  18559. count: indices.count,
  18560. materialIndex: 0
  18561. }];
  18562. } // create a data structure that contains all eges without duplicates
  18563. for (let o = 0, ol = groups.length; o < ol; ++o) {
  18564. const group = groups[o];
  18565. const start = group.start;
  18566. const count = group.count;
  18567. for (let i = start, l = start + count; i < l; i += 3) {
  18568. for (let j = 0; j < 3; j++) {
  18569. const edge1 = indices.getX(i + j);
  18570. const edge2 = indices.getX(i + (j + 1) % 3);
  18571. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  18572. edge[1] = Math.max(edge1, edge2);
  18573. const key = edge[0] + ',' + edge[1];
  18574. if (edges[key] === undefined) {
  18575. edges[key] = {
  18576. index1: edge[0],
  18577. index2: edge[1]
  18578. };
  18579. }
  18580. }
  18581. }
  18582. } // generate vertices
  18583. for (const key in edges) {
  18584. const e = edges[key];
  18585. vertex.fromBufferAttribute(position, e.index1);
  18586. vertices.push(vertex.x, vertex.y, vertex.z);
  18587. vertex.fromBufferAttribute(position, e.index2);
  18588. vertices.push(vertex.x, vertex.y, vertex.z);
  18589. }
  18590. } else {
  18591. // non-indexed BufferGeometry
  18592. const position = geometry.attributes.position;
  18593. for (let i = 0, l = position.count / 3; i < l; i++) {
  18594. for (let j = 0; j < 3; j++) {
  18595. // three edges per triangle, an edge is represented as (index1, index2)
  18596. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  18597. const index1 = 3 * i + j;
  18598. vertex.fromBufferAttribute(position, index1);
  18599. vertices.push(vertex.x, vertex.y, vertex.z);
  18600. const index2 = 3 * i + (j + 1) % 3;
  18601. vertex.fromBufferAttribute(position, index2);
  18602. vertices.push(vertex.x, vertex.y, vertex.z);
  18603. }
  18604. }
  18605. } // build geometry
  18606. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18607. }
  18608. }
  18609. var Geometries = /*#__PURE__*/Object.freeze({
  18610. __proto__: null,
  18611. BoxGeometry: BoxGeometry,
  18612. BoxBufferGeometry: BoxGeometry,
  18613. CircleGeometry: CircleGeometry,
  18614. CircleBufferGeometry: CircleGeometry,
  18615. ConeGeometry: ConeGeometry,
  18616. ConeBufferGeometry: ConeGeometry,
  18617. CylinderGeometry: CylinderGeometry,
  18618. CylinderBufferGeometry: CylinderGeometry,
  18619. DodecahedronGeometry: DodecahedronGeometry,
  18620. DodecahedronBufferGeometry: DodecahedronGeometry,
  18621. EdgesGeometry: EdgesGeometry,
  18622. ExtrudeGeometry: ExtrudeGeometry,
  18623. ExtrudeBufferGeometry: ExtrudeGeometry,
  18624. IcosahedronGeometry: IcosahedronGeometry,
  18625. IcosahedronBufferGeometry: IcosahedronGeometry,
  18626. LatheGeometry: LatheGeometry,
  18627. LatheBufferGeometry: LatheGeometry,
  18628. OctahedronGeometry: OctahedronGeometry,
  18629. OctahedronBufferGeometry: OctahedronGeometry,
  18630. ParametricGeometry: ParametricGeometry,
  18631. ParametricBufferGeometry: ParametricGeometry,
  18632. PlaneGeometry: PlaneGeometry,
  18633. PlaneBufferGeometry: PlaneGeometry,
  18634. PolyhedronGeometry: PolyhedronGeometry,
  18635. PolyhedronBufferGeometry: PolyhedronGeometry,
  18636. RingGeometry: RingGeometry,
  18637. RingBufferGeometry: RingGeometry,
  18638. ShapeGeometry: ShapeGeometry,
  18639. ShapeBufferGeometry: ShapeGeometry,
  18640. SphereGeometry: SphereGeometry,
  18641. SphereBufferGeometry: SphereGeometry,
  18642. TetrahedronGeometry: TetrahedronGeometry,
  18643. TetrahedronBufferGeometry: TetrahedronGeometry,
  18644. TextGeometry: TextGeometry,
  18645. TextBufferGeometry: TextGeometry,
  18646. TorusGeometry: TorusGeometry,
  18647. TorusBufferGeometry: TorusGeometry,
  18648. TorusKnotGeometry: TorusKnotGeometry,
  18649. TorusKnotBufferGeometry: TorusKnotGeometry,
  18650. TubeGeometry: TubeGeometry,
  18651. TubeBufferGeometry: TubeGeometry,
  18652. WireframeGeometry: WireframeGeometry
  18653. });
  18654. /**
  18655. * parameters = {
  18656. * color: <THREE.Color>
  18657. * }
  18658. */
  18659. class ShadowMaterial extends Material {
  18660. constructor(parameters) {
  18661. super();
  18662. this.type = 'ShadowMaterial';
  18663. this.color = new Color(0x000000);
  18664. this.transparent = true;
  18665. this.setValues(parameters);
  18666. }
  18667. copy(source) {
  18668. super.copy(source);
  18669. this.color.copy(source.color);
  18670. return this;
  18671. }
  18672. }
  18673. ShadowMaterial.prototype.isShadowMaterial = true;
  18674. class RawShaderMaterial extends ShaderMaterial {
  18675. constructor(parameters) {
  18676. super(parameters);
  18677. this.type = 'RawShaderMaterial';
  18678. }
  18679. }
  18680. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  18681. /**
  18682. * parameters = {
  18683. * color: <hex>,
  18684. * roughness: <float>,
  18685. * metalness: <float>,
  18686. * opacity: <float>,
  18687. *
  18688. * map: new THREE.Texture( <Image> ),
  18689. *
  18690. * lightMap: new THREE.Texture( <Image> ),
  18691. * lightMapIntensity: <float>
  18692. *
  18693. * aoMap: new THREE.Texture( <Image> ),
  18694. * aoMapIntensity: <float>
  18695. *
  18696. * emissive: <hex>,
  18697. * emissiveIntensity: <float>
  18698. * emissiveMap: new THREE.Texture( <Image> ),
  18699. *
  18700. * bumpMap: new THREE.Texture( <Image> ),
  18701. * bumpScale: <float>,
  18702. *
  18703. * normalMap: new THREE.Texture( <Image> ),
  18704. * normalMapType: THREE.TangentSpaceNormalMap,
  18705. * normalScale: <Vector2>,
  18706. *
  18707. * displacementMap: new THREE.Texture( <Image> ),
  18708. * displacementScale: <float>,
  18709. * displacementBias: <float>,
  18710. *
  18711. * roughnessMap: new THREE.Texture( <Image> ),
  18712. *
  18713. * metalnessMap: new THREE.Texture( <Image> ),
  18714. *
  18715. * alphaMap: new THREE.Texture( <Image> ),
  18716. *
  18717. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  18718. * envMapIntensity: <float>
  18719. *
  18720. * refractionRatio: <float>,
  18721. *
  18722. * wireframe: <boolean>,
  18723. * wireframeLinewidth: <float>,
  18724. *
  18725. * morphTargets: <bool>,
  18726. * morphNormals: <bool>,
  18727. *
  18728. * flatShading: <bool>
  18729. * }
  18730. */
  18731. class MeshStandardMaterial extends Material {
  18732. constructor(parameters) {
  18733. super();
  18734. this.defines = {
  18735. 'STANDARD': ''
  18736. };
  18737. this.type = 'MeshStandardMaterial';
  18738. this.color = new Color(0xffffff); // diffuse
  18739. this.roughness = 1.0;
  18740. this.metalness = 0.0;
  18741. this.map = null;
  18742. this.lightMap = null;
  18743. this.lightMapIntensity = 1.0;
  18744. this.aoMap = null;
  18745. this.aoMapIntensity = 1.0;
  18746. this.emissive = new Color(0x000000);
  18747. this.emissiveIntensity = 1.0;
  18748. this.emissiveMap = null;
  18749. this.bumpMap = null;
  18750. this.bumpScale = 1;
  18751. this.normalMap = null;
  18752. this.normalMapType = TangentSpaceNormalMap;
  18753. this.normalScale = new Vector2(1, 1);
  18754. this.displacementMap = null;
  18755. this.displacementScale = 1;
  18756. this.displacementBias = 0;
  18757. this.roughnessMap = null;
  18758. this.metalnessMap = null;
  18759. this.alphaMap = null;
  18760. this.envMap = null;
  18761. this.envMapIntensity = 1.0;
  18762. this.refractionRatio = 0.98;
  18763. this.wireframe = false;
  18764. this.wireframeLinewidth = 1;
  18765. this.wireframeLinecap = 'round';
  18766. this.wireframeLinejoin = 'round';
  18767. this.morphTargets = false;
  18768. this.morphNormals = false;
  18769. this.flatShading = false;
  18770. this.vertexTangents = false;
  18771. this.setValues(parameters);
  18772. }
  18773. copy(source) {
  18774. super.copy(source);
  18775. this.defines = {
  18776. 'STANDARD': ''
  18777. };
  18778. this.color.copy(source.color);
  18779. this.roughness = source.roughness;
  18780. this.metalness = source.metalness;
  18781. this.map = source.map;
  18782. this.lightMap = source.lightMap;
  18783. this.lightMapIntensity = source.lightMapIntensity;
  18784. this.aoMap = source.aoMap;
  18785. this.aoMapIntensity = source.aoMapIntensity;
  18786. this.emissive.copy(source.emissive);
  18787. this.emissiveMap = source.emissiveMap;
  18788. this.emissiveIntensity = source.emissiveIntensity;
  18789. this.bumpMap = source.bumpMap;
  18790. this.bumpScale = source.bumpScale;
  18791. this.normalMap = source.normalMap;
  18792. this.normalMapType = source.normalMapType;
  18793. this.normalScale.copy(source.normalScale);
  18794. this.displacementMap = source.displacementMap;
  18795. this.displacementScale = source.displacementScale;
  18796. this.displacementBias = source.displacementBias;
  18797. this.roughnessMap = source.roughnessMap;
  18798. this.metalnessMap = source.metalnessMap;
  18799. this.alphaMap = source.alphaMap;
  18800. this.envMap = source.envMap;
  18801. this.envMapIntensity = source.envMapIntensity;
  18802. this.refractionRatio = source.refractionRatio;
  18803. this.wireframe = source.wireframe;
  18804. this.wireframeLinewidth = source.wireframeLinewidth;
  18805. this.wireframeLinecap = source.wireframeLinecap;
  18806. this.wireframeLinejoin = source.wireframeLinejoin;
  18807. this.morphTargets = source.morphTargets;
  18808. this.morphNormals = source.morphNormals;
  18809. this.flatShading = source.flatShading;
  18810. this.vertexTangents = source.vertexTangents;
  18811. return this;
  18812. }
  18813. }
  18814. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  18815. /**
  18816. * parameters = {
  18817. * clearcoat: <float>,
  18818. * clearcoatMap: new THREE.Texture( <Image> ),
  18819. * clearcoatRoughness: <float>,
  18820. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  18821. * clearcoatNormalScale: <Vector2>,
  18822. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  18823. *
  18824. * reflectivity: <float>,
  18825. * ior: <float>,
  18826. *
  18827. * sheen: <Color>,
  18828. *
  18829. * transmission: <float>,
  18830. * transmissionMap: new THREE.Texture( <Image> ),
  18831. *
  18832. * thickness: <float>,
  18833. * thicknessMap: new THREE.Texture( <Image> ),
  18834. * attenuationDistance: <float>,
  18835. * attenuationColor: <Color>
  18836. * }
  18837. */
  18838. class MeshPhysicalMaterial extends MeshStandardMaterial {
  18839. constructor(parameters) {
  18840. super();
  18841. this.defines = {
  18842. 'STANDARD': '',
  18843. 'PHYSICAL': ''
  18844. };
  18845. this.type = 'MeshPhysicalMaterial';
  18846. this.clearcoat = 0.0;
  18847. this.clearcoatMap = null;
  18848. this.clearcoatRoughness = 0.0;
  18849. this.clearcoatRoughnessMap = null;
  18850. this.clearcoatNormalScale = new Vector2(1, 1);
  18851. this.clearcoatNormalMap = null;
  18852. this.reflectivity = 0.5; // maps to F0 = 0.04
  18853. Object.defineProperty(this, 'ior', {
  18854. get: function () {
  18855. return (1 + 0.4 * this.reflectivity) / (1 - 0.4 * this.reflectivity);
  18856. },
  18857. set: function (ior) {
  18858. this.reflectivity = clamp(2.5 * (ior - 1) / (ior + 1), 0, 1);
  18859. }
  18860. });
  18861. this.sheen = null; // null will disable sheen bsdf
  18862. this.transmission = 0.0;
  18863. this.transmissionMap = null;
  18864. this.thickness = 0.01;
  18865. this.thicknessMap = null;
  18866. this.attenuationDistance = 0.0;
  18867. this.attenuationColor = new Color(1, 1, 1);
  18868. this.setValues(parameters);
  18869. }
  18870. copy(source) {
  18871. super.copy(source);
  18872. this.defines = {
  18873. 'STANDARD': '',
  18874. 'PHYSICAL': ''
  18875. };
  18876. this.clearcoat = source.clearcoat;
  18877. this.clearcoatMap = source.clearcoatMap;
  18878. this.clearcoatRoughness = source.clearcoatRoughness;
  18879. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  18880. this.clearcoatNormalMap = source.clearcoatNormalMap;
  18881. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  18882. this.reflectivity = source.reflectivity;
  18883. if (source.sheen) {
  18884. this.sheen = (this.sheen || new Color()).copy(source.sheen);
  18885. } else {
  18886. this.sheen = null;
  18887. }
  18888. this.transmission = source.transmission;
  18889. this.transmissionMap = source.transmissionMap;
  18890. this.thickness = source.thickness;
  18891. this.thicknessMap = source.thicknessMap;
  18892. this.attenuationDistance = source.attenuationDistance;
  18893. this.attenuationColor.copy(source.attenuationColor);
  18894. return this;
  18895. }
  18896. }
  18897. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  18898. /**
  18899. * parameters = {
  18900. * color: <hex>,
  18901. * specular: <hex>,
  18902. * shininess: <float>,
  18903. * opacity: <float>,
  18904. *
  18905. * map: new THREE.Texture( <Image> ),
  18906. *
  18907. * lightMap: new THREE.Texture( <Image> ),
  18908. * lightMapIntensity: <float>
  18909. *
  18910. * aoMap: new THREE.Texture( <Image> ),
  18911. * aoMapIntensity: <float>
  18912. *
  18913. * emissive: <hex>,
  18914. * emissiveIntensity: <float>
  18915. * emissiveMap: new THREE.Texture( <Image> ),
  18916. *
  18917. * bumpMap: new THREE.Texture( <Image> ),
  18918. * bumpScale: <float>,
  18919. *
  18920. * normalMap: new THREE.Texture( <Image> ),
  18921. * normalMapType: THREE.TangentSpaceNormalMap,
  18922. * normalScale: <Vector2>,
  18923. *
  18924. * displacementMap: new THREE.Texture( <Image> ),
  18925. * displacementScale: <float>,
  18926. * displacementBias: <float>,
  18927. *
  18928. * specularMap: new THREE.Texture( <Image> ),
  18929. *
  18930. * alphaMap: new THREE.Texture( <Image> ),
  18931. *
  18932. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  18933. * combine: THREE.MultiplyOperation,
  18934. * reflectivity: <float>,
  18935. * refractionRatio: <float>,
  18936. *
  18937. * wireframe: <boolean>,
  18938. * wireframeLinewidth: <float>,
  18939. *
  18940. * morphTargets: <bool>,
  18941. * morphNormals: <bool>,
  18942. *
  18943. * flatShading: <bool>
  18944. * }
  18945. */
  18946. class MeshPhongMaterial extends Material {
  18947. constructor(parameters) {
  18948. super();
  18949. this.type = 'MeshPhongMaterial';
  18950. this.color = new Color(0xffffff); // diffuse
  18951. this.specular = new Color(0x111111);
  18952. this.shininess = 30;
  18953. this.map = null;
  18954. this.lightMap = null;
  18955. this.lightMapIntensity = 1.0;
  18956. this.aoMap = null;
  18957. this.aoMapIntensity = 1.0;
  18958. this.emissive = new Color(0x000000);
  18959. this.emissiveIntensity = 1.0;
  18960. this.emissiveMap = null;
  18961. this.bumpMap = null;
  18962. this.bumpScale = 1;
  18963. this.normalMap = null;
  18964. this.normalMapType = TangentSpaceNormalMap;
  18965. this.normalScale = new Vector2(1, 1);
  18966. this.displacementMap = null;
  18967. this.displacementScale = 1;
  18968. this.displacementBias = 0;
  18969. this.specularMap = null;
  18970. this.alphaMap = null;
  18971. this.envMap = null;
  18972. this.combine = MultiplyOperation;
  18973. this.reflectivity = 1;
  18974. this.refractionRatio = 0.98;
  18975. this.wireframe = false;
  18976. this.wireframeLinewidth = 1;
  18977. this.wireframeLinecap = 'round';
  18978. this.wireframeLinejoin = 'round';
  18979. this.morphTargets = false;
  18980. this.morphNormals = false;
  18981. this.flatShading = false;
  18982. this.setValues(parameters);
  18983. }
  18984. copy(source) {
  18985. super.copy(source);
  18986. this.color.copy(source.color);
  18987. this.specular.copy(source.specular);
  18988. this.shininess = source.shininess;
  18989. this.map = source.map;
  18990. this.lightMap = source.lightMap;
  18991. this.lightMapIntensity = source.lightMapIntensity;
  18992. this.aoMap = source.aoMap;
  18993. this.aoMapIntensity = source.aoMapIntensity;
  18994. this.emissive.copy(source.emissive);
  18995. this.emissiveMap = source.emissiveMap;
  18996. this.emissiveIntensity = source.emissiveIntensity;
  18997. this.bumpMap = source.bumpMap;
  18998. this.bumpScale = source.bumpScale;
  18999. this.normalMap = source.normalMap;
  19000. this.normalMapType = source.normalMapType;
  19001. this.normalScale.copy(source.normalScale);
  19002. this.displacementMap = source.displacementMap;
  19003. this.displacementScale = source.displacementScale;
  19004. this.displacementBias = source.displacementBias;
  19005. this.specularMap = source.specularMap;
  19006. this.alphaMap = source.alphaMap;
  19007. this.envMap = source.envMap;
  19008. this.combine = source.combine;
  19009. this.reflectivity = source.reflectivity;
  19010. this.refractionRatio = source.refractionRatio;
  19011. this.wireframe = source.wireframe;
  19012. this.wireframeLinewidth = source.wireframeLinewidth;
  19013. this.wireframeLinecap = source.wireframeLinecap;
  19014. this.wireframeLinejoin = source.wireframeLinejoin;
  19015. this.morphTargets = source.morphTargets;
  19016. this.morphNormals = source.morphNormals;
  19017. this.flatShading = source.flatShading;
  19018. return this;
  19019. }
  19020. }
  19021. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  19022. /**
  19023. * parameters = {
  19024. * color: <hex>,
  19025. *
  19026. * map: new THREE.Texture( <Image> ),
  19027. * gradientMap: new THREE.Texture( <Image> ),
  19028. *
  19029. * lightMap: new THREE.Texture( <Image> ),
  19030. * lightMapIntensity: <float>
  19031. *
  19032. * aoMap: new THREE.Texture( <Image> ),
  19033. * aoMapIntensity: <float>
  19034. *
  19035. * emissive: <hex>,
  19036. * emissiveIntensity: <float>
  19037. * emissiveMap: new THREE.Texture( <Image> ),
  19038. *
  19039. * bumpMap: new THREE.Texture( <Image> ),
  19040. * bumpScale: <float>,
  19041. *
  19042. * normalMap: new THREE.Texture( <Image> ),
  19043. * normalMapType: THREE.TangentSpaceNormalMap,
  19044. * normalScale: <Vector2>,
  19045. *
  19046. * displacementMap: new THREE.Texture( <Image> ),
  19047. * displacementScale: <float>,
  19048. * displacementBias: <float>,
  19049. *
  19050. * alphaMap: new THREE.Texture( <Image> ),
  19051. *
  19052. * wireframe: <boolean>,
  19053. * wireframeLinewidth: <float>,
  19054. *
  19055. * morphTargets: <bool>,
  19056. * morphNormals: <bool>
  19057. * }
  19058. */
  19059. class MeshToonMaterial extends Material {
  19060. constructor(parameters) {
  19061. super();
  19062. this.defines = {
  19063. 'TOON': ''
  19064. };
  19065. this.type = 'MeshToonMaterial';
  19066. this.color = new Color(0xffffff);
  19067. this.map = null;
  19068. this.gradientMap = null;
  19069. this.lightMap = null;
  19070. this.lightMapIntensity = 1.0;
  19071. this.aoMap = null;
  19072. this.aoMapIntensity = 1.0;
  19073. this.emissive = new Color(0x000000);
  19074. this.emissiveIntensity = 1.0;
  19075. this.emissiveMap = null;
  19076. this.bumpMap = null;
  19077. this.bumpScale = 1;
  19078. this.normalMap = null;
  19079. this.normalMapType = TangentSpaceNormalMap;
  19080. this.normalScale = new Vector2(1, 1);
  19081. this.displacementMap = null;
  19082. this.displacementScale = 1;
  19083. this.displacementBias = 0;
  19084. this.alphaMap = null;
  19085. this.wireframe = false;
  19086. this.wireframeLinewidth = 1;
  19087. this.wireframeLinecap = 'round';
  19088. this.wireframeLinejoin = 'round';
  19089. this.morphTargets = false;
  19090. this.morphNormals = false;
  19091. this.setValues(parameters);
  19092. }
  19093. copy(source) {
  19094. super.copy(source);
  19095. this.color.copy(source.color);
  19096. this.map = source.map;
  19097. this.gradientMap = source.gradientMap;
  19098. this.lightMap = source.lightMap;
  19099. this.lightMapIntensity = source.lightMapIntensity;
  19100. this.aoMap = source.aoMap;
  19101. this.aoMapIntensity = source.aoMapIntensity;
  19102. this.emissive.copy(source.emissive);
  19103. this.emissiveMap = source.emissiveMap;
  19104. this.emissiveIntensity = source.emissiveIntensity;
  19105. this.bumpMap = source.bumpMap;
  19106. this.bumpScale = source.bumpScale;
  19107. this.normalMap = source.normalMap;
  19108. this.normalMapType = source.normalMapType;
  19109. this.normalScale.copy(source.normalScale);
  19110. this.displacementMap = source.displacementMap;
  19111. this.displacementScale = source.displacementScale;
  19112. this.displacementBias = source.displacementBias;
  19113. this.alphaMap = source.alphaMap;
  19114. this.wireframe = source.wireframe;
  19115. this.wireframeLinewidth = source.wireframeLinewidth;
  19116. this.wireframeLinecap = source.wireframeLinecap;
  19117. this.wireframeLinejoin = source.wireframeLinejoin;
  19118. this.morphTargets = source.morphTargets;
  19119. this.morphNormals = source.morphNormals;
  19120. return this;
  19121. }
  19122. }
  19123. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  19124. /**
  19125. * parameters = {
  19126. * opacity: <float>,
  19127. *
  19128. * bumpMap: new THREE.Texture( <Image> ),
  19129. * bumpScale: <float>,
  19130. *
  19131. * normalMap: new THREE.Texture( <Image> ),
  19132. * normalMapType: THREE.TangentSpaceNormalMap,
  19133. * normalScale: <Vector2>,
  19134. *
  19135. * displacementMap: new THREE.Texture( <Image> ),
  19136. * displacementScale: <float>,
  19137. * displacementBias: <float>,
  19138. *
  19139. * wireframe: <boolean>,
  19140. * wireframeLinewidth: <float>
  19141. *
  19142. * morphTargets: <bool>,
  19143. * morphNormals: <bool>,
  19144. *
  19145. * flatShading: <bool>
  19146. * }
  19147. */
  19148. class MeshNormalMaterial extends Material {
  19149. constructor(parameters) {
  19150. super();
  19151. this.type = 'MeshNormalMaterial';
  19152. this.bumpMap = null;
  19153. this.bumpScale = 1;
  19154. this.normalMap = null;
  19155. this.normalMapType = TangentSpaceNormalMap;
  19156. this.normalScale = new Vector2(1, 1);
  19157. this.displacementMap = null;
  19158. this.displacementScale = 1;
  19159. this.displacementBias = 0;
  19160. this.wireframe = false;
  19161. this.wireframeLinewidth = 1;
  19162. this.fog = false;
  19163. this.morphTargets = false;
  19164. this.morphNormals = false;
  19165. this.flatShading = false;
  19166. this.setValues(parameters);
  19167. }
  19168. copy(source) {
  19169. super.copy(source);
  19170. this.bumpMap = source.bumpMap;
  19171. this.bumpScale = source.bumpScale;
  19172. this.normalMap = source.normalMap;
  19173. this.normalMapType = source.normalMapType;
  19174. this.normalScale.copy(source.normalScale);
  19175. this.displacementMap = source.displacementMap;
  19176. this.displacementScale = source.displacementScale;
  19177. this.displacementBias = source.displacementBias;
  19178. this.wireframe = source.wireframe;
  19179. this.wireframeLinewidth = source.wireframeLinewidth;
  19180. this.morphTargets = source.morphTargets;
  19181. this.morphNormals = source.morphNormals;
  19182. this.flatShading = source.flatShading;
  19183. return this;
  19184. }
  19185. }
  19186. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  19187. /**
  19188. * parameters = {
  19189. * color: <hex>,
  19190. * opacity: <float>,
  19191. *
  19192. * map: new THREE.Texture( <Image> ),
  19193. *
  19194. * lightMap: new THREE.Texture( <Image> ),
  19195. * lightMapIntensity: <float>
  19196. *
  19197. * aoMap: new THREE.Texture( <Image> ),
  19198. * aoMapIntensity: <float>
  19199. *
  19200. * emissive: <hex>,
  19201. * emissiveIntensity: <float>
  19202. * emissiveMap: new THREE.Texture( <Image> ),
  19203. *
  19204. * specularMap: new THREE.Texture( <Image> ),
  19205. *
  19206. * alphaMap: new THREE.Texture( <Image> ),
  19207. *
  19208. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19209. * combine: THREE.Multiply,
  19210. * reflectivity: <float>,
  19211. * refractionRatio: <float>,
  19212. *
  19213. * wireframe: <boolean>,
  19214. * wireframeLinewidth: <float>,
  19215. *
  19216. * morphTargets: <bool>,
  19217. * morphNormals: <bool>
  19218. * }
  19219. */
  19220. class MeshLambertMaterial extends Material {
  19221. constructor(parameters) {
  19222. super();
  19223. this.type = 'MeshLambertMaterial';
  19224. this.color = new Color(0xffffff); // diffuse
  19225. this.map = null;
  19226. this.lightMap = null;
  19227. this.lightMapIntensity = 1.0;
  19228. this.aoMap = null;
  19229. this.aoMapIntensity = 1.0;
  19230. this.emissive = new Color(0x000000);
  19231. this.emissiveIntensity = 1.0;
  19232. this.emissiveMap = null;
  19233. this.specularMap = null;
  19234. this.alphaMap = null;
  19235. this.envMap = null;
  19236. this.combine = MultiplyOperation;
  19237. this.reflectivity = 1;
  19238. this.refractionRatio = 0.98;
  19239. this.wireframe = false;
  19240. this.wireframeLinewidth = 1;
  19241. this.wireframeLinecap = 'round';
  19242. this.wireframeLinejoin = 'round';
  19243. this.morphTargets = false;
  19244. this.morphNormals = false;
  19245. this.setValues(parameters);
  19246. }
  19247. copy(source) {
  19248. super.copy(source);
  19249. this.color.copy(source.color);
  19250. this.map = source.map;
  19251. this.lightMap = source.lightMap;
  19252. this.lightMapIntensity = source.lightMapIntensity;
  19253. this.aoMap = source.aoMap;
  19254. this.aoMapIntensity = source.aoMapIntensity;
  19255. this.emissive.copy(source.emissive);
  19256. this.emissiveMap = source.emissiveMap;
  19257. this.emissiveIntensity = source.emissiveIntensity;
  19258. this.specularMap = source.specularMap;
  19259. this.alphaMap = source.alphaMap;
  19260. this.envMap = source.envMap;
  19261. this.combine = source.combine;
  19262. this.reflectivity = source.reflectivity;
  19263. this.refractionRatio = source.refractionRatio;
  19264. this.wireframe = source.wireframe;
  19265. this.wireframeLinewidth = source.wireframeLinewidth;
  19266. this.wireframeLinecap = source.wireframeLinecap;
  19267. this.wireframeLinejoin = source.wireframeLinejoin;
  19268. this.morphTargets = source.morphTargets;
  19269. this.morphNormals = source.morphNormals;
  19270. return this;
  19271. }
  19272. }
  19273. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  19274. /**
  19275. * parameters = {
  19276. * color: <hex>,
  19277. * opacity: <float>,
  19278. *
  19279. * matcap: new THREE.Texture( <Image> ),
  19280. *
  19281. * map: new THREE.Texture( <Image> ),
  19282. *
  19283. * bumpMap: new THREE.Texture( <Image> ),
  19284. * bumpScale: <float>,
  19285. *
  19286. * normalMap: new THREE.Texture( <Image> ),
  19287. * normalMapType: THREE.TangentSpaceNormalMap,
  19288. * normalScale: <Vector2>,
  19289. *
  19290. * displacementMap: new THREE.Texture( <Image> ),
  19291. * displacementScale: <float>,
  19292. * displacementBias: <float>,
  19293. *
  19294. * alphaMap: new THREE.Texture( <Image> ),
  19295. *
  19296. * morphTargets: <bool>,
  19297. * morphNormals: <bool>
  19298. *
  19299. * flatShading: <bool>
  19300. * }
  19301. */
  19302. class MeshMatcapMaterial extends Material {
  19303. constructor(parameters) {
  19304. super();
  19305. this.defines = {
  19306. 'MATCAP': ''
  19307. };
  19308. this.type = 'MeshMatcapMaterial';
  19309. this.color = new Color(0xffffff); // diffuse
  19310. this.matcap = null;
  19311. this.map = null;
  19312. this.bumpMap = null;
  19313. this.bumpScale = 1;
  19314. this.normalMap = null;
  19315. this.normalMapType = TangentSpaceNormalMap;
  19316. this.normalScale = new Vector2(1, 1);
  19317. this.displacementMap = null;
  19318. this.displacementScale = 1;
  19319. this.displacementBias = 0;
  19320. this.alphaMap = null;
  19321. this.morphTargets = false;
  19322. this.morphNormals = false;
  19323. this.flatShading = false;
  19324. this.setValues(parameters);
  19325. }
  19326. copy(source) {
  19327. super.copy(source);
  19328. this.defines = {
  19329. 'MATCAP': ''
  19330. };
  19331. this.color.copy(source.color);
  19332. this.matcap = source.matcap;
  19333. this.map = source.map;
  19334. this.bumpMap = source.bumpMap;
  19335. this.bumpScale = source.bumpScale;
  19336. this.normalMap = source.normalMap;
  19337. this.normalMapType = source.normalMapType;
  19338. this.normalScale.copy(source.normalScale);
  19339. this.displacementMap = source.displacementMap;
  19340. this.displacementScale = source.displacementScale;
  19341. this.displacementBias = source.displacementBias;
  19342. this.alphaMap = source.alphaMap;
  19343. this.morphTargets = source.morphTargets;
  19344. this.morphNormals = source.morphNormals;
  19345. this.flatShading = source.flatShading;
  19346. return this;
  19347. }
  19348. }
  19349. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  19350. /**
  19351. * parameters = {
  19352. * color: <hex>,
  19353. * opacity: <float>,
  19354. *
  19355. * linewidth: <float>,
  19356. *
  19357. * scale: <float>,
  19358. * dashSize: <float>,
  19359. * gapSize: <float>
  19360. * }
  19361. */
  19362. class LineDashedMaterial extends LineBasicMaterial {
  19363. constructor(parameters) {
  19364. super();
  19365. this.type = 'LineDashedMaterial';
  19366. this.scale = 1;
  19367. this.dashSize = 3;
  19368. this.gapSize = 1;
  19369. this.setValues(parameters);
  19370. }
  19371. copy(source) {
  19372. super.copy(source);
  19373. this.scale = source.scale;
  19374. this.dashSize = source.dashSize;
  19375. this.gapSize = source.gapSize;
  19376. return this;
  19377. }
  19378. }
  19379. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  19380. var Materials = /*#__PURE__*/Object.freeze({
  19381. __proto__: null,
  19382. ShadowMaterial: ShadowMaterial,
  19383. SpriteMaterial: SpriteMaterial,
  19384. RawShaderMaterial: RawShaderMaterial,
  19385. ShaderMaterial: ShaderMaterial,
  19386. PointsMaterial: PointsMaterial,
  19387. MeshPhysicalMaterial: MeshPhysicalMaterial,
  19388. MeshStandardMaterial: MeshStandardMaterial,
  19389. MeshPhongMaterial: MeshPhongMaterial,
  19390. MeshToonMaterial: MeshToonMaterial,
  19391. MeshNormalMaterial: MeshNormalMaterial,
  19392. MeshLambertMaterial: MeshLambertMaterial,
  19393. MeshDepthMaterial: MeshDepthMaterial,
  19394. MeshDistanceMaterial: MeshDistanceMaterial,
  19395. MeshBasicMaterial: MeshBasicMaterial,
  19396. MeshMatcapMaterial: MeshMatcapMaterial,
  19397. LineDashedMaterial: LineDashedMaterial,
  19398. LineBasicMaterial: LineBasicMaterial,
  19399. Material: Material
  19400. });
  19401. const AnimationUtils = {
  19402. // same as Array.prototype.slice, but also works on typed arrays
  19403. arraySlice: function (array, from, to) {
  19404. if (AnimationUtils.isTypedArray(array)) {
  19405. // in ios9 array.subarray(from, undefined) will return empty array
  19406. // but array.subarray(from) or array.subarray(from, len) is correct
  19407. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  19408. }
  19409. return array.slice(from, to);
  19410. },
  19411. // converts an array to a specific type
  19412. convertArray: function (array, type, forceClone) {
  19413. if (!array || // let 'undefined' and 'null' pass
  19414. !forceClone && array.constructor === type) return array;
  19415. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  19416. return new type(array); // create typed array
  19417. }
  19418. return Array.prototype.slice.call(array); // create Array
  19419. },
  19420. isTypedArray: function (object) {
  19421. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  19422. },
  19423. // returns an array by which times and values can be sorted
  19424. getKeyframeOrder: function (times) {
  19425. function compareTime(i, j) {
  19426. return times[i] - times[j];
  19427. }
  19428. const n = times.length;
  19429. const result = new Array(n);
  19430. for (let i = 0; i !== n; ++i) result[i] = i;
  19431. result.sort(compareTime);
  19432. return result;
  19433. },
  19434. // uses the array previously returned by 'getKeyframeOrder' to sort data
  19435. sortedArray: function (values, stride, order) {
  19436. const nValues = values.length;
  19437. const result = new values.constructor(nValues);
  19438. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  19439. const srcOffset = order[i] * stride;
  19440. for (let j = 0; j !== stride; ++j) {
  19441. result[dstOffset++] = values[srcOffset + j];
  19442. }
  19443. }
  19444. return result;
  19445. },
  19446. // function for parsing AOS keyframe formats
  19447. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  19448. let i = 1,
  19449. key = jsonKeys[0];
  19450. while (key !== undefined && key[valuePropertyName] === undefined) {
  19451. key = jsonKeys[i++];
  19452. }
  19453. if (key === undefined) return; // no data
  19454. let value = key[valuePropertyName];
  19455. if (value === undefined) return; // no data
  19456. if (Array.isArray(value)) {
  19457. do {
  19458. value = key[valuePropertyName];
  19459. if (value !== undefined) {
  19460. times.push(key.time);
  19461. values.push.apply(values, value); // push all elements
  19462. }
  19463. key = jsonKeys[i++];
  19464. } while (key !== undefined);
  19465. } else if (value.toArray !== undefined) {
  19466. // ...assume THREE.Math-ish
  19467. do {
  19468. value = key[valuePropertyName];
  19469. if (value !== undefined) {
  19470. times.push(key.time);
  19471. value.toArray(values, values.length);
  19472. }
  19473. key = jsonKeys[i++];
  19474. } while (key !== undefined);
  19475. } else {
  19476. // otherwise push as-is
  19477. do {
  19478. value = key[valuePropertyName];
  19479. if (value !== undefined) {
  19480. times.push(key.time);
  19481. values.push(value);
  19482. }
  19483. key = jsonKeys[i++];
  19484. } while (key !== undefined);
  19485. }
  19486. },
  19487. subclip: function (sourceClip, name, startFrame, endFrame, fps = 30) {
  19488. const clip = sourceClip.clone();
  19489. clip.name = name;
  19490. const tracks = [];
  19491. for (let i = 0; i < clip.tracks.length; ++i) {
  19492. const track = clip.tracks[i];
  19493. const valueSize = track.getValueSize();
  19494. const times = [];
  19495. const values = [];
  19496. for (let j = 0; j < track.times.length; ++j) {
  19497. const frame = track.times[j] * fps;
  19498. if (frame < startFrame || frame >= endFrame) continue;
  19499. times.push(track.times[j]);
  19500. for (let k = 0; k < valueSize; ++k) {
  19501. values.push(track.values[j * valueSize + k]);
  19502. }
  19503. }
  19504. if (times.length === 0) continue;
  19505. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  19506. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  19507. tracks.push(track);
  19508. }
  19509. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  19510. let minStartTime = Infinity;
  19511. for (let i = 0; i < clip.tracks.length; ++i) {
  19512. if (minStartTime > clip.tracks[i].times[0]) {
  19513. minStartTime = clip.tracks[i].times[0];
  19514. }
  19515. } // shift all tracks such that clip begins at t=0
  19516. for (let i = 0; i < clip.tracks.length; ++i) {
  19517. clip.tracks[i].shift(-1 * minStartTime);
  19518. }
  19519. clip.resetDuration();
  19520. return clip;
  19521. },
  19522. makeClipAdditive: function (targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  19523. if (fps <= 0) fps = 30;
  19524. const numTracks = referenceClip.tracks.length;
  19525. const referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  19526. for (let i = 0; i < numTracks; ++i) {
  19527. const referenceTrack = referenceClip.tracks[i];
  19528. const referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  19529. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue; // Find the track in the target clip whose name and type matches the reference track
  19530. const targetTrack = targetClip.tracks.find(function (track) {
  19531. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  19532. });
  19533. if (targetTrack === undefined) continue;
  19534. let referenceOffset = 0;
  19535. const referenceValueSize = referenceTrack.getValueSize();
  19536. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  19537. referenceOffset = referenceValueSize / 3;
  19538. }
  19539. let targetOffset = 0;
  19540. const targetValueSize = targetTrack.getValueSize();
  19541. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  19542. targetOffset = targetValueSize / 3;
  19543. }
  19544. const lastIndex = referenceTrack.times.length - 1;
  19545. let referenceValue; // Find the value to subtract out of the track
  19546. if (referenceTime <= referenceTrack.times[0]) {
  19547. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  19548. const startIndex = referenceOffset;
  19549. const endIndex = referenceValueSize - referenceOffset;
  19550. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  19551. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  19552. // Reference frame is after the last keyframe, so just use the last keyframe
  19553. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  19554. const endIndex = startIndex + referenceValueSize - referenceOffset;
  19555. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  19556. } else {
  19557. // Interpolate to the reference value
  19558. const interpolant = referenceTrack.createInterpolant();
  19559. const startIndex = referenceOffset;
  19560. const endIndex = referenceValueSize - referenceOffset;
  19561. interpolant.evaluate(referenceTime);
  19562. referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  19563. } // Conjugate the quaternion
  19564. if (referenceTrackType === 'quaternion') {
  19565. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  19566. referenceQuat.toArray(referenceValue);
  19567. } // Subtract the reference value from all of the track values
  19568. const numTimes = targetTrack.times.length;
  19569. for (let j = 0; j < numTimes; ++j) {
  19570. const valueStart = j * targetValueSize + targetOffset;
  19571. if (referenceTrackType === 'quaternion') {
  19572. // Multiply the conjugate for quaternion track types
  19573. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  19574. } else {
  19575. const valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  19576. for (let k = 0; k < valueEnd; ++k) {
  19577. targetTrack.values[valueStart + k] -= referenceValue[k];
  19578. }
  19579. }
  19580. }
  19581. }
  19582. targetClip.blendMode = AdditiveAnimationBlendMode;
  19583. return targetClip;
  19584. }
  19585. };
  19586. /**
  19587. * Abstract base class of interpolants over parametric samples.
  19588. *
  19589. * The parameter domain is one dimensional, typically the time or a path
  19590. * along a curve defined by the data.
  19591. *
  19592. * The sample values can have any dimensionality and derived classes may
  19593. * apply special interpretations to the data.
  19594. *
  19595. * This class provides the interval seek in a Template Method, deferring
  19596. * the actual interpolation to derived classes.
  19597. *
  19598. * Time complexity is O(1) for linear access crossing at most two points
  19599. * and O(log N) for random access, where N is the number of positions.
  19600. *
  19601. * References:
  19602. *
  19603. * http://www.oodesign.com/template-method-pattern.html
  19604. *
  19605. */
  19606. class Interpolant {
  19607. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  19608. this.parameterPositions = parameterPositions;
  19609. this._cachedIndex = 0;
  19610. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  19611. this.sampleValues = sampleValues;
  19612. this.valueSize = sampleSize;
  19613. this.settings = null;
  19614. this.DefaultSettings_ = {};
  19615. }
  19616. evaluate(t) {
  19617. const pp = this.parameterPositions;
  19618. let i1 = this._cachedIndex,
  19619. t1 = pp[i1],
  19620. t0 = pp[i1 - 1];
  19621. validate_interval: {
  19622. seek: {
  19623. let right;
  19624. linear_scan: {
  19625. //- See http://jsperf.com/comparison-to-undefined/3
  19626. //- slower code:
  19627. //-
  19628. //- if ( t >= t1 || t1 === undefined ) {
  19629. forward_scan: if (!(t < t1)) {
  19630. for (let giveUpAt = i1 + 2;;) {
  19631. if (t1 === undefined) {
  19632. if (t < t0) break forward_scan; // after end
  19633. i1 = pp.length;
  19634. this._cachedIndex = i1;
  19635. return this.afterEnd_(i1 - 1, t, t0);
  19636. }
  19637. if (i1 === giveUpAt) break; // this loop
  19638. t0 = t1;
  19639. t1 = pp[++i1];
  19640. if (t < t1) {
  19641. // we have arrived at the sought interval
  19642. break seek;
  19643. }
  19644. } // prepare binary search on the right side of the index
  19645. right = pp.length;
  19646. break linear_scan;
  19647. } //- slower code:
  19648. //- if ( t < t0 || t0 === undefined ) {
  19649. if (!(t >= t0)) {
  19650. // looping?
  19651. const t1global = pp[1];
  19652. if (t < t1global) {
  19653. i1 = 2; // + 1, using the scan for the details
  19654. t0 = t1global;
  19655. } // linear reverse scan
  19656. for (let giveUpAt = i1 - 2;;) {
  19657. if (t0 === undefined) {
  19658. // before start
  19659. this._cachedIndex = 0;
  19660. return this.beforeStart_(0, t, t1);
  19661. }
  19662. if (i1 === giveUpAt) break; // this loop
  19663. t1 = t0;
  19664. t0 = pp[--i1 - 1];
  19665. if (t >= t0) {
  19666. // we have arrived at the sought interval
  19667. break seek;
  19668. }
  19669. } // prepare binary search on the left side of the index
  19670. right = i1;
  19671. i1 = 0;
  19672. break linear_scan;
  19673. } // the interval is valid
  19674. break validate_interval;
  19675. } // linear scan
  19676. // binary search
  19677. while (i1 < right) {
  19678. const mid = i1 + right >>> 1;
  19679. if (t < pp[mid]) {
  19680. right = mid;
  19681. } else {
  19682. i1 = mid + 1;
  19683. }
  19684. }
  19685. t1 = pp[i1];
  19686. t0 = pp[i1 - 1]; // check boundary cases, again
  19687. if (t0 === undefined) {
  19688. this._cachedIndex = 0;
  19689. return this.beforeStart_(0, t, t1);
  19690. }
  19691. if (t1 === undefined) {
  19692. i1 = pp.length;
  19693. this._cachedIndex = i1;
  19694. return this.afterEnd_(i1 - 1, t0, t);
  19695. }
  19696. } // seek
  19697. this._cachedIndex = i1;
  19698. this.intervalChanged_(i1, t0, t1);
  19699. } // validate_interval
  19700. return this.interpolate_(i1, t0, t, t1);
  19701. }
  19702. getSettings_() {
  19703. return this.settings || this.DefaultSettings_;
  19704. }
  19705. copySampleValue_(index) {
  19706. // copies a sample value to the result buffer
  19707. const result = this.resultBuffer,
  19708. values = this.sampleValues,
  19709. stride = this.valueSize,
  19710. offset = index * stride;
  19711. for (let i = 0; i !== stride; ++i) {
  19712. result[i] = values[offset + i];
  19713. }
  19714. return result;
  19715. } // Template methods for derived classes:
  19716. interpolate_()
  19717. /* i1, t0, t, t1 */
  19718. {
  19719. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  19720. }
  19721. intervalChanged_()
  19722. /* i1, t0, t1 */
  19723. {// empty
  19724. }
  19725. } // ALIAS DEFINITIONS
  19726. Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
  19727. Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
  19728. /**
  19729. * Fast and simple cubic spline interpolant.
  19730. *
  19731. * It was derived from a Hermitian construction setting the first derivative
  19732. * at each sample position to the linear slope between neighboring positions
  19733. * over their parameter interval.
  19734. */
  19735. class CubicInterpolant extends Interpolant {
  19736. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  19737. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  19738. this._weightPrev = -0;
  19739. this._offsetPrev = -0;
  19740. this._weightNext = -0;
  19741. this._offsetNext = -0;
  19742. this.DefaultSettings_ = {
  19743. endingStart: ZeroCurvatureEnding,
  19744. endingEnd: ZeroCurvatureEnding
  19745. };
  19746. }
  19747. intervalChanged_(i1, t0, t1) {
  19748. const pp = this.parameterPositions;
  19749. let iPrev = i1 - 2,
  19750. iNext = i1 + 1,
  19751. tPrev = pp[iPrev],
  19752. tNext = pp[iNext];
  19753. if (tPrev === undefined) {
  19754. switch (this.getSettings_().endingStart) {
  19755. case ZeroSlopeEnding:
  19756. // f'(t0) = 0
  19757. iPrev = i1;
  19758. tPrev = 2 * t0 - t1;
  19759. break;
  19760. case WrapAroundEnding:
  19761. // use the other end of the curve
  19762. iPrev = pp.length - 2;
  19763. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  19764. break;
  19765. default:
  19766. // ZeroCurvatureEnding
  19767. // f''(t0) = 0 a.k.a. Natural Spline
  19768. iPrev = i1;
  19769. tPrev = t1;
  19770. }
  19771. }
  19772. if (tNext === undefined) {
  19773. switch (this.getSettings_().endingEnd) {
  19774. case ZeroSlopeEnding:
  19775. // f'(tN) = 0
  19776. iNext = i1;
  19777. tNext = 2 * t1 - t0;
  19778. break;
  19779. case WrapAroundEnding:
  19780. // use the other end of the curve
  19781. iNext = 1;
  19782. tNext = t1 + pp[1] - pp[0];
  19783. break;
  19784. default:
  19785. // ZeroCurvatureEnding
  19786. // f''(tN) = 0, a.k.a. Natural Spline
  19787. iNext = i1 - 1;
  19788. tNext = t0;
  19789. }
  19790. }
  19791. const halfDt = (t1 - t0) * 0.5,
  19792. stride = this.valueSize;
  19793. this._weightPrev = halfDt / (t0 - tPrev);
  19794. this._weightNext = halfDt / (tNext - t1);
  19795. this._offsetPrev = iPrev * stride;
  19796. this._offsetNext = iNext * stride;
  19797. }
  19798. interpolate_(i1, t0, t, t1) {
  19799. const result = this.resultBuffer,
  19800. values = this.sampleValues,
  19801. stride = this.valueSize,
  19802. o1 = i1 * stride,
  19803. o0 = o1 - stride,
  19804. oP = this._offsetPrev,
  19805. oN = this._offsetNext,
  19806. wP = this._weightPrev,
  19807. wN = this._weightNext,
  19808. p = (t - t0) / (t1 - t0),
  19809. pp = p * p,
  19810. ppp = pp * p; // evaluate polynomials
  19811. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  19812. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  19813. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  19814. const sN = wN * ppp - wN * pp; // combine data linearly
  19815. for (let i = 0; i !== stride; ++i) {
  19816. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  19817. }
  19818. return result;
  19819. }
  19820. }
  19821. class LinearInterpolant extends Interpolant {
  19822. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  19823. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  19824. }
  19825. interpolate_(i1, t0, t, t1) {
  19826. const result = this.resultBuffer,
  19827. values = this.sampleValues,
  19828. stride = this.valueSize,
  19829. offset1 = i1 * stride,
  19830. offset0 = offset1 - stride,
  19831. weight1 = (t - t0) / (t1 - t0),
  19832. weight0 = 1 - weight1;
  19833. for (let i = 0; i !== stride; ++i) {
  19834. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  19835. }
  19836. return result;
  19837. }
  19838. }
  19839. /**
  19840. *
  19841. * Interpolant that evaluates to the sample value at the position preceeding
  19842. * the parameter.
  19843. */
  19844. class DiscreteInterpolant extends Interpolant {
  19845. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  19846. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  19847. }
  19848. interpolate_(i1
  19849. /*, t0, t, t1 */
  19850. ) {
  19851. return this.copySampleValue_(i1 - 1);
  19852. }
  19853. }
  19854. class KeyframeTrack {
  19855. constructor(name, times, values, interpolation) {
  19856. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  19857. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  19858. this.name = name;
  19859. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  19860. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  19861. this.setInterpolation(interpolation || this.DefaultInterpolation);
  19862. } // Serialization (in static context, because of constructor invocation
  19863. // and automatic invocation of .toJSON):
  19864. static toJSON(track) {
  19865. const trackType = track.constructor;
  19866. let json; // derived classes can define a static toJSON method
  19867. if (trackType.toJSON !== this.toJSON) {
  19868. json = trackType.toJSON(track);
  19869. } else {
  19870. // by default, we assume the data can be serialized as-is
  19871. json = {
  19872. 'name': track.name,
  19873. 'times': AnimationUtils.convertArray(track.times, Array),
  19874. 'values': AnimationUtils.convertArray(track.values, Array)
  19875. };
  19876. const interpolation = track.getInterpolation();
  19877. if (interpolation !== track.DefaultInterpolation) {
  19878. json.interpolation = interpolation;
  19879. }
  19880. }
  19881. json.type = track.ValueTypeName; // mandatory
  19882. return json;
  19883. }
  19884. InterpolantFactoryMethodDiscrete(result) {
  19885. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  19886. }
  19887. InterpolantFactoryMethodLinear(result) {
  19888. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  19889. }
  19890. InterpolantFactoryMethodSmooth(result) {
  19891. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  19892. }
  19893. setInterpolation(interpolation) {
  19894. let factoryMethod;
  19895. switch (interpolation) {
  19896. case InterpolateDiscrete:
  19897. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  19898. break;
  19899. case InterpolateLinear:
  19900. factoryMethod = this.InterpolantFactoryMethodLinear;
  19901. break;
  19902. case InterpolateSmooth:
  19903. factoryMethod = this.InterpolantFactoryMethodSmooth;
  19904. break;
  19905. }
  19906. if (factoryMethod === undefined) {
  19907. const message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
  19908. if (this.createInterpolant === undefined) {
  19909. // fall back to default, unless the default itself is messed up
  19910. if (interpolation !== this.DefaultInterpolation) {
  19911. this.setInterpolation(this.DefaultInterpolation);
  19912. } else {
  19913. throw new Error(message); // fatal, in this case
  19914. }
  19915. }
  19916. console.warn('THREE.KeyframeTrack:', message);
  19917. return this;
  19918. }
  19919. this.createInterpolant = factoryMethod;
  19920. return this;
  19921. }
  19922. getInterpolation() {
  19923. switch (this.createInterpolant) {
  19924. case this.InterpolantFactoryMethodDiscrete:
  19925. return InterpolateDiscrete;
  19926. case this.InterpolantFactoryMethodLinear:
  19927. return InterpolateLinear;
  19928. case this.InterpolantFactoryMethodSmooth:
  19929. return InterpolateSmooth;
  19930. }
  19931. }
  19932. getValueSize() {
  19933. return this.values.length / this.times.length;
  19934. } // move all keyframes either forwards or backwards in time
  19935. shift(timeOffset) {
  19936. if (timeOffset !== 0.0) {
  19937. const times = this.times;
  19938. for (let i = 0, n = times.length; i !== n; ++i) {
  19939. times[i] += timeOffset;
  19940. }
  19941. }
  19942. return this;
  19943. } // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  19944. scale(timeScale) {
  19945. if (timeScale !== 1.0) {
  19946. const times = this.times;
  19947. for (let i = 0, n = times.length; i !== n; ++i) {
  19948. times[i] *= timeScale;
  19949. }
  19950. }
  19951. return this;
  19952. } // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  19953. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  19954. trim(startTime, endTime) {
  19955. const times = this.times,
  19956. nKeys = times.length;
  19957. let from = 0,
  19958. to = nKeys - 1;
  19959. while (from !== nKeys && times[from] < startTime) {
  19960. ++from;
  19961. }
  19962. while (to !== -1 && times[to] > endTime) {
  19963. --to;
  19964. }
  19965. ++to; // inclusive -> exclusive bound
  19966. if (from !== 0 || to !== nKeys) {
  19967. // empty tracks are forbidden, so keep at least one keyframe
  19968. if (from >= to) {
  19969. to = Math.max(to, 1);
  19970. from = to - 1;
  19971. }
  19972. const stride = this.getValueSize();
  19973. this.times = AnimationUtils.arraySlice(times, from, to);
  19974. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  19975. }
  19976. return this;
  19977. } // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  19978. validate() {
  19979. let valid = true;
  19980. const valueSize = this.getValueSize();
  19981. if (valueSize - Math.floor(valueSize) !== 0) {
  19982. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  19983. valid = false;
  19984. }
  19985. const times = this.times,
  19986. values = this.values,
  19987. nKeys = times.length;
  19988. if (nKeys === 0) {
  19989. console.error('THREE.KeyframeTrack: Track is empty.', this);
  19990. valid = false;
  19991. }
  19992. let prevTime = null;
  19993. for (let i = 0; i !== nKeys; i++) {
  19994. const currTime = times[i];
  19995. if (typeof currTime === 'number' && isNaN(currTime)) {
  19996. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  19997. valid = false;
  19998. break;
  19999. }
  20000. if (prevTime !== null && prevTime > currTime) {
  20001. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  20002. valid = false;
  20003. break;
  20004. }
  20005. prevTime = currTime;
  20006. }
  20007. if (values !== undefined) {
  20008. if (AnimationUtils.isTypedArray(values)) {
  20009. for (let i = 0, n = values.length; i !== n; ++i) {
  20010. const value = values[i];
  20011. if (isNaN(value)) {
  20012. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  20013. valid = false;
  20014. break;
  20015. }
  20016. }
  20017. }
  20018. }
  20019. return valid;
  20020. } // removes equivalent sequential keys as common in morph target sequences
  20021. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  20022. optimize() {
  20023. // times or values may be shared with other tracks, so overwriting is unsafe
  20024. const times = AnimationUtils.arraySlice(this.times),
  20025. values = AnimationUtils.arraySlice(this.values),
  20026. stride = this.getValueSize(),
  20027. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  20028. lastIndex = times.length - 1;
  20029. let writeIndex = 1;
  20030. for (let i = 1; i < lastIndex; ++i) {
  20031. let keep = false;
  20032. const time = times[i];
  20033. const timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  20034. if (time !== timeNext && (i !== 1 || time !== times[0])) {
  20035. if (!smoothInterpolation) {
  20036. // remove unnecessary keyframes same as their neighbors
  20037. const offset = i * stride,
  20038. offsetP = offset - stride,
  20039. offsetN = offset + stride;
  20040. for (let j = 0; j !== stride; ++j) {
  20041. const value = values[offset + j];
  20042. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  20043. keep = true;
  20044. break;
  20045. }
  20046. }
  20047. } else {
  20048. keep = true;
  20049. }
  20050. } // in-place compaction
  20051. if (keep) {
  20052. if (i !== writeIndex) {
  20053. times[writeIndex] = times[i];
  20054. const readOffset = i * stride,
  20055. writeOffset = writeIndex * stride;
  20056. for (let j = 0; j !== stride; ++j) {
  20057. values[writeOffset + j] = values[readOffset + j];
  20058. }
  20059. }
  20060. ++writeIndex;
  20061. }
  20062. } // flush last keyframe (compaction looks ahead)
  20063. if (lastIndex > 0) {
  20064. times[writeIndex] = times[lastIndex];
  20065. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  20066. values[writeOffset + j] = values[readOffset + j];
  20067. }
  20068. ++writeIndex;
  20069. }
  20070. if (writeIndex !== times.length) {
  20071. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  20072. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  20073. } else {
  20074. this.times = times;
  20075. this.values = values;
  20076. }
  20077. return this;
  20078. }
  20079. clone() {
  20080. const times = AnimationUtils.arraySlice(this.times, 0);
  20081. const values = AnimationUtils.arraySlice(this.values, 0);
  20082. const TypedKeyframeTrack = this.constructor;
  20083. const track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  20084. track.createInterpolant = this.createInterpolant;
  20085. return track;
  20086. }
  20087. }
  20088. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  20089. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  20090. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  20091. /**
  20092. * A Track of Boolean keyframe values.
  20093. */
  20094. class BooleanKeyframeTrack extends KeyframeTrack {}
  20095. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  20096. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  20097. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  20098. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  20099. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; // Note: Actually this track could have a optimized / compressed
  20100. /**
  20101. * A Track of keyframe values that represent color.
  20102. */
  20103. class ColorKeyframeTrack extends KeyframeTrack {}
  20104. ColorKeyframeTrack.prototype.ValueTypeName = 'color'; // ValueBufferType is inherited
  20105. /**
  20106. * A Track of numeric keyframe values.
  20107. */
  20108. class NumberKeyframeTrack extends KeyframeTrack {}
  20109. NumberKeyframeTrack.prototype.ValueTypeName = 'number'; // ValueBufferType is inherited
  20110. /**
  20111. * Spherical linear unit quaternion interpolant.
  20112. */
  20113. class QuaternionLinearInterpolant extends Interpolant {
  20114. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20115. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  20116. }
  20117. interpolate_(i1, t0, t, t1) {
  20118. const result = this.resultBuffer,
  20119. values = this.sampleValues,
  20120. stride = this.valueSize,
  20121. alpha = (t - t0) / (t1 - t0);
  20122. let offset = i1 * stride;
  20123. for (let end = offset + stride; offset !== end; offset += 4) {
  20124. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  20125. }
  20126. return result;
  20127. }
  20128. }
  20129. /**
  20130. * A Track of quaternion keyframe values.
  20131. */
  20132. class QuaternionKeyframeTrack extends KeyframeTrack {
  20133. InterpolantFactoryMethodLinear(result) {
  20134. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  20135. }
  20136. }
  20137. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; // ValueBufferType is inherited
  20138. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  20139. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  20140. /**
  20141. * A Track that interpolates Strings
  20142. */
  20143. class StringKeyframeTrack extends KeyframeTrack {}
  20144. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  20145. StringKeyframeTrack.prototype.ValueBufferType = Array;
  20146. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  20147. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  20148. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  20149. /**
  20150. * A Track of vectored keyframe values.
  20151. */
  20152. class VectorKeyframeTrack extends KeyframeTrack {}
  20153. VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; // ValueBufferType is inherited
  20154. class AnimationClip {
  20155. constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) {
  20156. this.name = name;
  20157. this.tracks = tracks;
  20158. this.duration = duration;
  20159. this.blendMode = blendMode;
  20160. this.uuid = generateUUID(); // this means it should figure out its duration by scanning the tracks
  20161. if (this.duration < 0) {
  20162. this.resetDuration();
  20163. }
  20164. }
  20165. static parse(json) {
  20166. const tracks = [],
  20167. jsonTracks = json.tracks,
  20168. frameTime = 1.0 / (json.fps || 1.0);
  20169. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  20170. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  20171. }
  20172. const clip = new this(json.name, json.duration, tracks, json.blendMode);
  20173. clip.uuid = json.uuid;
  20174. return clip;
  20175. }
  20176. static toJSON(clip) {
  20177. const tracks = [],
  20178. clipTracks = clip.tracks;
  20179. const json = {
  20180. 'name': clip.name,
  20181. 'duration': clip.duration,
  20182. 'tracks': tracks,
  20183. 'uuid': clip.uuid,
  20184. 'blendMode': clip.blendMode
  20185. };
  20186. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  20187. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  20188. }
  20189. return json;
  20190. }
  20191. static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  20192. const numMorphTargets = morphTargetSequence.length;
  20193. const tracks = [];
  20194. for (let i = 0; i < numMorphTargets; i++) {
  20195. let times = [];
  20196. let values = [];
  20197. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  20198. values.push(0, 1, 0);
  20199. const order = AnimationUtils.getKeyframeOrder(times);
  20200. times = AnimationUtils.sortedArray(times, 1, order);
  20201. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  20202. // last frame as well for perfect loop.
  20203. if (!noLoop && times[0] === 0) {
  20204. times.push(numMorphTargets);
  20205. values.push(values[0]);
  20206. }
  20207. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  20208. }
  20209. return new this(name, -1, tracks);
  20210. }
  20211. static findByName(objectOrClipArray, name) {
  20212. let clipArray = objectOrClipArray;
  20213. if (!Array.isArray(objectOrClipArray)) {
  20214. const o = objectOrClipArray;
  20215. clipArray = o.geometry && o.geometry.animations || o.animations;
  20216. }
  20217. for (let i = 0; i < clipArray.length; i++) {
  20218. if (clipArray[i].name === name) {
  20219. return clipArray[i];
  20220. }
  20221. }
  20222. return null;
  20223. }
  20224. static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  20225. const animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  20226. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  20227. const pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  20228. // patterns like Walk_001, Walk_002, Run_001, Run_002
  20229. for (let i = 0, il = morphTargets.length; i < il; i++) {
  20230. const morphTarget = morphTargets[i];
  20231. const parts = morphTarget.name.match(pattern);
  20232. if (parts && parts.length > 1) {
  20233. const name = parts[1];
  20234. let animationMorphTargets = animationToMorphTargets[name];
  20235. if (!animationMorphTargets) {
  20236. animationToMorphTargets[name] = animationMorphTargets = [];
  20237. }
  20238. animationMorphTargets.push(morphTarget);
  20239. }
  20240. }
  20241. const clips = [];
  20242. for (const name in animationToMorphTargets) {
  20243. clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  20244. }
  20245. return clips;
  20246. } // parse the animation.hierarchy format
  20247. static parseAnimation(animation, bones) {
  20248. if (!animation) {
  20249. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  20250. return null;
  20251. }
  20252. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  20253. // only return track if there are actually keys.
  20254. if (animationKeys.length !== 0) {
  20255. const times = [];
  20256. const values = [];
  20257. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  20258. if (times.length !== 0) {
  20259. destTracks.push(new trackType(trackName, times, values));
  20260. }
  20261. }
  20262. };
  20263. const tracks = [];
  20264. const clipName = animation.name || 'default';
  20265. const fps = animation.fps || 30;
  20266. const blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  20267. let duration = animation.length || -1;
  20268. const hierarchyTracks = animation.hierarchy || [];
  20269. for (let h = 0; h < hierarchyTracks.length; h++) {
  20270. const animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  20271. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  20272. if (animationKeys[0].morphTargets) {
  20273. // figure out all morph targets used in this track
  20274. const morphTargetNames = {};
  20275. let k;
  20276. for (k = 0; k < animationKeys.length; k++) {
  20277. if (animationKeys[k].morphTargets) {
  20278. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  20279. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  20280. }
  20281. }
  20282. } // create a track for each morph target with all zero
  20283. // morphTargetInfluences except for the keys in which
  20284. // the morphTarget is named.
  20285. for (const morphTargetName in morphTargetNames) {
  20286. const times = [];
  20287. const values = [];
  20288. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  20289. const animationKey = animationKeys[k];
  20290. times.push(animationKey.time);
  20291. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  20292. }
  20293. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  20294. }
  20295. duration = morphTargetNames.length * (fps || 1.0);
  20296. } else {
  20297. // ...assume skeletal animation
  20298. const boneName = '.bones[' + bones[h].name + ']';
  20299. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  20300. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  20301. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  20302. }
  20303. }
  20304. if (tracks.length === 0) {
  20305. return null;
  20306. }
  20307. const clip = new this(clipName, duration, tracks, blendMode);
  20308. return clip;
  20309. }
  20310. resetDuration() {
  20311. const tracks = this.tracks;
  20312. let duration = 0;
  20313. for (let i = 0, n = tracks.length; i !== n; ++i) {
  20314. const track = this.tracks[i];
  20315. duration = Math.max(duration, track.times[track.times.length - 1]);
  20316. }
  20317. this.duration = duration;
  20318. return this;
  20319. }
  20320. trim() {
  20321. for (let i = 0; i < this.tracks.length; i++) {
  20322. this.tracks[i].trim(0, this.duration);
  20323. }
  20324. return this;
  20325. }
  20326. validate() {
  20327. let valid = true;
  20328. for (let i = 0; i < this.tracks.length; i++) {
  20329. valid = valid && this.tracks[i].validate();
  20330. }
  20331. return valid;
  20332. }
  20333. optimize() {
  20334. for (let i = 0; i < this.tracks.length; i++) {
  20335. this.tracks[i].optimize();
  20336. }
  20337. return this;
  20338. }
  20339. clone() {
  20340. const tracks = [];
  20341. for (let i = 0; i < this.tracks.length; i++) {
  20342. tracks.push(this.tracks[i].clone());
  20343. }
  20344. return new this.constructor(this.name, this.duration, tracks, this.blendMode);
  20345. }
  20346. toJSON() {
  20347. return this.constructor.toJSON(this);
  20348. }
  20349. }
  20350. function getTrackTypeForValueTypeName(typeName) {
  20351. switch (typeName.toLowerCase()) {
  20352. case 'scalar':
  20353. case 'double':
  20354. case 'float':
  20355. case 'number':
  20356. case 'integer':
  20357. return NumberKeyframeTrack;
  20358. case 'vector':
  20359. case 'vector2':
  20360. case 'vector3':
  20361. case 'vector4':
  20362. return VectorKeyframeTrack;
  20363. case 'color':
  20364. return ColorKeyframeTrack;
  20365. case 'quaternion':
  20366. return QuaternionKeyframeTrack;
  20367. case 'bool':
  20368. case 'boolean':
  20369. return BooleanKeyframeTrack;
  20370. case 'string':
  20371. return StringKeyframeTrack;
  20372. }
  20373. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  20374. }
  20375. function parseKeyframeTrack(json) {
  20376. if (json.type === undefined) {
  20377. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  20378. }
  20379. const trackType = getTrackTypeForValueTypeName(json.type);
  20380. if (json.times === undefined) {
  20381. const times = [],
  20382. values = [];
  20383. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  20384. json.times = times;
  20385. json.values = values;
  20386. } // derived classes can define a static parse method
  20387. if (trackType.parse !== undefined) {
  20388. return trackType.parse(json);
  20389. } else {
  20390. // by default, we assume a constructor compatible with the base
  20391. return new trackType(json.name, json.times, json.values, json.interpolation);
  20392. }
  20393. }
  20394. const Cache = {
  20395. enabled: false,
  20396. files: {},
  20397. add: function (key, file) {
  20398. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  20399. this.files[key] = file;
  20400. },
  20401. get: function (key) {
  20402. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  20403. return this.files[key];
  20404. },
  20405. remove: function (key) {
  20406. delete this.files[key];
  20407. },
  20408. clear: function () {
  20409. this.files = {};
  20410. }
  20411. };
  20412. class LoadingManager {
  20413. constructor(onLoad, onProgress, onError) {
  20414. const scope = this;
  20415. let isLoading = false;
  20416. let itemsLoaded = 0;
  20417. let itemsTotal = 0;
  20418. let urlModifier = undefined;
  20419. const handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  20420. // in the constructor
  20421. this.onStart = undefined;
  20422. this.onLoad = onLoad;
  20423. this.onProgress = onProgress;
  20424. this.onError = onError;
  20425. this.itemStart = function (url) {
  20426. itemsTotal++;
  20427. if (isLoading === false) {
  20428. if (scope.onStart !== undefined) {
  20429. scope.onStart(url, itemsLoaded, itemsTotal);
  20430. }
  20431. }
  20432. isLoading = true;
  20433. };
  20434. this.itemEnd = function (url) {
  20435. itemsLoaded++;
  20436. if (scope.onProgress !== undefined) {
  20437. scope.onProgress(url, itemsLoaded, itemsTotal);
  20438. }
  20439. if (itemsLoaded === itemsTotal) {
  20440. isLoading = false;
  20441. if (scope.onLoad !== undefined) {
  20442. scope.onLoad();
  20443. }
  20444. }
  20445. };
  20446. this.itemError = function (url) {
  20447. if (scope.onError !== undefined) {
  20448. scope.onError(url);
  20449. }
  20450. };
  20451. this.resolveURL = function (url) {
  20452. if (urlModifier) {
  20453. return urlModifier(url);
  20454. }
  20455. return url;
  20456. };
  20457. this.setURLModifier = function (transform) {
  20458. urlModifier = transform;
  20459. return this;
  20460. };
  20461. this.addHandler = function (regex, loader) {
  20462. handlers.push(regex, loader);
  20463. return this;
  20464. };
  20465. this.removeHandler = function (regex) {
  20466. const index = handlers.indexOf(regex);
  20467. if (index !== -1) {
  20468. handlers.splice(index, 2);
  20469. }
  20470. return this;
  20471. };
  20472. this.getHandler = function (file) {
  20473. for (let i = 0, l = handlers.length; i < l; i += 2) {
  20474. const regex = handlers[i];
  20475. const loader = handlers[i + 1];
  20476. if (regex.global) regex.lastIndex = 0; // see #17920
  20477. if (regex.test(file)) {
  20478. return loader;
  20479. }
  20480. }
  20481. return null;
  20482. };
  20483. }
  20484. }
  20485. const DefaultLoadingManager = new LoadingManager();
  20486. class Loader {
  20487. constructor(manager) {
  20488. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  20489. this.crossOrigin = 'anonymous';
  20490. this.withCredentials = false;
  20491. this.path = '';
  20492. this.resourcePath = '';
  20493. this.requestHeader = {};
  20494. }
  20495. load()
  20496. /* url, onLoad, onProgress, onError */
  20497. {}
  20498. loadAsync(url, onProgress) {
  20499. const scope = this;
  20500. return new Promise(function (resolve, reject) {
  20501. scope.load(url, resolve, onProgress, reject);
  20502. });
  20503. }
  20504. parse()
  20505. /* data */
  20506. {}
  20507. setCrossOrigin(crossOrigin) {
  20508. this.crossOrigin = crossOrigin;
  20509. return this;
  20510. }
  20511. setWithCredentials(value) {
  20512. this.withCredentials = value;
  20513. return this;
  20514. }
  20515. setPath(path) {
  20516. this.path = path;
  20517. return this;
  20518. }
  20519. setResourcePath(resourcePath) {
  20520. this.resourcePath = resourcePath;
  20521. return this;
  20522. }
  20523. setRequestHeader(requestHeader) {
  20524. this.requestHeader = requestHeader;
  20525. return this;
  20526. }
  20527. }
  20528. const loading = {};
  20529. class FileLoader extends Loader {
  20530. constructor(manager) {
  20531. super(manager);
  20532. }
  20533. load(url, onLoad, onProgress, onError) {
  20534. if (url === undefined) url = '';
  20535. if (this.path !== undefined) url = this.path + url;
  20536. url = this.manager.resolveURL(url);
  20537. const scope = this;
  20538. const cached = Cache.get(url);
  20539. if (cached !== undefined) {
  20540. scope.manager.itemStart(url);
  20541. setTimeout(function () {
  20542. if (onLoad) onLoad(cached);
  20543. scope.manager.itemEnd(url);
  20544. }, 0);
  20545. return cached;
  20546. } // Check if request is duplicate
  20547. if (loading[url] !== undefined) {
  20548. loading[url].push({
  20549. onLoad: onLoad,
  20550. onProgress: onProgress,
  20551. onError: onError
  20552. });
  20553. return;
  20554. } // Check for data: URI
  20555. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  20556. const dataUriRegexResult = url.match(dataUriRegex);
  20557. let request; // Safari can not handle Data URIs through XMLHttpRequest so process manually
  20558. if (dataUriRegexResult) {
  20559. const mimeType = dataUriRegexResult[1];
  20560. const isBase64 = !!dataUriRegexResult[2];
  20561. let data = dataUriRegexResult[3];
  20562. data = decodeURIComponent(data);
  20563. if (isBase64) data = atob(data);
  20564. try {
  20565. let response;
  20566. const responseType = (this.responseType || '').toLowerCase();
  20567. switch (responseType) {
  20568. case 'arraybuffer':
  20569. case 'blob':
  20570. const view = new Uint8Array(data.length);
  20571. for (let i = 0; i < data.length; i++) {
  20572. view[i] = data.charCodeAt(i);
  20573. }
  20574. if (responseType === 'blob') {
  20575. response = new Blob([view.buffer], {
  20576. type: mimeType
  20577. });
  20578. } else {
  20579. response = view.buffer;
  20580. }
  20581. break;
  20582. case 'document':
  20583. const parser = new DOMParser();
  20584. response = parser.parseFromString(data, mimeType);
  20585. break;
  20586. case 'json':
  20587. response = JSON.parse(data);
  20588. break;
  20589. default:
  20590. // 'text' or other
  20591. response = data;
  20592. break;
  20593. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  20594. setTimeout(function () {
  20595. if (onLoad) onLoad(response);
  20596. scope.manager.itemEnd(url);
  20597. }, 0);
  20598. } catch (error) {
  20599. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  20600. setTimeout(function () {
  20601. if (onError) onError(error);
  20602. scope.manager.itemError(url);
  20603. scope.manager.itemEnd(url);
  20604. }, 0);
  20605. }
  20606. } else {
  20607. // Initialise array for duplicate requests
  20608. loading[url] = [];
  20609. loading[url].push({
  20610. onLoad: onLoad,
  20611. onProgress: onProgress,
  20612. onError: onError
  20613. });
  20614. request = new XMLHttpRequest();
  20615. request.open('GET', url, true);
  20616. request.addEventListener('load', function (event) {
  20617. const response = this.response;
  20618. const callbacks = loading[url];
  20619. delete loading[url];
  20620. if (this.status === 200 || this.status === 0) {
  20621. // Some browsers return HTTP Status 0 when using non-http protocol
  20622. // e.g. 'file://' or 'data://'. Handle as success.
  20623. 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
  20624. // error response bodies as proper responses to requests.
  20625. Cache.add(url, response);
  20626. for (let i = 0, il = callbacks.length; i < il; i++) {
  20627. const callback = callbacks[i];
  20628. if (callback.onLoad) callback.onLoad(response);
  20629. }
  20630. scope.manager.itemEnd(url);
  20631. } else {
  20632. for (let i = 0, il = callbacks.length; i < il; i++) {
  20633. const callback = callbacks[i];
  20634. if (callback.onError) callback.onError(event);
  20635. }
  20636. scope.manager.itemError(url);
  20637. scope.manager.itemEnd(url);
  20638. }
  20639. }, false);
  20640. request.addEventListener('progress', function (event) {
  20641. const callbacks = loading[url];
  20642. for (let i = 0, il = callbacks.length; i < il; i++) {
  20643. const callback = callbacks[i];
  20644. if (callback.onProgress) callback.onProgress(event);
  20645. }
  20646. }, false);
  20647. request.addEventListener('error', function (event) {
  20648. const callbacks = loading[url];
  20649. delete loading[url];
  20650. for (let i = 0, il = callbacks.length; i < il; i++) {
  20651. const callback = callbacks[i];
  20652. if (callback.onError) callback.onError(event);
  20653. }
  20654. scope.manager.itemError(url);
  20655. scope.manager.itemEnd(url);
  20656. }, false);
  20657. request.addEventListener('abort', function (event) {
  20658. const callbacks = loading[url];
  20659. delete loading[url];
  20660. for (let i = 0, il = callbacks.length; i < il; i++) {
  20661. const callback = callbacks[i];
  20662. if (callback.onError) callback.onError(event);
  20663. }
  20664. scope.manager.itemError(url);
  20665. scope.manager.itemEnd(url);
  20666. }, false);
  20667. if (this.responseType !== undefined) request.responseType = this.responseType;
  20668. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  20669. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  20670. for (const header in this.requestHeader) {
  20671. request.setRequestHeader(header, this.requestHeader[header]);
  20672. }
  20673. request.send(null);
  20674. }
  20675. scope.manager.itemStart(url);
  20676. return request;
  20677. }
  20678. setResponseType(value) {
  20679. this.responseType = value;
  20680. return this;
  20681. }
  20682. setMimeType(value) {
  20683. this.mimeType = value;
  20684. return this;
  20685. }
  20686. }
  20687. class AnimationLoader extends Loader {
  20688. constructor(manager) {
  20689. super(manager);
  20690. }
  20691. load(url, onLoad, onProgress, onError) {
  20692. const scope = this;
  20693. const loader = new FileLoader(this.manager);
  20694. loader.setPath(this.path);
  20695. loader.setRequestHeader(this.requestHeader);
  20696. loader.setWithCredentials(this.withCredentials);
  20697. loader.load(url, function (text) {
  20698. try {
  20699. onLoad(scope.parse(JSON.parse(text)));
  20700. } catch (e) {
  20701. if (onError) {
  20702. onError(e);
  20703. } else {
  20704. console.error(e);
  20705. }
  20706. scope.manager.itemError(url);
  20707. }
  20708. }, onProgress, onError);
  20709. }
  20710. parse(json) {
  20711. const animations = [];
  20712. for (let i = 0; i < json.length; i++) {
  20713. const clip = AnimationClip.parse(json[i]);
  20714. animations.push(clip);
  20715. }
  20716. return animations;
  20717. }
  20718. }
  20719. /**
  20720. * Abstract Base class to block based textures loader (dds, pvr, ...)
  20721. *
  20722. * Sub classes have to implement the parse() method which will be used in load().
  20723. */
  20724. class CompressedTextureLoader extends Loader {
  20725. constructor(manager) {
  20726. super(manager);
  20727. }
  20728. load(url, onLoad, onProgress, onError) {
  20729. const scope = this;
  20730. const images = [];
  20731. const texture = new CompressedTexture();
  20732. const loader = new FileLoader(this.manager);
  20733. loader.setPath(this.path);
  20734. loader.setResponseType('arraybuffer');
  20735. loader.setRequestHeader(this.requestHeader);
  20736. loader.setWithCredentials(scope.withCredentials);
  20737. let loaded = 0;
  20738. function loadTexture(i) {
  20739. loader.load(url[i], function (buffer) {
  20740. const texDatas = scope.parse(buffer, true);
  20741. images[i] = {
  20742. width: texDatas.width,
  20743. height: texDatas.height,
  20744. format: texDatas.format,
  20745. mipmaps: texDatas.mipmaps
  20746. };
  20747. loaded += 1;
  20748. if (loaded === 6) {
  20749. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  20750. texture.image = images;
  20751. texture.format = texDatas.format;
  20752. texture.needsUpdate = true;
  20753. if (onLoad) onLoad(texture);
  20754. }
  20755. }, onProgress, onError);
  20756. }
  20757. if (Array.isArray(url)) {
  20758. for (let i = 0, il = url.length; i < il; ++i) {
  20759. loadTexture(i);
  20760. }
  20761. } else {
  20762. // compressed cubemap texture stored in a single DDS file
  20763. loader.load(url, function (buffer) {
  20764. const texDatas = scope.parse(buffer, true);
  20765. if (texDatas.isCubemap) {
  20766. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  20767. for (let f = 0; f < faces; f++) {
  20768. images[f] = {
  20769. mipmaps: []
  20770. };
  20771. for (let i = 0; i < texDatas.mipmapCount; i++) {
  20772. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  20773. images[f].format = texDatas.format;
  20774. images[f].width = texDatas.width;
  20775. images[f].height = texDatas.height;
  20776. }
  20777. }
  20778. texture.image = images;
  20779. } else {
  20780. texture.image.width = texDatas.width;
  20781. texture.image.height = texDatas.height;
  20782. texture.mipmaps = texDatas.mipmaps;
  20783. }
  20784. if (texDatas.mipmapCount === 1) {
  20785. texture.minFilter = LinearFilter;
  20786. }
  20787. texture.format = texDatas.format;
  20788. texture.needsUpdate = true;
  20789. if (onLoad) onLoad(texture);
  20790. }, onProgress, onError);
  20791. }
  20792. return texture;
  20793. }
  20794. }
  20795. class ImageLoader extends Loader {
  20796. constructor(manager) {
  20797. super(manager);
  20798. }
  20799. load(url, onLoad, onProgress, onError) {
  20800. if (this.path !== undefined) url = this.path + url;
  20801. url = this.manager.resolveURL(url);
  20802. const scope = this;
  20803. const cached = Cache.get(url);
  20804. if (cached !== undefined) {
  20805. scope.manager.itemStart(url);
  20806. setTimeout(function () {
  20807. if (onLoad) onLoad(cached);
  20808. scope.manager.itemEnd(url);
  20809. }, 0);
  20810. return cached;
  20811. }
  20812. const image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  20813. function onImageLoad() {
  20814. image.removeEventListener('load', onImageLoad, false);
  20815. image.removeEventListener('error', onImageError, false);
  20816. Cache.add(url, this);
  20817. if (onLoad) onLoad(this);
  20818. scope.manager.itemEnd(url);
  20819. }
  20820. function onImageError(event) {
  20821. image.removeEventListener('load', onImageLoad, false);
  20822. image.removeEventListener('error', onImageError, false);
  20823. if (onError) onError(event);
  20824. scope.manager.itemError(url);
  20825. scope.manager.itemEnd(url);
  20826. }
  20827. image.addEventListener('load', onImageLoad, false);
  20828. image.addEventListener('error', onImageError, false);
  20829. if (url.substr(0, 5) !== 'data:') {
  20830. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  20831. }
  20832. scope.manager.itemStart(url);
  20833. image.src = url;
  20834. return image;
  20835. }
  20836. }
  20837. class CubeTextureLoader extends Loader {
  20838. constructor(manager) {
  20839. super(manager);
  20840. }
  20841. load(urls, onLoad, onProgress, onError) {
  20842. const texture = new CubeTexture();
  20843. const loader = new ImageLoader(this.manager);
  20844. loader.setCrossOrigin(this.crossOrigin);
  20845. loader.setPath(this.path);
  20846. let loaded = 0;
  20847. function loadTexture(i) {
  20848. loader.load(urls[i], function (image) {
  20849. texture.images[i] = image;
  20850. loaded++;
  20851. if (loaded === 6) {
  20852. texture.needsUpdate = true;
  20853. if (onLoad) onLoad(texture);
  20854. }
  20855. }, undefined, onError);
  20856. }
  20857. for (let i = 0; i < urls.length; ++i) {
  20858. loadTexture(i);
  20859. }
  20860. return texture;
  20861. }
  20862. }
  20863. /**
  20864. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  20865. *
  20866. * Sub classes have to implement the parse() method which will be used in load().
  20867. */
  20868. class DataTextureLoader extends Loader {
  20869. constructor(manager) {
  20870. super(manager);
  20871. }
  20872. load(url, onLoad, onProgress, onError) {
  20873. const scope = this;
  20874. const texture = new DataTexture();
  20875. const loader = new FileLoader(this.manager);
  20876. loader.setResponseType('arraybuffer');
  20877. loader.setRequestHeader(this.requestHeader);
  20878. loader.setPath(this.path);
  20879. loader.setWithCredentials(scope.withCredentials);
  20880. loader.load(url, function (buffer) {
  20881. const texData = scope.parse(buffer);
  20882. if (!texData) return;
  20883. if (texData.image !== undefined) {
  20884. texture.image = texData.image;
  20885. } else if (texData.data !== undefined) {
  20886. texture.image.width = texData.width;
  20887. texture.image.height = texData.height;
  20888. texture.image.data = texData.data;
  20889. }
  20890. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  20891. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  20892. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  20893. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  20894. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  20895. if (texData.encoding !== undefined) {
  20896. texture.encoding = texData.encoding;
  20897. }
  20898. if (texData.flipY !== undefined) {
  20899. texture.flipY = texData.flipY;
  20900. }
  20901. if (texData.format !== undefined) {
  20902. texture.format = texData.format;
  20903. }
  20904. if (texData.type !== undefined) {
  20905. texture.type = texData.type;
  20906. }
  20907. if (texData.mipmaps !== undefined) {
  20908. texture.mipmaps = texData.mipmaps;
  20909. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  20910. }
  20911. if (texData.mipmapCount === 1) {
  20912. texture.minFilter = LinearFilter;
  20913. }
  20914. if (texData.generateMipmaps !== undefined) {
  20915. texture.generateMipmaps = texData.generateMipmaps;
  20916. }
  20917. texture.needsUpdate = true;
  20918. if (onLoad) onLoad(texture, texData);
  20919. }, onProgress, onError);
  20920. return texture;
  20921. }
  20922. }
  20923. class TextureLoader extends Loader {
  20924. constructor(manager) {
  20925. super(manager);
  20926. }
  20927. load(url, onLoad, onProgress, onError) {
  20928. const texture = new Texture();
  20929. const loader = new ImageLoader(this.manager);
  20930. loader.setCrossOrigin(this.crossOrigin);
  20931. loader.setPath(this.path);
  20932. loader.load(url, function (image) {
  20933. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  20934. const isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  20935. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  20936. texture.needsUpdate = true;
  20937. if (onLoad !== undefined) {
  20938. onLoad(texture);
  20939. }
  20940. }, onProgress, onError);
  20941. return texture;
  20942. }
  20943. }
  20944. /**
  20945. * Extensible curve object.
  20946. *
  20947. * Some common of curve methods:
  20948. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  20949. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  20950. * .getPoints(), .getSpacedPoints()
  20951. * .getLength()
  20952. * .updateArcLengths()
  20953. *
  20954. * This following curves inherit from THREE.Curve:
  20955. *
  20956. * -- 2D curves --
  20957. * THREE.ArcCurve
  20958. * THREE.CubicBezierCurve
  20959. * THREE.EllipseCurve
  20960. * THREE.LineCurve
  20961. * THREE.QuadraticBezierCurve
  20962. * THREE.SplineCurve
  20963. *
  20964. * -- 3D curves --
  20965. * THREE.CatmullRomCurve3
  20966. * THREE.CubicBezierCurve3
  20967. * THREE.LineCurve3
  20968. * THREE.QuadraticBezierCurve3
  20969. *
  20970. * A series of curves can be represented as a THREE.CurvePath.
  20971. *
  20972. **/
  20973. class Curve {
  20974. constructor() {
  20975. this.type = 'Curve';
  20976. this.arcLengthDivisions = 200;
  20977. } // Virtual base class method to overwrite and implement in subclasses
  20978. // - t [0 .. 1]
  20979. getPoint()
  20980. /* t, optionalTarget */
  20981. {
  20982. console.warn('THREE.Curve: .getPoint() not implemented.');
  20983. return null;
  20984. } // Get point at relative position in curve according to arc length
  20985. // - u [0 .. 1]
  20986. getPointAt(u, optionalTarget) {
  20987. const t = this.getUtoTmapping(u);
  20988. return this.getPoint(t, optionalTarget);
  20989. } // Get sequence of points using getPoint( t )
  20990. getPoints(divisions = 5) {
  20991. const points = [];
  20992. for (let d = 0; d <= divisions; d++) {
  20993. points.push(this.getPoint(d / divisions));
  20994. }
  20995. return points;
  20996. } // Get sequence of points using getPointAt( u )
  20997. getSpacedPoints(divisions = 5) {
  20998. const points = [];
  20999. for (let d = 0; d <= divisions; d++) {
  21000. points.push(this.getPointAt(d / divisions));
  21001. }
  21002. return points;
  21003. } // Get total curve arc length
  21004. getLength() {
  21005. const lengths = this.getLengths();
  21006. return lengths[lengths.length - 1];
  21007. } // Get list of cumulative segment lengths
  21008. getLengths(divisions = this.arcLengthDivisions) {
  21009. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  21010. return this.cacheArcLengths;
  21011. }
  21012. this.needsUpdate = false;
  21013. const cache = [];
  21014. let current,
  21015. last = this.getPoint(0);
  21016. let sum = 0;
  21017. cache.push(0);
  21018. for (let p = 1; p <= divisions; p++) {
  21019. current = this.getPoint(p / divisions);
  21020. sum += current.distanceTo(last);
  21021. cache.push(sum);
  21022. last = current;
  21023. }
  21024. this.cacheArcLengths = cache;
  21025. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  21026. }
  21027. updateArcLengths() {
  21028. this.needsUpdate = true;
  21029. this.getLengths();
  21030. } // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  21031. getUtoTmapping(u, distance) {
  21032. const arcLengths = this.getLengths();
  21033. let i = 0;
  21034. const il = arcLengths.length;
  21035. let targetArcLength; // The targeted u distance value to get
  21036. if (distance) {
  21037. targetArcLength = distance;
  21038. } else {
  21039. targetArcLength = u * arcLengths[il - 1];
  21040. } // binary search for the index with largest value smaller than target u distance
  21041. let low = 0,
  21042. high = il - 1,
  21043. comparison;
  21044. while (low <= high) {
  21045. 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
  21046. comparison = arcLengths[i] - targetArcLength;
  21047. if (comparison < 0) {
  21048. low = i + 1;
  21049. } else if (comparison > 0) {
  21050. high = i - 1;
  21051. } else {
  21052. high = i;
  21053. break; // DONE
  21054. }
  21055. }
  21056. i = high;
  21057. if (arcLengths[i] === targetArcLength) {
  21058. return i / (il - 1);
  21059. } // we could get finer grain at lengths, or use simple interpolation between two points
  21060. const lengthBefore = arcLengths[i];
  21061. const lengthAfter = arcLengths[i + 1];
  21062. const segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  21063. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  21064. const t = (i + segmentFraction) / (il - 1);
  21065. return t;
  21066. } // Returns a unit vector tangent at t
  21067. // In case any sub curve does not implement its tangent derivation,
  21068. // 2 points a small delta apart will be used to find its gradient
  21069. // which seems to give a reasonable approximation
  21070. getTangent(t, optionalTarget) {
  21071. const delta = 0.0001;
  21072. let t1 = t - delta;
  21073. let t2 = t + delta; // Capping in case of danger
  21074. if (t1 < 0) t1 = 0;
  21075. if (t2 > 1) t2 = 1;
  21076. const pt1 = this.getPoint(t1);
  21077. const pt2 = this.getPoint(t2);
  21078. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  21079. tangent.copy(pt2).sub(pt1).normalize();
  21080. return tangent;
  21081. }
  21082. getTangentAt(u, optionalTarget) {
  21083. const t = this.getUtoTmapping(u);
  21084. return this.getTangent(t, optionalTarget);
  21085. }
  21086. computeFrenetFrames(segments, closed) {
  21087. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  21088. const normal = new Vector3();
  21089. const tangents = [];
  21090. const normals = [];
  21091. const binormals = [];
  21092. const vec = new Vector3();
  21093. const mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  21094. for (let i = 0; i <= segments; i++) {
  21095. const u = i / segments;
  21096. tangents[i] = this.getTangentAt(u, new Vector3());
  21097. tangents[i].normalize();
  21098. } // select an initial normal vector perpendicular to the first tangent vector,
  21099. // and in the direction of the minimum tangent xyz component
  21100. normals[0] = new Vector3();
  21101. binormals[0] = new Vector3();
  21102. let min = Number.MAX_VALUE;
  21103. const tx = Math.abs(tangents[0].x);
  21104. const ty = Math.abs(tangents[0].y);
  21105. const tz = Math.abs(tangents[0].z);
  21106. if (tx <= min) {
  21107. min = tx;
  21108. normal.set(1, 0, 0);
  21109. }
  21110. if (ty <= min) {
  21111. min = ty;
  21112. normal.set(0, 1, 0);
  21113. }
  21114. if (tz <= min) {
  21115. normal.set(0, 0, 1);
  21116. }
  21117. vec.crossVectors(tangents[0], normal).normalize();
  21118. normals[0].crossVectors(tangents[0], vec);
  21119. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  21120. for (let i = 1; i <= segments; i++) {
  21121. normals[i] = normals[i - 1].clone();
  21122. binormals[i] = binormals[i - 1].clone();
  21123. vec.crossVectors(tangents[i - 1], tangents[i]);
  21124. if (vec.length() > Number.EPSILON) {
  21125. vec.normalize();
  21126. const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  21127. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  21128. }
  21129. binormals[i].crossVectors(tangents[i], normals[i]);
  21130. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  21131. if (closed === true) {
  21132. let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1));
  21133. theta /= segments;
  21134. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  21135. theta = -theta;
  21136. }
  21137. for (let i = 1; i <= segments; i++) {
  21138. // twist a little...
  21139. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  21140. binormals[i].crossVectors(tangents[i], normals[i]);
  21141. }
  21142. }
  21143. return {
  21144. tangents: tangents,
  21145. normals: normals,
  21146. binormals: binormals
  21147. };
  21148. }
  21149. clone() {
  21150. return new this.constructor().copy(this);
  21151. }
  21152. copy(source) {
  21153. this.arcLengthDivisions = source.arcLengthDivisions;
  21154. return this;
  21155. }
  21156. toJSON() {
  21157. const data = {
  21158. metadata: {
  21159. version: 4.5,
  21160. type: 'Curve',
  21161. generator: 'Curve.toJSON'
  21162. }
  21163. };
  21164. data.arcLengthDivisions = this.arcLengthDivisions;
  21165. data.type = this.type;
  21166. return data;
  21167. }
  21168. fromJSON(json) {
  21169. this.arcLengthDivisions = json.arcLengthDivisions;
  21170. return this;
  21171. }
  21172. }
  21173. class EllipseCurve extends Curve {
  21174. constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) {
  21175. super();
  21176. this.type = 'EllipseCurve';
  21177. this.aX = aX;
  21178. this.aY = aY;
  21179. this.xRadius = xRadius;
  21180. this.yRadius = yRadius;
  21181. this.aStartAngle = aStartAngle;
  21182. this.aEndAngle = aEndAngle;
  21183. this.aClockwise = aClockwise;
  21184. this.aRotation = aRotation;
  21185. }
  21186. getPoint(t, optionalTarget) {
  21187. const point = optionalTarget || new Vector2();
  21188. const twoPi = Math.PI * 2;
  21189. let deltaAngle = this.aEndAngle - this.aStartAngle;
  21190. const samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  21191. while (deltaAngle < 0) deltaAngle += twoPi;
  21192. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  21193. if (deltaAngle < Number.EPSILON) {
  21194. if (samePoints) {
  21195. deltaAngle = 0;
  21196. } else {
  21197. deltaAngle = twoPi;
  21198. }
  21199. }
  21200. if (this.aClockwise === true && !samePoints) {
  21201. if (deltaAngle === twoPi) {
  21202. deltaAngle = -twoPi;
  21203. } else {
  21204. deltaAngle = deltaAngle - twoPi;
  21205. }
  21206. }
  21207. const angle = this.aStartAngle + t * deltaAngle;
  21208. let x = this.aX + this.xRadius * Math.cos(angle);
  21209. let y = this.aY + this.yRadius * Math.sin(angle);
  21210. if (this.aRotation !== 0) {
  21211. const cos = Math.cos(this.aRotation);
  21212. const sin = Math.sin(this.aRotation);
  21213. const tx = x - this.aX;
  21214. const ty = y - this.aY; // Rotate the point about the center of the ellipse.
  21215. x = tx * cos - ty * sin + this.aX;
  21216. y = tx * sin + ty * cos + this.aY;
  21217. }
  21218. return point.set(x, y);
  21219. }
  21220. copy(source) {
  21221. super.copy(source);
  21222. this.aX = source.aX;
  21223. this.aY = source.aY;
  21224. this.xRadius = source.xRadius;
  21225. this.yRadius = source.yRadius;
  21226. this.aStartAngle = source.aStartAngle;
  21227. this.aEndAngle = source.aEndAngle;
  21228. this.aClockwise = source.aClockwise;
  21229. this.aRotation = source.aRotation;
  21230. return this;
  21231. }
  21232. toJSON() {
  21233. const data = super.toJSON();
  21234. data.aX = this.aX;
  21235. data.aY = this.aY;
  21236. data.xRadius = this.xRadius;
  21237. data.yRadius = this.yRadius;
  21238. data.aStartAngle = this.aStartAngle;
  21239. data.aEndAngle = this.aEndAngle;
  21240. data.aClockwise = this.aClockwise;
  21241. data.aRotation = this.aRotation;
  21242. return data;
  21243. }
  21244. fromJSON(json) {
  21245. super.fromJSON(json);
  21246. this.aX = json.aX;
  21247. this.aY = json.aY;
  21248. this.xRadius = json.xRadius;
  21249. this.yRadius = json.yRadius;
  21250. this.aStartAngle = json.aStartAngle;
  21251. this.aEndAngle = json.aEndAngle;
  21252. this.aClockwise = json.aClockwise;
  21253. this.aRotation = json.aRotation;
  21254. return this;
  21255. }
  21256. }
  21257. EllipseCurve.prototype.isEllipseCurve = true;
  21258. class ArcCurve extends EllipseCurve {
  21259. constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  21260. super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  21261. this.type = 'ArcCurve';
  21262. }
  21263. }
  21264. ArcCurve.prototype.isArcCurve = true;
  21265. /**
  21266. * Centripetal CatmullRom Curve - which is useful for avoiding
  21267. * cusps and self-intersections in non-uniform catmull rom curves.
  21268. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  21269. *
  21270. * curve.type accepts centripetal(default), chordal and catmullrom
  21271. * curve.tension is used for catmullrom which defaults to 0.5
  21272. */
  21273. /*
  21274. Based on an optimized c++ solution in
  21275. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  21276. - http://ideone.com/NoEbVM
  21277. This CubicPoly class could be used for reusing some variables and calculations,
  21278. but for three.js curve use, it could be possible inlined and flatten into a single function call
  21279. which can be placed in CurveUtils.
  21280. */
  21281. function CubicPoly() {
  21282. let c0 = 0,
  21283. c1 = 0,
  21284. c2 = 0,
  21285. c3 = 0;
  21286. /*
  21287. * Compute coefficients for a cubic polynomial
  21288. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  21289. * such that
  21290. * p(0) = x0, p(1) = x1
  21291. * and
  21292. * p'(0) = t0, p'(1) = t1.
  21293. */
  21294. function init(x0, x1, t0, t1) {
  21295. c0 = x0;
  21296. c1 = t0;
  21297. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  21298. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  21299. }
  21300. return {
  21301. initCatmullRom: function (x0, x1, x2, x3, tension) {
  21302. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  21303. },
  21304. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  21305. // compute tangents when parameterized in [t1,t2]
  21306. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  21307. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  21308. t1 *= dt1;
  21309. t2 *= dt1;
  21310. init(x1, x2, t1, t2);
  21311. },
  21312. calc: function (t) {
  21313. const t2 = t * t;
  21314. const t3 = t2 * t;
  21315. return c0 + c1 * t + c2 * t2 + c3 * t3;
  21316. }
  21317. };
  21318. } //
  21319. const tmp = new Vector3();
  21320. const px = new CubicPoly(),
  21321. py = new CubicPoly(),
  21322. pz = new CubicPoly();
  21323. class CatmullRomCurve3 extends Curve {
  21324. constructor(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  21325. super();
  21326. this.type = 'CatmullRomCurve3';
  21327. this.points = points;
  21328. this.closed = closed;
  21329. this.curveType = curveType;
  21330. this.tension = tension;
  21331. }
  21332. getPoint(t, optionalTarget = new Vector3()) {
  21333. const point = optionalTarget;
  21334. const points = this.points;
  21335. const l = points.length;
  21336. const p = (l - (this.closed ? 0 : 1)) * t;
  21337. let intPoint = Math.floor(p);
  21338. let weight = p - intPoint;
  21339. if (this.closed) {
  21340. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  21341. } else if (weight === 0 && intPoint === l - 1) {
  21342. intPoint = l - 2;
  21343. weight = 1;
  21344. }
  21345. let p0, p3; // 4 points (p1 & p2 defined below)
  21346. if (this.closed || intPoint > 0) {
  21347. p0 = points[(intPoint - 1) % l];
  21348. } else {
  21349. // extrapolate first point
  21350. tmp.subVectors(points[0], points[1]).add(points[0]);
  21351. p0 = tmp;
  21352. }
  21353. const p1 = points[intPoint % l];
  21354. const p2 = points[(intPoint + 1) % l];
  21355. if (this.closed || intPoint + 2 < l) {
  21356. p3 = points[(intPoint + 2) % l];
  21357. } else {
  21358. // extrapolate last point
  21359. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  21360. p3 = tmp;
  21361. }
  21362. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  21363. // init Centripetal / Chordal Catmull-Rom
  21364. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  21365. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  21366. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  21367. let dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  21368. if (dt1 < 1e-4) dt1 = 1.0;
  21369. if (dt0 < 1e-4) dt0 = dt1;
  21370. if (dt2 < 1e-4) dt2 = dt1;
  21371. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  21372. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  21373. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  21374. } else if (this.curveType === 'catmullrom') {
  21375. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  21376. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  21377. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  21378. }
  21379. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  21380. return point;
  21381. }
  21382. copy(source) {
  21383. super.copy(source);
  21384. this.points = [];
  21385. for (let i = 0, l = source.points.length; i < l; i++) {
  21386. const point = source.points[i];
  21387. this.points.push(point.clone());
  21388. }
  21389. this.closed = source.closed;
  21390. this.curveType = source.curveType;
  21391. this.tension = source.tension;
  21392. return this;
  21393. }
  21394. toJSON() {
  21395. const data = super.toJSON();
  21396. data.points = [];
  21397. for (let i = 0, l = this.points.length; i < l; i++) {
  21398. const point = this.points[i];
  21399. data.points.push(point.toArray());
  21400. }
  21401. data.closed = this.closed;
  21402. data.curveType = this.curveType;
  21403. data.tension = this.tension;
  21404. return data;
  21405. }
  21406. fromJSON(json) {
  21407. super.fromJSON(json);
  21408. this.points = [];
  21409. for (let i = 0, l = json.points.length; i < l; i++) {
  21410. const point = json.points[i];
  21411. this.points.push(new Vector3().fromArray(point));
  21412. }
  21413. this.closed = json.closed;
  21414. this.curveType = json.curveType;
  21415. this.tension = json.tension;
  21416. return this;
  21417. }
  21418. }
  21419. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  21420. /**
  21421. * Bezier Curves formulas obtained from
  21422. * http://en.wikipedia.org/wiki/Bézier_curve
  21423. */
  21424. function CatmullRom(t, p0, p1, p2, p3) {
  21425. const v0 = (p2 - p0) * 0.5;
  21426. const v1 = (p3 - p1) * 0.5;
  21427. const t2 = t * t;
  21428. const t3 = t * t2;
  21429. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  21430. } //
  21431. function QuadraticBezierP0(t, p) {
  21432. const k = 1 - t;
  21433. return k * k * p;
  21434. }
  21435. function QuadraticBezierP1(t, p) {
  21436. return 2 * (1 - t) * t * p;
  21437. }
  21438. function QuadraticBezierP2(t, p) {
  21439. return t * t * p;
  21440. }
  21441. function QuadraticBezier(t, p0, p1, p2) {
  21442. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  21443. } //
  21444. function CubicBezierP0(t, p) {
  21445. const k = 1 - t;
  21446. return k * k * k * p;
  21447. }
  21448. function CubicBezierP1(t, p) {
  21449. const k = 1 - t;
  21450. return 3 * k * k * t * p;
  21451. }
  21452. function CubicBezierP2(t, p) {
  21453. return 3 * (1 - t) * t * t * p;
  21454. }
  21455. function CubicBezierP3(t, p) {
  21456. return t * t * t * p;
  21457. }
  21458. function CubicBezier(t, p0, p1, p2, p3) {
  21459. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  21460. }
  21461. class CubicBezierCurve extends Curve {
  21462. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  21463. super();
  21464. this.type = 'CubicBezierCurve';
  21465. this.v0 = v0;
  21466. this.v1 = v1;
  21467. this.v2 = v2;
  21468. this.v3 = v3;
  21469. }
  21470. getPoint(t, optionalTarget = new Vector2()) {
  21471. const point = optionalTarget;
  21472. const v0 = this.v0,
  21473. v1 = this.v1,
  21474. v2 = this.v2,
  21475. v3 = this.v3;
  21476. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  21477. return point;
  21478. }
  21479. copy(source) {
  21480. super.copy(source);
  21481. this.v0.copy(source.v0);
  21482. this.v1.copy(source.v1);
  21483. this.v2.copy(source.v2);
  21484. this.v3.copy(source.v3);
  21485. return this;
  21486. }
  21487. toJSON() {
  21488. const data = super.toJSON();
  21489. data.v0 = this.v0.toArray();
  21490. data.v1 = this.v1.toArray();
  21491. data.v2 = this.v2.toArray();
  21492. data.v3 = this.v3.toArray();
  21493. return data;
  21494. }
  21495. fromJSON(json) {
  21496. super.fromJSON(json);
  21497. this.v0.fromArray(json.v0);
  21498. this.v1.fromArray(json.v1);
  21499. this.v2.fromArray(json.v2);
  21500. this.v3.fromArray(json.v3);
  21501. return this;
  21502. }
  21503. }
  21504. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  21505. class CubicBezierCurve3 extends Curve {
  21506. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  21507. super();
  21508. this.type = 'CubicBezierCurve3';
  21509. this.v0 = v0;
  21510. this.v1 = v1;
  21511. this.v2 = v2;
  21512. this.v3 = v3;
  21513. }
  21514. getPoint(t, optionalTarget = new Vector3()) {
  21515. const point = optionalTarget;
  21516. const v0 = this.v0,
  21517. v1 = this.v1,
  21518. v2 = this.v2,
  21519. v3 = this.v3;
  21520. 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));
  21521. return point;
  21522. }
  21523. copy(source) {
  21524. super.copy(source);
  21525. this.v0.copy(source.v0);
  21526. this.v1.copy(source.v1);
  21527. this.v2.copy(source.v2);
  21528. this.v3.copy(source.v3);
  21529. return this;
  21530. }
  21531. toJSON() {
  21532. const data = super.toJSON();
  21533. data.v0 = this.v0.toArray();
  21534. data.v1 = this.v1.toArray();
  21535. data.v2 = this.v2.toArray();
  21536. data.v3 = this.v3.toArray();
  21537. return data;
  21538. }
  21539. fromJSON(json) {
  21540. super.fromJSON(json);
  21541. this.v0.fromArray(json.v0);
  21542. this.v1.fromArray(json.v1);
  21543. this.v2.fromArray(json.v2);
  21544. this.v3.fromArray(json.v3);
  21545. return this;
  21546. }
  21547. }
  21548. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  21549. class LineCurve extends Curve {
  21550. constructor(v1 = new Vector2(), v2 = new Vector2()) {
  21551. super();
  21552. this.type = 'LineCurve';
  21553. this.v1 = v1;
  21554. this.v2 = v2;
  21555. }
  21556. getPoint(t, optionalTarget = new Vector2()) {
  21557. const point = optionalTarget;
  21558. if (t === 1) {
  21559. point.copy(this.v2);
  21560. } else {
  21561. point.copy(this.v2).sub(this.v1);
  21562. point.multiplyScalar(t).add(this.v1);
  21563. }
  21564. return point;
  21565. } // Line curve is linear, so we can overwrite default getPointAt
  21566. getPointAt(u, optionalTarget) {
  21567. return this.getPoint(u, optionalTarget);
  21568. }
  21569. getTangent(t, optionalTarget) {
  21570. const tangent = optionalTarget || new Vector2();
  21571. tangent.copy(this.v2).sub(this.v1).normalize();
  21572. return tangent;
  21573. }
  21574. copy(source) {
  21575. super.copy(source);
  21576. this.v1.copy(source.v1);
  21577. this.v2.copy(source.v2);
  21578. return this;
  21579. }
  21580. toJSON() {
  21581. const data = super.toJSON();
  21582. data.v1 = this.v1.toArray();
  21583. data.v2 = this.v2.toArray();
  21584. return data;
  21585. }
  21586. fromJSON(json) {
  21587. super.fromJSON(json);
  21588. this.v1.fromArray(json.v1);
  21589. this.v2.fromArray(json.v2);
  21590. return this;
  21591. }
  21592. }
  21593. LineCurve.prototype.isLineCurve = true;
  21594. class LineCurve3 extends Curve {
  21595. constructor(v1 = new Vector3(), v2 = new Vector3()) {
  21596. super();
  21597. this.type = 'LineCurve3';
  21598. this.isLineCurve3 = true;
  21599. this.v1 = v1;
  21600. this.v2 = v2;
  21601. }
  21602. getPoint(t, optionalTarget = new Vector3()) {
  21603. const point = optionalTarget;
  21604. if (t === 1) {
  21605. point.copy(this.v2);
  21606. } else {
  21607. point.copy(this.v2).sub(this.v1);
  21608. point.multiplyScalar(t).add(this.v1);
  21609. }
  21610. return point;
  21611. } // Line curve is linear, so we can overwrite default getPointAt
  21612. getPointAt(u, optionalTarget) {
  21613. return this.getPoint(u, optionalTarget);
  21614. }
  21615. copy(source) {
  21616. super.copy(source);
  21617. this.v1.copy(source.v1);
  21618. this.v2.copy(source.v2);
  21619. return this;
  21620. }
  21621. toJSON() {
  21622. const data = super.toJSON();
  21623. data.v1 = this.v1.toArray();
  21624. data.v2 = this.v2.toArray();
  21625. return data;
  21626. }
  21627. fromJSON(json) {
  21628. super.fromJSON(json);
  21629. this.v1.fromArray(json.v1);
  21630. this.v2.fromArray(json.v2);
  21631. return this;
  21632. }
  21633. }
  21634. class QuadraticBezierCurve extends Curve {
  21635. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  21636. super();
  21637. this.type = 'QuadraticBezierCurve';
  21638. this.v0 = v0;
  21639. this.v1 = v1;
  21640. this.v2 = v2;
  21641. }
  21642. getPoint(t, optionalTarget = new Vector2()) {
  21643. const point = optionalTarget;
  21644. const v0 = this.v0,
  21645. v1 = this.v1,
  21646. v2 = this.v2;
  21647. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  21648. return point;
  21649. }
  21650. copy(source) {
  21651. super.copy(source);
  21652. this.v0.copy(source.v0);
  21653. this.v1.copy(source.v1);
  21654. this.v2.copy(source.v2);
  21655. return this;
  21656. }
  21657. toJSON() {
  21658. const data = super.toJSON();
  21659. data.v0 = this.v0.toArray();
  21660. data.v1 = this.v1.toArray();
  21661. data.v2 = this.v2.toArray();
  21662. return data;
  21663. }
  21664. fromJSON(json) {
  21665. super.fromJSON(json);
  21666. this.v0.fromArray(json.v0);
  21667. this.v1.fromArray(json.v1);
  21668. this.v2.fromArray(json.v2);
  21669. return this;
  21670. }
  21671. }
  21672. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  21673. class QuadraticBezierCurve3 extends Curve {
  21674. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  21675. super();
  21676. this.type = 'QuadraticBezierCurve3';
  21677. this.v0 = v0;
  21678. this.v1 = v1;
  21679. this.v2 = v2;
  21680. }
  21681. getPoint(t, optionalTarget = new Vector3()) {
  21682. const point = optionalTarget;
  21683. const v0 = this.v0,
  21684. v1 = this.v1,
  21685. v2 = this.v2;
  21686. 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));
  21687. return point;
  21688. }
  21689. copy(source) {
  21690. super.copy(source);
  21691. this.v0.copy(source.v0);
  21692. this.v1.copy(source.v1);
  21693. this.v2.copy(source.v2);
  21694. return this;
  21695. }
  21696. toJSON() {
  21697. const data = super.toJSON();
  21698. data.v0 = this.v0.toArray();
  21699. data.v1 = this.v1.toArray();
  21700. data.v2 = this.v2.toArray();
  21701. return data;
  21702. }
  21703. fromJSON(json) {
  21704. super.fromJSON(json);
  21705. this.v0.fromArray(json.v0);
  21706. this.v1.fromArray(json.v1);
  21707. this.v2.fromArray(json.v2);
  21708. return this;
  21709. }
  21710. }
  21711. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  21712. class SplineCurve extends Curve {
  21713. constructor(points = []) {
  21714. super();
  21715. this.type = 'SplineCurve';
  21716. this.points = points;
  21717. }
  21718. getPoint(t, optionalTarget = new Vector2()) {
  21719. const point = optionalTarget;
  21720. const points = this.points;
  21721. const p = (points.length - 1) * t;
  21722. const intPoint = Math.floor(p);
  21723. const weight = p - intPoint;
  21724. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  21725. const p1 = points[intPoint];
  21726. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  21727. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  21728. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  21729. return point;
  21730. }
  21731. copy(source) {
  21732. super.copy(source);
  21733. this.points = [];
  21734. for (let i = 0, l = source.points.length; i < l; i++) {
  21735. const point = source.points[i];
  21736. this.points.push(point.clone());
  21737. }
  21738. return this;
  21739. }
  21740. toJSON() {
  21741. const data = super.toJSON();
  21742. data.points = [];
  21743. for (let i = 0, l = this.points.length; i < l; i++) {
  21744. const point = this.points[i];
  21745. data.points.push(point.toArray());
  21746. }
  21747. return data;
  21748. }
  21749. fromJSON(json) {
  21750. super.fromJSON(json);
  21751. this.points = [];
  21752. for (let i = 0, l = json.points.length; i < l; i++) {
  21753. const point = json.points[i];
  21754. this.points.push(new Vector2().fromArray(point));
  21755. }
  21756. return this;
  21757. }
  21758. }
  21759. SplineCurve.prototype.isSplineCurve = true;
  21760. var Curves = /*#__PURE__*/Object.freeze({
  21761. __proto__: null,
  21762. ArcCurve: ArcCurve,
  21763. CatmullRomCurve3: CatmullRomCurve3,
  21764. CubicBezierCurve: CubicBezierCurve,
  21765. CubicBezierCurve3: CubicBezierCurve3,
  21766. EllipseCurve: EllipseCurve,
  21767. LineCurve: LineCurve,
  21768. LineCurve3: LineCurve3,
  21769. QuadraticBezierCurve: QuadraticBezierCurve,
  21770. QuadraticBezierCurve3: QuadraticBezierCurve3,
  21771. SplineCurve: SplineCurve
  21772. });
  21773. /**************************************************************
  21774. * Curved Path - a curve path is simply a array of connected
  21775. * curves, but retains the api of a curve
  21776. **************************************************************/
  21777. class CurvePath extends Curve {
  21778. constructor() {
  21779. super();
  21780. this.type = 'CurvePath';
  21781. this.curves = [];
  21782. this.autoClose = false; // Automatically closes the path
  21783. }
  21784. add(curve) {
  21785. this.curves.push(curve);
  21786. }
  21787. closePath() {
  21788. // Add a line curve if start and end of lines are not connected
  21789. const startPoint = this.curves[0].getPoint(0);
  21790. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  21791. if (!startPoint.equals(endPoint)) {
  21792. this.curves.push(new LineCurve(endPoint, startPoint));
  21793. }
  21794. } // To get accurate point with reference to
  21795. // entire path distance at time t,
  21796. // following has to be done:
  21797. // 1. Length of each sub path have to be known
  21798. // 2. Locate and identify type of curve
  21799. // 3. Get t for the curve
  21800. // 4. Return curve.getPointAt(t')
  21801. getPoint(t) {
  21802. const d = t * this.getLength();
  21803. const curveLengths = this.getCurveLengths();
  21804. let i = 0; // To think about boundaries points.
  21805. while (i < curveLengths.length) {
  21806. if (curveLengths[i] >= d) {
  21807. const diff = curveLengths[i] - d;
  21808. const curve = this.curves[i];
  21809. const segmentLength = curve.getLength();
  21810. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  21811. return curve.getPointAt(u);
  21812. }
  21813. i++;
  21814. }
  21815. return null; // loop where sum != 0, sum > d , sum+1 <d
  21816. } // We cannot use the default THREE.Curve getPoint() with getLength() because in
  21817. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  21818. // getPoint() depends on getLength
  21819. getLength() {
  21820. const lens = this.getCurveLengths();
  21821. return lens[lens.length - 1];
  21822. } // cacheLengths must be recalculated.
  21823. updateArcLengths() {
  21824. this.needsUpdate = true;
  21825. this.cacheLengths = null;
  21826. this.getCurveLengths();
  21827. } // Compute lengths and cache them
  21828. // We cannot overwrite getLengths() because UtoT mapping uses it.
  21829. getCurveLengths() {
  21830. // We use cache values if curves and cache array are same length
  21831. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  21832. return this.cacheLengths;
  21833. } // Get length of sub-curve
  21834. // Push sums into cached array
  21835. const lengths = [];
  21836. let sums = 0;
  21837. for (let i = 0, l = this.curves.length; i < l; i++) {
  21838. sums += this.curves[i].getLength();
  21839. lengths.push(sums);
  21840. }
  21841. this.cacheLengths = lengths;
  21842. return lengths;
  21843. }
  21844. getSpacedPoints(divisions = 40) {
  21845. const points = [];
  21846. for (let i = 0; i <= divisions; i++) {
  21847. points.push(this.getPoint(i / divisions));
  21848. }
  21849. if (this.autoClose) {
  21850. points.push(points[0]);
  21851. }
  21852. return points;
  21853. }
  21854. getPoints(divisions = 12) {
  21855. const points = [];
  21856. let last;
  21857. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  21858. const curve = curves[i];
  21859. const resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  21860. const pts = curve.getPoints(resolution);
  21861. for (let j = 0; j < pts.length; j++) {
  21862. const point = pts[j];
  21863. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  21864. points.push(point);
  21865. last = point;
  21866. }
  21867. }
  21868. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  21869. points.push(points[0]);
  21870. }
  21871. return points;
  21872. }
  21873. copy(source) {
  21874. super.copy(source);
  21875. this.curves = [];
  21876. for (let i = 0, l = source.curves.length; i < l; i++) {
  21877. const curve = source.curves[i];
  21878. this.curves.push(curve.clone());
  21879. }
  21880. this.autoClose = source.autoClose;
  21881. return this;
  21882. }
  21883. toJSON() {
  21884. const data = super.toJSON();
  21885. data.autoClose = this.autoClose;
  21886. data.curves = [];
  21887. for (let i = 0, l = this.curves.length; i < l; i++) {
  21888. const curve = this.curves[i];
  21889. data.curves.push(curve.toJSON());
  21890. }
  21891. return data;
  21892. }
  21893. fromJSON(json) {
  21894. super.fromJSON(json);
  21895. this.autoClose = json.autoClose;
  21896. this.curves = [];
  21897. for (let i = 0, l = json.curves.length; i < l; i++) {
  21898. const curve = json.curves[i];
  21899. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  21900. }
  21901. return this;
  21902. }
  21903. }
  21904. class Path extends CurvePath {
  21905. constructor(points) {
  21906. super();
  21907. this.type = 'Path';
  21908. this.currentPoint = new Vector2();
  21909. if (points) {
  21910. this.setFromPoints(points);
  21911. }
  21912. }
  21913. setFromPoints(points) {
  21914. this.moveTo(points[0].x, points[0].y);
  21915. for (let i = 1, l = points.length; i < l; i++) {
  21916. this.lineTo(points[i].x, points[i].y);
  21917. }
  21918. return this;
  21919. }
  21920. moveTo(x, y) {
  21921. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  21922. return this;
  21923. }
  21924. lineTo(x, y) {
  21925. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  21926. this.curves.push(curve);
  21927. this.currentPoint.set(x, y);
  21928. return this;
  21929. }
  21930. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  21931. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  21932. this.curves.push(curve);
  21933. this.currentPoint.set(aX, aY);
  21934. return this;
  21935. }
  21936. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  21937. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  21938. this.curves.push(curve);
  21939. this.currentPoint.set(aX, aY);
  21940. return this;
  21941. }
  21942. splineThru(pts
  21943. /*Array of Vector*/
  21944. ) {
  21945. const npts = [this.currentPoint.clone()].concat(pts);
  21946. const curve = new SplineCurve(npts);
  21947. this.curves.push(curve);
  21948. this.currentPoint.copy(pts[pts.length - 1]);
  21949. return this;
  21950. }
  21951. arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  21952. const x0 = this.currentPoint.x;
  21953. const y0 = this.currentPoint.y;
  21954. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  21955. return this;
  21956. }
  21957. absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  21958. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  21959. return this;
  21960. }
  21961. ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  21962. const x0 = this.currentPoint.x;
  21963. const y0 = this.currentPoint.y;
  21964. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  21965. return this;
  21966. }
  21967. absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  21968. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  21969. if (this.curves.length > 0) {
  21970. // if a previous curve is present, attempt to join
  21971. const firstPoint = curve.getPoint(0);
  21972. if (!firstPoint.equals(this.currentPoint)) {
  21973. this.lineTo(firstPoint.x, firstPoint.y);
  21974. }
  21975. }
  21976. this.curves.push(curve);
  21977. const lastPoint = curve.getPoint(1);
  21978. this.currentPoint.copy(lastPoint);
  21979. return this;
  21980. }
  21981. copy(source) {
  21982. super.copy(source);
  21983. this.currentPoint.copy(source.currentPoint);
  21984. return this;
  21985. }
  21986. toJSON() {
  21987. const data = super.toJSON();
  21988. data.currentPoint = this.currentPoint.toArray();
  21989. return data;
  21990. }
  21991. fromJSON(json) {
  21992. super.fromJSON(json);
  21993. this.currentPoint.fromArray(json.currentPoint);
  21994. return this;
  21995. }
  21996. }
  21997. class Shape extends Path {
  21998. constructor(points) {
  21999. super(points);
  22000. this.uuid = generateUUID();
  22001. this.type = 'Shape';
  22002. this.holes = [];
  22003. }
  22004. getPointsHoles(divisions) {
  22005. const holesPts = [];
  22006. for (let i = 0, l = this.holes.length; i < l; i++) {
  22007. holesPts[i] = this.holes[i].getPoints(divisions);
  22008. }
  22009. return holesPts;
  22010. } // get points of shape and holes (keypoints based on segments parameter)
  22011. extractPoints(divisions) {
  22012. return {
  22013. shape: this.getPoints(divisions),
  22014. holes: this.getPointsHoles(divisions)
  22015. };
  22016. }
  22017. copy(source) {
  22018. super.copy(source);
  22019. this.holes = [];
  22020. for (let i = 0, l = source.holes.length; i < l; i++) {
  22021. const hole = source.holes[i];
  22022. this.holes.push(hole.clone());
  22023. }
  22024. return this;
  22025. }
  22026. toJSON() {
  22027. const data = super.toJSON();
  22028. data.uuid = this.uuid;
  22029. data.holes = [];
  22030. for (let i = 0, l = this.holes.length; i < l; i++) {
  22031. const hole = this.holes[i];
  22032. data.holes.push(hole.toJSON());
  22033. }
  22034. return data;
  22035. }
  22036. fromJSON(json) {
  22037. super.fromJSON(json);
  22038. this.uuid = json.uuid;
  22039. this.holes = [];
  22040. for (let i = 0, l = json.holes.length; i < l; i++) {
  22041. const hole = json.holes[i];
  22042. this.holes.push(new Path().fromJSON(hole));
  22043. }
  22044. return this;
  22045. }
  22046. }
  22047. class Light extends Object3D {
  22048. constructor(color, intensity = 1) {
  22049. super();
  22050. this.type = 'Light';
  22051. this.color = new Color(color);
  22052. this.intensity = intensity;
  22053. }
  22054. dispose() {// Empty here in base class; some subclasses override.
  22055. }
  22056. copy(source) {
  22057. super.copy(source);
  22058. this.color.copy(source.color);
  22059. this.intensity = source.intensity;
  22060. return this;
  22061. }
  22062. toJSON(meta) {
  22063. const data = super.toJSON(meta);
  22064. data.object.color = this.color.getHex();
  22065. data.object.intensity = this.intensity;
  22066. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  22067. if (this.distance !== undefined) data.object.distance = this.distance;
  22068. if (this.angle !== undefined) data.object.angle = this.angle;
  22069. if (this.decay !== undefined) data.object.decay = this.decay;
  22070. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  22071. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  22072. return data;
  22073. }
  22074. }
  22075. Light.prototype.isLight = true;
  22076. class HemisphereLight extends Light {
  22077. constructor(skyColor, groundColor, intensity) {
  22078. super(skyColor, intensity);
  22079. this.type = 'HemisphereLight';
  22080. this.position.copy(Object3D.DefaultUp);
  22081. this.updateMatrix();
  22082. this.groundColor = new Color(groundColor);
  22083. }
  22084. copy(source) {
  22085. Light.prototype.copy.call(this, source);
  22086. this.groundColor.copy(source.groundColor);
  22087. return this;
  22088. }
  22089. }
  22090. HemisphereLight.prototype.isHemisphereLight = true;
  22091. const _projScreenMatrix$1 = /*@__PURE__*/new Matrix4();
  22092. const _lightPositionWorld$1 = /*@__PURE__*/new Vector3();
  22093. const _lookTarget$1 = /*@__PURE__*/new Vector3();
  22094. class LightShadow {
  22095. constructor(camera) {
  22096. this.camera = camera;
  22097. this.bias = 0;
  22098. this.normalBias = 0;
  22099. this.radius = 1;
  22100. this.mapSize = new Vector2(512, 512);
  22101. this.map = null;
  22102. this.mapPass = null;
  22103. this.matrix = new Matrix4();
  22104. this.autoUpdate = true;
  22105. this.needsUpdate = false;
  22106. this._frustum = new Frustum();
  22107. this._frameExtents = new Vector2(1, 1);
  22108. this._viewportCount = 1;
  22109. this._viewports = [new Vector4(0, 0, 1, 1)];
  22110. }
  22111. getViewportCount() {
  22112. return this._viewportCount;
  22113. }
  22114. getFrustum() {
  22115. return this._frustum;
  22116. }
  22117. updateMatrices(light) {
  22118. const shadowCamera = this.camera;
  22119. const shadowMatrix = this.matrix;
  22120. _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld);
  22121. shadowCamera.position.copy(_lightPositionWorld$1);
  22122. _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld);
  22123. shadowCamera.lookAt(_lookTarget$1);
  22124. shadowCamera.updateMatrixWorld();
  22125. _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  22126. this._frustum.setFromProjectionMatrix(_projScreenMatrix$1);
  22127. 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);
  22128. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  22129. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  22130. }
  22131. getViewport(viewportIndex) {
  22132. return this._viewports[viewportIndex];
  22133. }
  22134. getFrameExtents() {
  22135. return this._frameExtents;
  22136. }
  22137. dispose() {
  22138. if (this.map) {
  22139. this.map.dispose();
  22140. }
  22141. if (this.mapPass) {
  22142. this.mapPass.dispose();
  22143. }
  22144. }
  22145. copy(source) {
  22146. this.camera = source.camera.clone();
  22147. this.bias = source.bias;
  22148. this.radius = source.radius;
  22149. this.mapSize.copy(source.mapSize);
  22150. return this;
  22151. }
  22152. clone() {
  22153. return new this.constructor().copy(this);
  22154. }
  22155. toJSON() {
  22156. const object = {};
  22157. if (this.bias !== 0) object.bias = this.bias;
  22158. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  22159. if (this.radius !== 1) object.radius = this.radius;
  22160. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  22161. object.camera = this.camera.toJSON(false).object;
  22162. delete object.camera.matrix;
  22163. return object;
  22164. }
  22165. }
  22166. class SpotLightShadow extends LightShadow {
  22167. constructor() {
  22168. super(new PerspectiveCamera(50, 1, 0.5, 500));
  22169. this.focus = 1;
  22170. }
  22171. updateMatrices(light) {
  22172. const camera = this.camera;
  22173. const fov = RAD2DEG * 2 * light.angle * this.focus;
  22174. const aspect = this.mapSize.width / this.mapSize.height;
  22175. const far = light.distance || camera.far;
  22176. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  22177. camera.fov = fov;
  22178. camera.aspect = aspect;
  22179. camera.far = far;
  22180. camera.updateProjectionMatrix();
  22181. }
  22182. super.updateMatrices(light);
  22183. }
  22184. copy(source) {
  22185. super.copy(source);
  22186. this.focus = source.focus;
  22187. return this;
  22188. }
  22189. }
  22190. SpotLightShadow.prototype.isSpotLightShadow = true;
  22191. class SpotLight extends Light {
  22192. constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1) {
  22193. super(color, intensity);
  22194. this.type = 'SpotLight';
  22195. this.position.copy(Object3D.DefaultUp);
  22196. this.updateMatrix();
  22197. this.target = new Object3D();
  22198. this.distance = distance;
  22199. this.angle = angle;
  22200. this.penumbra = penumbra;
  22201. this.decay = decay; // for physically correct lights, should be 2.
  22202. this.shadow = new SpotLightShadow();
  22203. }
  22204. get power() {
  22205. // intensity = power per solid angle.
  22206. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22207. return this.intensity * Math.PI;
  22208. }
  22209. set power(power) {
  22210. // intensity = power per solid angle.
  22211. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22212. this.intensity = power / Math.PI;
  22213. }
  22214. dispose() {
  22215. this.shadow.dispose();
  22216. }
  22217. copy(source) {
  22218. super.copy(source);
  22219. this.distance = source.distance;
  22220. this.angle = source.angle;
  22221. this.penumbra = source.penumbra;
  22222. this.decay = source.decay;
  22223. this.target = source.target.clone();
  22224. this.shadow = source.shadow.clone();
  22225. return this;
  22226. }
  22227. }
  22228. SpotLight.prototype.isSpotLight = true;
  22229. const _projScreenMatrix = /*@__PURE__*/new Matrix4();
  22230. const _lightPositionWorld = /*@__PURE__*/new Vector3();
  22231. const _lookTarget = /*@__PURE__*/new Vector3();
  22232. class PointLightShadow extends LightShadow {
  22233. constructor() {
  22234. super(new PerspectiveCamera(90, 1, 0.5, 500));
  22235. this._frameExtents = new Vector2(4, 2);
  22236. this._viewportCount = 6;
  22237. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  22238. // following orientation:
  22239. //
  22240. // xzXZ
  22241. // y Y
  22242. //
  22243. // X - Positive x direction
  22244. // x - Negative x direction
  22245. // Y - Positive y direction
  22246. // y - Negative y direction
  22247. // Z - Positive z direction
  22248. // z - Negative z direction
  22249. // positive X
  22250. new Vector4(2, 1, 1, 1), // negative X
  22251. new Vector4(0, 1, 1, 1), // positive Z
  22252. new Vector4(3, 1, 1, 1), // negative Z
  22253. new Vector4(1, 1, 1, 1), // positive Y
  22254. new Vector4(3, 0, 1, 1), // negative Y
  22255. new Vector4(1, 0, 1, 1)];
  22256. 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)];
  22257. 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)];
  22258. }
  22259. updateMatrices(light, viewportIndex = 0) {
  22260. const camera = this.camera;
  22261. const shadowMatrix = this.matrix;
  22262. const far = light.distance || camera.far;
  22263. if (far !== camera.far) {
  22264. camera.far = far;
  22265. camera.updateProjectionMatrix();
  22266. }
  22267. _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  22268. camera.position.copy(_lightPositionWorld);
  22269. _lookTarget.copy(camera.position);
  22270. _lookTarget.add(this._cubeDirections[viewportIndex]);
  22271. camera.up.copy(this._cubeUps[viewportIndex]);
  22272. camera.lookAt(_lookTarget);
  22273. camera.updateMatrixWorld();
  22274. shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
  22275. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  22276. this._frustum.setFromProjectionMatrix(_projScreenMatrix);
  22277. }
  22278. }
  22279. PointLightShadow.prototype.isPointLightShadow = true;
  22280. class PointLight extends Light {
  22281. constructor(color, intensity, distance = 0, decay = 1) {
  22282. super(color, intensity);
  22283. this.type = 'PointLight';
  22284. this.distance = distance;
  22285. this.decay = decay; // for physically correct lights, should be 2.
  22286. this.shadow = new PointLightShadow();
  22287. }
  22288. get power() {
  22289. // intensity = power per solid angle.
  22290. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22291. return this.intensity * 4 * Math.PI;
  22292. }
  22293. set power(power) {
  22294. // intensity = power per solid angle.
  22295. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22296. this.intensity = power / (4 * Math.PI);
  22297. }
  22298. dispose() {
  22299. this.shadow.dispose();
  22300. }
  22301. copy(source) {
  22302. super.copy(source);
  22303. this.distance = source.distance;
  22304. this.decay = source.decay;
  22305. this.shadow = source.shadow.clone();
  22306. return this;
  22307. }
  22308. }
  22309. PointLight.prototype.isPointLight = true;
  22310. class OrthographicCamera extends Camera {
  22311. constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) {
  22312. super();
  22313. this.type = 'OrthographicCamera';
  22314. this.zoom = 1;
  22315. this.view = null;
  22316. this.left = left;
  22317. this.right = right;
  22318. this.top = top;
  22319. this.bottom = bottom;
  22320. this.near = near;
  22321. this.far = far;
  22322. this.updateProjectionMatrix();
  22323. }
  22324. copy(source, recursive) {
  22325. super.copy(source, recursive);
  22326. this.left = source.left;
  22327. this.right = source.right;
  22328. this.top = source.top;
  22329. this.bottom = source.bottom;
  22330. this.near = source.near;
  22331. this.far = source.far;
  22332. this.zoom = source.zoom;
  22333. this.view = source.view === null ? null : Object.assign({}, source.view);
  22334. return this;
  22335. }
  22336. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  22337. if (this.view === null) {
  22338. this.view = {
  22339. enabled: true,
  22340. fullWidth: 1,
  22341. fullHeight: 1,
  22342. offsetX: 0,
  22343. offsetY: 0,
  22344. width: 1,
  22345. height: 1
  22346. };
  22347. }
  22348. this.view.enabled = true;
  22349. this.view.fullWidth = fullWidth;
  22350. this.view.fullHeight = fullHeight;
  22351. this.view.offsetX = x;
  22352. this.view.offsetY = y;
  22353. this.view.width = width;
  22354. this.view.height = height;
  22355. this.updateProjectionMatrix();
  22356. }
  22357. clearViewOffset() {
  22358. if (this.view !== null) {
  22359. this.view.enabled = false;
  22360. }
  22361. this.updateProjectionMatrix();
  22362. }
  22363. updateProjectionMatrix() {
  22364. const dx = (this.right - this.left) / (2 * this.zoom);
  22365. const dy = (this.top - this.bottom) / (2 * this.zoom);
  22366. const cx = (this.right + this.left) / 2;
  22367. const cy = (this.top + this.bottom) / 2;
  22368. let left = cx - dx;
  22369. let right = cx + dx;
  22370. let top = cy + dy;
  22371. let bottom = cy - dy;
  22372. if (this.view !== null && this.view.enabled) {
  22373. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  22374. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  22375. left += scaleW * this.view.offsetX;
  22376. right = left + scaleW * this.view.width;
  22377. top -= scaleH * this.view.offsetY;
  22378. bottom = top - scaleH * this.view.height;
  22379. }
  22380. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  22381. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  22382. }
  22383. toJSON(meta) {
  22384. const data = super.toJSON(meta);
  22385. data.object.zoom = this.zoom;
  22386. data.object.left = this.left;
  22387. data.object.right = this.right;
  22388. data.object.top = this.top;
  22389. data.object.bottom = this.bottom;
  22390. data.object.near = this.near;
  22391. data.object.far = this.far;
  22392. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  22393. return data;
  22394. }
  22395. }
  22396. OrthographicCamera.prototype.isOrthographicCamera = true;
  22397. class DirectionalLightShadow extends LightShadow {
  22398. constructor() {
  22399. super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  22400. }
  22401. }
  22402. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  22403. class DirectionalLight extends Light {
  22404. constructor(color, intensity) {
  22405. super(color, intensity);
  22406. this.type = 'DirectionalLight';
  22407. this.position.copy(Object3D.DefaultUp);
  22408. this.updateMatrix();
  22409. this.target = new Object3D();
  22410. this.shadow = new DirectionalLightShadow();
  22411. }
  22412. dispose() {
  22413. this.shadow.dispose();
  22414. }
  22415. copy(source) {
  22416. super.copy(source);
  22417. this.target = source.target.clone();
  22418. this.shadow = source.shadow.clone();
  22419. return this;
  22420. }
  22421. }
  22422. DirectionalLight.prototype.isDirectionalLight = true;
  22423. class AmbientLight extends Light {
  22424. constructor(color, intensity) {
  22425. super(color, intensity);
  22426. this.type = 'AmbientLight';
  22427. }
  22428. }
  22429. AmbientLight.prototype.isAmbientLight = true;
  22430. class RectAreaLight extends Light {
  22431. constructor(color, intensity, width = 10, height = 10) {
  22432. super(color, intensity);
  22433. this.type = 'RectAreaLight';
  22434. this.width = width;
  22435. this.height = height;
  22436. }
  22437. copy(source) {
  22438. super.copy(source);
  22439. this.width = source.width;
  22440. this.height = source.height;
  22441. return this;
  22442. }
  22443. toJSON(meta) {
  22444. const data = super.toJSON(meta);
  22445. data.object.width = this.width;
  22446. data.object.height = this.height;
  22447. return data;
  22448. }
  22449. }
  22450. RectAreaLight.prototype.isRectAreaLight = true;
  22451. /**
  22452. * Primary reference:
  22453. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  22454. *
  22455. * Secondary reference:
  22456. * https://www.ppsloan.org/publications/StupidSH36.pdf
  22457. */
  22458. // 3-band SH defined by 9 coefficients
  22459. class SphericalHarmonics3 {
  22460. constructor() {
  22461. this.coefficients = [];
  22462. for (let i = 0; i < 9; i++) {
  22463. this.coefficients.push(new Vector3());
  22464. }
  22465. }
  22466. set(coefficients) {
  22467. for (let i = 0; i < 9; i++) {
  22468. this.coefficients[i].copy(coefficients[i]);
  22469. }
  22470. return this;
  22471. }
  22472. zero() {
  22473. for (let i = 0; i < 9; i++) {
  22474. this.coefficients[i].set(0, 0, 0);
  22475. }
  22476. return this;
  22477. } // get the radiance in the direction of the normal
  22478. // target is a Vector3
  22479. getAt(normal, target) {
  22480. // normal is assumed to be unit length
  22481. const x = normal.x,
  22482. y = normal.y,
  22483. z = normal.z;
  22484. const coeff = this.coefficients; // band 0
  22485. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  22486. target.addScaledVector(coeff[1], 0.488603 * y);
  22487. target.addScaledVector(coeff[2], 0.488603 * z);
  22488. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  22489. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  22490. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  22491. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  22492. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  22493. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  22494. return target;
  22495. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  22496. // target is a Vector3
  22497. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  22498. getIrradianceAt(normal, target) {
  22499. // normal is assumed to be unit length
  22500. const x = normal.x,
  22501. y = normal.y,
  22502. z = normal.z;
  22503. const coeff = this.coefficients; // band 0
  22504. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  22505. // band 1
  22506. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  22507. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  22508. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  22509. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  22510. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  22511. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  22512. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  22513. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  22514. return target;
  22515. }
  22516. add(sh) {
  22517. for (let i = 0; i < 9; i++) {
  22518. this.coefficients[i].add(sh.coefficients[i]);
  22519. }
  22520. return this;
  22521. }
  22522. addScaledSH(sh, s) {
  22523. for (let i = 0; i < 9; i++) {
  22524. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  22525. }
  22526. return this;
  22527. }
  22528. scale(s) {
  22529. for (let i = 0; i < 9; i++) {
  22530. this.coefficients[i].multiplyScalar(s);
  22531. }
  22532. return this;
  22533. }
  22534. lerp(sh, alpha) {
  22535. for (let i = 0; i < 9; i++) {
  22536. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  22537. }
  22538. return this;
  22539. }
  22540. equals(sh) {
  22541. for (let i = 0; i < 9; i++) {
  22542. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  22543. return false;
  22544. }
  22545. }
  22546. return true;
  22547. }
  22548. copy(sh) {
  22549. return this.set(sh.coefficients);
  22550. }
  22551. clone() {
  22552. return new this.constructor().copy(this);
  22553. }
  22554. fromArray(array, offset = 0) {
  22555. const coefficients = this.coefficients;
  22556. for (let i = 0; i < 9; i++) {
  22557. coefficients[i].fromArray(array, offset + i * 3);
  22558. }
  22559. return this;
  22560. }
  22561. toArray(array = [], offset = 0) {
  22562. const coefficients = this.coefficients;
  22563. for (let i = 0; i < 9; i++) {
  22564. coefficients[i].toArray(array, offset + i * 3);
  22565. }
  22566. return array;
  22567. } // evaluate the basis functions
  22568. // shBasis is an Array[ 9 ]
  22569. static getBasisAt(normal, shBasis) {
  22570. // normal is assumed to be unit length
  22571. const x = normal.x,
  22572. y = normal.y,
  22573. z = normal.z; // band 0
  22574. shBasis[0] = 0.282095; // band 1
  22575. shBasis[1] = 0.488603 * y;
  22576. shBasis[2] = 0.488603 * z;
  22577. shBasis[3] = 0.488603 * x; // band 2
  22578. shBasis[4] = 1.092548 * x * y;
  22579. shBasis[5] = 1.092548 * y * z;
  22580. shBasis[6] = 0.315392 * (3 * z * z - 1);
  22581. shBasis[7] = 1.092548 * x * z;
  22582. shBasis[8] = 0.546274 * (x * x - y * y);
  22583. }
  22584. }
  22585. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  22586. class LightProbe extends Light {
  22587. constructor(sh = new SphericalHarmonics3(), intensity = 1) {
  22588. super(undefined, intensity);
  22589. this.sh = sh;
  22590. }
  22591. copy(source) {
  22592. super.copy(source);
  22593. this.sh.copy(source.sh);
  22594. return this;
  22595. }
  22596. fromJSON(json) {
  22597. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  22598. this.sh.fromArray(json.sh);
  22599. return this;
  22600. }
  22601. toJSON(meta) {
  22602. const data = super.toJSON(meta);
  22603. data.object.sh = this.sh.toArray();
  22604. return data;
  22605. }
  22606. }
  22607. LightProbe.prototype.isLightProbe = true;
  22608. class MaterialLoader extends Loader {
  22609. constructor(manager) {
  22610. super(manager);
  22611. this.textures = {};
  22612. }
  22613. load(url, onLoad, onProgress, onError) {
  22614. const scope = this;
  22615. const loader = new FileLoader(scope.manager);
  22616. loader.setPath(scope.path);
  22617. loader.setRequestHeader(scope.requestHeader);
  22618. loader.setWithCredentials(scope.withCredentials);
  22619. loader.load(url, function (text) {
  22620. try {
  22621. onLoad(scope.parse(JSON.parse(text)));
  22622. } catch (e) {
  22623. if (onError) {
  22624. onError(e);
  22625. } else {
  22626. console.error(e);
  22627. }
  22628. scope.manager.itemError(url);
  22629. }
  22630. }, onProgress, onError);
  22631. }
  22632. parse(json) {
  22633. const textures = this.textures;
  22634. function getTexture(name) {
  22635. if (textures[name] === undefined) {
  22636. console.warn('THREE.MaterialLoader: Undefined texture', name);
  22637. }
  22638. return textures[name];
  22639. }
  22640. const material = new Materials[json.type]();
  22641. if (json.uuid !== undefined) material.uuid = json.uuid;
  22642. if (json.name !== undefined) material.name = json.name;
  22643. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  22644. if (json.roughness !== undefined) material.roughness = json.roughness;
  22645. if (json.metalness !== undefined) material.metalness = json.metalness;
  22646. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  22647. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  22648. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  22649. if (json.shininess !== undefined) material.shininess = json.shininess;
  22650. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  22651. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  22652. if (json.transmission !== undefined) material.transmission = json.transmission;
  22653. if (json.thickness !== undefined) material.thickness = json.thickness;
  22654. if (json.attenuationDistance !== undefined) material.attenuationDistance = json.attenuationDistance;
  22655. if (json.attenuationColor !== undefined && material.attenuationColor !== undefined) material.attenuationColor.setHex(json.attenuationColor);
  22656. if (json.fog !== undefined) material.fog = json.fog;
  22657. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  22658. if (json.blending !== undefined) material.blending = json.blending;
  22659. if (json.combine !== undefined) material.combine = json.combine;
  22660. if (json.side !== undefined) material.side = json.side;
  22661. if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
  22662. if (json.opacity !== undefined) material.opacity = json.opacity;
  22663. if (json.transparent !== undefined) material.transparent = json.transparent;
  22664. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  22665. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  22666. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  22667. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  22668. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  22669. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  22670. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  22671. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  22672. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  22673. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  22674. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  22675. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  22676. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  22677. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  22678. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  22679. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  22680. if (json.rotation !== undefined) material.rotation = json.rotation;
  22681. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  22682. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  22683. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  22684. if (json.scale !== undefined) material.scale = json.scale;
  22685. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  22686. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  22687. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  22688. if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
  22689. if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
  22690. if (json.dithering !== undefined) material.dithering = json.dithering;
  22691. if (json.alphaToCoverage !== undefined) material.alphaToCoverage = json.alphaToCoverage;
  22692. if (json.premultipliedAlpha !== undefined) material.premultipliedAlpha = json.premultipliedAlpha;
  22693. if (json.vertexTangents !== undefined) material.vertexTangents = json.vertexTangents;
  22694. if (json.visible !== undefined) material.visible = json.visible;
  22695. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  22696. if (json.userData !== undefined) material.userData = json.userData;
  22697. if (json.vertexColors !== undefined) {
  22698. if (typeof json.vertexColors === 'number') {
  22699. material.vertexColors = json.vertexColors > 0 ? true : false;
  22700. } else {
  22701. material.vertexColors = json.vertexColors;
  22702. }
  22703. } // Shader Material
  22704. if (json.uniforms !== undefined) {
  22705. for (const name in json.uniforms) {
  22706. const uniform = json.uniforms[name];
  22707. material.uniforms[name] = {};
  22708. switch (uniform.type) {
  22709. case 't':
  22710. material.uniforms[name].value = getTexture(uniform.value);
  22711. break;
  22712. case 'c':
  22713. material.uniforms[name].value = new Color().setHex(uniform.value);
  22714. break;
  22715. case 'v2':
  22716. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  22717. break;
  22718. case 'v3':
  22719. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  22720. break;
  22721. case 'v4':
  22722. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  22723. break;
  22724. case 'm3':
  22725. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  22726. break;
  22727. case 'm4':
  22728. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  22729. break;
  22730. default:
  22731. material.uniforms[name].value = uniform.value;
  22732. }
  22733. }
  22734. }
  22735. if (json.defines !== undefined) material.defines = json.defines;
  22736. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  22737. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  22738. if (json.extensions !== undefined) {
  22739. for (const key in json.extensions) {
  22740. material.extensions[key] = json.extensions[key];
  22741. }
  22742. } // Deprecated
  22743. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  22744. // for PointsMaterial
  22745. if (json.size !== undefined) material.size = json.size;
  22746. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  22747. if (json.map !== undefined) material.map = getTexture(json.map);
  22748. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  22749. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  22750. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  22751. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  22752. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  22753. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  22754. if (json.normalScale !== undefined) {
  22755. let normalScale = json.normalScale;
  22756. if (Array.isArray(normalScale) === false) {
  22757. // Blender exporter used to export a scalar. See #7459
  22758. normalScale = [normalScale, normalScale];
  22759. }
  22760. material.normalScale = new Vector2().fromArray(normalScale);
  22761. }
  22762. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  22763. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  22764. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  22765. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  22766. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  22767. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  22768. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  22769. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  22770. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  22771. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  22772. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  22773. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  22774. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  22775. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  22776. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  22777. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  22778. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  22779. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  22780. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  22781. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  22782. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  22783. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  22784. if (json.thicknessMap !== undefined) material.thicknessMap = getTexture(json.thicknessMap);
  22785. return material;
  22786. }
  22787. setTextures(value) {
  22788. this.textures = value;
  22789. return this;
  22790. }
  22791. }
  22792. class LoaderUtils {
  22793. static decodeText(array) {
  22794. if (typeof TextDecoder !== 'undefined') {
  22795. return new TextDecoder().decode(array);
  22796. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  22797. // throws a "maximum call stack size exceeded" error for large arrays.
  22798. let s = '';
  22799. for (let i = 0, il = array.length; i < il; i++) {
  22800. // Implicitly assumes little-endian.
  22801. s += String.fromCharCode(array[i]);
  22802. }
  22803. try {
  22804. // merges multi-byte utf-8 characters.
  22805. return decodeURIComponent(escape(s));
  22806. } catch (e) {
  22807. // see #16358
  22808. return s;
  22809. }
  22810. }
  22811. static extractUrlBase(url) {
  22812. const index = url.lastIndexOf('/');
  22813. if (index === -1) return './';
  22814. return url.substr(0, index + 1);
  22815. }
  22816. }
  22817. class InstancedBufferGeometry extends BufferGeometry {
  22818. constructor() {
  22819. super();
  22820. this.type = 'InstancedBufferGeometry';
  22821. this.instanceCount = Infinity;
  22822. }
  22823. copy(source) {
  22824. super.copy(source);
  22825. this.instanceCount = source.instanceCount;
  22826. return this;
  22827. }
  22828. clone() {
  22829. return new this.constructor().copy(this);
  22830. }
  22831. toJSON() {
  22832. const data = super.toJSON(this);
  22833. data.instanceCount = this.instanceCount;
  22834. data.isInstancedBufferGeometry = true;
  22835. return data;
  22836. }
  22837. }
  22838. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  22839. class InstancedBufferAttribute extends BufferAttribute {
  22840. constructor(array, itemSize, normalized, meshPerAttribute) {
  22841. if (typeof normalized === 'number') {
  22842. meshPerAttribute = normalized;
  22843. normalized = false;
  22844. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  22845. }
  22846. super(array, itemSize, normalized);
  22847. this.meshPerAttribute = meshPerAttribute || 1;
  22848. }
  22849. copy(source) {
  22850. super.copy(source);
  22851. this.meshPerAttribute = source.meshPerAttribute;
  22852. return this;
  22853. }
  22854. toJSON() {
  22855. const data = super.toJSON();
  22856. data.meshPerAttribute = this.meshPerAttribute;
  22857. data.isInstancedBufferAttribute = true;
  22858. return data;
  22859. }
  22860. }
  22861. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  22862. class BufferGeometryLoader extends Loader {
  22863. constructor(manager) {
  22864. super(manager);
  22865. }
  22866. load(url, onLoad, onProgress, onError) {
  22867. const scope = this;
  22868. const loader = new FileLoader(scope.manager);
  22869. loader.setPath(scope.path);
  22870. loader.setRequestHeader(scope.requestHeader);
  22871. loader.setWithCredentials(scope.withCredentials);
  22872. loader.load(url, function (text) {
  22873. try {
  22874. onLoad(scope.parse(JSON.parse(text)));
  22875. } catch (e) {
  22876. if (onError) {
  22877. onError(e);
  22878. } else {
  22879. console.error(e);
  22880. }
  22881. scope.manager.itemError(url);
  22882. }
  22883. }, onProgress, onError);
  22884. }
  22885. parse(json) {
  22886. const interleavedBufferMap = {};
  22887. const arrayBufferMap = {};
  22888. function getInterleavedBuffer(json, uuid) {
  22889. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  22890. const interleavedBuffers = json.interleavedBuffers;
  22891. const interleavedBuffer = interleavedBuffers[uuid];
  22892. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  22893. const array = getTypedArray(interleavedBuffer.type, buffer);
  22894. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  22895. ib.uuid = interleavedBuffer.uuid;
  22896. interleavedBufferMap[uuid] = ib;
  22897. return ib;
  22898. }
  22899. function getArrayBuffer(json, uuid) {
  22900. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  22901. const arrayBuffers = json.arrayBuffers;
  22902. const arrayBuffer = arrayBuffers[uuid];
  22903. const ab = new Uint32Array(arrayBuffer).buffer;
  22904. arrayBufferMap[uuid] = ab;
  22905. return ab;
  22906. }
  22907. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  22908. const index = json.data.index;
  22909. if (index !== undefined) {
  22910. const typedArray = getTypedArray(index.type, index.array);
  22911. geometry.setIndex(new BufferAttribute(typedArray, 1));
  22912. }
  22913. const attributes = json.data.attributes;
  22914. for (const key in attributes) {
  22915. const attribute = attributes[key];
  22916. let bufferAttribute;
  22917. if (attribute.isInterleavedBufferAttribute) {
  22918. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  22919. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  22920. } else {
  22921. const typedArray = getTypedArray(attribute.type, attribute.array);
  22922. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  22923. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  22924. }
  22925. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  22926. if (attribute.usage !== undefined) bufferAttribute.setUsage(attribute.usage);
  22927. if (attribute.updateRange !== undefined) {
  22928. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  22929. bufferAttribute.updateRange.count = attribute.updateRange.count;
  22930. }
  22931. geometry.setAttribute(key, bufferAttribute);
  22932. }
  22933. const morphAttributes = json.data.morphAttributes;
  22934. if (morphAttributes) {
  22935. for (const key in morphAttributes) {
  22936. const attributeArray = morphAttributes[key];
  22937. const array = [];
  22938. for (let i = 0, il = attributeArray.length; i < il; i++) {
  22939. const attribute = attributeArray[i];
  22940. let bufferAttribute;
  22941. if (attribute.isInterleavedBufferAttribute) {
  22942. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  22943. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  22944. } else {
  22945. const typedArray = getTypedArray(attribute.type, attribute.array);
  22946. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  22947. }
  22948. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  22949. array.push(bufferAttribute);
  22950. }
  22951. geometry.morphAttributes[key] = array;
  22952. }
  22953. }
  22954. const morphTargetsRelative = json.data.morphTargetsRelative;
  22955. if (morphTargetsRelative) {
  22956. geometry.morphTargetsRelative = true;
  22957. }
  22958. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  22959. if (groups !== undefined) {
  22960. for (let i = 0, n = groups.length; i !== n; ++i) {
  22961. const group = groups[i];
  22962. geometry.addGroup(group.start, group.count, group.materialIndex);
  22963. }
  22964. }
  22965. const boundingSphere = json.data.boundingSphere;
  22966. if (boundingSphere !== undefined) {
  22967. const center = new Vector3();
  22968. if (boundingSphere.center !== undefined) {
  22969. center.fromArray(boundingSphere.center);
  22970. }
  22971. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  22972. }
  22973. if (json.name) geometry.name = json.name;
  22974. if (json.userData) geometry.userData = json.userData;
  22975. return geometry;
  22976. }
  22977. }
  22978. class ObjectLoader extends Loader {
  22979. constructor(manager) {
  22980. super(manager);
  22981. }
  22982. load(url, onLoad, onProgress, onError) {
  22983. const scope = this;
  22984. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  22985. this.resourcePath = this.resourcePath || path;
  22986. const loader = new FileLoader(this.manager);
  22987. loader.setPath(this.path);
  22988. loader.setRequestHeader(this.requestHeader);
  22989. loader.setWithCredentials(this.withCredentials);
  22990. loader.load(url, function (text) {
  22991. let json = null;
  22992. try {
  22993. json = JSON.parse(text);
  22994. } catch (error) {
  22995. if (onError !== undefined) onError(error);
  22996. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  22997. return;
  22998. }
  22999. const metadata = json.metadata;
  23000. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  23001. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  23002. return;
  23003. }
  23004. scope.parse(json, onLoad);
  23005. }, onProgress, onError);
  23006. }
  23007. parse(json, onLoad) {
  23008. const animations = this.parseAnimations(json.animations);
  23009. const shapes = this.parseShapes(json.shapes);
  23010. const geometries = this.parseGeometries(json.geometries, shapes);
  23011. const images = this.parseImages(json.images, function () {
  23012. if (onLoad !== undefined) onLoad(object);
  23013. });
  23014. const textures = this.parseTextures(json.textures, images);
  23015. const materials = this.parseMaterials(json.materials, textures);
  23016. const object = this.parseObject(json.object, geometries, materials, animations);
  23017. const skeletons = this.parseSkeletons(json.skeletons, object);
  23018. this.bindSkeletons(object, skeletons); //
  23019. if (onLoad !== undefined) {
  23020. let hasImages = false;
  23021. for (const uuid in images) {
  23022. if (images[uuid] instanceof HTMLImageElement) {
  23023. hasImages = true;
  23024. break;
  23025. }
  23026. }
  23027. if (hasImages === false) onLoad(object);
  23028. }
  23029. return object;
  23030. }
  23031. parseShapes(json) {
  23032. const shapes = {};
  23033. if (json !== undefined) {
  23034. for (let i = 0, l = json.length; i < l; i++) {
  23035. const shape = new Shape().fromJSON(json[i]);
  23036. shapes[shape.uuid] = shape;
  23037. }
  23038. }
  23039. return shapes;
  23040. }
  23041. parseSkeletons(json, object) {
  23042. const skeletons = {};
  23043. const bones = {}; // generate bone lookup table
  23044. object.traverse(function (child) {
  23045. if (child.isBone) bones[child.uuid] = child;
  23046. }); // create skeletons
  23047. if (json !== undefined) {
  23048. for (let i = 0, l = json.length; i < l; i++) {
  23049. const skeleton = new Skeleton().fromJSON(json[i], bones);
  23050. skeletons[skeleton.uuid] = skeleton;
  23051. }
  23052. }
  23053. return skeletons;
  23054. }
  23055. parseGeometries(json, shapes) {
  23056. const geometries = {};
  23057. let geometryShapes;
  23058. if (json !== undefined) {
  23059. const bufferGeometryLoader = new BufferGeometryLoader();
  23060. for (let i = 0, l = json.length; i < l; i++) {
  23061. let geometry;
  23062. const data = json[i];
  23063. switch (data.type) {
  23064. case 'PlaneGeometry':
  23065. case 'PlaneBufferGeometry':
  23066. geometry = new Geometries[data.type](data.width, data.height, data.widthSegments, data.heightSegments);
  23067. break;
  23068. case 'BoxGeometry':
  23069. case 'BoxBufferGeometry':
  23070. geometry = new Geometries[data.type](data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  23071. break;
  23072. case 'CircleGeometry':
  23073. case 'CircleBufferGeometry':
  23074. geometry = new Geometries[data.type](data.radius, data.segments, data.thetaStart, data.thetaLength);
  23075. break;
  23076. case 'CylinderGeometry':
  23077. case 'CylinderBufferGeometry':
  23078. geometry = new Geometries[data.type](data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  23079. break;
  23080. case 'ConeGeometry':
  23081. case 'ConeBufferGeometry':
  23082. geometry = new Geometries[data.type](data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  23083. break;
  23084. case 'SphereGeometry':
  23085. case 'SphereBufferGeometry':
  23086. geometry = new Geometries[data.type](data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  23087. break;
  23088. case 'DodecahedronGeometry':
  23089. case 'DodecahedronBufferGeometry':
  23090. case 'IcosahedronGeometry':
  23091. case 'IcosahedronBufferGeometry':
  23092. case 'OctahedronGeometry':
  23093. case 'OctahedronBufferGeometry':
  23094. case 'TetrahedronGeometry':
  23095. case 'TetrahedronBufferGeometry':
  23096. geometry = new Geometries[data.type](data.radius, data.detail);
  23097. break;
  23098. case 'RingGeometry':
  23099. case 'RingBufferGeometry':
  23100. geometry = new Geometries[data.type](data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  23101. break;
  23102. case 'TorusGeometry':
  23103. case 'TorusBufferGeometry':
  23104. geometry = new Geometries[data.type](data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  23105. break;
  23106. case 'TorusKnotGeometry':
  23107. case 'TorusKnotBufferGeometry':
  23108. geometry = new Geometries[data.type](data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  23109. break;
  23110. case 'TubeGeometry':
  23111. case 'TubeBufferGeometry':
  23112. // This only works for built-in curves (e.g. CatmullRomCurve3).
  23113. // User defined curves or instances of CurvePath will not be deserialized.
  23114. geometry = new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  23115. break;
  23116. case 'LatheGeometry':
  23117. case 'LatheBufferGeometry':
  23118. geometry = new Geometries[data.type](data.points, data.segments, data.phiStart, data.phiLength);
  23119. break;
  23120. case 'PolyhedronGeometry':
  23121. case 'PolyhedronBufferGeometry':
  23122. geometry = new Geometries[data.type](data.vertices, data.indices, data.radius, data.details);
  23123. break;
  23124. case 'ShapeGeometry':
  23125. case 'ShapeBufferGeometry':
  23126. geometryShapes = [];
  23127. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  23128. const shape = shapes[data.shapes[j]];
  23129. geometryShapes.push(shape);
  23130. }
  23131. geometry = new Geometries[data.type](geometryShapes, data.curveSegments);
  23132. break;
  23133. case 'ExtrudeGeometry':
  23134. case 'ExtrudeBufferGeometry':
  23135. geometryShapes = [];
  23136. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  23137. const shape = shapes[data.shapes[j]];
  23138. geometryShapes.push(shape);
  23139. }
  23140. const extrudePath = data.options.extrudePath;
  23141. if (extrudePath !== undefined) {
  23142. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  23143. }
  23144. geometry = new Geometries[data.type](geometryShapes, data.options);
  23145. break;
  23146. case 'BufferGeometry':
  23147. case 'InstancedBufferGeometry':
  23148. geometry = bufferGeometryLoader.parse(data);
  23149. break;
  23150. case 'Geometry':
  23151. console.error('THREE.ObjectLoader: Loading "Geometry" is not supported anymore.');
  23152. break;
  23153. default:
  23154. console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');
  23155. continue;
  23156. }
  23157. geometry.uuid = data.uuid;
  23158. if (data.name !== undefined) geometry.name = data.name;
  23159. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  23160. geometries[data.uuid] = geometry;
  23161. }
  23162. }
  23163. return geometries;
  23164. }
  23165. parseMaterials(json, textures) {
  23166. const cache = {}; // MultiMaterial
  23167. const materials = {};
  23168. if (json !== undefined) {
  23169. const loader = new MaterialLoader();
  23170. loader.setTextures(textures);
  23171. for (let i = 0, l = json.length; i < l; i++) {
  23172. const data = json[i];
  23173. if (data.type === 'MultiMaterial') {
  23174. // Deprecated
  23175. const array = [];
  23176. for (let j = 0; j < data.materials.length; j++) {
  23177. const material = data.materials[j];
  23178. if (cache[material.uuid] === undefined) {
  23179. cache[material.uuid] = loader.parse(material);
  23180. }
  23181. array.push(cache[material.uuid]);
  23182. }
  23183. materials[data.uuid] = array;
  23184. } else {
  23185. if (cache[data.uuid] === undefined) {
  23186. cache[data.uuid] = loader.parse(data);
  23187. }
  23188. materials[data.uuid] = cache[data.uuid];
  23189. }
  23190. }
  23191. }
  23192. return materials;
  23193. }
  23194. parseAnimations(json) {
  23195. const animations = {};
  23196. if (json !== undefined) {
  23197. for (let i = 0; i < json.length; i++) {
  23198. const data = json[i];
  23199. const clip = AnimationClip.parse(data);
  23200. animations[clip.uuid] = clip;
  23201. }
  23202. }
  23203. return animations;
  23204. }
  23205. parseImages(json, onLoad) {
  23206. const scope = this;
  23207. const images = {};
  23208. let loader;
  23209. function loadImage(url) {
  23210. scope.manager.itemStart(url);
  23211. return loader.load(url, function () {
  23212. scope.manager.itemEnd(url);
  23213. }, undefined, function () {
  23214. scope.manager.itemError(url);
  23215. scope.manager.itemEnd(url);
  23216. });
  23217. }
  23218. function deserializeImage(image) {
  23219. if (typeof image === 'string') {
  23220. const url = image;
  23221. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  23222. return loadImage(path);
  23223. } else {
  23224. if (image.data) {
  23225. return {
  23226. data: getTypedArray(image.type, image.data),
  23227. width: image.width,
  23228. height: image.height
  23229. };
  23230. } else {
  23231. return null;
  23232. }
  23233. }
  23234. }
  23235. if (json !== undefined && json.length > 0) {
  23236. const manager = new LoadingManager(onLoad);
  23237. loader = new ImageLoader(manager);
  23238. loader.setCrossOrigin(this.crossOrigin);
  23239. for (let i = 0, il = json.length; i < il; i++) {
  23240. const image = json[i];
  23241. const url = image.url;
  23242. if (Array.isArray(url)) {
  23243. // load array of images e.g CubeTexture
  23244. images[image.uuid] = [];
  23245. for (let j = 0, jl = url.length; j < jl; j++) {
  23246. const currentUrl = url[j];
  23247. const deserializedImage = deserializeImage(currentUrl);
  23248. if (deserializedImage !== null) {
  23249. if (deserializedImage instanceof HTMLImageElement) {
  23250. images[image.uuid].push(deserializedImage);
  23251. } else {
  23252. // special case: handle array of data textures for cube textures
  23253. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  23254. }
  23255. }
  23256. }
  23257. } else {
  23258. // load single image
  23259. const deserializedImage = deserializeImage(image.url);
  23260. if (deserializedImage !== null) {
  23261. images[image.uuid] = deserializedImage;
  23262. }
  23263. }
  23264. }
  23265. }
  23266. return images;
  23267. }
  23268. parseTextures(json, images) {
  23269. function parseConstant(value, type) {
  23270. if (typeof value === 'number') return value;
  23271. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  23272. return type[value];
  23273. }
  23274. const textures = {};
  23275. if (json !== undefined) {
  23276. for (let i = 0, l = json.length; i < l; i++) {
  23277. const data = json[i];
  23278. if (data.image === undefined) {
  23279. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  23280. }
  23281. if (images[data.image] === undefined) {
  23282. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  23283. }
  23284. let texture;
  23285. const image = images[data.image];
  23286. if (Array.isArray(image)) {
  23287. texture = new CubeTexture(image);
  23288. if (image.length === 6) texture.needsUpdate = true;
  23289. } else {
  23290. if (image && image.data) {
  23291. texture = new DataTexture(image.data, image.width, image.height);
  23292. } else {
  23293. texture = new Texture(image);
  23294. }
  23295. if (image) texture.needsUpdate = true; // textures can have undefined image data
  23296. }
  23297. texture.uuid = data.uuid;
  23298. if (data.name !== undefined) texture.name = data.name;
  23299. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  23300. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  23301. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  23302. if (data.center !== undefined) texture.center.fromArray(data.center);
  23303. if (data.rotation !== undefined) texture.rotation = data.rotation;
  23304. if (data.wrap !== undefined) {
  23305. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  23306. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  23307. }
  23308. if (data.format !== undefined) texture.format = data.format;
  23309. if (data.type !== undefined) texture.type = data.type;
  23310. if (data.encoding !== undefined) texture.encoding = data.encoding;
  23311. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  23312. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  23313. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  23314. if (data.flipY !== undefined) texture.flipY = data.flipY;
  23315. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  23316. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  23317. textures[data.uuid] = texture;
  23318. }
  23319. }
  23320. return textures;
  23321. }
  23322. parseObject(data, geometries, materials, animations) {
  23323. let object;
  23324. function getGeometry(name) {
  23325. if (geometries[name] === undefined) {
  23326. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  23327. }
  23328. return geometries[name];
  23329. }
  23330. function getMaterial(name) {
  23331. if (name === undefined) return undefined;
  23332. if (Array.isArray(name)) {
  23333. const array = [];
  23334. for (let i = 0, l = name.length; i < l; i++) {
  23335. const uuid = name[i];
  23336. if (materials[uuid] === undefined) {
  23337. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  23338. }
  23339. array.push(materials[uuid]);
  23340. }
  23341. return array;
  23342. }
  23343. if (materials[name] === undefined) {
  23344. console.warn('THREE.ObjectLoader: Undefined material', name);
  23345. }
  23346. return materials[name];
  23347. }
  23348. let geometry, material;
  23349. switch (data.type) {
  23350. case 'Scene':
  23351. object = new Scene();
  23352. if (data.background !== undefined) {
  23353. if (Number.isInteger(data.background)) {
  23354. object.background = new Color(data.background);
  23355. }
  23356. }
  23357. if (data.fog !== undefined) {
  23358. if (data.fog.type === 'Fog') {
  23359. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  23360. } else if (data.fog.type === 'FogExp2') {
  23361. object.fog = new FogExp2(data.fog.color, data.fog.density);
  23362. }
  23363. }
  23364. break;
  23365. case 'PerspectiveCamera':
  23366. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  23367. if (data.focus !== undefined) object.focus = data.focus;
  23368. if (data.zoom !== undefined) object.zoom = data.zoom;
  23369. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  23370. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  23371. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  23372. break;
  23373. case 'OrthographicCamera':
  23374. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  23375. if (data.zoom !== undefined) object.zoom = data.zoom;
  23376. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  23377. break;
  23378. case 'AmbientLight':
  23379. object = new AmbientLight(data.color, data.intensity);
  23380. break;
  23381. case 'DirectionalLight':
  23382. object = new DirectionalLight(data.color, data.intensity);
  23383. break;
  23384. case 'PointLight':
  23385. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  23386. break;
  23387. case 'RectAreaLight':
  23388. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  23389. break;
  23390. case 'SpotLight':
  23391. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  23392. break;
  23393. case 'HemisphereLight':
  23394. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  23395. break;
  23396. case 'LightProbe':
  23397. object = new LightProbe().fromJSON(data);
  23398. break;
  23399. case 'SkinnedMesh':
  23400. geometry = getGeometry(data.geometry);
  23401. material = getMaterial(data.material);
  23402. object = new SkinnedMesh(geometry, material);
  23403. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  23404. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  23405. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  23406. break;
  23407. case 'Mesh':
  23408. geometry = getGeometry(data.geometry);
  23409. material = getMaterial(data.material);
  23410. object = new Mesh(geometry, material);
  23411. break;
  23412. case 'InstancedMesh':
  23413. geometry = getGeometry(data.geometry);
  23414. material = getMaterial(data.material);
  23415. const count = data.count;
  23416. const instanceMatrix = data.instanceMatrix;
  23417. const instanceColor = data.instanceColor;
  23418. object = new InstancedMesh(geometry, material, count);
  23419. object.instanceMatrix = new BufferAttribute(new Float32Array(instanceMatrix.array), 16);
  23420. if (instanceColor !== undefined) object.instanceColor = new BufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
  23421. break;
  23422. case 'LOD':
  23423. object = new LOD();
  23424. break;
  23425. case 'Line':
  23426. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  23427. break;
  23428. case 'LineLoop':
  23429. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  23430. break;
  23431. case 'LineSegments':
  23432. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  23433. break;
  23434. case 'PointCloud':
  23435. case 'Points':
  23436. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  23437. break;
  23438. case 'Sprite':
  23439. object = new Sprite(getMaterial(data.material));
  23440. break;
  23441. case 'Group':
  23442. object = new Group();
  23443. break;
  23444. case 'Bone':
  23445. object = new Bone();
  23446. break;
  23447. default:
  23448. object = new Object3D();
  23449. }
  23450. object.uuid = data.uuid;
  23451. if (data.name !== undefined) object.name = data.name;
  23452. if (data.matrix !== undefined) {
  23453. object.matrix.fromArray(data.matrix);
  23454. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  23455. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  23456. } else {
  23457. if (data.position !== undefined) object.position.fromArray(data.position);
  23458. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  23459. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  23460. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  23461. }
  23462. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  23463. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  23464. if (data.shadow) {
  23465. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  23466. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  23467. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  23468. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  23469. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  23470. }
  23471. if (data.visible !== undefined) object.visible = data.visible;
  23472. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  23473. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  23474. if (data.userData !== undefined) object.userData = data.userData;
  23475. if (data.layers !== undefined) object.layers.mask = data.layers;
  23476. if (data.children !== undefined) {
  23477. const children = data.children;
  23478. for (let i = 0; i < children.length; i++) {
  23479. object.add(this.parseObject(children[i], geometries, materials, animations));
  23480. }
  23481. }
  23482. if (data.animations !== undefined) {
  23483. const objectAnimations = data.animations;
  23484. for (let i = 0; i < objectAnimations.length; i++) {
  23485. const uuid = objectAnimations[i];
  23486. object.animations.push(animations[uuid]);
  23487. }
  23488. }
  23489. if (data.type === 'LOD') {
  23490. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  23491. const levels = data.levels;
  23492. for (let l = 0; l < levels.length; l++) {
  23493. const level = levels[l];
  23494. const child = object.getObjectByProperty('uuid', level.object);
  23495. if (child !== undefined) {
  23496. object.addLevel(child, level.distance);
  23497. }
  23498. }
  23499. }
  23500. return object;
  23501. }
  23502. bindSkeletons(object, skeletons) {
  23503. if (Object.keys(skeletons).length === 0) return;
  23504. object.traverse(function (child) {
  23505. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  23506. const skeleton = skeletons[child.skeleton];
  23507. if (skeleton === undefined) {
  23508. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  23509. } else {
  23510. child.bind(skeleton, child.bindMatrix);
  23511. }
  23512. }
  23513. });
  23514. }
  23515. /* DEPRECATED */
  23516. setTexturePath(value) {
  23517. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  23518. return this.setResourcePath(value);
  23519. }
  23520. }
  23521. const TEXTURE_MAPPING = {
  23522. UVMapping: UVMapping,
  23523. CubeReflectionMapping: CubeReflectionMapping,
  23524. CubeRefractionMapping: CubeRefractionMapping,
  23525. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  23526. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  23527. CubeUVReflectionMapping: CubeUVReflectionMapping,
  23528. CubeUVRefractionMapping: CubeUVRefractionMapping
  23529. };
  23530. const TEXTURE_WRAPPING = {
  23531. RepeatWrapping: RepeatWrapping,
  23532. ClampToEdgeWrapping: ClampToEdgeWrapping,
  23533. MirroredRepeatWrapping: MirroredRepeatWrapping
  23534. };
  23535. const TEXTURE_FILTER = {
  23536. NearestFilter: NearestFilter,
  23537. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  23538. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  23539. LinearFilter: LinearFilter,
  23540. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  23541. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  23542. };
  23543. class ImageBitmapLoader extends Loader {
  23544. constructor(manager) {
  23545. super(manager);
  23546. if (typeof createImageBitmap === 'undefined') {
  23547. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  23548. }
  23549. if (typeof fetch === 'undefined') {
  23550. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  23551. }
  23552. this.options = {
  23553. premultiplyAlpha: 'none'
  23554. };
  23555. }
  23556. setOptions(options) {
  23557. this.options = options;
  23558. return this;
  23559. }
  23560. load(url, onLoad, onProgress, onError) {
  23561. if (url === undefined) url = '';
  23562. if (this.path !== undefined) url = this.path + url;
  23563. url = this.manager.resolveURL(url);
  23564. const scope = this;
  23565. const cached = Cache.get(url);
  23566. if (cached !== undefined) {
  23567. scope.manager.itemStart(url);
  23568. setTimeout(function () {
  23569. if (onLoad) onLoad(cached);
  23570. scope.manager.itemEnd(url);
  23571. }, 0);
  23572. return cached;
  23573. }
  23574. const fetchOptions = {};
  23575. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  23576. fetchOptions.headers = this.requestHeader;
  23577. fetch(url, fetchOptions).then(function (res) {
  23578. return res.blob();
  23579. }).then(function (blob) {
  23580. return createImageBitmap(blob, Object.assign(scope.options, {
  23581. colorSpaceConversion: 'none'
  23582. }));
  23583. }).then(function (imageBitmap) {
  23584. Cache.add(url, imageBitmap);
  23585. if (onLoad) onLoad(imageBitmap);
  23586. scope.manager.itemEnd(url);
  23587. }).catch(function (e) {
  23588. if (onError) onError(e);
  23589. scope.manager.itemError(url);
  23590. scope.manager.itemEnd(url);
  23591. });
  23592. scope.manager.itemStart(url);
  23593. }
  23594. }
  23595. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  23596. class ShapePath {
  23597. constructor() {
  23598. this.type = 'ShapePath';
  23599. this.color = new Color();
  23600. this.subPaths = [];
  23601. this.currentPath = null;
  23602. }
  23603. moveTo(x, y) {
  23604. this.currentPath = new Path();
  23605. this.subPaths.push(this.currentPath);
  23606. this.currentPath.moveTo(x, y);
  23607. return this;
  23608. }
  23609. lineTo(x, y) {
  23610. this.currentPath.lineTo(x, y);
  23611. return this;
  23612. }
  23613. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  23614. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  23615. return this;
  23616. }
  23617. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  23618. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  23619. return this;
  23620. }
  23621. splineThru(pts) {
  23622. this.currentPath.splineThru(pts);
  23623. return this;
  23624. }
  23625. toShapes(isCCW, noHoles) {
  23626. function toShapesNoHoles(inSubpaths) {
  23627. const shapes = [];
  23628. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  23629. const tmpPath = inSubpaths[i];
  23630. const tmpShape = new Shape();
  23631. tmpShape.curves = tmpPath.curves;
  23632. shapes.push(tmpShape);
  23633. }
  23634. return shapes;
  23635. }
  23636. function isPointInsidePolygon(inPt, inPolygon) {
  23637. const polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  23638. // toggling of inside/outside at every single! intersection point of an edge
  23639. // with the horizontal line through inPt, left of inPt
  23640. // not counting lowerY endpoints of edges and whole edges on that line
  23641. let inside = false;
  23642. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  23643. let edgeLowPt = inPolygon[p];
  23644. let edgeHighPt = inPolygon[q];
  23645. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  23646. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  23647. if (Math.abs(edgeDy) > Number.EPSILON) {
  23648. // not parallel
  23649. if (edgeDy < 0) {
  23650. edgeLowPt = inPolygon[q];
  23651. edgeDx = -edgeDx;
  23652. edgeHighPt = inPolygon[p];
  23653. edgeDy = -edgeDy;
  23654. }
  23655. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  23656. if (inPt.y === edgeLowPt.y) {
  23657. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  23658. // continue; // no intersection or edgeLowPt => doesn't count !!!
  23659. } else {
  23660. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  23661. if (perpEdge === 0) return true; // inPt is on contour ?
  23662. if (perpEdge < 0) continue;
  23663. inside = !inside; // true intersection left of inPt
  23664. }
  23665. } else {
  23666. // parallel or collinear
  23667. if (inPt.y !== edgeLowPt.y) continue; // parallel
  23668. // edge lies on the same horizontal line as inPt
  23669. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  23670. // continue;
  23671. }
  23672. }
  23673. return inside;
  23674. }
  23675. const isClockWise = ShapeUtils.isClockWise;
  23676. const subPaths = this.subPaths;
  23677. if (subPaths.length === 0) return [];
  23678. if (noHoles === true) return toShapesNoHoles(subPaths);
  23679. let solid, tmpPath, tmpShape;
  23680. const shapes = [];
  23681. if (subPaths.length === 1) {
  23682. tmpPath = subPaths[0];
  23683. tmpShape = new Shape();
  23684. tmpShape.curves = tmpPath.curves;
  23685. shapes.push(tmpShape);
  23686. return shapes;
  23687. }
  23688. let holesFirst = !isClockWise(subPaths[0].getPoints());
  23689. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  23690. const betterShapeHoles = [];
  23691. const newShapes = [];
  23692. let newShapeHoles = [];
  23693. let mainIdx = 0;
  23694. let tmpPoints;
  23695. newShapes[mainIdx] = undefined;
  23696. newShapeHoles[mainIdx] = [];
  23697. for (let i = 0, l = subPaths.length; i < l; i++) {
  23698. tmpPath = subPaths[i];
  23699. tmpPoints = tmpPath.getPoints();
  23700. solid = isClockWise(tmpPoints);
  23701. solid = isCCW ? !solid : solid;
  23702. if (solid) {
  23703. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  23704. newShapes[mainIdx] = {
  23705. s: new Shape(),
  23706. p: tmpPoints
  23707. };
  23708. newShapes[mainIdx].s.curves = tmpPath.curves;
  23709. if (holesFirst) mainIdx++;
  23710. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  23711. } else {
  23712. newShapeHoles[mainIdx].push({
  23713. h: tmpPath,
  23714. p: tmpPoints[0]
  23715. }); //console.log('ccw', i);
  23716. }
  23717. } // only Holes? -> probably all Shapes with wrong orientation
  23718. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  23719. if (newShapes.length > 1) {
  23720. let ambiguous = false;
  23721. const toChange = [];
  23722. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  23723. betterShapeHoles[sIdx] = [];
  23724. }
  23725. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  23726. const sho = newShapeHoles[sIdx];
  23727. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  23728. const ho = sho[hIdx];
  23729. let hole_unassigned = true;
  23730. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  23731. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  23732. if (sIdx !== s2Idx) toChange.push({
  23733. froms: sIdx,
  23734. tos: s2Idx,
  23735. hole: hIdx
  23736. });
  23737. if (hole_unassigned) {
  23738. hole_unassigned = false;
  23739. betterShapeHoles[s2Idx].push(ho);
  23740. } else {
  23741. ambiguous = true;
  23742. }
  23743. }
  23744. }
  23745. if (hole_unassigned) {
  23746. betterShapeHoles[sIdx].push(ho);
  23747. }
  23748. }
  23749. } // console.log("ambiguous: ", ambiguous);
  23750. if (toChange.length > 0) {
  23751. // console.log("to change: ", toChange);
  23752. if (!ambiguous) newShapeHoles = betterShapeHoles;
  23753. }
  23754. }
  23755. let tmpHoles;
  23756. for (let i = 0, il = newShapes.length; i < il; i++) {
  23757. tmpShape = newShapes[i].s;
  23758. shapes.push(tmpShape);
  23759. tmpHoles = newShapeHoles[i];
  23760. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  23761. tmpShape.holes.push(tmpHoles[j].h);
  23762. }
  23763. } //console.log("shape", shapes);
  23764. return shapes;
  23765. }
  23766. }
  23767. class Font {
  23768. constructor(data) {
  23769. this.type = 'Font';
  23770. this.data = data;
  23771. }
  23772. generateShapes(text, size = 100) {
  23773. const shapes = [];
  23774. const paths = createPaths(text, size, this.data);
  23775. for (let p = 0, pl = paths.length; p < pl; p++) {
  23776. Array.prototype.push.apply(shapes, paths[p].toShapes());
  23777. }
  23778. return shapes;
  23779. }
  23780. }
  23781. function createPaths(text, size, data) {
  23782. const chars = Array.from(text);
  23783. const scale = size / data.resolution;
  23784. const line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  23785. const paths = [];
  23786. let offsetX = 0,
  23787. offsetY = 0;
  23788. for (let i = 0; i < chars.length; i++) {
  23789. const char = chars[i];
  23790. if (char === '\n') {
  23791. offsetX = 0;
  23792. offsetY -= line_height;
  23793. } else {
  23794. const ret = createPath(char, scale, offsetX, offsetY, data);
  23795. offsetX += ret.offsetX;
  23796. paths.push(ret.path);
  23797. }
  23798. }
  23799. return paths;
  23800. }
  23801. function createPath(char, scale, offsetX, offsetY, data) {
  23802. const glyph = data.glyphs[char] || data.glyphs['?'];
  23803. if (!glyph) {
  23804. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  23805. return;
  23806. }
  23807. const path = new ShapePath();
  23808. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  23809. if (glyph.o) {
  23810. const outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  23811. for (let i = 0, l = outline.length; i < l;) {
  23812. const action = outline[i++];
  23813. switch (action) {
  23814. case 'm':
  23815. // moveTo
  23816. x = outline[i++] * scale + offsetX;
  23817. y = outline[i++] * scale + offsetY;
  23818. path.moveTo(x, y);
  23819. break;
  23820. case 'l':
  23821. // lineTo
  23822. x = outline[i++] * scale + offsetX;
  23823. y = outline[i++] * scale + offsetY;
  23824. path.lineTo(x, y);
  23825. break;
  23826. case 'q':
  23827. // quadraticCurveTo
  23828. cpx = outline[i++] * scale + offsetX;
  23829. cpy = outline[i++] * scale + offsetY;
  23830. cpx1 = outline[i++] * scale + offsetX;
  23831. cpy1 = outline[i++] * scale + offsetY;
  23832. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  23833. break;
  23834. case 'b':
  23835. // bezierCurveTo
  23836. cpx = outline[i++] * scale + offsetX;
  23837. cpy = outline[i++] * scale + offsetY;
  23838. cpx1 = outline[i++] * scale + offsetX;
  23839. cpy1 = outline[i++] * scale + offsetY;
  23840. cpx2 = outline[i++] * scale + offsetX;
  23841. cpy2 = outline[i++] * scale + offsetY;
  23842. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  23843. break;
  23844. }
  23845. }
  23846. }
  23847. return {
  23848. offsetX: glyph.ha * scale,
  23849. path: path
  23850. };
  23851. }
  23852. Font.prototype.isFont = true;
  23853. class FontLoader extends Loader {
  23854. constructor(manager) {
  23855. super(manager);
  23856. }
  23857. load(url, onLoad, onProgress, onError) {
  23858. const scope = this;
  23859. const loader = new FileLoader(this.manager);
  23860. loader.setPath(this.path);
  23861. loader.setRequestHeader(this.requestHeader);
  23862. loader.setWithCredentials(scope.withCredentials);
  23863. loader.load(url, function (text) {
  23864. let json;
  23865. try {
  23866. json = JSON.parse(text);
  23867. } catch (e) {
  23868. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  23869. json = JSON.parse(text.substring(65, text.length - 2));
  23870. }
  23871. const font = scope.parse(json);
  23872. if (onLoad) onLoad(font);
  23873. }, onProgress, onError);
  23874. }
  23875. parse(json) {
  23876. return new Font(json);
  23877. }
  23878. }
  23879. let _context;
  23880. const AudioContext = {
  23881. getContext: function () {
  23882. if (_context === undefined) {
  23883. _context = new (window.AudioContext || window.webkitAudioContext)();
  23884. }
  23885. return _context;
  23886. },
  23887. setContext: function (value) {
  23888. _context = value;
  23889. }
  23890. };
  23891. class AudioLoader extends Loader {
  23892. constructor(manager) {
  23893. super(manager);
  23894. }
  23895. load(url, onLoad, onProgress, onError) {
  23896. const scope = this;
  23897. const loader = new FileLoader(this.manager);
  23898. loader.setResponseType('arraybuffer');
  23899. loader.setPath(this.path);
  23900. loader.setRequestHeader(this.requestHeader);
  23901. loader.setWithCredentials(this.withCredentials);
  23902. loader.load(url, function (buffer) {
  23903. try {
  23904. // Create a copy of the buffer. The `decodeAudioData` method
  23905. // detaches the buffer when complete, preventing reuse.
  23906. const bufferCopy = buffer.slice(0);
  23907. const context = AudioContext.getContext();
  23908. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  23909. onLoad(audioBuffer);
  23910. });
  23911. } catch (e) {
  23912. if (onError) {
  23913. onError(e);
  23914. } else {
  23915. console.error(e);
  23916. }
  23917. scope.manager.itemError(url);
  23918. }
  23919. }, onProgress, onError);
  23920. }
  23921. }
  23922. class HemisphereLightProbe extends LightProbe {
  23923. constructor(skyColor, groundColor, intensity = 1) {
  23924. super(undefined, intensity);
  23925. const color1 = new Color().set(skyColor);
  23926. const color2 = new Color().set(groundColor);
  23927. const sky = new Vector3(color1.r, color1.g, color1.b);
  23928. const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  23929. const c0 = Math.sqrt(Math.PI);
  23930. const c1 = c0 * Math.sqrt(0.75);
  23931. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  23932. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  23933. }
  23934. }
  23935. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  23936. class AmbientLightProbe extends LightProbe {
  23937. constructor(color, intensity = 1) {
  23938. super(undefined, intensity);
  23939. const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  23940. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  23941. }
  23942. }
  23943. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  23944. const _eyeRight = /*@__PURE__*/new Matrix4();
  23945. const _eyeLeft = /*@__PURE__*/new Matrix4();
  23946. class StereoCamera {
  23947. constructor() {
  23948. this.type = 'StereoCamera';
  23949. this.aspect = 1;
  23950. this.eyeSep = 0.064;
  23951. this.cameraL = new PerspectiveCamera();
  23952. this.cameraL.layers.enable(1);
  23953. this.cameraL.matrixAutoUpdate = false;
  23954. this.cameraR = new PerspectiveCamera();
  23955. this.cameraR.layers.enable(2);
  23956. this.cameraR.matrixAutoUpdate = false;
  23957. this._cache = {
  23958. focus: null,
  23959. fov: null,
  23960. aspect: null,
  23961. near: null,
  23962. far: null,
  23963. zoom: null,
  23964. eyeSep: null
  23965. };
  23966. }
  23967. update(camera) {
  23968. const cache = this._cache;
  23969. 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;
  23970. if (needsUpdate) {
  23971. cache.focus = camera.focus;
  23972. cache.fov = camera.fov;
  23973. cache.aspect = camera.aspect * this.aspect;
  23974. cache.near = camera.near;
  23975. cache.far = camera.far;
  23976. cache.zoom = camera.zoom;
  23977. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  23978. // http://paulbourke.net/stereographics/stereorender/
  23979. const projectionMatrix = camera.projectionMatrix.clone();
  23980. const eyeSepHalf = cache.eyeSep / 2;
  23981. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  23982. const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom;
  23983. let xmin, xmax; // translate xOffset
  23984. _eyeLeft.elements[12] = -eyeSepHalf;
  23985. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  23986. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  23987. xmax = ymax * cache.aspect + eyeSepOnProjection;
  23988. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  23989. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  23990. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  23991. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  23992. xmax = ymax * cache.aspect - eyeSepOnProjection;
  23993. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  23994. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  23995. this.cameraR.projectionMatrix.copy(projectionMatrix);
  23996. }
  23997. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  23998. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  23999. }
  24000. }
  24001. class Clock {
  24002. constructor(autoStart = true) {
  24003. this.autoStart = autoStart;
  24004. this.startTime = 0;
  24005. this.oldTime = 0;
  24006. this.elapsedTime = 0;
  24007. this.running = false;
  24008. }
  24009. start() {
  24010. this.startTime = now();
  24011. this.oldTime = this.startTime;
  24012. this.elapsedTime = 0;
  24013. this.running = true;
  24014. }
  24015. stop() {
  24016. this.getElapsedTime();
  24017. this.running = false;
  24018. this.autoStart = false;
  24019. }
  24020. getElapsedTime() {
  24021. this.getDelta();
  24022. return this.elapsedTime;
  24023. }
  24024. getDelta() {
  24025. let diff = 0;
  24026. if (this.autoStart && !this.running) {
  24027. this.start();
  24028. return 0;
  24029. }
  24030. if (this.running) {
  24031. const newTime = now();
  24032. diff = (newTime - this.oldTime) / 1000;
  24033. this.oldTime = newTime;
  24034. this.elapsedTime += diff;
  24035. }
  24036. return diff;
  24037. }
  24038. }
  24039. function now() {
  24040. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  24041. }
  24042. const _position$1 = /*@__PURE__*/new Vector3();
  24043. const _quaternion$1 = /*@__PURE__*/new Quaternion();
  24044. const _scale$1 = /*@__PURE__*/new Vector3();
  24045. const _orientation$1 = /*@__PURE__*/new Vector3();
  24046. class AudioListener extends Object3D {
  24047. constructor() {
  24048. super();
  24049. this.type = 'AudioListener';
  24050. this.context = AudioContext.getContext();
  24051. this.gain = this.context.createGain();
  24052. this.gain.connect(this.context.destination);
  24053. this.filter = null;
  24054. this.timeDelta = 0; // private
  24055. this._clock = new Clock();
  24056. }
  24057. getInput() {
  24058. return this.gain;
  24059. }
  24060. removeFilter() {
  24061. if (this.filter !== null) {
  24062. this.gain.disconnect(this.filter);
  24063. this.filter.disconnect(this.context.destination);
  24064. this.gain.connect(this.context.destination);
  24065. this.filter = null;
  24066. }
  24067. return this;
  24068. }
  24069. getFilter() {
  24070. return this.filter;
  24071. }
  24072. setFilter(value) {
  24073. if (this.filter !== null) {
  24074. this.gain.disconnect(this.filter);
  24075. this.filter.disconnect(this.context.destination);
  24076. } else {
  24077. this.gain.disconnect(this.context.destination);
  24078. }
  24079. this.filter = value;
  24080. this.gain.connect(this.filter);
  24081. this.filter.connect(this.context.destination);
  24082. return this;
  24083. }
  24084. getMasterVolume() {
  24085. return this.gain.gain.value;
  24086. }
  24087. setMasterVolume(value) {
  24088. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  24089. return this;
  24090. }
  24091. updateMatrixWorld(force) {
  24092. super.updateMatrixWorld(force);
  24093. const listener = this.context.listener;
  24094. const up = this.up;
  24095. this.timeDelta = this._clock.getDelta();
  24096. this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
  24097. _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
  24098. if (listener.positionX) {
  24099. // code path for Chrome (see #14393)
  24100. const endTime = this.context.currentTime + this.timeDelta;
  24101. listener.positionX.linearRampToValueAtTime(_position$1.x, endTime);
  24102. listener.positionY.linearRampToValueAtTime(_position$1.y, endTime);
  24103. listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime);
  24104. listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime);
  24105. listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
  24106. listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  24107. listener.upX.linearRampToValueAtTime(up.x, endTime);
  24108. listener.upY.linearRampToValueAtTime(up.y, endTime);
  24109. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  24110. } else {
  24111. listener.setPosition(_position$1.x, _position$1.y, _position$1.z);
  24112. listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
  24113. }
  24114. }
  24115. }
  24116. class Audio extends Object3D {
  24117. constructor(listener) {
  24118. super();
  24119. this.type = 'Audio';
  24120. this.listener = listener;
  24121. this.context = listener.context;
  24122. this.gain = this.context.createGain();
  24123. this.gain.connect(listener.getInput());
  24124. this.autoplay = false;
  24125. this.buffer = null;
  24126. this.detune = 0;
  24127. this.loop = false;
  24128. this.loopStart = 0;
  24129. this.loopEnd = 0;
  24130. this.offset = 0;
  24131. this.duration = undefined;
  24132. this.playbackRate = 1;
  24133. this.isPlaying = false;
  24134. this.hasPlaybackControl = true;
  24135. this.source = null;
  24136. this.sourceType = 'empty';
  24137. this._startedAt = 0;
  24138. this._progress = 0;
  24139. this._connected = false;
  24140. this.filters = [];
  24141. }
  24142. getOutput() {
  24143. return this.gain;
  24144. }
  24145. setNodeSource(audioNode) {
  24146. this.hasPlaybackControl = false;
  24147. this.sourceType = 'audioNode';
  24148. this.source = audioNode;
  24149. this.connect();
  24150. return this;
  24151. }
  24152. setMediaElementSource(mediaElement) {
  24153. this.hasPlaybackControl = false;
  24154. this.sourceType = 'mediaNode';
  24155. this.source = this.context.createMediaElementSource(mediaElement);
  24156. this.connect();
  24157. return this;
  24158. }
  24159. setMediaStreamSource(mediaStream) {
  24160. this.hasPlaybackControl = false;
  24161. this.sourceType = 'mediaStreamNode';
  24162. this.source = this.context.createMediaStreamSource(mediaStream);
  24163. this.connect();
  24164. return this;
  24165. }
  24166. setBuffer(audioBuffer) {
  24167. this.buffer = audioBuffer;
  24168. this.sourceType = 'buffer';
  24169. if (this.autoplay) this.play();
  24170. return this;
  24171. }
  24172. play(delay = 0) {
  24173. if (this.isPlaying === true) {
  24174. console.warn('THREE.Audio: Audio is already playing.');
  24175. return;
  24176. }
  24177. if (this.hasPlaybackControl === false) {
  24178. console.warn('THREE.Audio: this Audio has no playback control.');
  24179. return;
  24180. }
  24181. this._startedAt = this.context.currentTime + delay;
  24182. const source = this.context.createBufferSource();
  24183. source.buffer = this.buffer;
  24184. source.loop = this.loop;
  24185. source.loopStart = this.loopStart;
  24186. source.loopEnd = this.loopEnd;
  24187. source.onended = this.onEnded.bind(this);
  24188. source.start(this._startedAt, this._progress + this.offset, this.duration);
  24189. this.isPlaying = true;
  24190. this.source = source;
  24191. this.setDetune(this.detune);
  24192. this.setPlaybackRate(this.playbackRate);
  24193. return this.connect();
  24194. }
  24195. pause() {
  24196. if (this.hasPlaybackControl === false) {
  24197. console.warn('THREE.Audio: this Audio has no playback control.');
  24198. return;
  24199. }
  24200. if (this.isPlaying === true) {
  24201. // update current progress
  24202. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  24203. if (this.loop === true) {
  24204. // ensure _progress does not exceed duration with looped audios
  24205. this._progress = this._progress % (this.duration || this.buffer.duration);
  24206. }
  24207. this.source.stop();
  24208. this.source.onended = null;
  24209. this.isPlaying = false;
  24210. }
  24211. return this;
  24212. }
  24213. stop() {
  24214. if (this.hasPlaybackControl === false) {
  24215. console.warn('THREE.Audio: this Audio has no playback control.');
  24216. return;
  24217. }
  24218. this._progress = 0;
  24219. this.source.stop();
  24220. this.source.onended = null;
  24221. this.isPlaying = false;
  24222. return this;
  24223. }
  24224. connect() {
  24225. if (this.filters.length > 0) {
  24226. this.source.connect(this.filters[0]);
  24227. for (let i = 1, l = this.filters.length; i < l; i++) {
  24228. this.filters[i - 1].connect(this.filters[i]);
  24229. }
  24230. this.filters[this.filters.length - 1].connect(this.getOutput());
  24231. } else {
  24232. this.source.connect(this.getOutput());
  24233. }
  24234. this._connected = true;
  24235. return this;
  24236. }
  24237. disconnect() {
  24238. if (this.filters.length > 0) {
  24239. this.source.disconnect(this.filters[0]);
  24240. for (let i = 1, l = this.filters.length; i < l; i++) {
  24241. this.filters[i - 1].disconnect(this.filters[i]);
  24242. }
  24243. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  24244. } else {
  24245. this.source.disconnect(this.getOutput());
  24246. }
  24247. this._connected = false;
  24248. return this;
  24249. }
  24250. getFilters() {
  24251. return this.filters;
  24252. }
  24253. setFilters(value) {
  24254. if (!value) value = [];
  24255. if (this._connected === true) {
  24256. this.disconnect();
  24257. this.filters = value.slice();
  24258. this.connect();
  24259. } else {
  24260. this.filters = value.slice();
  24261. }
  24262. return this;
  24263. }
  24264. setDetune(value) {
  24265. this.detune = value;
  24266. if (this.source.detune === undefined) return; // only set detune when available
  24267. if (this.isPlaying === true) {
  24268. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  24269. }
  24270. return this;
  24271. }
  24272. getDetune() {
  24273. return this.detune;
  24274. }
  24275. getFilter() {
  24276. return this.getFilters()[0];
  24277. }
  24278. setFilter(filter) {
  24279. return this.setFilters(filter ? [filter] : []);
  24280. }
  24281. setPlaybackRate(value) {
  24282. if (this.hasPlaybackControl === false) {
  24283. console.warn('THREE.Audio: this Audio has no playback control.');
  24284. return;
  24285. }
  24286. this.playbackRate = value;
  24287. if (this.isPlaying === true) {
  24288. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  24289. }
  24290. return this;
  24291. }
  24292. getPlaybackRate() {
  24293. return this.playbackRate;
  24294. }
  24295. onEnded() {
  24296. this.isPlaying = false;
  24297. }
  24298. getLoop() {
  24299. if (this.hasPlaybackControl === false) {
  24300. console.warn('THREE.Audio: this Audio has no playback control.');
  24301. return false;
  24302. }
  24303. return this.loop;
  24304. }
  24305. setLoop(value) {
  24306. if (this.hasPlaybackControl === false) {
  24307. console.warn('THREE.Audio: this Audio has no playback control.');
  24308. return;
  24309. }
  24310. this.loop = value;
  24311. if (this.isPlaying === true) {
  24312. this.source.loop = this.loop;
  24313. }
  24314. return this;
  24315. }
  24316. setLoopStart(value) {
  24317. this.loopStart = value;
  24318. return this;
  24319. }
  24320. setLoopEnd(value) {
  24321. this.loopEnd = value;
  24322. return this;
  24323. }
  24324. getVolume() {
  24325. return this.gain.gain.value;
  24326. }
  24327. setVolume(value) {
  24328. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  24329. return this;
  24330. }
  24331. }
  24332. const _position = /*@__PURE__*/new Vector3();
  24333. const _quaternion = /*@__PURE__*/new Quaternion();
  24334. const _scale = /*@__PURE__*/new Vector3();
  24335. const _orientation = /*@__PURE__*/new Vector3();
  24336. class PositionalAudio extends Audio {
  24337. constructor(listener) {
  24338. super(listener);
  24339. this.panner = this.context.createPanner();
  24340. this.panner.panningModel = 'HRTF';
  24341. this.panner.connect(this.gain);
  24342. }
  24343. getOutput() {
  24344. return this.panner;
  24345. }
  24346. getRefDistance() {
  24347. return this.panner.refDistance;
  24348. }
  24349. setRefDistance(value) {
  24350. this.panner.refDistance = value;
  24351. return this;
  24352. }
  24353. getRolloffFactor() {
  24354. return this.panner.rolloffFactor;
  24355. }
  24356. setRolloffFactor(value) {
  24357. this.panner.rolloffFactor = value;
  24358. return this;
  24359. }
  24360. getDistanceModel() {
  24361. return this.panner.distanceModel;
  24362. }
  24363. setDistanceModel(value) {
  24364. this.panner.distanceModel = value;
  24365. return this;
  24366. }
  24367. getMaxDistance() {
  24368. return this.panner.maxDistance;
  24369. }
  24370. setMaxDistance(value) {
  24371. this.panner.maxDistance = value;
  24372. return this;
  24373. }
  24374. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  24375. this.panner.coneInnerAngle = coneInnerAngle;
  24376. this.panner.coneOuterAngle = coneOuterAngle;
  24377. this.panner.coneOuterGain = coneOuterGain;
  24378. return this;
  24379. }
  24380. updateMatrixWorld(force) {
  24381. super.updateMatrixWorld(force);
  24382. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  24383. this.matrixWorld.decompose(_position, _quaternion, _scale);
  24384. _orientation.set(0, 0, 1).applyQuaternion(_quaternion);
  24385. const panner = this.panner;
  24386. if (panner.positionX) {
  24387. // code path for Chrome and Firefox (see #14393)
  24388. const endTime = this.context.currentTime + this.listener.timeDelta;
  24389. panner.positionX.linearRampToValueAtTime(_position.x, endTime);
  24390. panner.positionY.linearRampToValueAtTime(_position.y, endTime);
  24391. panner.positionZ.linearRampToValueAtTime(_position.z, endTime);
  24392. panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime);
  24393. panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime);
  24394. panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime);
  24395. } else {
  24396. panner.setPosition(_position.x, _position.y, _position.z);
  24397. panner.setOrientation(_orientation.x, _orientation.y, _orientation.z);
  24398. }
  24399. }
  24400. }
  24401. class AudioAnalyser {
  24402. constructor(audio, fftSize = 2048) {
  24403. this.analyser = audio.context.createAnalyser();
  24404. this.analyser.fftSize = fftSize;
  24405. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  24406. audio.getOutput().connect(this.analyser);
  24407. }
  24408. getFrequencyData() {
  24409. this.analyser.getByteFrequencyData(this.data);
  24410. return this.data;
  24411. }
  24412. getAverageFrequency() {
  24413. let value = 0;
  24414. const data = this.getFrequencyData();
  24415. for (let i = 0; i < data.length; i++) {
  24416. value += data[i];
  24417. }
  24418. return value / data.length;
  24419. }
  24420. }
  24421. class PropertyMixer {
  24422. constructor(binding, typeName, valueSize) {
  24423. this.binding = binding;
  24424. this.valueSize = valueSize;
  24425. let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  24426. //
  24427. // interpolators can use .buffer as their .result
  24428. // the data then goes to 'incoming'
  24429. //
  24430. // 'accu0' and 'accu1' are used frame-interleaved for
  24431. // the cumulative result and are compared to detect
  24432. // changes
  24433. //
  24434. // 'orig' stores the original state of the property
  24435. //
  24436. // 'add' is used for additive cumulative results
  24437. //
  24438. // 'work' is optional and is only present for quaternion types. It is used
  24439. // to store intermediate quaternion multiplication results
  24440. switch (typeName) {
  24441. case 'quaternion':
  24442. mixFunction = this._slerp;
  24443. mixFunctionAdditive = this._slerpAdditive;
  24444. setIdentity = this._setAdditiveIdentityQuaternion;
  24445. this.buffer = new Float64Array(valueSize * 6);
  24446. this._workIndex = 5;
  24447. break;
  24448. case 'string':
  24449. case 'bool':
  24450. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  24451. // additive is not relevant for non-numeric types
  24452. mixFunctionAdditive = this._select;
  24453. setIdentity = this._setAdditiveIdentityOther;
  24454. this.buffer = new Array(valueSize * 5);
  24455. break;
  24456. default:
  24457. mixFunction = this._lerp;
  24458. mixFunctionAdditive = this._lerpAdditive;
  24459. setIdentity = this._setAdditiveIdentityNumeric;
  24460. this.buffer = new Float64Array(valueSize * 5);
  24461. }
  24462. this._mixBufferRegion = mixFunction;
  24463. this._mixBufferRegionAdditive = mixFunctionAdditive;
  24464. this._setIdentity = setIdentity;
  24465. this._origIndex = 3;
  24466. this._addIndex = 4;
  24467. this.cumulativeWeight = 0;
  24468. this.cumulativeWeightAdditive = 0;
  24469. this.useCount = 0;
  24470. this.referenceCount = 0;
  24471. } // accumulate data in the 'incoming' region into 'accu<i>'
  24472. accumulate(accuIndex, weight) {
  24473. // note: happily accumulating nothing when weight = 0, the caller knows
  24474. // the weight and shouldn't have made the call in the first place
  24475. const buffer = this.buffer,
  24476. stride = this.valueSize,
  24477. offset = accuIndex * stride + stride;
  24478. let currentWeight = this.cumulativeWeight;
  24479. if (currentWeight === 0) {
  24480. // accuN := incoming * weight
  24481. for (let i = 0; i !== stride; ++i) {
  24482. buffer[offset + i] = buffer[i];
  24483. }
  24484. currentWeight = weight;
  24485. } else {
  24486. // accuN := accuN + incoming * weight
  24487. currentWeight += weight;
  24488. const mix = weight / currentWeight;
  24489. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  24490. }
  24491. this.cumulativeWeight = currentWeight;
  24492. } // accumulate data in the 'incoming' region into 'add'
  24493. accumulateAdditive(weight) {
  24494. const buffer = this.buffer,
  24495. stride = this.valueSize,
  24496. offset = stride * this._addIndex;
  24497. if (this.cumulativeWeightAdditive === 0) {
  24498. // add = identity
  24499. this._setIdentity();
  24500. } // add := add + incoming * weight
  24501. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  24502. this.cumulativeWeightAdditive += weight;
  24503. } // apply the state of 'accu<i>' to the binding when accus differ
  24504. apply(accuIndex) {
  24505. const stride = this.valueSize,
  24506. buffer = this.buffer,
  24507. offset = accuIndex * stride + stride,
  24508. weight = this.cumulativeWeight,
  24509. weightAdditive = this.cumulativeWeightAdditive,
  24510. binding = this.binding;
  24511. this.cumulativeWeight = 0;
  24512. this.cumulativeWeightAdditive = 0;
  24513. if (weight < 1) {
  24514. // accuN := accuN + original * ( 1 - cumulativeWeight )
  24515. const originalValueOffset = stride * this._origIndex;
  24516. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  24517. }
  24518. if (weightAdditive > 0) {
  24519. // accuN := accuN + additive accuN
  24520. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  24521. }
  24522. for (let i = stride, e = stride + stride; i !== e; ++i) {
  24523. if (buffer[i] !== buffer[i + stride]) {
  24524. // value has changed -> update scene graph
  24525. binding.setValue(buffer, offset);
  24526. break;
  24527. }
  24528. }
  24529. } // remember the state of the bound property and copy it to both accus
  24530. saveOriginalState() {
  24531. const binding = this.binding;
  24532. const buffer = this.buffer,
  24533. stride = this.valueSize,
  24534. originalValueOffset = stride * this._origIndex;
  24535. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  24536. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  24537. buffer[i] = buffer[originalValueOffset + i % stride];
  24538. } // Add to identity for additive
  24539. this._setIdentity();
  24540. this.cumulativeWeight = 0;
  24541. this.cumulativeWeightAdditive = 0;
  24542. } // apply the state previously taken via 'saveOriginalState' to the binding
  24543. restoreOriginalState() {
  24544. const originalValueOffset = this.valueSize * 3;
  24545. this.binding.setValue(this.buffer, originalValueOffset);
  24546. }
  24547. _setAdditiveIdentityNumeric() {
  24548. const startIndex = this._addIndex * this.valueSize;
  24549. const endIndex = startIndex + this.valueSize;
  24550. for (let i = startIndex; i < endIndex; i++) {
  24551. this.buffer[i] = 0;
  24552. }
  24553. }
  24554. _setAdditiveIdentityQuaternion() {
  24555. this._setAdditiveIdentityNumeric();
  24556. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  24557. }
  24558. _setAdditiveIdentityOther() {
  24559. const startIndex = this._origIndex * this.valueSize;
  24560. const targetIndex = this._addIndex * this.valueSize;
  24561. for (let i = 0; i < this.valueSize; i++) {
  24562. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  24563. }
  24564. } // mix functions
  24565. _select(buffer, dstOffset, srcOffset, t, stride) {
  24566. if (t >= 0.5) {
  24567. for (let i = 0; i !== stride; ++i) {
  24568. buffer[dstOffset + i] = buffer[srcOffset + i];
  24569. }
  24570. }
  24571. }
  24572. _slerp(buffer, dstOffset, srcOffset, t) {
  24573. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  24574. }
  24575. _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  24576. const workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  24577. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  24578. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  24579. }
  24580. _lerp(buffer, dstOffset, srcOffset, t, stride) {
  24581. const s = 1 - t;
  24582. for (let i = 0; i !== stride; ++i) {
  24583. const j = dstOffset + i;
  24584. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  24585. }
  24586. }
  24587. _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  24588. for (let i = 0; i !== stride; ++i) {
  24589. const j = dstOffset + i;
  24590. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  24591. }
  24592. }
  24593. }
  24594. // Characters [].:/ are reserved for track binding syntax.
  24595. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  24596. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  24597. // only latin characters, and the unicode \p{L} is not yet supported. So
  24598. // instead, we exclude reserved characters and match everything else.
  24599. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  24600. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  24601. // be matched to parse the rest of the track name.
  24602. const _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  24603. const _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  24604. // characters. Accessor may contain any character except closing bracket.
  24605. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  24606. // contain any non-bracket characters.
  24607. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  24608. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  24609. const _supportedObjectNames = ['material', 'materials', 'bones'];
  24610. class Composite {
  24611. constructor(targetGroup, path, optionalParsedPath) {
  24612. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  24613. this._targetGroup = targetGroup;
  24614. this._bindings = targetGroup.subscribe_(path, parsedPath);
  24615. }
  24616. getValue(array, offset) {
  24617. this.bind(); // bind all binding
  24618. const firstValidIndex = this._targetGroup.nCachedObjects_,
  24619. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  24620. if (binding !== undefined) binding.getValue(array, offset);
  24621. }
  24622. setValue(array, offset) {
  24623. const bindings = this._bindings;
  24624. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  24625. bindings[i].setValue(array, offset);
  24626. }
  24627. }
  24628. bind() {
  24629. const bindings = this._bindings;
  24630. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  24631. bindings[i].bind();
  24632. }
  24633. }
  24634. unbind() {
  24635. const bindings = this._bindings;
  24636. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  24637. bindings[i].unbind();
  24638. }
  24639. }
  24640. } // Note: This class uses a State pattern on a per-method basis:
  24641. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  24642. // prototype version of these methods with one that represents
  24643. // the bound state. When the property is not found, the methods
  24644. // become no-ops.
  24645. class PropertyBinding {
  24646. constructor(rootNode, path, parsedPath) {
  24647. this.path = path;
  24648. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  24649. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  24650. this.rootNode = rootNode; // initial state of these methods that calls 'bind'
  24651. this.getValue = this._getValue_unbound;
  24652. this.setValue = this._setValue_unbound;
  24653. }
  24654. static create(root, path, parsedPath) {
  24655. if (!(root && root.isAnimationObjectGroup)) {
  24656. return new PropertyBinding(root, path, parsedPath);
  24657. } else {
  24658. return new PropertyBinding.Composite(root, path, parsedPath);
  24659. }
  24660. }
  24661. /**
  24662. * Replaces spaces with underscores and removes unsupported characters from
  24663. * node names, to ensure compatibility with parseTrackName().
  24664. *
  24665. * @param {string} name Node name to be sanitized.
  24666. * @return {string}
  24667. */
  24668. static sanitizeNodeName(name) {
  24669. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  24670. }
  24671. static parseTrackName(trackName) {
  24672. const matches = _trackRe.exec(trackName);
  24673. if (!matches) {
  24674. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  24675. }
  24676. const results = {
  24677. // directoryName: matches[ 1 ], // (tschw) currently unused
  24678. nodeName: matches[2],
  24679. objectName: matches[3],
  24680. objectIndex: matches[4],
  24681. propertyName: matches[5],
  24682. // required
  24683. propertyIndex: matches[6]
  24684. };
  24685. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  24686. if (lastDot !== undefined && lastDot !== -1) {
  24687. const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  24688. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  24689. // 'bar' could be the objectName, or part of a nodeName (which can
  24690. // include '.' characters).
  24691. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  24692. results.nodeName = results.nodeName.substring(0, lastDot);
  24693. results.objectName = objectName;
  24694. }
  24695. }
  24696. if (results.propertyName === null || results.propertyName.length === 0) {
  24697. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  24698. }
  24699. return results;
  24700. }
  24701. static findNode(root, nodeName) {
  24702. if (!nodeName || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  24703. return root;
  24704. } // search into skeleton bones.
  24705. if (root.skeleton) {
  24706. const bone = root.skeleton.getBoneByName(nodeName);
  24707. if (bone !== undefined) {
  24708. return bone;
  24709. }
  24710. } // search into node subtree.
  24711. if (root.children) {
  24712. const searchNodeSubtree = function (children) {
  24713. for (let i = 0; i < children.length; i++) {
  24714. const childNode = children[i];
  24715. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  24716. return childNode;
  24717. }
  24718. const result = searchNodeSubtree(childNode.children);
  24719. if (result) return result;
  24720. }
  24721. return null;
  24722. };
  24723. const subTreeNode = searchNodeSubtree(root.children);
  24724. if (subTreeNode) {
  24725. return subTreeNode;
  24726. }
  24727. }
  24728. return null;
  24729. } // these are used to "bind" a nonexistent property
  24730. _getValue_unavailable() {}
  24731. _setValue_unavailable() {} // Getters
  24732. _getValue_direct(buffer, offset) {
  24733. buffer[offset] = this.node[this.propertyName];
  24734. }
  24735. _getValue_array(buffer, offset) {
  24736. const source = this.resolvedProperty;
  24737. for (let i = 0, n = source.length; i !== n; ++i) {
  24738. buffer[offset++] = source[i];
  24739. }
  24740. }
  24741. _getValue_arrayElement(buffer, offset) {
  24742. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  24743. }
  24744. _getValue_toArray(buffer, offset) {
  24745. this.resolvedProperty.toArray(buffer, offset);
  24746. } // Direct
  24747. _setValue_direct(buffer, offset) {
  24748. this.targetObject[this.propertyName] = buffer[offset];
  24749. }
  24750. _setValue_direct_setNeedsUpdate(buffer, offset) {
  24751. this.targetObject[this.propertyName] = buffer[offset];
  24752. this.targetObject.needsUpdate = true;
  24753. }
  24754. _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  24755. this.targetObject[this.propertyName] = buffer[offset];
  24756. this.targetObject.matrixWorldNeedsUpdate = true;
  24757. } // EntireArray
  24758. _setValue_array(buffer, offset) {
  24759. const dest = this.resolvedProperty;
  24760. for (let i = 0, n = dest.length; i !== n; ++i) {
  24761. dest[i] = buffer[offset++];
  24762. }
  24763. }
  24764. _setValue_array_setNeedsUpdate(buffer, offset) {
  24765. const dest = this.resolvedProperty;
  24766. for (let i = 0, n = dest.length; i !== n; ++i) {
  24767. dest[i] = buffer[offset++];
  24768. }
  24769. this.targetObject.needsUpdate = true;
  24770. }
  24771. _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  24772. const dest = this.resolvedProperty;
  24773. for (let i = 0, n = dest.length; i !== n; ++i) {
  24774. dest[i] = buffer[offset++];
  24775. }
  24776. this.targetObject.matrixWorldNeedsUpdate = true;
  24777. } // ArrayElement
  24778. _setValue_arrayElement(buffer, offset) {
  24779. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  24780. }
  24781. _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  24782. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  24783. this.targetObject.needsUpdate = true;
  24784. }
  24785. _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  24786. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  24787. this.targetObject.matrixWorldNeedsUpdate = true;
  24788. } // HasToFromArray
  24789. _setValue_fromArray(buffer, offset) {
  24790. this.resolvedProperty.fromArray(buffer, offset);
  24791. }
  24792. _setValue_fromArray_setNeedsUpdate(buffer, offset) {
  24793. this.resolvedProperty.fromArray(buffer, offset);
  24794. this.targetObject.needsUpdate = true;
  24795. }
  24796. _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  24797. this.resolvedProperty.fromArray(buffer, offset);
  24798. this.targetObject.matrixWorldNeedsUpdate = true;
  24799. }
  24800. _getValue_unbound(targetArray, offset) {
  24801. this.bind();
  24802. this.getValue(targetArray, offset);
  24803. }
  24804. _setValue_unbound(sourceArray, offset) {
  24805. this.bind();
  24806. this.setValue(sourceArray, offset);
  24807. } // create getter / setter pair for a property in the scene graph
  24808. bind() {
  24809. let targetObject = this.node;
  24810. const parsedPath = this.parsedPath;
  24811. const objectName = parsedPath.objectName;
  24812. const propertyName = parsedPath.propertyName;
  24813. let propertyIndex = parsedPath.propertyIndex;
  24814. if (!targetObject) {
  24815. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  24816. this.node = targetObject;
  24817. } // set fail state so we can just 'return' on error
  24818. this.getValue = this._getValue_unavailable;
  24819. this.setValue = this._setValue_unavailable; // ensure there is a value node
  24820. if (!targetObject) {
  24821. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  24822. return;
  24823. }
  24824. if (objectName) {
  24825. let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  24826. switch (objectName) {
  24827. case 'materials':
  24828. if (!targetObject.material) {
  24829. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  24830. return;
  24831. }
  24832. if (!targetObject.material.materials) {
  24833. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  24834. return;
  24835. }
  24836. targetObject = targetObject.material.materials;
  24837. break;
  24838. case 'bones':
  24839. if (!targetObject.skeleton) {
  24840. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  24841. return;
  24842. } // potential future optimization: skip this if propertyIndex is already an integer
  24843. // and convert the integer string to a true integer.
  24844. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  24845. for (let i = 0; i < targetObject.length; i++) {
  24846. if (targetObject[i].name === objectIndex) {
  24847. objectIndex = i;
  24848. break;
  24849. }
  24850. }
  24851. break;
  24852. default:
  24853. if (targetObject[objectName] === undefined) {
  24854. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  24855. return;
  24856. }
  24857. targetObject = targetObject[objectName];
  24858. }
  24859. if (objectIndex !== undefined) {
  24860. if (targetObject[objectIndex] === undefined) {
  24861. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  24862. return;
  24863. }
  24864. targetObject = targetObject[objectIndex];
  24865. }
  24866. } // resolve property
  24867. const nodeProperty = targetObject[propertyName];
  24868. if (nodeProperty === undefined) {
  24869. const nodeName = parsedPath.nodeName;
  24870. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  24871. return;
  24872. } // determine versioning scheme
  24873. let versioning = this.Versioning.None;
  24874. this.targetObject = targetObject;
  24875. if (targetObject.needsUpdate !== undefined) {
  24876. // material
  24877. versioning = this.Versioning.NeedsUpdate;
  24878. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  24879. // node transform
  24880. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  24881. } // determine how the property gets bound
  24882. let bindingType = this.BindingType.Direct;
  24883. if (propertyIndex !== undefined) {
  24884. // access a sub element of the property array (only primitives are supported right now)
  24885. if (propertyName === 'morphTargetInfluences') {
  24886. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  24887. // support resolving morphTarget names into indices.
  24888. if (!targetObject.geometry) {
  24889. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  24890. return;
  24891. }
  24892. if (targetObject.geometry.isBufferGeometry) {
  24893. if (!targetObject.geometry.morphAttributes) {
  24894. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  24895. return;
  24896. }
  24897. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  24898. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  24899. }
  24900. } else {
  24901. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
  24902. return;
  24903. }
  24904. }
  24905. bindingType = this.BindingType.ArrayElement;
  24906. this.resolvedProperty = nodeProperty;
  24907. this.propertyIndex = propertyIndex;
  24908. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  24909. // must use copy for Object3D.Euler/Quaternion
  24910. bindingType = this.BindingType.HasFromToArray;
  24911. this.resolvedProperty = nodeProperty;
  24912. } else if (Array.isArray(nodeProperty)) {
  24913. bindingType = this.BindingType.EntireArray;
  24914. this.resolvedProperty = nodeProperty;
  24915. } else {
  24916. this.propertyName = propertyName;
  24917. } // select getter / setter
  24918. this.getValue = this.GetterByBindingType[bindingType];
  24919. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  24920. }
  24921. unbind() {
  24922. this.node = null; // back to the prototype version of getValue / setValue
  24923. // note: avoiding to mutate the shape of 'this' via 'delete'
  24924. this.getValue = this._getValue_unbound;
  24925. this.setValue = this._setValue_unbound;
  24926. }
  24927. }
  24928. PropertyBinding.Composite = Composite;
  24929. PropertyBinding.prototype.BindingType = {
  24930. Direct: 0,
  24931. EntireArray: 1,
  24932. ArrayElement: 2,
  24933. HasFromToArray: 3
  24934. };
  24935. PropertyBinding.prototype.Versioning = {
  24936. None: 0,
  24937. NeedsUpdate: 1,
  24938. MatrixWorldNeedsUpdate: 2
  24939. };
  24940. PropertyBinding.prototype.GetterByBindingType = [PropertyBinding.prototype._getValue_direct, PropertyBinding.prototype._getValue_array, PropertyBinding.prototype._getValue_arrayElement, PropertyBinding.prototype._getValue_toArray];
  24941. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [[// Direct
  24942. PropertyBinding.prototype._setValue_direct, PropertyBinding.prototype._setValue_direct_setNeedsUpdate, PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate], [// EntireArray
  24943. PropertyBinding.prototype._setValue_array, PropertyBinding.prototype._setValue_array_setNeedsUpdate, PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate], [// ArrayElement
  24944. PropertyBinding.prototype._setValue_arrayElement, PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate], [// HasToFromArray
  24945. PropertyBinding.prototype._setValue_fromArray, PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];
  24946. /**
  24947. *
  24948. * A group of objects that receives a shared animation state.
  24949. *
  24950. * Usage:
  24951. *
  24952. * - Add objects you would otherwise pass as 'root' to the
  24953. * constructor or the .clipAction method of AnimationMixer.
  24954. *
  24955. * - Instead pass this object as 'root'.
  24956. *
  24957. * - You can also add and remove objects later when the mixer
  24958. * is running.
  24959. *
  24960. * Note:
  24961. *
  24962. * Objects of this class appear as one object to the mixer,
  24963. * so cache control of the individual objects must be done
  24964. * on the group.
  24965. *
  24966. * Limitation:
  24967. *
  24968. * - The animated properties must be compatible among the
  24969. * all objects in the group.
  24970. *
  24971. * - A single property can either be controlled through a
  24972. * target group or directly, but not both.
  24973. */
  24974. class AnimationObjectGroup {
  24975. constructor() {
  24976. this.uuid = generateUUID(); // cached objects followed by the active ones
  24977. this._objects = Array.prototype.slice.call(arguments);
  24978. this.nCachedObjects_ = 0; // threshold
  24979. // note: read by PropertyBinding.Composite
  24980. const indices = {};
  24981. this._indicesByUUID = indices; // for bookkeeping
  24982. for (let i = 0, n = arguments.length; i !== n; ++i) {
  24983. indices[arguments[i].uuid] = i;
  24984. }
  24985. this._paths = []; // inside: string
  24986. this._parsedPaths = []; // inside: { we don't care, here }
  24987. this._bindings = []; // inside: Array< PropertyBinding >
  24988. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  24989. const scope = this;
  24990. this.stats = {
  24991. objects: {
  24992. get total() {
  24993. return scope._objects.length;
  24994. },
  24995. get inUse() {
  24996. return this.total - scope.nCachedObjects_;
  24997. }
  24998. },
  24999. get bindingsPerObject() {
  25000. return scope._bindings.length;
  25001. }
  25002. };
  25003. }
  25004. add() {
  25005. const objects = this._objects,
  25006. indicesByUUID = this._indicesByUUID,
  25007. paths = this._paths,
  25008. parsedPaths = this._parsedPaths,
  25009. bindings = this._bindings,
  25010. nBindings = bindings.length;
  25011. let knownObject = undefined,
  25012. nObjects = objects.length,
  25013. nCachedObjects = this.nCachedObjects_;
  25014. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25015. const object = arguments[i],
  25016. uuid = object.uuid;
  25017. let index = indicesByUUID[uuid];
  25018. if (index === undefined) {
  25019. // unknown object -> add it to the ACTIVE region
  25020. index = nObjects++;
  25021. indicesByUUID[uuid] = index;
  25022. objects.push(object); // accounting is done, now do the same for all bindings
  25023. for (let j = 0, m = nBindings; j !== m; ++j) {
  25024. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  25025. }
  25026. } else if (index < nCachedObjects) {
  25027. knownObject = objects[index]; // move existing object to the ACTIVE region
  25028. const firstActiveIndex = --nCachedObjects,
  25029. lastCachedObject = objects[firstActiveIndex];
  25030. indicesByUUID[lastCachedObject.uuid] = index;
  25031. objects[index] = lastCachedObject;
  25032. indicesByUUID[uuid] = firstActiveIndex;
  25033. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  25034. for (let j = 0, m = nBindings; j !== m; ++j) {
  25035. const bindingsForPath = bindings[j],
  25036. lastCached = bindingsForPath[firstActiveIndex];
  25037. let binding = bindingsForPath[index];
  25038. bindingsForPath[index] = lastCached;
  25039. if (binding === undefined) {
  25040. // since we do not bother to create new bindings
  25041. // for objects that are cached, the binding may
  25042. // or may not exist
  25043. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  25044. }
  25045. bindingsForPath[firstActiveIndex] = binding;
  25046. }
  25047. } else if (objects[index] !== knownObject) {
  25048. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  25049. } // else the object is already where we want it to be
  25050. } // for arguments
  25051. this.nCachedObjects_ = nCachedObjects;
  25052. }
  25053. remove() {
  25054. const objects = this._objects,
  25055. indicesByUUID = this._indicesByUUID,
  25056. bindings = this._bindings,
  25057. nBindings = bindings.length;
  25058. let nCachedObjects = this.nCachedObjects_;
  25059. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25060. const object = arguments[i],
  25061. uuid = object.uuid,
  25062. index = indicesByUUID[uuid];
  25063. if (index !== undefined && index >= nCachedObjects) {
  25064. // move existing object into the CACHED region
  25065. const lastCachedIndex = nCachedObjects++,
  25066. firstActiveObject = objects[lastCachedIndex];
  25067. indicesByUUID[firstActiveObject.uuid] = index;
  25068. objects[index] = firstActiveObject;
  25069. indicesByUUID[uuid] = lastCachedIndex;
  25070. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  25071. for (let j = 0, m = nBindings; j !== m; ++j) {
  25072. const bindingsForPath = bindings[j],
  25073. firstActive = bindingsForPath[lastCachedIndex],
  25074. binding = bindingsForPath[index];
  25075. bindingsForPath[index] = firstActive;
  25076. bindingsForPath[lastCachedIndex] = binding;
  25077. }
  25078. }
  25079. } // for arguments
  25080. this.nCachedObjects_ = nCachedObjects;
  25081. } // remove & forget
  25082. uncache() {
  25083. const objects = this._objects,
  25084. indicesByUUID = this._indicesByUUID,
  25085. bindings = this._bindings,
  25086. nBindings = bindings.length;
  25087. let nCachedObjects = this.nCachedObjects_,
  25088. nObjects = objects.length;
  25089. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25090. const object = arguments[i],
  25091. uuid = object.uuid,
  25092. index = indicesByUUID[uuid];
  25093. if (index !== undefined) {
  25094. delete indicesByUUID[uuid];
  25095. if (index < nCachedObjects) {
  25096. // object is cached, shrink the CACHED region
  25097. const firstActiveIndex = --nCachedObjects,
  25098. lastCachedObject = objects[firstActiveIndex],
  25099. lastIndex = --nObjects,
  25100. lastObject = objects[lastIndex]; // last cached object takes this object's place
  25101. indicesByUUID[lastCachedObject.uuid] = index;
  25102. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  25103. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  25104. objects[firstActiveIndex] = lastObject;
  25105. objects.pop(); // accounting is done, now do the same for all bindings
  25106. for (let j = 0, m = nBindings; j !== m; ++j) {
  25107. const bindingsForPath = bindings[j],
  25108. lastCached = bindingsForPath[firstActiveIndex],
  25109. last = bindingsForPath[lastIndex];
  25110. bindingsForPath[index] = lastCached;
  25111. bindingsForPath[firstActiveIndex] = last;
  25112. bindingsForPath.pop();
  25113. }
  25114. } else {
  25115. // object is active, just swap with the last and pop
  25116. const lastIndex = --nObjects,
  25117. lastObject = objects[lastIndex];
  25118. if (lastIndex > 0) {
  25119. indicesByUUID[lastObject.uuid] = index;
  25120. }
  25121. objects[index] = lastObject;
  25122. objects.pop(); // accounting is done, now do the same for all bindings
  25123. for (let j = 0, m = nBindings; j !== m; ++j) {
  25124. const bindingsForPath = bindings[j];
  25125. bindingsForPath[index] = bindingsForPath[lastIndex];
  25126. bindingsForPath.pop();
  25127. }
  25128. } // cached or active
  25129. } // if object is known
  25130. } // for arguments
  25131. this.nCachedObjects_ = nCachedObjects;
  25132. } // Internal interface used by befriended PropertyBinding.Composite:
  25133. subscribe_(path, parsedPath) {
  25134. // returns an array of bindings for the given path that is changed
  25135. // according to the contained objects in the group
  25136. const indicesByPath = this._bindingsIndicesByPath;
  25137. let index = indicesByPath[path];
  25138. const bindings = this._bindings;
  25139. if (index !== undefined) return bindings[index];
  25140. const paths = this._paths,
  25141. parsedPaths = this._parsedPaths,
  25142. objects = this._objects,
  25143. nObjects = objects.length,
  25144. nCachedObjects = this.nCachedObjects_,
  25145. bindingsForPath = new Array(nObjects);
  25146. index = bindings.length;
  25147. indicesByPath[path] = index;
  25148. paths.push(path);
  25149. parsedPaths.push(parsedPath);
  25150. bindings.push(bindingsForPath);
  25151. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  25152. const object = objects[i];
  25153. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  25154. }
  25155. return bindingsForPath;
  25156. }
  25157. unsubscribe_(path) {
  25158. // tells the group to forget about a property path and no longer
  25159. // update the array previously obtained with 'subscribe_'
  25160. const indicesByPath = this._bindingsIndicesByPath,
  25161. index = indicesByPath[path];
  25162. if (index !== undefined) {
  25163. const paths = this._paths,
  25164. parsedPaths = this._parsedPaths,
  25165. bindings = this._bindings,
  25166. lastBindingsIndex = bindings.length - 1,
  25167. lastBindings = bindings[lastBindingsIndex],
  25168. lastBindingsPath = path[lastBindingsIndex];
  25169. indicesByPath[lastBindingsPath] = index;
  25170. bindings[index] = lastBindings;
  25171. bindings.pop();
  25172. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  25173. parsedPaths.pop();
  25174. paths[index] = paths[lastBindingsIndex];
  25175. paths.pop();
  25176. }
  25177. }
  25178. }
  25179. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  25180. class AnimationAction {
  25181. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  25182. this._mixer = mixer;
  25183. this._clip = clip;
  25184. this._localRoot = localRoot;
  25185. this.blendMode = blendMode;
  25186. const tracks = clip.tracks,
  25187. nTracks = tracks.length,
  25188. interpolants = new Array(nTracks);
  25189. const interpolantSettings = {
  25190. endingStart: ZeroCurvatureEnding,
  25191. endingEnd: ZeroCurvatureEnding
  25192. };
  25193. for (let i = 0; i !== nTracks; ++i) {
  25194. const interpolant = tracks[i].createInterpolant(null);
  25195. interpolants[i] = interpolant;
  25196. interpolant.settings = interpolantSettings;
  25197. }
  25198. this._interpolantSettings = interpolantSettings;
  25199. this._interpolants = interpolants; // bound by the mixer
  25200. // inside: PropertyMixer (managed by the mixer)
  25201. this._propertyBindings = new Array(nTracks);
  25202. this._cacheIndex = null; // for the memory manager
  25203. this._byClipCacheIndex = null; // for the memory manager
  25204. this._timeScaleInterpolant = null;
  25205. this._weightInterpolant = null;
  25206. this.loop = LoopRepeat;
  25207. this._loopCount = -1; // global mixer time when the action is to be started
  25208. // it's set back to 'null' upon start of the action
  25209. this._startTime = null; // scaled local time of the action
  25210. // gets clamped or wrapped to 0..clip.duration according to loop
  25211. this.time = 0;
  25212. this.timeScale = 1;
  25213. this._effectiveTimeScale = 1;
  25214. this.weight = 1;
  25215. this._effectiveWeight = 1;
  25216. this.repetitions = Infinity; // no. of repetitions when looping
  25217. this.paused = false; // true -> zero effective time scale
  25218. this.enabled = true; // false -> zero effective weight
  25219. this.clampWhenFinished = false; // keep feeding the last frame?
  25220. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  25221. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  25222. } // State & Scheduling
  25223. play() {
  25224. this._mixer._activateAction(this);
  25225. return this;
  25226. }
  25227. stop() {
  25228. this._mixer._deactivateAction(this);
  25229. return this.reset();
  25230. }
  25231. reset() {
  25232. this.paused = false;
  25233. this.enabled = true;
  25234. this.time = 0; // restart clip
  25235. this._loopCount = -1; // forget previous loops
  25236. this._startTime = null; // forget scheduling
  25237. return this.stopFading().stopWarping();
  25238. }
  25239. isRunning() {
  25240. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  25241. } // return true when play has been called
  25242. isScheduled() {
  25243. return this._mixer._isActiveAction(this);
  25244. }
  25245. startAt(time) {
  25246. this._startTime = time;
  25247. return this;
  25248. }
  25249. setLoop(mode, repetitions) {
  25250. this.loop = mode;
  25251. this.repetitions = repetitions;
  25252. return this;
  25253. } // Weight
  25254. // set the weight stopping any scheduled fading
  25255. // although .enabled = false yields an effective weight of zero, this
  25256. // method does *not* change .enabled, because it would be confusing
  25257. setEffectiveWeight(weight) {
  25258. this.weight = weight; // note: same logic as when updated at runtime
  25259. this._effectiveWeight = this.enabled ? weight : 0;
  25260. return this.stopFading();
  25261. } // return the weight considering fading and .enabled
  25262. getEffectiveWeight() {
  25263. return this._effectiveWeight;
  25264. }
  25265. fadeIn(duration) {
  25266. return this._scheduleFading(duration, 0, 1);
  25267. }
  25268. fadeOut(duration) {
  25269. return this._scheduleFading(duration, 1, 0);
  25270. }
  25271. crossFadeFrom(fadeOutAction, duration, warp) {
  25272. fadeOutAction.fadeOut(duration);
  25273. this.fadeIn(duration);
  25274. if (warp) {
  25275. const fadeInDuration = this._clip.duration,
  25276. fadeOutDuration = fadeOutAction._clip.duration,
  25277. startEndRatio = fadeOutDuration / fadeInDuration,
  25278. endStartRatio = fadeInDuration / fadeOutDuration;
  25279. fadeOutAction.warp(1.0, startEndRatio, duration);
  25280. this.warp(endStartRatio, 1.0, duration);
  25281. }
  25282. return this;
  25283. }
  25284. crossFadeTo(fadeInAction, duration, warp) {
  25285. return fadeInAction.crossFadeFrom(this, duration, warp);
  25286. }
  25287. stopFading() {
  25288. const weightInterpolant = this._weightInterpolant;
  25289. if (weightInterpolant !== null) {
  25290. this._weightInterpolant = null;
  25291. this._mixer._takeBackControlInterpolant(weightInterpolant);
  25292. }
  25293. return this;
  25294. } // Time Scale Control
  25295. // set the time scale stopping any scheduled warping
  25296. // although .paused = true yields an effective time scale of zero, this
  25297. // method does *not* change .paused, because it would be confusing
  25298. setEffectiveTimeScale(timeScale) {
  25299. this.timeScale = timeScale;
  25300. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  25301. return this.stopWarping();
  25302. } // return the time scale considering warping and .paused
  25303. getEffectiveTimeScale() {
  25304. return this._effectiveTimeScale;
  25305. }
  25306. setDuration(duration) {
  25307. this.timeScale = this._clip.duration / duration;
  25308. return this.stopWarping();
  25309. }
  25310. syncWith(action) {
  25311. this.time = action.time;
  25312. this.timeScale = action.timeScale;
  25313. return this.stopWarping();
  25314. }
  25315. halt(duration) {
  25316. return this.warp(this._effectiveTimeScale, 0, duration);
  25317. }
  25318. warp(startTimeScale, endTimeScale, duration) {
  25319. const mixer = this._mixer,
  25320. now = mixer.time,
  25321. timeScale = this.timeScale;
  25322. let interpolant = this._timeScaleInterpolant;
  25323. if (interpolant === null) {
  25324. interpolant = mixer._lendControlInterpolant();
  25325. this._timeScaleInterpolant = interpolant;
  25326. }
  25327. const times = interpolant.parameterPositions,
  25328. values = interpolant.sampleValues;
  25329. times[0] = now;
  25330. times[1] = now + duration;
  25331. values[0] = startTimeScale / timeScale;
  25332. values[1] = endTimeScale / timeScale;
  25333. return this;
  25334. }
  25335. stopWarping() {
  25336. const timeScaleInterpolant = this._timeScaleInterpolant;
  25337. if (timeScaleInterpolant !== null) {
  25338. this._timeScaleInterpolant = null;
  25339. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  25340. }
  25341. return this;
  25342. } // Object Accessors
  25343. getMixer() {
  25344. return this._mixer;
  25345. }
  25346. getClip() {
  25347. return this._clip;
  25348. }
  25349. getRoot() {
  25350. return this._localRoot || this._mixer._root;
  25351. } // Interna
  25352. _update(time, deltaTime, timeDirection, accuIndex) {
  25353. // called by the mixer
  25354. if (!this.enabled) {
  25355. // call ._updateWeight() to update ._effectiveWeight
  25356. this._updateWeight(time);
  25357. return;
  25358. }
  25359. const startTime = this._startTime;
  25360. if (startTime !== null) {
  25361. // check for scheduled start of action
  25362. const timeRunning = (time - startTime) * timeDirection;
  25363. if (timeRunning < 0 || timeDirection === 0) {
  25364. return; // yet to come / don't decide when delta = 0
  25365. } // start
  25366. this._startTime = null; // unschedule
  25367. deltaTime = timeDirection * timeRunning;
  25368. } // apply time scale and advance time
  25369. deltaTime *= this._updateTimeScale(time);
  25370. const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  25371. // an effective weight of 0
  25372. const weight = this._updateWeight(time);
  25373. if (weight > 0) {
  25374. const interpolants = this._interpolants;
  25375. const propertyMixers = this._propertyBindings;
  25376. switch (this.blendMode) {
  25377. case AdditiveAnimationBlendMode:
  25378. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  25379. interpolants[j].evaluate(clipTime);
  25380. propertyMixers[j].accumulateAdditive(weight);
  25381. }
  25382. break;
  25383. case NormalAnimationBlendMode:
  25384. default:
  25385. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  25386. interpolants[j].evaluate(clipTime);
  25387. propertyMixers[j].accumulate(accuIndex, weight);
  25388. }
  25389. }
  25390. }
  25391. }
  25392. _updateWeight(time) {
  25393. let weight = 0;
  25394. if (this.enabled) {
  25395. weight = this.weight;
  25396. const interpolant = this._weightInterpolant;
  25397. if (interpolant !== null) {
  25398. const interpolantValue = interpolant.evaluate(time)[0];
  25399. weight *= interpolantValue;
  25400. if (time > interpolant.parameterPositions[1]) {
  25401. this.stopFading();
  25402. if (interpolantValue === 0) {
  25403. // faded out, disable
  25404. this.enabled = false;
  25405. }
  25406. }
  25407. }
  25408. }
  25409. this._effectiveWeight = weight;
  25410. return weight;
  25411. }
  25412. _updateTimeScale(time) {
  25413. let timeScale = 0;
  25414. if (!this.paused) {
  25415. timeScale = this.timeScale;
  25416. const interpolant = this._timeScaleInterpolant;
  25417. if (interpolant !== null) {
  25418. const interpolantValue = interpolant.evaluate(time)[0];
  25419. timeScale *= interpolantValue;
  25420. if (time > interpolant.parameterPositions[1]) {
  25421. this.stopWarping();
  25422. if (timeScale === 0) {
  25423. // motion has halted, pause
  25424. this.paused = true;
  25425. } else {
  25426. // warp done - apply final time scale
  25427. this.timeScale = timeScale;
  25428. }
  25429. }
  25430. }
  25431. }
  25432. this._effectiveTimeScale = timeScale;
  25433. return timeScale;
  25434. }
  25435. _updateTime(deltaTime) {
  25436. const duration = this._clip.duration;
  25437. const loop = this.loop;
  25438. let time = this.time + deltaTime;
  25439. let loopCount = this._loopCount;
  25440. const pingPong = loop === LoopPingPong;
  25441. if (deltaTime === 0) {
  25442. if (loopCount === -1) return time;
  25443. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  25444. }
  25445. if (loop === LoopOnce) {
  25446. if (loopCount === -1) {
  25447. // just started
  25448. this._loopCount = 0;
  25449. this._setEndings(true, true, false);
  25450. }
  25451. handle_stop: {
  25452. if (time >= duration) {
  25453. time = duration;
  25454. } else if (time < 0) {
  25455. time = 0;
  25456. } else {
  25457. this.time = time;
  25458. break handle_stop;
  25459. }
  25460. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  25461. this.time = time;
  25462. this._mixer.dispatchEvent({
  25463. type: 'finished',
  25464. action: this,
  25465. direction: deltaTime < 0 ? -1 : 1
  25466. });
  25467. }
  25468. } else {
  25469. // repetitive Repeat or PingPong
  25470. if (loopCount === -1) {
  25471. // just started
  25472. if (deltaTime >= 0) {
  25473. loopCount = 0;
  25474. this._setEndings(true, this.repetitions === 0, pingPong);
  25475. } else {
  25476. // when looping in reverse direction, the initial
  25477. // transition through zero counts as a repetition,
  25478. // so leave loopCount at -1
  25479. this._setEndings(this.repetitions === 0, true, pingPong);
  25480. }
  25481. }
  25482. if (time >= duration || time < 0) {
  25483. // wrap around
  25484. const loopDelta = Math.floor(time / duration); // signed
  25485. time -= duration * loopDelta;
  25486. loopCount += Math.abs(loopDelta);
  25487. const pending = this.repetitions - loopCount;
  25488. if (pending <= 0) {
  25489. // have to stop (switch state, clamp time, fire event)
  25490. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  25491. time = deltaTime > 0 ? duration : 0;
  25492. this.time = time;
  25493. this._mixer.dispatchEvent({
  25494. type: 'finished',
  25495. action: this,
  25496. direction: deltaTime > 0 ? 1 : -1
  25497. });
  25498. } else {
  25499. // keep running
  25500. if (pending === 1) {
  25501. // entering the last round
  25502. const atStart = deltaTime < 0;
  25503. this._setEndings(atStart, !atStart, pingPong);
  25504. } else {
  25505. this._setEndings(false, false, pingPong);
  25506. }
  25507. this._loopCount = loopCount;
  25508. this.time = time;
  25509. this._mixer.dispatchEvent({
  25510. type: 'loop',
  25511. action: this,
  25512. loopDelta: loopDelta
  25513. });
  25514. }
  25515. } else {
  25516. this.time = time;
  25517. }
  25518. if (pingPong && (loopCount & 1) === 1) {
  25519. // invert time for the "pong round"
  25520. return duration - time;
  25521. }
  25522. }
  25523. return time;
  25524. }
  25525. _setEndings(atStart, atEnd, pingPong) {
  25526. const settings = this._interpolantSettings;
  25527. if (pingPong) {
  25528. settings.endingStart = ZeroSlopeEnding;
  25529. settings.endingEnd = ZeroSlopeEnding;
  25530. } else {
  25531. // assuming for LoopOnce atStart == atEnd == true
  25532. if (atStart) {
  25533. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  25534. } else {
  25535. settings.endingStart = WrapAroundEnding;
  25536. }
  25537. if (atEnd) {
  25538. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  25539. } else {
  25540. settings.endingEnd = WrapAroundEnding;
  25541. }
  25542. }
  25543. }
  25544. _scheduleFading(duration, weightNow, weightThen) {
  25545. const mixer = this._mixer,
  25546. now = mixer.time;
  25547. let interpolant = this._weightInterpolant;
  25548. if (interpolant === null) {
  25549. interpolant = mixer._lendControlInterpolant();
  25550. this._weightInterpolant = interpolant;
  25551. }
  25552. const times = interpolant.parameterPositions,
  25553. values = interpolant.sampleValues;
  25554. times[0] = now;
  25555. values[0] = weightNow;
  25556. times[1] = now + duration;
  25557. values[1] = weightThen;
  25558. return this;
  25559. }
  25560. }
  25561. class AnimationMixer extends EventDispatcher {
  25562. constructor(root) {
  25563. super();
  25564. this._root = root;
  25565. this._initMemoryManager();
  25566. this._accuIndex = 0;
  25567. this.time = 0;
  25568. this.timeScale = 1.0;
  25569. }
  25570. _bindAction(action, prototypeAction) {
  25571. const root = action._localRoot || this._root,
  25572. tracks = action._clip.tracks,
  25573. nTracks = tracks.length,
  25574. bindings = action._propertyBindings,
  25575. interpolants = action._interpolants,
  25576. rootUuid = root.uuid,
  25577. bindingsByRoot = this._bindingsByRootAndName;
  25578. let bindingsByName = bindingsByRoot[rootUuid];
  25579. if (bindingsByName === undefined) {
  25580. bindingsByName = {};
  25581. bindingsByRoot[rootUuid] = bindingsByName;
  25582. }
  25583. for (let i = 0; i !== nTracks; ++i) {
  25584. const track = tracks[i],
  25585. trackName = track.name;
  25586. let binding = bindingsByName[trackName];
  25587. if (binding !== undefined) {
  25588. bindings[i] = binding;
  25589. } else {
  25590. binding = bindings[i];
  25591. if (binding !== undefined) {
  25592. // existing binding, make sure the cache knows
  25593. if (binding._cacheIndex === null) {
  25594. ++binding.referenceCount;
  25595. this._addInactiveBinding(binding, rootUuid, trackName);
  25596. }
  25597. continue;
  25598. }
  25599. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  25600. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  25601. ++binding.referenceCount;
  25602. this._addInactiveBinding(binding, rootUuid, trackName);
  25603. bindings[i] = binding;
  25604. }
  25605. interpolants[i].resultBuffer = binding.buffer;
  25606. }
  25607. }
  25608. _activateAction(action) {
  25609. if (!this._isActiveAction(action)) {
  25610. if (action._cacheIndex === null) {
  25611. // this action has been forgotten by the cache, but the user
  25612. // appears to be still using it -> rebind
  25613. const rootUuid = (action._localRoot || this._root).uuid,
  25614. clipUuid = action._clip.uuid,
  25615. actionsForClip = this._actionsByClip[clipUuid];
  25616. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  25617. this._addInactiveAction(action, clipUuid, rootUuid);
  25618. }
  25619. const bindings = action._propertyBindings; // increment reference counts / sort out state
  25620. for (let i = 0, n = bindings.length; i !== n; ++i) {
  25621. const binding = bindings[i];
  25622. if (binding.useCount++ === 0) {
  25623. this._lendBinding(binding);
  25624. binding.saveOriginalState();
  25625. }
  25626. }
  25627. this._lendAction(action);
  25628. }
  25629. }
  25630. _deactivateAction(action) {
  25631. if (this._isActiveAction(action)) {
  25632. const bindings = action._propertyBindings; // decrement reference counts / sort out state
  25633. for (let i = 0, n = bindings.length; i !== n; ++i) {
  25634. const binding = bindings[i];
  25635. if (--binding.useCount === 0) {
  25636. binding.restoreOriginalState();
  25637. this._takeBackBinding(binding);
  25638. }
  25639. }
  25640. this._takeBackAction(action);
  25641. }
  25642. } // Memory manager
  25643. _initMemoryManager() {
  25644. this._actions = []; // 'nActiveActions' followed by inactive ones
  25645. this._nActiveActions = 0;
  25646. this._actionsByClip = {}; // inside:
  25647. // {
  25648. // knownActions: Array< AnimationAction > - used as prototypes
  25649. // actionByRoot: AnimationAction - lookup
  25650. // }
  25651. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  25652. this._nActiveBindings = 0;
  25653. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  25654. this._controlInterpolants = []; // same game as above
  25655. this._nActiveControlInterpolants = 0;
  25656. const scope = this;
  25657. this.stats = {
  25658. actions: {
  25659. get total() {
  25660. return scope._actions.length;
  25661. },
  25662. get inUse() {
  25663. return scope._nActiveActions;
  25664. }
  25665. },
  25666. bindings: {
  25667. get total() {
  25668. return scope._bindings.length;
  25669. },
  25670. get inUse() {
  25671. return scope._nActiveBindings;
  25672. }
  25673. },
  25674. controlInterpolants: {
  25675. get total() {
  25676. return scope._controlInterpolants.length;
  25677. },
  25678. get inUse() {
  25679. return scope._nActiveControlInterpolants;
  25680. }
  25681. }
  25682. };
  25683. } // Memory management for AnimationAction objects
  25684. _isActiveAction(action) {
  25685. const index = action._cacheIndex;
  25686. return index !== null && index < this._nActiveActions;
  25687. }
  25688. _addInactiveAction(action, clipUuid, rootUuid) {
  25689. const actions = this._actions,
  25690. actionsByClip = this._actionsByClip;
  25691. let actionsForClip = actionsByClip[clipUuid];
  25692. if (actionsForClip === undefined) {
  25693. actionsForClip = {
  25694. knownActions: [action],
  25695. actionByRoot: {}
  25696. };
  25697. action._byClipCacheIndex = 0;
  25698. actionsByClip[clipUuid] = actionsForClip;
  25699. } else {
  25700. const knownActions = actionsForClip.knownActions;
  25701. action._byClipCacheIndex = knownActions.length;
  25702. knownActions.push(action);
  25703. }
  25704. action._cacheIndex = actions.length;
  25705. actions.push(action);
  25706. actionsForClip.actionByRoot[rootUuid] = action;
  25707. }
  25708. _removeInactiveAction(action) {
  25709. const actions = this._actions,
  25710. lastInactiveAction = actions[actions.length - 1],
  25711. cacheIndex = action._cacheIndex;
  25712. lastInactiveAction._cacheIndex = cacheIndex;
  25713. actions[cacheIndex] = lastInactiveAction;
  25714. actions.pop();
  25715. action._cacheIndex = null;
  25716. const clipUuid = action._clip.uuid,
  25717. actionsByClip = this._actionsByClip,
  25718. actionsForClip = actionsByClip[clipUuid],
  25719. knownActionsForClip = actionsForClip.knownActions,
  25720. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  25721. byClipCacheIndex = action._byClipCacheIndex;
  25722. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  25723. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  25724. knownActionsForClip.pop();
  25725. action._byClipCacheIndex = null;
  25726. const actionByRoot = actionsForClip.actionByRoot,
  25727. rootUuid = (action._localRoot || this._root).uuid;
  25728. delete actionByRoot[rootUuid];
  25729. if (knownActionsForClip.length === 0) {
  25730. delete actionsByClip[clipUuid];
  25731. }
  25732. this._removeInactiveBindingsForAction(action);
  25733. }
  25734. _removeInactiveBindingsForAction(action) {
  25735. const bindings = action._propertyBindings;
  25736. for (let i = 0, n = bindings.length; i !== n; ++i) {
  25737. const binding = bindings[i];
  25738. if (--binding.referenceCount === 0) {
  25739. this._removeInactiveBinding(binding);
  25740. }
  25741. }
  25742. }
  25743. _lendAction(action) {
  25744. // [ active actions | inactive actions ]
  25745. // [ active actions >| inactive actions ]
  25746. // s a
  25747. // <-swap->
  25748. // a s
  25749. const actions = this._actions,
  25750. prevIndex = action._cacheIndex,
  25751. lastActiveIndex = this._nActiveActions++,
  25752. firstInactiveAction = actions[lastActiveIndex];
  25753. action._cacheIndex = lastActiveIndex;
  25754. actions[lastActiveIndex] = action;
  25755. firstInactiveAction._cacheIndex = prevIndex;
  25756. actions[prevIndex] = firstInactiveAction;
  25757. }
  25758. _takeBackAction(action) {
  25759. // [ active actions | inactive actions ]
  25760. // [ active actions |< inactive actions ]
  25761. // a s
  25762. // <-swap->
  25763. // s a
  25764. const actions = this._actions,
  25765. prevIndex = action._cacheIndex,
  25766. firstInactiveIndex = --this._nActiveActions,
  25767. lastActiveAction = actions[firstInactiveIndex];
  25768. action._cacheIndex = firstInactiveIndex;
  25769. actions[firstInactiveIndex] = action;
  25770. lastActiveAction._cacheIndex = prevIndex;
  25771. actions[prevIndex] = lastActiveAction;
  25772. } // Memory management for PropertyMixer objects
  25773. _addInactiveBinding(binding, rootUuid, trackName) {
  25774. const bindingsByRoot = this._bindingsByRootAndName,
  25775. bindings = this._bindings;
  25776. let bindingByName = bindingsByRoot[rootUuid];
  25777. if (bindingByName === undefined) {
  25778. bindingByName = {};
  25779. bindingsByRoot[rootUuid] = bindingByName;
  25780. }
  25781. bindingByName[trackName] = binding;
  25782. binding._cacheIndex = bindings.length;
  25783. bindings.push(binding);
  25784. }
  25785. _removeInactiveBinding(binding) {
  25786. const bindings = this._bindings,
  25787. propBinding = binding.binding,
  25788. rootUuid = propBinding.rootNode.uuid,
  25789. trackName = propBinding.path,
  25790. bindingsByRoot = this._bindingsByRootAndName,
  25791. bindingByName = bindingsByRoot[rootUuid],
  25792. lastInactiveBinding = bindings[bindings.length - 1],
  25793. cacheIndex = binding._cacheIndex;
  25794. lastInactiveBinding._cacheIndex = cacheIndex;
  25795. bindings[cacheIndex] = lastInactiveBinding;
  25796. bindings.pop();
  25797. delete bindingByName[trackName];
  25798. if (Object.keys(bindingByName).length === 0) {
  25799. delete bindingsByRoot[rootUuid];
  25800. }
  25801. }
  25802. _lendBinding(binding) {
  25803. const bindings = this._bindings,
  25804. prevIndex = binding._cacheIndex,
  25805. lastActiveIndex = this._nActiveBindings++,
  25806. firstInactiveBinding = bindings[lastActiveIndex];
  25807. binding._cacheIndex = lastActiveIndex;
  25808. bindings[lastActiveIndex] = binding;
  25809. firstInactiveBinding._cacheIndex = prevIndex;
  25810. bindings[prevIndex] = firstInactiveBinding;
  25811. }
  25812. _takeBackBinding(binding) {
  25813. const bindings = this._bindings,
  25814. prevIndex = binding._cacheIndex,
  25815. firstInactiveIndex = --this._nActiveBindings,
  25816. lastActiveBinding = bindings[firstInactiveIndex];
  25817. binding._cacheIndex = firstInactiveIndex;
  25818. bindings[firstInactiveIndex] = binding;
  25819. lastActiveBinding._cacheIndex = prevIndex;
  25820. bindings[prevIndex] = lastActiveBinding;
  25821. } // Memory management of Interpolants for weight and time scale
  25822. _lendControlInterpolant() {
  25823. const interpolants = this._controlInterpolants,
  25824. lastActiveIndex = this._nActiveControlInterpolants++;
  25825. let interpolant = interpolants[lastActiveIndex];
  25826. if (interpolant === undefined) {
  25827. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  25828. interpolant.__cacheIndex = lastActiveIndex;
  25829. interpolants[lastActiveIndex] = interpolant;
  25830. }
  25831. return interpolant;
  25832. }
  25833. _takeBackControlInterpolant(interpolant) {
  25834. const interpolants = this._controlInterpolants,
  25835. prevIndex = interpolant.__cacheIndex,
  25836. firstInactiveIndex = --this._nActiveControlInterpolants,
  25837. lastActiveInterpolant = interpolants[firstInactiveIndex];
  25838. interpolant.__cacheIndex = firstInactiveIndex;
  25839. interpolants[firstInactiveIndex] = interpolant;
  25840. lastActiveInterpolant.__cacheIndex = prevIndex;
  25841. interpolants[prevIndex] = lastActiveInterpolant;
  25842. } // return an action for a clip optionally using a custom root target
  25843. // object (this method allocates a lot of dynamic memory in case a
  25844. // previously unknown clip/root combination is specified)
  25845. clipAction(clip, optionalRoot, blendMode) {
  25846. const root = optionalRoot || this._root,
  25847. rootUuid = root.uuid;
  25848. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  25849. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  25850. const actionsForClip = this._actionsByClip[clipUuid];
  25851. let prototypeAction = null;
  25852. if (blendMode === undefined) {
  25853. if (clipObject !== null) {
  25854. blendMode = clipObject.blendMode;
  25855. } else {
  25856. blendMode = NormalAnimationBlendMode;
  25857. }
  25858. }
  25859. if (actionsForClip !== undefined) {
  25860. const existingAction = actionsForClip.actionByRoot[rootUuid];
  25861. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  25862. return existingAction;
  25863. } // we know the clip, so we don't have to parse all
  25864. // the bindings again but can just copy
  25865. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  25866. if (clipObject === null) clipObject = prototypeAction._clip;
  25867. } // clip must be known when specified via string
  25868. if (clipObject === null) return null; // allocate all resources required to run it
  25869. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  25870. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  25871. this._addInactiveAction(newAction, clipUuid, rootUuid);
  25872. return newAction;
  25873. } // get an existing action
  25874. existingAction(clip, optionalRoot) {
  25875. const root = optionalRoot || this._root,
  25876. rootUuid = root.uuid,
  25877. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  25878. clipUuid = clipObject ? clipObject.uuid : clip,
  25879. actionsForClip = this._actionsByClip[clipUuid];
  25880. if (actionsForClip !== undefined) {
  25881. return actionsForClip.actionByRoot[rootUuid] || null;
  25882. }
  25883. return null;
  25884. } // deactivates all previously scheduled actions
  25885. stopAllAction() {
  25886. const actions = this._actions,
  25887. nActions = this._nActiveActions;
  25888. for (let i = nActions - 1; i >= 0; --i) {
  25889. actions[i].stop();
  25890. }
  25891. return this;
  25892. } // advance the time and update apply the animation
  25893. update(deltaTime) {
  25894. deltaTime *= this.timeScale;
  25895. const actions = this._actions,
  25896. nActions = this._nActiveActions,
  25897. time = this.time += deltaTime,
  25898. timeDirection = Math.sign(deltaTime),
  25899. accuIndex = this._accuIndex ^= 1; // run active actions
  25900. for (let i = 0; i !== nActions; ++i) {
  25901. const action = actions[i];
  25902. action._update(time, deltaTime, timeDirection, accuIndex);
  25903. } // update scene graph
  25904. const bindings = this._bindings,
  25905. nBindings = this._nActiveBindings;
  25906. for (let i = 0; i !== nBindings; ++i) {
  25907. bindings[i].apply(accuIndex);
  25908. }
  25909. return this;
  25910. } // Allows you to seek to a specific time in an animation.
  25911. setTime(timeInSeconds) {
  25912. this.time = 0; // Zero out time attribute for AnimationMixer object;
  25913. for (let i = 0; i < this._actions.length; i++) {
  25914. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  25915. }
  25916. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  25917. } // return this mixer's root target object
  25918. getRoot() {
  25919. return this._root;
  25920. } // free all resources specific to a particular clip
  25921. uncacheClip(clip) {
  25922. const actions = this._actions,
  25923. clipUuid = clip.uuid,
  25924. actionsByClip = this._actionsByClip,
  25925. actionsForClip = actionsByClip[clipUuid];
  25926. if (actionsForClip !== undefined) {
  25927. // note: just calling _removeInactiveAction would mess up the
  25928. // iteration state and also require updating the state we can
  25929. // just throw away
  25930. const actionsToRemove = actionsForClip.knownActions;
  25931. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  25932. const action = actionsToRemove[i];
  25933. this._deactivateAction(action);
  25934. const cacheIndex = action._cacheIndex,
  25935. lastInactiveAction = actions[actions.length - 1];
  25936. action._cacheIndex = null;
  25937. action._byClipCacheIndex = null;
  25938. lastInactiveAction._cacheIndex = cacheIndex;
  25939. actions[cacheIndex] = lastInactiveAction;
  25940. actions.pop();
  25941. this._removeInactiveBindingsForAction(action);
  25942. }
  25943. delete actionsByClip[clipUuid];
  25944. }
  25945. } // free all resources specific to a particular root target object
  25946. uncacheRoot(root) {
  25947. const rootUuid = root.uuid,
  25948. actionsByClip = this._actionsByClip;
  25949. for (const clipUuid in actionsByClip) {
  25950. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  25951. action = actionByRoot[rootUuid];
  25952. if (action !== undefined) {
  25953. this._deactivateAction(action);
  25954. this._removeInactiveAction(action);
  25955. }
  25956. }
  25957. const bindingsByRoot = this._bindingsByRootAndName,
  25958. bindingByName = bindingsByRoot[rootUuid];
  25959. if (bindingByName !== undefined) {
  25960. for (const trackName in bindingByName) {
  25961. const binding = bindingByName[trackName];
  25962. binding.restoreOriginalState();
  25963. this._removeInactiveBinding(binding);
  25964. }
  25965. }
  25966. } // remove a targeted clip from the cache
  25967. uncacheAction(clip, optionalRoot) {
  25968. const action = this.existingAction(clip, optionalRoot);
  25969. if (action !== null) {
  25970. this._deactivateAction(action);
  25971. this._removeInactiveAction(action);
  25972. }
  25973. }
  25974. }
  25975. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array(1);
  25976. class Uniform {
  25977. constructor(value) {
  25978. if (typeof value === 'string') {
  25979. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  25980. value = arguments[1];
  25981. }
  25982. this.value = value;
  25983. }
  25984. clone() {
  25985. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  25986. }
  25987. }
  25988. class InstancedInterleavedBuffer extends InterleavedBuffer {
  25989. constructor(array, stride, meshPerAttribute = 1) {
  25990. super(array, stride);
  25991. this.meshPerAttribute = meshPerAttribute || 1;
  25992. }
  25993. copy(source) {
  25994. super.copy(source);
  25995. this.meshPerAttribute = source.meshPerAttribute;
  25996. return this;
  25997. }
  25998. clone(data) {
  25999. const ib = super.clone(data);
  26000. ib.meshPerAttribute = this.meshPerAttribute;
  26001. return ib;
  26002. }
  26003. toJSON(data) {
  26004. const json = super.toJSON(data);
  26005. json.isInstancedInterleavedBuffer = true;
  26006. json.meshPerAttribute = this.meshPerAttribute;
  26007. return json;
  26008. }
  26009. }
  26010. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  26011. class GLBufferAttribute {
  26012. constructor(buffer, type, itemSize, elementSize, count) {
  26013. this.buffer = buffer;
  26014. this.type = type;
  26015. this.itemSize = itemSize;
  26016. this.elementSize = elementSize;
  26017. this.count = count;
  26018. this.version = 0;
  26019. }
  26020. set needsUpdate(value) {
  26021. if (value === true) this.version++;
  26022. }
  26023. setBuffer(buffer) {
  26024. this.buffer = buffer;
  26025. return this;
  26026. }
  26027. setType(type, elementSize) {
  26028. this.type = type;
  26029. this.elementSize = elementSize;
  26030. return this;
  26031. }
  26032. setItemSize(itemSize) {
  26033. this.itemSize = itemSize;
  26034. return this;
  26035. }
  26036. setCount(count) {
  26037. this.count = count;
  26038. return this;
  26039. }
  26040. }
  26041. GLBufferAttribute.prototype.isGLBufferAttribute = true;
  26042. class Raycaster {
  26043. constructor(origin, direction, near = 0, far = Infinity) {
  26044. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  26045. this.near = near;
  26046. this.far = far;
  26047. this.camera = null;
  26048. this.layers = new Layers();
  26049. this.params = {
  26050. Mesh: {},
  26051. Line: {
  26052. threshold: 1
  26053. },
  26054. LOD: {},
  26055. Points: {
  26056. threshold: 1
  26057. },
  26058. Sprite: {}
  26059. };
  26060. }
  26061. set(origin, direction) {
  26062. // direction is assumed to be normalized (for accurate distance calculations)
  26063. this.ray.set(origin, direction);
  26064. }
  26065. setFromCamera(coords, camera) {
  26066. if (camera && camera.isPerspectiveCamera) {
  26067. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  26068. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  26069. this.camera = camera;
  26070. } else if (camera && camera.isOrthographicCamera) {
  26071. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  26072. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  26073. this.camera = camera;
  26074. } else {
  26075. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  26076. }
  26077. }
  26078. intersectObject(object, recursive = false, intersects = []) {
  26079. intersectObject(object, this, intersects, recursive);
  26080. intersects.sort(ascSort);
  26081. return intersects;
  26082. }
  26083. intersectObjects(objects, recursive = false, intersects = []) {
  26084. for (let i = 0, l = objects.length; i < l; i++) {
  26085. intersectObject(objects[i], this, intersects, recursive);
  26086. }
  26087. intersects.sort(ascSort);
  26088. return intersects;
  26089. }
  26090. }
  26091. function ascSort(a, b) {
  26092. return a.distance - b.distance;
  26093. }
  26094. function intersectObject(object, raycaster, intersects, recursive) {
  26095. if (object.layers.test(raycaster.layers)) {
  26096. object.raycast(raycaster, intersects);
  26097. }
  26098. if (recursive === true) {
  26099. const children = object.children;
  26100. for (let i = 0, l = children.length; i < l; i++) {
  26101. intersectObject(children[i], raycaster, intersects, true);
  26102. }
  26103. }
  26104. }
  26105. /**
  26106. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  26107. *
  26108. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  26109. * The azimuthal angle (theta) is measured from the positive z-axis.
  26110. */
  26111. class Spherical {
  26112. constructor(radius = 1, phi = 0, theta = 0) {
  26113. this.radius = radius;
  26114. this.phi = phi; // polar angle
  26115. this.theta = theta; // azimuthal angle
  26116. return this;
  26117. }
  26118. set(radius, phi, theta) {
  26119. this.radius = radius;
  26120. this.phi = phi;
  26121. this.theta = theta;
  26122. return this;
  26123. }
  26124. copy(other) {
  26125. this.radius = other.radius;
  26126. this.phi = other.phi;
  26127. this.theta = other.theta;
  26128. return this;
  26129. } // restrict phi to be betwee EPS and PI-EPS
  26130. makeSafe() {
  26131. const EPS = 0.000001;
  26132. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  26133. return this;
  26134. }
  26135. setFromVector3(v) {
  26136. return this.setFromCartesianCoords(v.x, v.y, v.z);
  26137. }
  26138. setFromCartesianCoords(x, y, z) {
  26139. this.radius = Math.sqrt(x * x + y * y + z * z);
  26140. if (this.radius === 0) {
  26141. this.theta = 0;
  26142. this.phi = 0;
  26143. } else {
  26144. this.theta = Math.atan2(x, z);
  26145. this.phi = Math.acos(clamp(y / this.radius, -1, 1));
  26146. }
  26147. return this;
  26148. }
  26149. clone() {
  26150. return new this.constructor().copy(this);
  26151. }
  26152. }
  26153. /**
  26154. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  26155. */
  26156. class Cylindrical {
  26157. constructor(radius = 1, theta = 0, y = 0) {
  26158. this.radius = radius; // distance from the origin to a point in the x-z plane
  26159. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  26160. this.y = y; // height above the x-z plane
  26161. return this;
  26162. }
  26163. set(radius, theta, y) {
  26164. this.radius = radius;
  26165. this.theta = theta;
  26166. this.y = y;
  26167. return this;
  26168. }
  26169. copy(other) {
  26170. this.radius = other.radius;
  26171. this.theta = other.theta;
  26172. this.y = other.y;
  26173. return this;
  26174. }
  26175. setFromVector3(v) {
  26176. return this.setFromCartesianCoords(v.x, v.y, v.z);
  26177. }
  26178. setFromCartesianCoords(x, y, z) {
  26179. this.radius = Math.sqrt(x * x + z * z);
  26180. this.theta = Math.atan2(x, z);
  26181. this.y = y;
  26182. return this;
  26183. }
  26184. clone() {
  26185. return new this.constructor().copy(this);
  26186. }
  26187. }
  26188. const _vector$4 = /*@__PURE__*/new Vector2();
  26189. class Box2 {
  26190. constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) {
  26191. this.min = min;
  26192. this.max = max;
  26193. }
  26194. set(min, max) {
  26195. this.min.copy(min);
  26196. this.max.copy(max);
  26197. return this;
  26198. }
  26199. setFromPoints(points) {
  26200. this.makeEmpty();
  26201. for (let i = 0, il = points.length; i < il; i++) {
  26202. this.expandByPoint(points[i]);
  26203. }
  26204. return this;
  26205. }
  26206. setFromCenterAndSize(center, size) {
  26207. const halfSize = _vector$4.copy(size).multiplyScalar(0.5);
  26208. this.min.copy(center).sub(halfSize);
  26209. this.max.copy(center).add(halfSize);
  26210. return this;
  26211. }
  26212. clone() {
  26213. return new this.constructor().copy(this);
  26214. }
  26215. copy(box) {
  26216. this.min.copy(box.min);
  26217. this.max.copy(box.max);
  26218. return this;
  26219. }
  26220. makeEmpty() {
  26221. this.min.x = this.min.y = +Infinity;
  26222. this.max.x = this.max.y = -Infinity;
  26223. return this;
  26224. }
  26225. isEmpty() {
  26226. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  26227. return this.max.x < this.min.x || this.max.y < this.min.y;
  26228. }
  26229. getCenter(target) {
  26230. if (target === undefined) {
  26231. console.warn('THREE.Box2: .getCenter() target is now required');
  26232. target = new Vector2();
  26233. }
  26234. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  26235. }
  26236. getSize(target) {
  26237. if (target === undefined) {
  26238. console.warn('THREE.Box2: .getSize() target is now required');
  26239. target = new Vector2();
  26240. }
  26241. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  26242. }
  26243. expandByPoint(point) {
  26244. this.min.min(point);
  26245. this.max.max(point);
  26246. return this;
  26247. }
  26248. expandByVector(vector) {
  26249. this.min.sub(vector);
  26250. this.max.add(vector);
  26251. return this;
  26252. }
  26253. expandByScalar(scalar) {
  26254. this.min.addScalar(-scalar);
  26255. this.max.addScalar(scalar);
  26256. return this;
  26257. }
  26258. containsPoint(point) {
  26259. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  26260. }
  26261. containsBox(box) {
  26262. 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;
  26263. }
  26264. getParameter(point, target) {
  26265. // This can potentially have a divide by zero if the box
  26266. // has a size dimension of 0.
  26267. if (target === undefined) {
  26268. console.warn('THREE.Box2: .getParameter() target is now required');
  26269. target = new Vector2();
  26270. }
  26271. 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));
  26272. }
  26273. intersectsBox(box) {
  26274. // using 4 splitting planes to rule out intersections
  26275. 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;
  26276. }
  26277. clampPoint(point, target) {
  26278. if (target === undefined) {
  26279. console.warn('THREE.Box2: .clampPoint() target is now required');
  26280. target = new Vector2();
  26281. }
  26282. return target.copy(point).clamp(this.min, this.max);
  26283. }
  26284. distanceToPoint(point) {
  26285. const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max);
  26286. return clampedPoint.sub(point).length();
  26287. }
  26288. intersect(box) {
  26289. this.min.max(box.min);
  26290. this.max.min(box.max);
  26291. return this;
  26292. }
  26293. union(box) {
  26294. this.min.min(box.min);
  26295. this.max.max(box.max);
  26296. return this;
  26297. }
  26298. translate(offset) {
  26299. this.min.add(offset);
  26300. this.max.add(offset);
  26301. return this;
  26302. }
  26303. equals(box) {
  26304. return box.min.equals(this.min) && box.max.equals(this.max);
  26305. }
  26306. }
  26307. Box2.prototype.isBox2 = true;
  26308. const _startP = /*@__PURE__*/new Vector3();
  26309. const _startEnd = /*@__PURE__*/new Vector3();
  26310. class Line3 {
  26311. constructor(start = new Vector3(), end = new Vector3()) {
  26312. this.start = start;
  26313. this.end = end;
  26314. }
  26315. set(start, end) {
  26316. this.start.copy(start);
  26317. this.end.copy(end);
  26318. return this;
  26319. }
  26320. copy(line) {
  26321. this.start.copy(line.start);
  26322. this.end.copy(line.end);
  26323. return this;
  26324. }
  26325. getCenter(target) {
  26326. if (target === undefined) {
  26327. console.warn('THREE.Line3: .getCenter() target is now required');
  26328. target = new Vector3();
  26329. }
  26330. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  26331. }
  26332. delta(target) {
  26333. if (target === undefined) {
  26334. console.warn('THREE.Line3: .delta() target is now required');
  26335. target = new Vector3();
  26336. }
  26337. return target.subVectors(this.end, this.start);
  26338. }
  26339. distanceSq() {
  26340. return this.start.distanceToSquared(this.end);
  26341. }
  26342. distance() {
  26343. return this.start.distanceTo(this.end);
  26344. }
  26345. at(t, target) {
  26346. if (target === undefined) {
  26347. console.warn('THREE.Line3: .at() target is now required');
  26348. target = new Vector3();
  26349. }
  26350. return this.delta(target).multiplyScalar(t).add(this.start);
  26351. }
  26352. closestPointToPointParameter(point, clampToLine) {
  26353. _startP.subVectors(point, this.start);
  26354. _startEnd.subVectors(this.end, this.start);
  26355. const startEnd2 = _startEnd.dot(_startEnd);
  26356. const startEnd_startP = _startEnd.dot(_startP);
  26357. let t = startEnd_startP / startEnd2;
  26358. if (clampToLine) {
  26359. t = clamp(t, 0, 1);
  26360. }
  26361. return t;
  26362. }
  26363. closestPointToPoint(point, clampToLine, target) {
  26364. const t = this.closestPointToPointParameter(point, clampToLine);
  26365. if (target === undefined) {
  26366. console.warn('THREE.Line3: .closestPointToPoint() target is now required');
  26367. target = new Vector3();
  26368. }
  26369. return this.delta(target).multiplyScalar(t).add(this.start);
  26370. }
  26371. applyMatrix4(matrix) {
  26372. this.start.applyMatrix4(matrix);
  26373. this.end.applyMatrix4(matrix);
  26374. return this;
  26375. }
  26376. equals(line) {
  26377. return line.start.equals(this.start) && line.end.equals(this.end);
  26378. }
  26379. clone() {
  26380. return new this.constructor().copy(this);
  26381. }
  26382. }
  26383. class ImmediateRenderObject extends Object3D {
  26384. constructor(material) {
  26385. super();
  26386. this.material = material;
  26387. this.render = function ()
  26388. /* renderCallback */
  26389. {};
  26390. this.hasPositions = false;
  26391. this.hasNormals = false;
  26392. this.hasColors = false;
  26393. this.hasUvs = false;
  26394. this.positionArray = null;
  26395. this.normalArray = null;
  26396. this.colorArray = null;
  26397. this.uvArray = null;
  26398. this.count = 0;
  26399. }
  26400. }
  26401. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  26402. const _vector$3 = /*@__PURE__*/new Vector3();
  26403. class SpotLightHelper extends Object3D {
  26404. constructor(light, color) {
  26405. super();
  26406. this.light = light;
  26407. this.light.updateMatrixWorld();
  26408. this.matrix = light.matrixWorld;
  26409. this.matrixAutoUpdate = false;
  26410. this.color = color;
  26411. const geometry = new BufferGeometry();
  26412. 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];
  26413. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  26414. const p1 = i / l * Math.PI * 2;
  26415. const p2 = j / l * Math.PI * 2;
  26416. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  26417. }
  26418. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  26419. const material = new LineBasicMaterial({
  26420. fog: false,
  26421. toneMapped: false
  26422. });
  26423. this.cone = new LineSegments(geometry, material);
  26424. this.add(this.cone);
  26425. this.update();
  26426. }
  26427. dispose() {
  26428. this.cone.geometry.dispose();
  26429. this.cone.material.dispose();
  26430. }
  26431. update() {
  26432. this.light.updateMatrixWorld();
  26433. const coneLength = this.light.distance ? this.light.distance : 1000;
  26434. const coneWidth = coneLength * Math.tan(this.light.angle);
  26435. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  26436. _vector$3.setFromMatrixPosition(this.light.target.matrixWorld);
  26437. this.cone.lookAt(_vector$3);
  26438. if (this.color !== undefined) {
  26439. this.cone.material.color.set(this.color);
  26440. } else {
  26441. this.cone.material.color.copy(this.light.color);
  26442. }
  26443. }
  26444. }
  26445. const _vector$2 = /*@__PURE__*/new Vector3();
  26446. const _boneMatrix = /*@__PURE__*/new Matrix4();
  26447. const _matrixWorldInv = /*@__PURE__*/new Matrix4();
  26448. class SkeletonHelper extends LineSegments {
  26449. constructor(object) {
  26450. const bones = getBoneList(object);
  26451. const geometry = new BufferGeometry();
  26452. const vertices = [];
  26453. const colors = [];
  26454. const color1 = new Color(0, 0, 1);
  26455. const color2 = new Color(0, 1, 0);
  26456. for (let i = 0; i < bones.length; i++) {
  26457. const bone = bones[i];
  26458. if (bone.parent && bone.parent.isBone) {
  26459. vertices.push(0, 0, 0);
  26460. vertices.push(0, 0, 0);
  26461. colors.push(color1.r, color1.g, color1.b);
  26462. colors.push(color2.r, color2.g, color2.b);
  26463. }
  26464. }
  26465. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26466. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26467. const material = new LineBasicMaterial({
  26468. vertexColors: true,
  26469. depthTest: false,
  26470. depthWrite: false,
  26471. toneMapped: false,
  26472. transparent: true
  26473. });
  26474. super(geometry, material);
  26475. this.type = 'SkeletonHelper';
  26476. this.isSkeletonHelper = true;
  26477. this.root = object;
  26478. this.bones = bones;
  26479. this.matrix = object.matrixWorld;
  26480. this.matrixAutoUpdate = false;
  26481. }
  26482. updateMatrixWorld(force) {
  26483. const bones = this.bones;
  26484. const geometry = this.geometry;
  26485. const position = geometry.getAttribute('position');
  26486. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  26487. for (let i = 0, j = 0; i < bones.length; i++) {
  26488. const bone = bones[i];
  26489. if (bone.parent && bone.parent.isBone) {
  26490. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  26491. _vector$2.setFromMatrixPosition(_boneMatrix);
  26492. position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z);
  26493. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  26494. _vector$2.setFromMatrixPosition(_boneMatrix);
  26495. position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z);
  26496. j += 2;
  26497. }
  26498. }
  26499. geometry.getAttribute('position').needsUpdate = true;
  26500. super.updateMatrixWorld(force);
  26501. }
  26502. }
  26503. function getBoneList(object) {
  26504. const boneList = [];
  26505. if (object && object.isBone) {
  26506. boneList.push(object);
  26507. }
  26508. for (let i = 0; i < object.children.length; i++) {
  26509. boneList.push.apply(boneList, getBoneList(object.children[i]));
  26510. }
  26511. return boneList;
  26512. }
  26513. class PointLightHelper extends Mesh {
  26514. constructor(light, sphereSize, color) {
  26515. const geometry = new SphereGeometry(sphereSize, 4, 2);
  26516. const material = new MeshBasicMaterial({
  26517. wireframe: true,
  26518. fog: false,
  26519. toneMapped: false
  26520. });
  26521. super(geometry, material);
  26522. this.light = light;
  26523. this.light.updateMatrixWorld();
  26524. this.color = color;
  26525. this.type = 'PointLightHelper';
  26526. this.matrix = this.light.matrixWorld;
  26527. this.matrixAutoUpdate = false;
  26528. this.update();
  26529. /*
  26530. // TODO: delete this comment?
  26531. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  26532. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  26533. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  26534. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  26535. const d = light.distance;
  26536. if ( d === 0.0 ) {
  26537. this.lightDistance.visible = false;
  26538. } else {
  26539. this.lightDistance.scale.set( d, d, d );
  26540. }
  26541. this.add( this.lightDistance );
  26542. */
  26543. }
  26544. dispose() {
  26545. this.geometry.dispose();
  26546. this.material.dispose();
  26547. }
  26548. update() {
  26549. if (this.color !== undefined) {
  26550. this.material.color.set(this.color);
  26551. } else {
  26552. this.material.color.copy(this.light.color);
  26553. }
  26554. /*
  26555. const d = this.light.distance;
  26556. if ( d === 0.0 ) {
  26557. this.lightDistance.visible = false;
  26558. } else {
  26559. this.lightDistance.visible = true;
  26560. this.lightDistance.scale.set( d, d, d );
  26561. }
  26562. */
  26563. }
  26564. }
  26565. const _vector$1 = /*@__PURE__*/new Vector3();
  26566. const _color1 = /*@__PURE__*/new Color();
  26567. const _color2 = /*@__PURE__*/new Color();
  26568. class HemisphereLightHelper extends Object3D {
  26569. constructor(light, size, color) {
  26570. super();
  26571. this.light = light;
  26572. this.light.updateMatrixWorld();
  26573. this.matrix = light.matrixWorld;
  26574. this.matrixAutoUpdate = false;
  26575. this.color = color;
  26576. const geometry = new OctahedronGeometry(size);
  26577. geometry.rotateY(Math.PI * 0.5);
  26578. this.material = new MeshBasicMaterial({
  26579. wireframe: true,
  26580. fog: false,
  26581. toneMapped: false
  26582. });
  26583. if (this.color === undefined) this.material.vertexColors = true;
  26584. const position = geometry.getAttribute('position');
  26585. const colors = new Float32Array(position.count * 3);
  26586. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  26587. this.add(new Mesh(geometry, this.material));
  26588. this.update();
  26589. }
  26590. dispose() {
  26591. this.children[0].geometry.dispose();
  26592. this.children[0].material.dispose();
  26593. }
  26594. update() {
  26595. const mesh = this.children[0];
  26596. if (this.color !== undefined) {
  26597. this.material.color.set(this.color);
  26598. } else {
  26599. const colors = mesh.geometry.getAttribute('color');
  26600. _color1.copy(this.light.color);
  26601. _color2.copy(this.light.groundColor);
  26602. for (let i = 0, l = colors.count; i < l; i++) {
  26603. const color = i < l / 2 ? _color1 : _color2;
  26604. colors.setXYZ(i, color.r, color.g, color.b);
  26605. }
  26606. colors.needsUpdate = true;
  26607. }
  26608. mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
  26609. }
  26610. }
  26611. class GridHelper extends LineSegments {
  26612. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  26613. color1 = new Color(color1);
  26614. color2 = new Color(color2);
  26615. const center = divisions / 2;
  26616. const step = size / divisions;
  26617. const halfSize = size / 2;
  26618. const vertices = [],
  26619. colors = [];
  26620. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  26621. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  26622. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  26623. const color = i === center ? color1 : color2;
  26624. color.toArray(colors, j);
  26625. j += 3;
  26626. color.toArray(colors, j);
  26627. j += 3;
  26628. color.toArray(colors, j);
  26629. j += 3;
  26630. color.toArray(colors, j);
  26631. j += 3;
  26632. }
  26633. const geometry = new BufferGeometry();
  26634. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26635. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26636. const material = new LineBasicMaterial({
  26637. vertexColors: true,
  26638. toneMapped: false
  26639. });
  26640. super(geometry, material);
  26641. this.type = 'GridHelper';
  26642. }
  26643. }
  26644. class PolarGridHelper extends LineSegments {
  26645. constructor(radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  26646. color1 = new Color(color1);
  26647. color2 = new Color(color2);
  26648. const vertices = [];
  26649. const colors = []; // create the radials
  26650. for (let i = 0; i <= radials; i++) {
  26651. const v = i / radials * (Math.PI * 2);
  26652. const x = Math.sin(v) * radius;
  26653. const z = Math.cos(v) * radius;
  26654. vertices.push(0, 0, 0);
  26655. vertices.push(x, 0, z);
  26656. const color = i & 1 ? color1 : color2;
  26657. colors.push(color.r, color.g, color.b);
  26658. colors.push(color.r, color.g, color.b);
  26659. } // create the circles
  26660. for (let i = 0; i <= circles; i++) {
  26661. const color = i & 1 ? color1 : color2;
  26662. const r = radius - radius / circles * i;
  26663. for (let j = 0; j < divisions; j++) {
  26664. // first vertex
  26665. let v = j / divisions * (Math.PI * 2);
  26666. let x = Math.sin(v) * r;
  26667. let z = Math.cos(v) * r;
  26668. vertices.push(x, 0, z);
  26669. colors.push(color.r, color.g, color.b); // second vertex
  26670. v = (j + 1) / divisions * (Math.PI * 2);
  26671. x = Math.sin(v) * r;
  26672. z = Math.cos(v) * r;
  26673. vertices.push(x, 0, z);
  26674. colors.push(color.r, color.g, color.b);
  26675. }
  26676. }
  26677. const geometry = new BufferGeometry();
  26678. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26679. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26680. const material = new LineBasicMaterial({
  26681. vertexColors: true,
  26682. toneMapped: false
  26683. });
  26684. super(geometry, material);
  26685. this.type = 'PolarGridHelper';
  26686. }
  26687. }
  26688. const _v1 = /*@__PURE__*/new Vector3();
  26689. const _v2 = /*@__PURE__*/new Vector3();
  26690. const _v3 = /*@__PURE__*/new Vector3();
  26691. class DirectionalLightHelper extends Object3D {
  26692. constructor(light, size, color) {
  26693. super();
  26694. this.light = light;
  26695. this.light.updateMatrixWorld();
  26696. this.matrix = light.matrixWorld;
  26697. this.matrixAutoUpdate = false;
  26698. this.color = color;
  26699. if (size === undefined) size = 1;
  26700. let geometry = new BufferGeometry();
  26701. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  26702. const material = new LineBasicMaterial({
  26703. fog: false,
  26704. toneMapped: false
  26705. });
  26706. this.lightPlane = new Line(geometry, material);
  26707. this.add(this.lightPlane);
  26708. geometry = new BufferGeometry();
  26709. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  26710. this.targetLine = new Line(geometry, material);
  26711. this.add(this.targetLine);
  26712. this.update();
  26713. }
  26714. dispose() {
  26715. this.lightPlane.geometry.dispose();
  26716. this.lightPlane.material.dispose();
  26717. this.targetLine.geometry.dispose();
  26718. this.targetLine.material.dispose();
  26719. }
  26720. update() {
  26721. _v1.setFromMatrixPosition(this.light.matrixWorld);
  26722. _v2.setFromMatrixPosition(this.light.target.matrixWorld);
  26723. _v3.subVectors(_v2, _v1);
  26724. this.lightPlane.lookAt(_v2);
  26725. if (this.color !== undefined) {
  26726. this.lightPlane.material.color.set(this.color);
  26727. this.targetLine.material.color.set(this.color);
  26728. } else {
  26729. this.lightPlane.material.color.copy(this.light.color);
  26730. this.targetLine.material.color.copy(this.light.color);
  26731. }
  26732. this.targetLine.lookAt(_v2);
  26733. this.targetLine.scale.z = _v3.length();
  26734. }
  26735. }
  26736. const _vector = /*@__PURE__*/new Vector3();
  26737. const _camera = /*@__PURE__*/new Camera();
  26738. /**
  26739. * - shows frustum, line of sight and up of the camera
  26740. * - suitable for fast updates
  26741. * - based on frustum visualization in lightgl.js shadowmap example
  26742. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  26743. */
  26744. class CameraHelper extends LineSegments {
  26745. constructor(camera) {
  26746. const geometry = new BufferGeometry();
  26747. const material = new LineBasicMaterial({
  26748. color: 0xffffff,
  26749. vertexColors: true,
  26750. toneMapped: false
  26751. });
  26752. const vertices = [];
  26753. const colors = [];
  26754. const pointMap = {}; // colors
  26755. const colorFrustum = new Color(0xffaa00);
  26756. const colorCone = new Color(0xff0000);
  26757. const colorUp = new Color(0x00aaff);
  26758. const colorTarget = new Color(0xffffff);
  26759. const colorCross = new Color(0x333333); // near
  26760. addLine('n1', 'n2', colorFrustum);
  26761. addLine('n2', 'n4', colorFrustum);
  26762. addLine('n4', 'n3', colorFrustum);
  26763. addLine('n3', 'n1', colorFrustum); // far
  26764. addLine('f1', 'f2', colorFrustum);
  26765. addLine('f2', 'f4', colorFrustum);
  26766. addLine('f4', 'f3', colorFrustum);
  26767. addLine('f3', 'f1', colorFrustum); // sides
  26768. addLine('n1', 'f1', colorFrustum);
  26769. addLine('n2', 'f2', colorFrustum);
  26770. addLine('n3', 'f3', colorFrustum);
  26771. addLine('n4', 'f4', colorFrustum); // cone
  26772. addLine('p', 'n1', colorCone);
  26773. addLine('p', 'n2', colorCone);
  26774. addLine('p', 'n3', colorCone);
  26775. addLine('p', 'n4', colorCone); // up
  26776. addLine('u1', 'u2', colorUp);
  26777. addLine('u2', 'u3', colorUp);
  26778. addLine('u3', 'u1', colorUp); // target
  26779. addLine('c', 't', colorTarget);
  26780. addLine('p', 'c', colorCross); // cross
  26781. addLine('cn1', 'cn2', colorCross);
  26782. addLine('cn3', 'cn4', colorCross);
  26783. addLine('cf1', 'cf2', colorCross);
  26784. addLine('cf3', 'cf4', colorCross);
  26785. function addLine(a, b, color) {
  26786. addPoint(a, color);
  26787. addPoint(b, color);
  26788. }
  26789. function addPoint(id, color) {
  26790. vertices.push(0, 0, 0);
  26791. colors.push(color.r, color.g, color.b);
  26792. if (pointMap[id] === undefined) {
  26793. pointMap[id] = [];
  26794. }
  26795. pointMap[id].push(vertices.length / 3 - 1);
  26796. }
  26797. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26798. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26799. super(geometry, material);
  26800. this.type = 'CameraHelper';
  26801. this.camera = camera;
  26802. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  26803. this.matrix = camera.matrixWorld;
  26804. this.matrixAutoUpdate = false;
  26805. this.pointMap = pointMap;
  26806. this.update();
  26807. }
  26808. update() {
  26809. const geometry = this.geometry;
  26810. const pointMap = this.pointMap;
  26811. const w = 1,
  26812. h = 1; // we need just camera projection matrix inverse
  26813. // world matrix must be identity
  26814. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  26815. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  26816. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  26817. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  26818. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  26819. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  26820. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  26821. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  26822. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  26823. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  26824. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  26825. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  26826. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  26827. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  26828. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  26829. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  26830. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  26831. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  26832. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  26833. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  26834. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  26835. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  26836. geometry.getAttribute('position').needsUpdate = true;
  26837. }
  26838. dispose() {
  26839. this.geometry.dispose();
  26840. this.material.dispose();
  26841. }
  26842. }
  26843. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  26844. _vector.set(x, y, z).unproject(camera);
  26845. const points = pointMap[point];
  26846. if (points !== undefined) {
  26847. const position = geometry.getAttribute('position');
  26848. for (let i = 0, l = points.length; i < l; i++) {
  26849. position.setXYZ(points[i], _vector.x, _vector.y, _vector.z);
  26850. }
  26851. }
  26852. }
  26853. const _box = /*@__PURE__*/new Box3();
  26854. class BoxHelper extends LineSegments {
  26855. constructor(object, color = 0xffff00) {
  26856. 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]);
  26857. const positions = new Float32Array(8 * 3);
  26858. const geometry = new BufferGeometry();
  26859. geometry.setIndex(new BufferAttribute(indices, 1));
  26860. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  26861. super(geometry, new LineBasicMaterial({
  26862. color: color,
  26863. toneMapped: false
  26864. }));
  26865. this.object = object;
  26866. this.type = 'BoxHelper';
  26867. this.matrixAutoUpdate = false;
  26868. this.update();
  26869. }
  26870. update(object) {
  26871. if (object !== undefined) {
  26872. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  26873. }
  26874. if (this.object !== undefined) {
  26875. _box.setFromObject(this.object);
  26876. }
  26877. if (_box.isEmpty()) return;
  26878. const min = _box.min;
  26879. const max = _box.max;
  26880. /*
  26881. 5____4
  26882. 1/___0/|
  26883. | 6__|_7
  26884. 2/___3/
  26885. 0: max.x, max.y, max.z
  26886. 1: min.x, max.y, max.z
  26887. 2: min.x, min.y, max.z
  26888. 3: max.x, min.y, max.z
  26889. 4: max.x, max.y, min.z
  26890. 5: min.x, max.y, min.z
  26891. 6: min.x, min.y, min.z
  26892. 7: max.x, min.y, min.z
  26893. */
  26894. const position = this.geometry.attributes.position;
  26895. const array = position.array;
  26896. array[0] = max.x;
  26897. array[1] = max.y;
  26898. array[2] = max.z;
  26899. array[3] = min.x;
  26900. array[4] = max.y;
  26901. array[5] = max.z;
  26902. array[6] = min.x;
  26903. array[7] = min.y;
  26904. array[8] = max.z;
  26905. array[9] = max.x;
  26906. array[10] = min.y;
  26907. array[11] = max.z;
  26908. array[12] = max.x;
  26909. array[13] = max.y;
  26910. array[14] = min.z;
  26911. array[15] = min.x;
  26912. array[16] = max.y;
  26913. array[17] = min.z;
  26914. array[18] = min.x;
  26915. array[19] = min.y;
  26916. array[20] = min.z;
  26917. array[21] = max.x;
  26918. array[22] = min.y;
  26919. array[23] = min.z;
  26920. position.needsUpdate = true;
  26921. this.geometry.computeBoundingSphere();
  26922. }
  26923. setFromObject(object) {
  26924. this.object = object;
  26925. this.update();
  26926. return this;
  26927. }
  26928. copy(source) {
  26929. LineSegments.prototype.copy.call(this, source);
  26930. this.object = source.object;
  26931. return this;
  26932. }
  26933. }
  26934. class Box3Helper extends LineSegments {
  26935. constructor(box, color = 0xffff00) {
  26936. 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]);
  26937. 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];
  26938. const geometry = new BufferGeometry();
  26939. geometry.setIndex(new BufferAttribute(indices, 1));
  26940. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  26941. super(geometry, new LineBasicMaterial({
  26942. color: color,
  26943. toneMapped: false
  26944. }));
  26945. this.box = box;
  26946. this.type = 'Box3Helper';
  26947. this.geometry.computeBoundingSphere();
  26948. }
  26949. updateMatrixWorld(force) {
  26950. const box = this.box;
  26951. if (box.isEmpty()) return;
  26952. box.getCenter(this.position);
  26953. box.getSize(this.scale);
  26954. this.scale.multiplyScalar(0.5);
  26955. super.updateMatrixWorld(force);
  26956. }
  26957. }
  26958. class PlaneHelper extends Line {
  26959. constructor(plane, size = 1, hex = 0xffff00) {
  26960. const color = hex;
  26961. 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];
  26962. const geometry = new BufferGeometry();
  26963. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  26964. geometry.computeBoundingSphere();
  26965. super(geometry, new LineBasicMaterial({
  26966. color: color,
  26967. toneMapped: false
  26968. }));
  26969. this.type = 'PlaneHelper';
  26970. this.plane = plane;
  26971. this.size = size;
  26972. const positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  26973. const geometry2 = new BufferGeometry();
  26974. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  26975. geometry2.computeBoundingSphere();
  26976. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  26977. color: color,
  26978. opacity: 0.2,
  26979. transparent: true,
  26980. depthWrite: false,
  26981. toneMapped: false
  26982. })));
  26983. }
  26984. updateMatrixWorld(force) {
  26985. let scale = -this.plane.constant;
  26986. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  26987. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  26988. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  26989. this.lookAt(this.plane.normal);
  26990. super.updateMatrixWorld(force);
  26991. }
  26992. }
  26993. const _axis = /*@__PURE__*/new Vector3();
  26994. let _lineGeometry, _coneGeometry;
  26995. class ArrowHelper extends Object3D {
  26996. // dir is assumed to be normalized
  26997. 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) {
  26998. super();
  26999. this.type = 'ArrowHelper';
  27000. if (_lineGeometry === undefined) {
  27001. _lineGeometry = new BufferGeometry();
  27002. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  27003. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  27004. _coneGeometry.translate(0, -0.5, 0);
  27005. }
  27006. this.position.copy(origin);
  27007. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  27008. color: color,
  27009. toneMapped: false
  27010. }));
  27011. this.line.matrixAutoUpdate = false;
  27012. this.add(this.line);
  27013. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  27014. color: color,
  27015. toneMapped: false
  27016. }));
  27017. this.cone.matrixAutoUpdate = false;
  27018. this.add(this.cone);
  27019. this.setDirection(dir);
  27020. this.setLength(length, headLength, headWidth);
  27021. }
  27022. setDirection(dir) {
  27023. // dir is assumed to be normalized
  27024. if (dir.y > 0.99999) {
  27025. this.quaternion.set(0, 0, 0, 1);
  27026. } else if (dir.y < -0.99999) {
  27027. this.quaternion.set(1, 0, 0, 0);
  27028. } else {
  27029. _axis.set(dir.z, 0, -dir.x).normalize();
  27030. const radians = Math.acos(dir.y);
  27031. this.quaternion.setFromAxisAngle(_axis, radians);
  27032. }
  27033. }
  27034. setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
  27035. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  27036. this.line.updateMatrix();
  27037. this.cone.scale.set(headWidth, headLength, headWidth);
  27038. this.cone.position.y = length;
  27039. this.cone.updateMatrix();
  27040. }
  27041. setColor(color) {
  27042. this.line.material.color.set(color);
  27043. this.cone.material.color.set(color);
  27044. }
  27045. copy(source) {
  27046. super.copy(source, false);
  27047. this.line.copy(source.line);
  27048. this.cone.copy(source.cone);
  27049. return this;
  27050. }
  27051. }
  27052. class AxesHelper extends LineSegments {
  27053. constructor(size = 1) {
  27054. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  27055. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  27056. const geometry = new BufferGeometry();
  27057. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27058. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27059. const material = new LineBasicMaterial({
  27060. vertexColors: true,
  27061. toneMapped: false
  27062. });
  27063. super(geometry, material);
  27064. this.type = 'AxesHelper';
  27065. }
  27066. dispose() {
  27067. this.geometry.dispose();
  27068. this.material.dispose();
  27069. }
  27070. }
  27071. const _floatView = new Float32Array(1);
  27072. const _int32View = new Int32Array(_floatView.buffer);
  27073. class DataUtils {
  27074. // Converts float32 to float16 (stored as uint16 value).
  27075. static toHalfFloat(val) {
  27076. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  27077. /* This method is faster than the OpenEXR implementation (very often
  27078. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  27079. * by James Tursa?s half-precision code. */
  27080. _floatView[0] = val;
  27081. const x = _int32View[0];
  27082. let bits = x >> 16 & 0x8000;
  27083. /* Get the sign */
  27084. let m = x >> 12 & 0x07ff;
  27085. /* Keep one extra bit for rounding */
  27086. const e = x >> 23 & 0xff;
  27087. /* Using int is faster here */
  27088. /* If zero, or denormal, or exponent underflows too much for a denormal
  27089. * half, return signed zero. */
  27090. if (e < 103) return bits;
  27091. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  27092. if (e > 142) {
  27093. bits |= 0x7c00;
  27094. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  27095. * not Inf, so make sure we set one mantissa bit too. */
  27096. bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
  27097. return bits;
  27098. }
  27099. /* If exponent underflows but not too much, return a denormal */
  27100. if (e < 113) {
  27101. m |= 0x0800;
  27102. /* Extra rounding may overflow and set mantissa to 0 and exponent
  27103. * to 1, which is OK. */
  27104. bits |= (m >> 114 - e) + (m >> 113 - e & 1);
  27105. return bits;
  27106. }
  27107. bits |= e - 112 << 10 | m >> 1;
  27108. /* Extra rounding. An overflow will set mantissa to 0 and increment
  27109. * the exponent, which is OK. */
  27110. bits += m & 1;
  27111. return bits;
  27112. }
  27113. }
  27114. const LOD_MIN = 4;
  27115. const LOD_MAX = 8;
  27116. const SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
  27117. // chosen to approximate a Trowbridge-Reitz distribution function times the
  27118. // geometric shadowing function. These sigma values squared must match the
  27119. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  27120. const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  27121. 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
  27122. // samples and exit early, but not recompile the shader.
  27123. const MAX_SAMPLES = 20;
  27124. const ENCODINGS = {
  27125. [LinearEncoding]: 0,
  27126. [sRGBEncoding]: 1,
  27127. [RGBEEncoding]: 2,
  27128. [RGBM7Encoding]: 3,
  27129. [RGBM16Encoding]: 4,
  27130. [RGBDEncoding]: 5,
  27131. [GammaEncoding]: 6
  27132. };
  27133. const backgroundMaterial = new MeshBasicMaterial({
  27134. side: BackSide,
  27135. depthWrite: false,
  27136. depthTest: false
  27137. });
  27138. const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
  27139. const _flatCamera = /*@__PURE__*/new OrthographicCamera();
  27140. const {
  27141. _lodPlanes,
  27142. _sizeLods,
  27143. _sigmas
  27144. } = /*@__PURE__*/_createPlanes();
  27145. const _clearColor = /*@__PURE__*/new Color();
  27146. let _oldTarget = null; // Golden Ratio
  27147. const PHI = (1 + Math.sqrt(5)) / 2;
  27148. const INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  27149. // same axis), used as axis directions evenly spread on a sphere.
  27150. 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)];
  27151. /**
  27152. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  27153. * (PMREM) from a cubeMap environment texture. This allows different levels of
  27154. * blur to be quickly accessed based on material roughness. It is packed into a
  27155. * special CubeUV format that allows us to perform custom interpolation so that
  27156. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  27157. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  27158. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  27159. * higher roughness levels. In this way we maintain resolution to smoothly
  27160. * interpolate diffuse lighting while limiting sampling computation.
  27161. *
  27162. * Paper: Fast, Accurate Image-Based Lighting
  27163. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  27164. */
  27165. function convertLinearToRGBE(color) {
  27166. const maxComponent = Math.max(color.r, color.g, color.b);
  27167. const fExp = Math.min(Math.max(Math.ceil(Math.log2(maxComponent)), -128.0), 127.0);
  27168. color.multiplyScalar(Math.pow(2.0, -fExp));
  27169. const alpha = (fExp + 128.0) / 255.0;
  27170. return alpha;
  27171. }
  27172. class PMREMGenerator {
  27173. constructor(renderer) {
  27174. this._renderer = renderer;
  27175. this._pingPongRenderTarget = null;
  27176. this._blurMaterial = _getBlurShader(MAX_SAMPLES);
  27177. this._equirectShader = null;
  27178. this._cubemapShader = null;
  27179. this._compileMaterial(this._blurMaterial);
  27180. }
  27181. /**
  27182. * Generates a PMREM from a supplied Scene, which can be faster than using an
  27183. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  27184. * in radians to be applied to the scene before PMREM generation. Optional near
  27185. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  27186. * is placed at the origin).
  27187. */
  27188. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  27189. _oldTarget = this._renderer.getRenderTarget();
  27190. const cubeUVRenderTarget = this._allocateTargets();
  27191. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  27192. if (sigma > 0) {
  27193. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  27194. }
  27195. this._applyPMREM(cubeUVRenderTarget);
  27196. this._cleanup(cubeUVRenderTarget);
  27197. return cubeUVRenderTarget;
  27198. }
  27199. /**
  27200. * Generates a PMREM from an equirectangular texture, which can be either LDR
  27201. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  27202. * as this matches best with the 256 x 256 cubemap output.
  27203. */
  27204. fromEquirectangular(equirectangular) {
  27205. return this._fromTexture(equirectangular);
  27206. }
  27207. /**
  27208. * Generates a PMREM from an cubemap texture, which can be either LDR
  27209. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  27210. * as this matches best with the 256 x 256 cubemap output.
  27211. */
  27212. fromCubemap(cubemap) {
  27213. return this._fromTexture(cubemap);
  27214. }
  27215. /**
  27216. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  27217. * your texture's network fetch for increased concurrency.
  27218. */
  27219. compileCubemapShader() {
  27220. if (this._cubemapShader === null) {
  27221. this._cubemapShader = _getCubemapShader();
  27222. this._compileMaterial(this._cubemapShader);
  27223. }
  27224. }
  27225. /**
  27226. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  27227. * your texture's network fetch for increased concurrency.
  27228. */
  27229. compileEquirectangularShader() {
  27230. if (this._equirectShader === null) {
  27231. this._equirectShader = _getEquirectShader();
  27232. this._compileMaterial(this._equirectShader);
  27233. }
  27234. }
  27235. /**
  27236. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  27237. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  27238. * one of them will cause any others to also become unusable.
  27239. */
  27240. dispose() {
  27241. this._blurMaterial.dispose();
  27242. if (this._cubemapShader !== null) this._cubemapShader.dispose();
  27243. if (this._equirectShader !== null) this._equirectShader.dispose();
  27244. for (let i = 0; i < _lodPlanes.length; i++) {
  27245. _lodPlanes[i].dispose();
  27246. }
  27247. } // private interface
  27248. _cleanup(outputTarget) {
  27249. this._pingPongRenderTarget.dispose();
  27250. this._renderer.setRenderTarget(_oldTarget);
  27251. outputTarget.scissorTest = false;
  27252. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  27253. }
  27254. _fromTexture(texture) {
  27255. _oldTarget = this._renderer.getRenderTarget();
  27256. const cubeUVRenderTarget = this._allocateTargets(texture);
  27257. this._textureToCubeUV(texture, cubeUVRenderTarget);
  27258. this._applyPMREM(cubeUVRenderTarget);
  27259. this._cleanup(cubeUVRenderTarget);
  27260. return cubeUVRenderTarget;
  27261. }
  27262. _allocateTargets(texture) {
  27263. // warning: null texture is valid
  27264. const params = {
  27265. magFilter: NearestFilter,
  27266. minFilter: NearestFilter,
  27267. generateMipmaps: false,
  27268. type: UnsignedByteType,
  27269. format: RGBEFormat,
  27270. encoding: _isLDR(texture) ? texture.encoding : RGBEEncoding,
  27271. depthBuffer: false
  27272. };
  27273. const cubeUVRenderTarget = _createRenderTarget(params);
  27274. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  27275. this._pingPongRenderTarget = _createRenderTarget(params);
  27276. return cubeUVRenderTarget;
  27277. }
  27278. _compileMaterial(material) {
  27279. const tmpMesh = new Mesh(_lodPlanes[0], material);
  27280. this._renderer.compile(tmpMesh, _flatCamera);
  27281. }
  27282. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  27283. const fov = 90;
  27284. const aspect = 1;
  27285. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  27286. const upSign = [1, -1, 1, 1, 1, 1];
  27287. const forwardSign = [1, 1, 1, -1, -1, -1];
  27288. const renderer = this._renderer;
  27289. const originalAutoClear = renderer.autoClear;
  27290. const outputEncoding = renderer.outputEncoding;
  27291. const toneMapping = renderer.toneMapping;
  27292. renderer.getClearColor(_clearColor);
  27293. renderer.toneMapping = NoToneMapping;
  27294. renderer.outputEncoding = LinearEncoding;
  27295. renderer.autoClear = false;
  27296. let useSolidColor = false;
  27297. const background = scene.background;
  27298. if (background) {
  27299. if (background.isColor) {
  27300. backgroundMaterial.color.copy(background).convertSRGBToLinear();
  27301. scene.background = null;
  27302. const alpha = convertLinearToRGBE(backgroundMaterial.color);
  27303. backgroundMaterial.opacity = alpha;
  27304. useSolidColor = true;
  27305. }
  27306. } else {
  27307. backgroundMaterial.color.copy(_clearColor).convertSRGBToLinear();
  27308. const alpha = convertLinearToRGBE(backgroundMaterial.color);
  27309. backgroundMaterial.opacity = alpha;
  27310. useSolidColor = true;
  27311. }
  27312. for (let i = 0; i < 6; i++) {
  27313. const col = i % 3;
  27314. if (col == 0) {
  27315. cubeCamera.up.set(0, upSign[i], 0);
  27316. cubeCamera.lookAt(forwardSign[i], 0, 0);
  27317. } else if (col == 1) {
  27318. cubeCamera.up.set(0, 0, upSign[i]);
  27319. cubeCamera.lookAt(0, forwardSign[i], 0);
  27320. } else {
  27321. cubeCamera.up.set(0, upSign[i], 0);
  27322. cubeCamera.lookAt(0, 0, forwardSign[i]);
  27323. }
  27324. _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
  27325. renderer.setRenderTarget(cubeUVRenderTarget);
  27326. if (useSolidColor) {
  27327. renderer.render(backgroundBox, cubeCamera);
  27328. }
  27329. renderer.render(scene, cubeCamera);
  27330. }
  27331. renderer.toneMapping = toneMapping;
  27332. renderer.outputEncoding = outputEncoding;
  27333. renderer.autoClear = originalAutoClear;
  27334. }
  27335. _textureToCubeUV(texture, cubeUVRenderTarget) {
  27336. const renderer = this._renderer;
  27337. if (texture.isCubeTexture) {
  27338. if (this._cubemapShader == null) {
  27339. this._cubemapShader = _getCubemapShader();
  27340. }
  27341. } else {
  27342. if (this._equirectShader == null) {
  27343. this._equirectShader = _getEquirectShader();
  27344. }
  27345. }
  27346. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  27347. const mesh = new Mesh(_lodPlanes[0], material);
  27348. const uniforms = material.uniforms;
  27349. uniforms['envMap'].value = texture;
  27350. if (!texture.isCubeTexture) {
  27351. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  27352. }
  27353. uniforms['inputEncoding'].value = ENCODINGS[texture.encoding];
  27354. uniforms['outputEncoding'].value = ENCODINGS[cubeUVRenderTarget.texture.encoding];
  27355. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  27356. renderer.setRenderTarget(cubeUVRenderTarget);
  27357. renderer.render(mesh, _flatCamera);
  27358. }
  27359. _applyPMREM(cubeUVRenderTarget) {
  27360. const renderer = this._renderer;
  27361. const autoClear = renderer.autoClear;
  27362. renderer.autoClear = false;
  27363. for (let i = 1; i < TOTAL_LODS; i++) {
  27364. const sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  27365. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  27366. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  27367. }
  27368. renderer.autoClear = autoClear;
  27369. }
  27370. /**
  27371. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  27372. * vertically and horizontally, but this breaks down on a cube. Here we apply
  27373. * the blur latitudinally (around the poles), and then longitudinally (towards
  27374. * the poles) to approximate the orthogonally-separable blur. It is least
  27375. * accurate at the poles, but still does a decent job.
  27376. */
  27377. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  27378. const pingPongRenderTarget = this._pingPongRenderTarget;
  27379. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  27380. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  27381. }
  27382. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  27383. const renderer = this._renderer;
  27384. const blurMaterial = this._blurMaterial;
  27385. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  27386. console.error('blur direction must be either latitudinal or longitudinal!');
  27387. } // Number of standard deviations at which to cut off the discrete approximation.
  27388. const STANDARD_DEVIATIONS = 3;
  27389. const blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
  27390. const blurUniforms = blurMaterial.uniforms;
  27391. const pixels = _sizeLods[lodIn] - 1;
  27392. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  27393. const sigmaPixels = sigmaRadians / radiansPerPixel;
  27394. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  27395. if (samples > MAX_SAMPLES) {
  27396. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  27397. }
  27398. const weights = [];
  27399. let sum = 0;
  27400. for (let i = 0; i < MAX_SAMPLES; ++i) {
  27401. const x = i / sigmaPixels;
  27402. const weight = Math.exp(-x * x / 2);
  27403. weights.push(weight);
  27404. if (i == 0) {
  27405. sum += weight;
  27406. } else if (i < samples) {
  27407. sum += 2 * weight;
  27408. }
  27409. }
  27410. for (let i = 0; i < weights.length; i++) {
  27411. weights[i] = weights[i] / sum;
  27412. }
  27413. blurUniforms['envMap'].value = targetIn.texture;
  27414. blurUniforms['samples'].value = samples;
  27415. blurUniforms['weights'].value = weights;
  27416. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  27417. if (poleAxis) {
  27418. blurUniforms['poleAxis'].value = poleAxis;
  27419. }
  27420. blurUniforms['dTheta'].value = radiansPerPixel;
  27421. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  27422. blurUniforms['inputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  27423. blurUniforms['outputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  27424. const outputSize = _sizeLods[lodOut];
  27425. const x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  27426. const y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  27427. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  27428. renderer.setRenderTarget(targetOut);
  27429. renderer.render(blurMesh, _flatCamera);
  27430. }
  27431. }
  27432. function _isLDR(texture) {
  27433. if (texture === undefined || texture.type !== UnsignedByteType) return false;
  27434. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  27435. }
  27436. function _createPlanes() {
  27437. const _lodPlanes = [];
  27438. const _sizeLods = [];
  27439. const _sigmas = [];
  27440. let lod = LOD_MAX;
  27441. for (let i = 0; i < TOTAL_LODS; i++) {
  27442. const sizeLod = Math.pow(2, lod);
  27443. _sizeLods.push(sizeLod);
  27444. let sigma = 1.0 / sizeLod;
  27445. if (i > LOD_MAX - LOD_MIN) {
  27446. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  27447. } else if (i == 0) {
  27448. sigma = 0;
  27449. }
  27450. _sigmas.push(sigma);
  27451. const texelSize = 1.0 / (sizeLod - 1);
  27452. const min = -texelSize / 2;
  27453. const max = 1 + texelSize / 2;
  27454. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  27455. const cubeFaces = 6;
  27456. const vertices = 6;
  27457. const positionSize = 3;
  27458. const uvSize = 2;
  27459. const faceIndexSize = 1;
  27460. const position = new Float32Array(positionSize * vertices * cubeFaces);
  27461. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  27462. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  27463. for (let face = 0; face < cubeFaces; face++) {
  27464. const x = face % 3 * 2 / 3 - 1;
  27465. const y = face > 2 ? 0 : -1;
  27466. 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];
  27467. position.set(coordinates, positionSize * vertices * face);
  27468. uv.set(uv1, uvSize * vertices * face);
  27469. const fill = [face, face, face, face, face, face];
  27470. faceIndex.set(fill, faceIndexSize * vertices * face);
  27471. }
  27472. const planes = new BufferGeometry();
  27473. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  27474. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  27475. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  27476. _lodPlanes.push(planes);
  27477. if (lod > LOD_MIN) {
  27478. lod--;
  27479. }
  27480. }
  27481. return {
  27482. _lodPlanes,
  27483. _sizeLods,
  27484. _sigmas
  27485. };
  27486. }
  27487. function _createRenderTarget(params) {
  27488. const cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  27489. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  27490. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  27491. cubeUVRenderTarget.scissorTest = true;
  27492. return cubeUVRenderTarget;
  27493. }
  27494. function _setViewport(target, x, y, width, height) {
  27495. target.viewport.set(x, y, width, height);
  27496. target.scissor.set(x, y, width, height);
  27497. }
  27498. function _getBlurShader(maxSamples) {
  27499. const weights = new Float32Array(maxSamples);
  27500. const poleAxis = new Vector3(0, 1, 0);
  27501. const shaderMaterial = new RawShaderMaterial({
  27502. name: 'SphericalGaussianBlur',
  27503. defines: {
  27504. 'n': maxSamples
  27505. },
  27506. uniforms: {
  27507. 'envMap': {
  27508. value: null
  27509. },
  27510. 'samples': {
  27511. value: 1
  27512. },
  27513. 'weights': {
  27514. value: weights
  27515. },
  27516. 'latitudinal': {
  27517. value: false
  27518. },
  27519. 'dTheta': {
  27520. value: 0
  27521. },
  27522. 'mipInt': {
  27523. value: 0
  27524. },
  27525. 'poleAxis': {
  27526. value: poleAxis
  27527. },
  27528. 'inputEncoding': {
  27529. value: ENCODINGS[LinearEncoding]
  27530. },
  27531. 'outputEncoding': {
  27532. value: ENCODINGS[LinearEncoding]
  27533. }
  27534. },
  27535. vertexShader: _getCommonVertexShader(),
  27536. fragmentShader:
  27537. /* glsl */
  27538. `
  27539. precision mediump float;
  27540. precision mediump int;
  27541. varying vec3 vOutputDirection;
  27542. uniform sampler2D envMap;
  27543. uniform int samples;
  27544. uniform float weights[ n ];
  27545. uniform bool latitudinal;
  27546. uniform float dTheta;
  27547. uniform float mipInt;
  27548. uniform vec3 poleAxis;
  27549. ${_getEncodings()}
  27550. #define ENVMAP_TYPE_CUBE_UV
  27551. #include <cube_uv_reflection_fragment>
  27552. vec3 getSample( float theta, vec3 axis ) {
  27553. float cosTheta = cos( theta );
  27554. // Rodrigues' axis-angle rotation
  27555. vec3 sampleDirection = vOutputDirection * cosTheta
  27556. + cross( axis, vOutputDirection ) * sin( theta )
  27557. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  27558. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  27559. }
  27560. void main() {
  27561. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  27562. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  27563. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  27564. }
  27565. axis = normalize( axis );
  27566. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  27567. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  27568. for ( int i = 1; i < n; i++ ) {
  27569. if ( i >= samples ) {
  27570. break;
  27571. }
  27572. float theta = dTheta * float( i );
  27573. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  27574. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  27575. }
  27576. gl_FragColor = linearToOutputTexel( gl_FragColor );
  27577. }
  27578. `,
  27579. blending: NoBlending,
  27580. depthTest: false,
  27581. depthWrite: false
  27582. });
  27583. return shaderMaterial;
  27584. }
  27585. function _getEquirectShader() {
  27586. const texelSize = new Vector2(1, 1);
  27587. const shaderMaterial = new RawShaderMaterial({
  27588. name: 'EquirectangularToCubeUV',
  27589. uniforms: {
  27590. 'envMap': {
  27591. value: null
  27592. },
  27593. 'texelSize': {
  27594. value: texelSize
  27595. },
  27596. 'inputEncoding': {
  27597. value: ENCODINGS[LinearEncoding]
  27598. },
  27599. 'outputEncoding': {
  27600. value: ENCODINGS[LinearEncoding]
  27601. }
  27602. },
  27603. vertexShader: _getCommonVertexShader(),
  27604. fragmentShader:
  27605. /* glsl */
  27606. `
  27607. precision mediump float;
  27608. precision mediump int;
  27609. varying vec3 vOutputDirection;
  27610. uniform sampler2D envMap;
  27611. uniform vec2 texelSize;
  27612. ${_getEncodings()}
  27613. #include <common>
  27614. void main() {
  27615. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  27616. vec3 outputDirection = normalize( vOutputDirection );
  27617. vec2 uv = equirectUv( outputDirection );
  27618. vec2 f = fract( uv / texelSize - 0.5 );
  27619. uv -= f * texelSize;
  27620. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27621. uv.x += texelSize.x;
  27622. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27623. uv.y += texelSize.y;
  27624. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27625. uv.x -= texelSize.x;
  27626. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27627. vec3 tm = mix( tl, tr, f.x );
  27628. vec3 bm = mix( bl, br, f.x );
  27629. gl_FragColor.rgb = mix( tm, bm, f.y );
  27630. gl_FragColor = linearToOutputTexel( gl_FragColor );
  27631. }
  27632. `,
  27633. blending: NoBlending,
  27634. depthTest: false,
  27635. depthWrite: false
  27636. });
  27637. return shaderMaterial;
  27638. }
  27639. function _getCubemapShader() {
  27640. const shaderMaterial = new RawShaderMaterial({
  27641. name: 'CubemapToCubeUV',
  27642. uniforms: {
  27643. 'envMap': {
  27644. value: null
  27645. },
  27646. 'inputEncoding': {
  27647. value: ENCODINGS[LinearEncoding]
  27648. },
  27649. 'outputEncoding': {
  27650. value: ENCODINGS[LinearEncoding]
  27651. }
  27652. },
  27653. vertexShader: _getCommonVertexShader(),
  27654. fragmentShader:
  27655. /* glsl */
  27656. `
  27657. precision mediump float;
  27658. precision mediump int;
  27659. varying vec3 vOutputDirection;
  27660. uniform samplerCube envMap;
  27661. ${_getEncodings()}
  27662. void main() {
  27663. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  27664. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  27665. gl_FragColor = linearToOutputTexel( gl_FragColor );
  27666. }
  27667. `,
  27668. blending: NoBlending,
  27669. depthTest: false,
  27670. depthWrite: false
  27671. });
  27672. return shaderMaterial;
  27673. }
  27674. function _getCommonVertexShader() {
  27675. return (
  27676. /* glsl */
  27677. `
  27678. precision mediump float;
  27679. precision mediump int;
  27680. attribute vec3 position;
  27681. attribute vec2 uv;
  27682. attribute float faceIndex;
  27683. varying vec3 vOutputDirection;
  27684. // RH coordinate system; PMREM face-indexing convention
  27685. vec3 getDirection( vec2 uv, float face ) {
  27686. uv = 2.0 * uv - 1.0;
  27687. vec3 direction = vec3( uv, 1.0 );
  27688. if ( face == 0.0 ) {
  27689. direction = direction.zyx; // ( 1, v, u ) pos x
  27690. } else if ( face == 1.0 ) {
  27691. direction = direction.xzy;
  27692. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  27693. } else if ( face == 2.0 ) {
  27694. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  27695. } else if ( face == 3.0 ) {
  27696. direction = direction.zyx;
  27697. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  27698. } else if ( face == 4.0 ) {
  27699. direction = direction.xzy;
  27700. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  27701. } else if ( face == 5.0 ) {
  27702. direction.z *= -1.0; // ( u, v, -1 ) neg z
  27703. }
  27704. return direction;
  27705. }
  27706. void main() {
  27707. vOutputDirection = getDirection( uv, faceIndex );
  27708. gl_Position = vec4( position, 1.0 );
  27709. }
  27710. `
  27711. );
  27712. }
  27713. function _getEncodings() {
  27714. return (
  27715. /* glsl */
  27716. `
  27717. uniform int inputEncoding;
  27718. uniform int outputEncoding;
  27719. #include <encodings_pars_fragment>
  27720. vec4 inputTexelToLinear( vec4 value ) {
  27721. if ( inputEncoding == 0 ) {
  27722. return value;
  27723. } else if ( inputEncoding == 1 ) {
  27724. return sRGBToLinear( value );
  27725. } else if ( inputEncoding == 2 ) {
  27726. return RGBEToLinear( value );
  27727. } else if ( inputEncoding == 3 ) {
  27728. return RGBMToLinear( value, 7.0 );
  27729. } else if ( inputEncoding == 4 ) {
  27730. return RGBMToLinear( value, 16.0 );
  27731. } else if ( inputEncoding == 5 ) {
  27732. return RGBDToLinear( value, 256.0 );
  27733. } else {
  27734. return GammaToLinear( value, 2.2 );
  27735. }
  27736. }
  27737. vec4 linearToOutputTexel( vec4 value ) {
  27738. if ( outputEncoding == 0 ) {
  27739. return value;
  27740. } else if ( outputEncoding == 1 ) {
  27741. return LinearTosRGB( value );
  27742. } else if ( outputEncoding == 2 ) {
  27743. return LinearToRGBE( value );
  27744. } else if ( outputEncoding == 3 ) {
  27745. return LinearToRGBM( value, 7.0 );
  27746. } else if ( outputEncoding == 4 ) {
  27747. return LinearToRGBM( value, 16.0 );
  27748. } else if ( outputEncoding == 5 ) {
  27749. return LinearToRGBD( value, 256.0 );
  27750. } else {
  27751. return LinearToGamma( value, 2.2 );
  27752. }
  27753. }
  27754. vec4 envMapTexelToLinear( vec4 color ) {
  27755. return inputTexelToLinear( color );
  27756. }
  27757. `
  27758. );
  27759. }
  27760. const LineStrip = 0;
  27761. const LinePieces = 1;
  27762. const NoColors = 0;
  27763. const FaceColors = 1;
  27764. const VertexColors = 2;
  27765. function MeshFaceMaterial(materials) {
  27766. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  27767. return materials;
  27768. }
  27769. function MultiMaterial(materials = []) {
  27770. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  27771. materials.isMultiMaterial = true;
  27772. materials.materials = materials;
  27773. materials.clone = function () {
  27774. return materials.slice();
  27775. };
  27776. return materials;
  27777. }
  27778. function PointCloud(geometry, material) {
  27779. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  27780. return new Points(geometry, material);
  27781. }
  27782. function Particle(material) {
  27783. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  27784. return new Sprite(material);
  27785. }
  27786. function ParticleSystem(geometry, material) {
  27787. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  27788. return new Points(geometry, material);
  27789. }
  27790. function PointCloudMaterial(parameters) {
  27791. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  27792. return new PointsMaterial(parameters);
  27793. }
  27794. function ParticleBasicMaterial(parameters) {
  27795. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  27796. return new PointsMaterial(parameters);
  27797. }
  27798. function ParticleSystemMaterial(parameters) {
  27799. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  27800. return new PointsMaterial(parameters);
  27801. }
  27802. function Vertex(x, y, z) {
  27803. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  27804. return new Vector3(x, y, z);
  27805. } //
  27806. function DynamicBufferAttribute(array, itemSize) {
  27807. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  27808. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  27809. }
  27810. function Int8Attribute(array, itemSize) {
  27811. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  27812. return new Int8BufferAttribute(array, itemSize);
  27813. }
  27814. function Uint8Attribute(array, itemSize) {
  27815. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  27816. return new Uint8BufferAttribute(array, itemSize);
  27817. }
  27818. function Uint8ClampedAttribute(array, itemSize) {
  27819. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  27820. return new Uint8ClampedBufferAttribute(array, itemSize);
  27821. }
  27822. function Int16Attribute(array, itemSize) {
  27823. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  27824. return new Int16BufferAttribute(array, itemSize);
  27825. }
  27826. function Uint16Attribute(array, itemSize) {
  27827. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  27828. return new Uint16BufferAttribute(array, itemSize);
  27829. }
  27830. function Int32Attribute(array, itemSize) {
  27831. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  27832. return new Int32BufferAttribute(array, itemSize);
  27833. }
  27834. function Uint32Attribute(array, itemSize) {
  27835. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  27836. return new Uint32BufferAttribute(array, itemSize);
  27837. }
  27838. function Float32Attribute(array, itemSize) {
  27839. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  27840. return new Float32BufferAttribute(array, itemSize);
  27841. }
  27842. function Float64Attribute(array, itemSize) {
  27843. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  27844. return new Float64BufferAttribute(array, itemSize);
  27845. } //
  27846. Curve.create = function (construct, getPoint) {
  27847. console.log('THREE.Curve.create() has been deprecated');
  27848. construct.prototype = Object.create(Curve.prototype);
  27849. construct.prototype.constructor = construct;
  27850. construct.prototype.getPoint = getPoint;
  27851. return construct;
  27852. }; //
  27853. Path.prototype.fromPoints = function (points) {
  27854. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  27855. return this.setFromPoints(points);
  27856. }; //
  27857. function AxisHelper(size) {
  27858. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  27859. return new AxesHelper(size);
  27860. }
  27861. function BoundingBoxHelper(object, color) {
  27862. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  27863. return new BoxHelper(object, color);
  27864. }
  27865. function EdgesHelper(object, hex) {
  27866. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  27867. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  27868. color: hex !== undefined ? hex : 0xffffff
  27869. }));
  27870. }
  27871. GridHelper.prototype.setColors = function () {
  27872. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  27873. };
  27874. SkeletonHelper.prototype.update = function () {
  27875. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  27876. };
  27877. function WireframeHelper(object, hex) {
  27878. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  27879. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  27880. color: hex !== undefined ? hex : 0xffffff
  27881. }));
  27882. } //
  27883. Loader.prototype.extractUrlBase = function (url) {
  27884. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  27885. return LoaderUtils.extractUrlBase(url);
  27886. };
  27887. Loader.Handlers = {
  27888. add: function ()
  27889. /* regex, loader */
  27890. {
  27891. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  27892. },
  27893. get: function ()
  27894. /* file */
  27895. {
  27896. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  27897. }
  27898. };
  27899. function XHRLoader(manager) {
  27900. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  27901. return new FileLoader(manager);
  27902. }
  27903. function BinaryTextureLoader(manager) {
  27904. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  27905. return new DataTextureLoader(manager);
  27906. } //
  27907. Box2.prototype.center = function (optionalTarget) {
  27908. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  27909. return this.getCenter(optionalTarget);
  27910. };
  27911. Box2.prototype.empty = function () {
  27912. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  27913. return this.isEmpty();
  27914. };
  27915. Box2.prototype.isIntersectionBox = function (box) {
  27916. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  27917. return this.intersectsBox(box);
  27918. };
  27919. Box2.prototype.size = function (optionalTarget) {
  27920. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  27921. return this.getSize(optionalTarget);
  27922. }; //
  27923. Box3.prototype.center = function (optionalTarget) {
  27924. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  27925. return this.getCenter(optionalTarget);
  27926. };
  27927. Box3.prototype.empty = function () {
  27928. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  27929. return this.isEmpty();
  27930. };
  27931. Box3.prototype.isIntersectionBox = function (box) {
  27932. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  27933. return this.intersectsBox(box);
  27934. };
  27935. Box3.prototype.isIntersectionSphere = function (sphere) {
  27936. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  27937. return this.intersectsSphere(sphere);
  27938. };
  27939. Box3.prototype.size = function (optionalTarget) {
  27940. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  27941. return this.getSize(optionalTarget);
  27942. }; //
  27943. Sphere.prototype.empty = function () {
  27944. console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
  27945. return this.isEmpty();
  27946. }; //
  27947. Frustum.prototype.setFromMatrix = function (m) {
  27948. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  27949. return this.setFromProjectionMatrix(m);
  27950. }; //
  27951. Line3.prototype.center = function (optionalTarget) {
  27952. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  27953. return this.getCenter(optionalTarget);
  27954. }; //
  27955. Matrix3.prototype.flattenToArrayOffset = function (array, offset) {
  27956. console.warn('THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  27957. return this.toArray(array, offset);
  27958. };
  27959. Matrix3.prototype.multiplyVector3 = function (vector) {
  27960. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  27961. return vector.applyMatrix3(this);
  27962. };
  27963. Matrix3.prototype.multiplyVector3Array = function ()
  27964. /* a */
  27965. {
  27966. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  27967. };
  27968. Matrix3.prototype.applyToBufferAttribute = function (attribute) {
  27969. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  27970. return attribute.applyMatrix3(this);
  27971. };
  27972. Matrix3.prototype.applyToVector3Array = function ()
  27973. /* array, offset, length */
  27974. {
  27975. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  27976. };
  27977. Matrix3.prototype.getInverse = function (matrix) {
  27978. console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  27979. return this.copy(matrix).invert();
  27980. }; //
  27981. Matrix4.prototype.extractPosition = function (m) {
  27982. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  27983. return this.copyPosition(m);
  27984. };
  27985. Matrix4.prototype.flattenToArrayOffset = function (array, offset) {
  27986. console.warn('THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  27987. return this.toArray(array, offset);
  27988. };
  27989. Matrix4.prototype.getPosition = function () {
  27990. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  27991. return new Vector3().setFromMatrixColumn(this, 3);
  27992. };
  27993. Matrix4.prototype.setRotationFromQuaternion = function (q) {
  27994. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  27995. return this.makeRotationFromQuaternion(q);
  27996. };
  27997. Matrix4.prototype.multiplyToArray = function () {
  27998. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  27999. };
  28000. Matrix4.prototype.multiplyVector3 = function (vector) {
  28001. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28002. return vector.applyMatrix4(this);
  28003. };
  28004. Matrix4.prototype.multiplyVector4 = function (vector) {
  28005. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28006. return vector.applyMatrix4(this);
  28007. };
  28008. Matrix4.prototype.multiplyVector3Array = function ()
  28009. /* a */
  28010. {
  28011. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  28012. };
  28013. Matrix4.prototype.rotateAxis = function (v) {
  28014. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  28015. v.transformDirection(this);
  28016. };
  28017. Matrix4.prototype.crossVector = function (vector) {
  28018. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28019. return vector.applyMatrix4(this);
  28020. };
  28021. Matrix4.prototype.translate = function () {
  28022. console.error('THREE.Matrix4: .translate() has been removed.');
  28023. };
  28024. Matrix4.prototype.rotateX = function () {
  28025. console.error('THREE.Matrix4: .rotateX() has been removed.');
  28026. };
  28027. Matrix4.prototype.rotateY = function () {
  28028. console.error('THREE.Matrix4: .rotateY() has been removed.');
  28029. };
  28030. Matrix4.prototype.rotateZ = function () {
  28031. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  28032. };
  28033. Matrix4.prototype.rotateByAxis = function () {
  28034. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  28035. };
  28036. Matrix4.prototype.applyToBufferAttribute = function (attribute) {
  28037. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  28038. return attribute.applyMatrix4(this);
  28039. };
  28040. Matrix4.prototype.applyToVector3Array = function ()
  28041. /* array, offset, length */
  28042. {
  28043. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  28044. };
  28045. Matrix4.prototype.makeFrustum = function (left, right, bottom, top, near, far) {
  28046. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  28047. return this.makePerspective(left, right, top, bottom, near, far);
  28048. };
  28049. Matrix4.prototype.getInverse = function (matrix) {
  28050. console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  28051. return this.copy(matrix).invert();
  28052. }; //
  28053. Plane.prototype.isIntersectionLine = function (line) {
  28054. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  28055. return this.intersectsLine(line);
  28056. }; //
  28057. Quaternion.prototype.multiplyVector3 = function (vector) {
  28058. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  28059. return vector.applyQuaternion(this);
  28060. };
  28061. Quaternion.prototype.inverse = function () {
  28062. console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
  28063. return this.invert();
  28064. }; //
  28065. Ray.prototype.isIntersectionBox = function (box) {
  28066. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  28067. return this.intersectsBox(box);
  28068. };
  28069. Ray.prototype.isIntersectionPlane = function (plane) {
  28070. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  28071. return this.intersectsPlane(plane);
  28072. };
  28073. Ray.prototype.isIntersectionSphere = function (sphere) {
  28074. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28075. return this.intersectsSphere(sphere);
  28076. }; //
  28077. Triangle.prototype.area = function () {
  28078. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  28079. return this.getArea();
  28080. };
  28081. Triangle.prototype.barycoordFromPoint = function (point, target) {
  28082. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28083. return this.getBarycoord(point, target);
  28084. };
  28085. Triangle.prototype.midpoint = function (target) {
  28086. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  28087. return this.getMidpoint(target);
  28088. };
  28089. Triangle.prototypenormal = function (target) {
  28090. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28091. return this.getNormal(target);
  28092. };
  28093. Triangle.prototype.plane = function (target) {
  28094. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  28095. return this.getPlane(target);
  28096. };
  28097. Triangle.barycoordFromPoint = function (point, a, b, c, target) {
  28098. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28099. return Triangle.getBarycoord(point, a, b, c, target);
  28100. };
  28101. Triangle.normal = function (a, b, c, target) {
  28102. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28103. return Triangle.getNormal(a, b, c, target);
  28104. }; //
  28105. Shape.prototype.extractAllPoints = function (divisions) {
  28106. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  28107. return this.extractPoints(divisions);
  28108. };
  28109. Shape.prototype.extrude = function (options) {
  28110. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  28111. return new ExtrudeGeometry(this, options);
  28112. };
  28113. Shape.prototype.makeGeometry = function (options) {
  28114. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  28115. return new ShapeGeometry(this, options);
  28116. }; //
  28117. Vector2.prototype.fromAttribute = function (attribute, index, offset) {
  28118. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28119. return this.fromBufferAttribute(attribute, index, offset);
  28120. };
  28121. Vector2.prototype.distanceToManhattan = function (v) {
  28122. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28123. return this.manhattanDistanceTo(v);
  28124. };
  28125. Vector2.prototype.lengthManhattan = function () {
  28126. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  28127. return this.manhattanLength();
  28128. }; //
  28129. Vector3.prototype.setEulerFromRotationMatrix = function () {
  28130. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  28131. };
  28132. Vector3.prototype.setEulerFromQuaternion = function () {
  28133. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  28134. };
  28135. Vector3.prototype.getPositionFromMatrix = function (m) {
  28136. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  28137. return this.setFromMatrixPosition(m);
  28138. };
  28139. Vector3.prototype.getScaleFromMatrix = function (m) {
  28140. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  28141. return this.setFromMatrixScale(m);
  28142. };
  28143. Vector3.prototype.getColumnFromMatrix = function (index, matrix) {
  28144. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  28145. return this.setFromMatrixColumn(matrix, index);
  28146. };
  28147. Vector3.prototype.applyProjection = function (m) {
  28148. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  28149. return this.applyMatrix4(m);
  28150. };
  28151. Vector3.prototype.fromAttribute = function (attribute, index, offset) {
  28152. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28153. return this.fromBufferAttribute(attribute, index, offset);
  28154. };
  28155. Vector3.prototype.distanceToManhattan = function (v) {
  28156. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28157. return this.manhattanDistanceTo(v);
  28158. };
  28159. Vector3.prototype.lengthManhattan = function () {
  28160. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  28161. return this.manhattanLength();
  28162. }; //
  28163. Vector4.prototype.fromAttribute = function (attribute, index, offset) {
  28164. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28165. return this.fromBufferAttribute(attribute, index, offset);
  28166. };
  28167. Vector4.prototype.lengthManhattan = function () {
  28168. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  28169. return this.manhattanLength();
  28170. }; //
  28171. Object3D.prototype.getChildByName = function (name) {
  28172. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  28173. return this.getObjectByName(name);
  28174. };
  28175. Object3D.prototype.renderDepth = function () {
  28176. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  28177. };
  28178. Object3D.prototype.translate = function (distance, axis) {
  28179. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  28180. return this.translateOnAxis(axis, distance);
  28181. };
  28182. Object3D.prototype.getWorldRotation = function () {
  28183. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  28184. };
  28185. Object3D.prototype.applyMatrix = function (matrix) {
  28186. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  28187. return this.applyMatrix4(matrix);
  28188. };
  28189. Object.defineProperties(Object3D.prototype, {
  28190. eulerOrder: {
  28191. get: function () {
  28192. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28193. return this.rotation.order;
  28194. },
  28195. set: function (value) {
  28196. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28197. this.rotation.order = value;
  28198. }
  28199. },
  28200. useQuaternion: {
  28201. get: function () {
  28202. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28203. },
  28204. set: function () {
  28205. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28206. }
  28207. }
  28208. });
  28209. Mesh.prototype.setDrawMode = function () {
  28210. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28211. };
  28212. Object.defineProperties(Mesh.prototype, {
  28213. drawMode: {
  28214. get: function () {
  28215. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  28216. return TrianglesDrawMode;
  28217. },
  28218. set: function () {
  28219. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28220. }
  28221. }
  28222. });
  28223. SkinnedMesh.prototype.initBones = function () {
  28224. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  28225. }; //
  28226. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  28227. console.warn('THREE.PerspectiveCamera.setLens is deprecated. ' + 'Use .setFocalLength and .filmGauge for a photographic setup.');
  28228. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  28229. this.setFocalLength(focalLength);
  28230. }; //
  28231. Object.defineProperties(Light.prototype, {
  28232. onlyShadow: {
  28233. set: function () {
  28234. console.warn('THREE.Light: .onlyShadow has been removed.');
  28235. }
  28236. },
  28237. shadowCameraFov: {
  28238. set: function (value) {
  28239. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  28240. this.shadow.camera.fov = value;
  28241. }
  28242. },
  28243. shadowCameraLeft: {
  28244. set: function (value) {
  28245. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  28246. this.shadow.camera.left = value;
  28247. }
  28248. },
  28249. shadowCameraRight: {
  28250. set: function (value) {
  28251. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  28252. this.shadow.camera.right = value;
  28253. }
  28254. },
  28255. shadowCameraTop: {
  28256. set: function (value) {
  28257. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  28258. this.shadow.camera.top = value;
  28259. }
  28260. },
  28261. shadowCameraBottom: {
  28262. set: function (value) {
  28263. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  28264. this.shadow.camera.bottom = value;
  28265. }
  28266. },
  28267. shadowCameraNear: {
  28268. set: function (value) {
  28269. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  28270. this.shadow.camera.near = value;
  28271. }
  28272. },
  28273. shadowCameraFar: {
  28274. set: function (value) {
  28275. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  28276. this.shadow.camera.far = value;
  28277. }
  28278. },
  28279. shadowCameraVisible: {
  28280. set: function () {
  28281. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  28282. }
  28283. },
  28284. shadowBias: {
  28285. set: function (value) {
  28286. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  28287. this.shadow.bias = value;
  28288. }
  28289. },
  28290. shadowDarkness: {
  28291. set: function () {
  28292. console.warn('THREE.Light: .shadowDarkness has been removed.');
  28293. }
  28294. },
  28295. shadowMapWidth: {
  28296. set: function (value) {
  28297. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  28298. this.shadow.mapSize.width = value;
  28299. }
  28300. },
  28301. shadowMapHeight: {
  28302. set: function (value) {
  28303. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  28304. this.shadow.mapSize.height = value;
  28305. }
  28306. }
  28307. }); //
  28308. Object.defineProperties(BufferAttribute.prototype, {
  28309. length: {
  28310. get: function () {
  28311. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  28312. return this.array.length;
  28313. }
  28314. },
  28315. dynamic: {
  28316. get: function () {
  28317. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28318. return this.usage === DynamicDrawUsage;
  28319. },
  28320. set: function ()
  28321. /* value */
  28322. {
  28323. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28324. this.setUsage(DynamicDrawUsage);
  28325. }
  28326. }
  28327. });
  28328. BufferAttribute.prototype.setDynamic = function (value) {
  28329. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28330. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28331. return this;
  28332. };
  28333. BufferAttribute.prototype.copyIndicesArray = function ()
  28334. /* indices */
  28335. {
  28336. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  28337. }, BufferAttribute.prototype.setArray = function ()
  28338. /* array */
  28339. {
  28340. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28341. }; //
  28342. BufferGeometry.prototype.addIndex = function (index) {
  28343. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  28344. this.setIndex(index);
  28345. };
  28346. BufferGeometry.prototype.addAttribute = function (name, attribute) {
  28347. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  28348. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  28349. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  28350. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  28351. }
  28352. if (name === 'index') {
  28353. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  28354. this.setIndex(attribute);
  28355. return this;
  28356. }
  28357. return this.setAttribute(name, attribute);
  28358. };
  28359. BufferGeometry.prototype.addDrawCall = function (start, count, indexOffset) {
  28360. if (indexOffset !== undefined) {
  28361. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  28362. }
  28363. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  28364. this.addGroup(start, count);
  28365. };
  28366. BufferGeometry.prototype.clearDrawCalls = function () {
  28367. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  28368. this.clearGroups();
  28369. };
  28370. BufferGeometry.prototype.computeOffsets = function () {
  28371. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  28372. };
  28373. BufferGeometry.prototype.removeAttribute = function (name) {
  28374. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  28375. return this.deleteAttribute(name);
  28376. };
  28377. BufferGeometry.prototype.applyMatrix = function (matrix) {
  28378. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  28379. return this.applyMatrix4(matrix);
  28380. };
  28381. Object.defineProperties(BufferGeometry.prototype, {
  28382. drawcalls: {
  28383. get: function () {
  28384. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  28385. return this.groups;
  28386. }
  28387. },
  28388. offsets: {
  28389. get: function () {
  28390. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  28391. return this.groups;
  28392. }
  28393. }
  28394. });
  28395. InterleavedBuffer.prototype.setDynamic = function (value) {
  28396. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28397. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28398. return this;
  28399. };
  28400. InterleavedBuffer.prototype.setArray = function ()
  28401. /* array */
  28402. {
  28403. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28404. }; //
  28405. ExtrudeGeometry.prototype.getArrays = function () {
  28406. console.error('THREE.ExtrudeGeometry: .getArrays() has been removed.');
  28407. };
  28408. ExtrudeGeometry.prototype.addShapeList = function () {
  28409. console.error('THREE.ExtrudeGeometry: .addShapeList() has been removed.');
  28410. };
  28411. ExtrudeGeometry.prototype.addShape = function () {
  28412. console.error('THREE.ExtrudeGeometry: .addShape() has been removed.');
  28413. }; //
  28414. Scene.prototype.dispose = function () {
  28415. console.error('THREE.Scene: .dispose() has been removed.');
  28416. }; //
  28417. Uniform.prototype.onUpdate = function () {
  28418. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  28419. return this;
  28420. }; //
  28421. Object.defineProperties(Material.prototype, {
  28422. wrapAround: {
  28423. get: function () {
  28424. console.warn('THREE.Material: .wrapAround has been removed.');
  28425. },
  28426. set: function () {
  28427. console.warn('THREE.Material: .wrapAround has been removed.');
  28428. }
  28429. },
  28430. overdraw: {
  28431. get: function () {
  28432. console.warn('THREE.Material: .overdraw has been removed.');
  28433. },
  28434. set: function () {
  28435. console.warn('THREE.Material: .overdraw has been removed.');
  28436. }
  28437. },
  28438. wrapRGB: {
  28439. get: function () {
  28440. console.warn('THREE.Material: .wrapRGB has been removed.');
  28441. return new Color();
  28442. }
  28443. },
  28444. shading: {
  28445. get: function () {
  28446. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28447. },
  28448. set: function (value) {
  28449. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28450. this.flatShading = value === FlatShading;
  28451. }
  28452. },
  28453. stencilMask: {
  28454. get: function () {
  28455. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28456. return this.stencilFuncMask;
  28457. },
  28458. set: function (value) {
  28459. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28460. this.stencilFuncMask = value;
  28461. }
  28462. }
  28463. });
  28464. Object.defineProperties(ShaderMaterial.prototype, {
  28465. derivatives: {
  28466. get: function () {
  28467. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28468. return this.extensions.derivatives;
  28469. },
  28470. set: function (value) {
  28471. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28472. this.extensions.derivatives = value;
  28473. }
  28474. }
  28475. }); //
  28476. WebGLRenderer.prototype.clearTarget = function (renderTarget, color, depth, stencil) {
  28477. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  28478. this.setRenderTarget(renderTarget);
  28479. this.clear(color, depth, stencil);
  28480. };
  28481. WebGLRenderer.prototype.animate = function (callback) {
  28482. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  28483. this.setAnimationLoop(callback);
  28484. };
  28485. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  28486. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  28487. return this.getRenderTarget();
  28488. };
  28489. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  28490. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  28491. return this.capabilities.getMaxAnisotropy();
  28492. };
  28493. WebGLRenderer.prototype.getPrecision = function () {
  28494. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  28495. return this.capabilities.precision;
  28496. };
  28497. WebGLRenderer.prototype.resetGLState = function () {
  28498. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  28499. return this.state.reset();
  28500. };
  28501. WebGLRenderer.prototype.supportsFloatTextures = function () {
  28502. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  28503. return this.extensions.get('OES_texture_float');
  28504. };
  28505. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  28506. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  28507. return this.extensions.get('OES_texture_half_float');
  28508. };
  28509. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  28510. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  28511. return this.extensions.get('OES_standard_derivatives');
  28512. };
  28513. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  28514. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  28515. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  28516. };
  28517. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  28518. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  28519. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  28520. };
  28521. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  28522. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  28523. return this.extensions.get('EXT_blend_minmax');
  28524. };
  28525. WebGLRenderer.prototype.supportsVertexTextures = function () {
  28526. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  28527. return this.capabilities.vertexTextures;
  28528. };
  28529. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  28530. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  28531. return this.extensions.get('ANGLE_instanced_arrays');
  28532. };
  28533. WebGLRenderer.prototype.enableScissorTest = function (boolean) {
  28534. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  28535. this.setScissorTest(boolean);
  28536. };
  28537. WebGLRenderer.prototype.initMaterial = function () {
  28538. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  28539. };
  28540. WebGLRenderer.prototype.addPrePlugin = function () {
  28541. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  28542. };
  28543. WebGLRenderer.prototype.addPostPlugin = function () {
  28544. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  28545. };
  28546. WebGLRenderer.prototype.updateShadowMap = function () {
  28547. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  28548. };
  28549. WebGLRenderer.prototype.setFaceCulling = function () {
  28550. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  28551. };
  28552. WebGLRenderer.prototype.allocTextureUnit = function () {
  28553. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  28554. };
  28555. WebGLRenderer.prototype.setTexture = function () {
  28556. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  28557. };
  28558. WebGLRenderer.prototype.setTexture2D = function () {
  28559. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  28560. };
  28561. WebGLRenderer.prototype.setTextureCube = function () {
  28562. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  28563. };
  28564. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  28565. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  28566. return this.getActiveMipmapLevel();
  28567. };
  28568. Object.defineProperties(WebGLRenderer.prototype, {
  28569. shadowMapEnabled: {
  28570. get: function () {
  28571. return this.shadowMap.enabled;
  28572. },
  28573. set: function (value) {
  28574. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  28575. this.shadowMap.enabled = value;
  28576. }
  28577. },
  28578. shadowMapType: {
  28579. get: function () {
  28580. return this.shadowMap.type;
  28581. },
  28582. set: function (value) {
  28583. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  28584. this.shadowMap.type = value;
  28585. }
  28586. },
  28587. shadowMapCullFace: {
  28588. get: function () {
  28589. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28590. return undefined;
  28591. },
  28592. set: function ()
  28593. /* value */
  28594. {
  28595. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28596. }
  28597. },
  28598. context: {
  28599. get: function () {
  28600. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  28601. return this.getContext();
  28602. }
  28603. },
  28604. vr: {
  28605. get: function () {
  28606. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  28607. return this.xr;
  28608. }
  28609. },
  28610. gammaInput: {
  28611. get: function () {
  28612. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  28613. return false;
  28614. },
  28615. set: function () {
  28616. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  28617. }
  28618. },
  28619. gammaOutput: {
  28620. get: function () {
  28621. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  28622. return false;
  28623. },
  28624. set: function (value) {
  28625. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  28626. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  28627. }
  28628. },
  28629. toneMappingWhitePoint: {
  28630. get: function () {
  28631. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  28632. return 1.0;
  28633. },
  28634. set: function () {
  28635. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  28636. }
  28637. }
  28638. });
  28639. Object.defineProperties(WebGLShadowMap.prototype, {
  28640. cullFace: {
  28641. get: function () {
  28642. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  28643. return undefined;
  28644. },
  28645. set: function ()
  28646. /* cullFace */
  28647. {
  28648. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  28649. }
  28650. },
  28651. renderReverseSided: {
  28652. get: function () {
  28653. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  28654. return undefined;
  28655. },
  28656. set: function () {
  28657. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  28658. }
  28659. },
  28660. renderSingleSided: {
  28661. get: function () {
  28662. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  28663. return undefined;
  28664. },
  28665. set: function () {
  28666. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  28667. }
  28668. }
  28669. });
  28670. function WebGLRenderTargetCube(width, height, options) {
  28671. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  28672. return new WebGLCubeRenderTarget(width, options);
  28673. } //
  28674. Object.defineProperties(WebGLRenderTarget.prototype, {
  28675. wrapS: {
  28676. get: function () {
  28677. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  28678. return this.texture.wrapS;
  28679. },
  28680. set: function (value) {
  28681. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  28682. this.texture.wrapS = value;
  28683. }
  28684. },
  28685. wrapT: {
  28686. get: function () {
  28687. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  28688. return this.texture.wrapT;
  28689. },
  28690. set: function (value) {
  28691. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  28692. this.texture.wrapT = value;
  28693. }
  28694. },
  28695. magFilter: {
  28696. get: function () {
  28697. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  28698. return this.texture.magFilter;
  28699. },
  28700. set: function (value) {
  28701. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  28702. this.texture.magFilter = value;
  28703. }
  28704. },
  28705. minFilter: {
  28706. get: function () {
  28707. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  28708. return this.texture.minFilter;
  28709. },
  28710. set: function (value) {
  28711. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  28712. this.texture.minFilter = value;
  28713. }
  28714. },
  28715. anisotropy: {
  28716. get: function () {
  28717. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  28718. return this.texture.anisotropy;
  28719. },
  28720. set: function (value) {
  28721. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  28722. this.texture.anisotropy = value;
  28723. }
  28724. },
  28725. offset: {
  28726. get: function () {
  28727. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  28728. return this.texture.offset;
  28729. },
  28730. set: function (value) {
  28731. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  28732. this.texture.offset = value;
  28733. }
  28734. },
  28735. repeat: {
  28736. get: function () {
  28737. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  28738. return this.texture.repeat;
  28739. },
  28740. set: function (value) {
  28741. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  28742. this.texture.repeat = value;
  28743. }
  28744. },
  28745. format: {
  28746. get: function () {
  28747. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  28748. return this.texture.format;
  28749. },
  28750. set: function (value) {
  28751. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  28752. this.texture.format = value;
  28753. }
  28754. },
  28755. type: {
  28756. get: function () {
  28757. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  28758. return this.texture.type;
  28759. },
  28760. set: function (value) {
  28761. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  28762. this.texture.type = value;
  28763. }
  28764. },
  28765. generateMipmaps: {
  28766. get: function () {
  28767. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  28768. return this.texture.generateMipmaps;
  28769. },
  28770. set: function (value) {
  28771. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  28772. this.texture.generateMipmaps = value;
  28773. }
  28774. }
  28775. }); //
  28776. Audio.prototype.load = function (file) {
  28777. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  28778. const scope = this;
  28779. const audioLoader = new AudioLoader();
  28780. audioLoader.load(file, function (buffer) {
  28781. scope.setBuffer(buffer);
  28782. });
  28783. return this;
  28784. };
  28785. AudioAnalyser.prototype.getData = function () {
  28786. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  28787. return this.getFrequencyData();
  28788. }; //
  28789. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  28790. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  28791. return this.update(renderer, scene);
  28792. };
  28793. CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
  28794. console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
  28795. return this.renderTarget.clear(renderer, color, depth, stencil);
  28796. };
  28797. ImageUtils.crossOrigin = undefined;
  28798. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  28799. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  28800. const loader = new TextureLoader();
  28801. loader.setCrossOrigin(this.crossOrigin);
  28802. const texture = loader.load(url, onLoad, undefined, onError);
  28803. if (mapping) texture.mapping = mapping;
  28804. return texture;
  28805. };
  28806. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  28807. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  28808. const loader = new CubeTextureLoader();
  28809. loader.setCrossOrigin(this.crossOrigin);
  28810. const texture = loader.load(urls, onLoad, undefined, onError);
  28811. if (mapping) texture.mapping = mapping;
  28812. return texture;
  28813. };
  28814. ImageUtils.loadCompressedTexture = function () {
  28815. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  28816. };
  28817. ImageUtils.loadCompressedTextureCube = function () {
  28818. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  28819. }; //
  28820. function CanvasRenderer() {
  28821. console.error('THREE.CanvasRenderer has been removed');
  28822. } //
  28823. function JSONLoader() {
  28824. console.error('THREE.JSONLoader has been removed.');
  28825. } //
  28826. const SceneUtils = {
  28827. createMultiMaterialObject: function ()
  28828. /* geometry, materials */
  28829. {
  28830. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28831. },
  28832. detach: function ()
  28833. /* child, parent, scene */
  28834. {
  28835. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28836. },
  28837. attach: function ()
  28838. /* child, scene, parent */
  28839. {
  28840. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28841. }
  28842. }; //
  28843. function LensFlare() {
  28844. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  28845. }
  28846. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  28847. /* eslint-disable no-undef */
  28848. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  28849. detail: {
  28850. revision: REVISION
  28851. }
  28852. }));
  28853. /* eslint-enable no-undef */
  28854. }
  28855. if (typeof window !== 'undefined') {
  28856. if (window.__THREE__) {
  28857. console.warn('WARNING: Multiple instances of Three.js being imported.');
  28858. } else {
  28859. window.__THREE__ = REVISION;
  28860. }
  28861. }
  28862. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  28863. exports.AddEquation = AddEquation;
  28864. exports.AddOperation = AddOperation;
  28865. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  28866. exports.AdditiveBlending = AdditiveBlending;
  28867. exports.AlphaFormat = AlphaFormat;
  28868. exports.AlwaysDepth = AlwaysDepth;
  28869. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  28870. exports.AmbientLight = AmbientLight;
  28871. exports.AmbientLightProbe = AmbientLightProbe;
  28872. exports.AnimationClip = AnimationClip;
  28873. exports.AnimationLoader = AnimationLoader;
  28874. exports.AnimationMixer = AnimationMixer;
  28875. exports.AnimationObjectGroup = AnimationObjectGroup;
  28876. exports.AnimationUtils = AnimationUtils;
  28877. exports.ArcCurve = ArcCurve;
  28878. exports.ArrayCamera = ArrayCamera;
  28879. exports.ArrowHelper = ArrowHelper;
  28880. exports.Audio = Audio;
  28881. exports.AudioAnalyser = AudioAnalyser;
  28882. exports.AudioContext = AudioContext;
  28883. exports.AudioListener = AudioListener;
  28884. exports.AudioLoader = AudioLoader;
  28885. exports.AxesHelper = AxesHelper;
  28886. exports.AxisHelper = AxisHelper;
  28887. exports.BackSide = BackSide;
  28888. exports.BasicDepthPacking = BasicDepthPacking;
  28889. exports.BasicShadowMap = BasicShadowMap;
  28890. exports.BinaryTextureLoader = BinaryTextureLoader;
  28891. exports.Bone = Bone;
  28892. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  28893. exports.BoundingBoxHelper = BoundingBoxHelper;
  28894. exports.Box2 = Box2;
  28895. exports.Box3 = Box3;
  28896. exports.Box3Helper = Box3Helper;
  28897. exports.BoxBufferGeometry = BoxGeometry;
  28898. exports.BoxGeometry = BoxGeometry;
  28899. exports.BoxHelper = BoxHelper;
  28900. exports.BufferAttribute = BufferAttribute;
  28901. exports.BufferGeometry = BufferGeometry;
  28902. exports.BufferGeometryLoader = BufferGeometryLoader;
  28903. exports.ByteType = ByteType;
  28904. exports.Cache = Cache;
  28905. exports.Camera = Camera;
  28906. exports.CameraHelper = CameraHelper;
  28907. exports.CanvasRenderer = CanvasRenderer;
  28908. exports.CanvasTexture = CanvasTexture;
  28909. exports.CatmullRomCurve3 = CatmullRomCurve3;
  28910. exports.CineonToneMapping = CineonToneMapping;
  28911. exports.CircleBufferGeometry = CircleGeometry;
  28912. exports.CircleGeometry = CircleGeometry;
  28913. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  28914. exports.Clock = Clock;
  28915. exports.Color = Color;
  28916. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  28917. exports.CompressedTexture = CompressedTexture;
  28918. exports.CompressedTextureLoader = CompressedTextureLoader;
  28919. exports.ConeBufferGeometry = ConeGeometry;
  28920. exports.ConeGeometry = ConeGeometry;
  28921. exports.CubeCamera = CubeCamera;
  28922. exports.CubeReflectionMapping = CubeReflectionMapping;
  28923. exports.CubeRefractionMapping = CubeRefractionMapping;
  28924. exports.CubeTexture = CubeTexture;
  28925. exports.CubeTextureLoader = CubeTextureLoader;
  28926. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  28927. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  28928. exports.CubicBezierCurve = CubicBezierCurve;
  28929. exports.CubicBezierCurve3 = CubicBezierCurve3;
  28930. exports.CubicInterpolant = CubicInterpolant;
  28931. exports.CullFaceBack = CullFaceBack;
  28932. exports.CullFaceFront = CullFaceFront;
  28933. exports.CullFaceFrontBack = CullFaceFrontBack;
  28934. exports.CullFaceNone = CullFaceNone;
  28935. exports.Curve = Curve;
  28936. exports.CurvePath = CurvePath;
  28937. exports.CustomBlending = CustomBlending;
  28938. exports.CustomToneMapping = CustomToneMapping;
  28939. exports.CylinderBufferGeometry = CylinderGeometry;
  28940. exports.CylinderGeometry = CylinderGeometry;
  28941. exports.Cylindrical = Cylindrical;
  28942. exports.DataTexture = DataTexture;
  28943. exports.DataTexture2DArray = DataTexture2DArray;
  28944. exports.DataTexture3D = DataTexture3D;
  28945. exports.DataTextureLoader = DataTextureLoader;
  28946. exports.DataUtils = DataUtils;
  28947. exports.DecrementStencilOp = DecrementStencilOp;
  28948. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  28949. exports.DefaultLoadingManager = DefaultLoadingManager;
  28950. exports.DepthFormat = DepthFormat;
  28951. exports.DepthStencilFormat = DepthStencilFormat;
  28952. exports.DepthTexture = DepthTexture;
  28953. exports.DirectionalLight = DirectionalLight;
  28954. exports.DirectionalLightHelper = DirectionalLightHelper;
  28955. exports.DiscreteInterpolant = DiscreteInterpolant;
  28956. exports.DodecahedronBufferGeometry = DodecahedronGeometry;
  28957. exports.DodecahedronGeometry = DodecahedronGeometry;
  28958. exports.DoubleSide = DoubleSide;
  28959. exports.DstAlphaFactor = DstAlphaFactor;
  28960. exports.DstColorFactor = DstColorFactor;
  28961. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  28962. exports.DynamicCopyUsage = DynamicCopyUsage;
  28963. exports.DynamicDrawUsage = DynamicDrawUsage;
  28964. exports.DynamicReadUsage = DynamicReadUsage;
  28965. exports.EdgesGeometry = EdgesGeometry;
  28966. exports.EdgesHelper = EdgesHelper;
  28967. exports.EllipseCurve = EllipseCurve;
  28968. exports.EqualDepth = EqualDepth;
  28969. exports.EqualStencilFunc = EqualStencilFunc;
  28970. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  28971. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  28972. exports.Euler = Euler;
  28973. exports.EventDispatcher = EventDispatcher;
  28974. exports.ExtrudeBufferGeometry = ExtrudeGeometry;
  28975. exports.ExtrudeGeometry = ExtrudeGeometry;
  28976. exports.FaceColors = FaceColors;
  28977. exports.FileLoader = FileLoader;
  28978. exports.FlatShading = FlatShading;
  28979. exports.Float16BufferAttribute = Float16BufferAttribute;
  28980. exports.Float32Attribute = Float32Attribute;
  28981. exports.Float32BufferAttribute = Float32BufferAttribute;
  28982. exports.Float64Attribute = Float64Attribute;
  28983. exports.Float64BufferAttribute = Float64BufferAttribute;
  28984. exports.FloatType = FloatType;
  28985. exports.Fog = Fog;
  28986. exports.FogExp2 = FogExp2;
  28987. exports.Font = Font;
  28988. exports.FontLoader = FontLoader;
  28989. exports.FrontSide = FrontSide;
  28990. exports.Frustum = Frustum;
  28991. exports.GLBufferAttribute = GLBufferAttribute;
  28992. exports.GLSL1 = GLSL1;
  28993. exports.GLSL3 = GLSL3;
  28994. exports.GammaEncoding = GammaEncoding;
  28995. exports.GreaterDepth = GreaterDepth;
  28996. exports.GreaterEqualDepth = GreaterEqualDepth;
  28997. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  28998. exports.GreaterStencilFunc = GreaterStencilFunc;
  28999. exports.GridHelper = GridHelper;
  29000. exports.Group = Group;
  29001. exports.HalfFloatType = HalfFloatType;
  29002. exports.HemisphereLight = HemisphereLight;
  29003. exports.HemisphereLightHelper = HemisphereLightHelper;
  29004. exports.HemisphereLightProbe = HemisphereLightProbe;
  29005. exports.IcosahedronBufferGeometry = IcosahedronGeometry;
  29006. exports.IcosahedronGeometry = IcosahedronGeometry;
  29007. exports.ImageBitmapLoader = ImageBitmapLoader;
  29008. exports.ImageLoader = ImageLoader;
  29009. exports.ImageUtils = ImageUtils;
  29010. exports.ImmediateRenderObject = ImmediateRenderObject;
  29011. exports.IncrementStencilOp = IncrementStencilOp;
  29012. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  29013. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  29014. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  29015. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  29016. exports.InstancedMesh = InstancedMesh;
  29017. exports.Int16Attribute = Int16Attribute;
  29018. exports.Int16BufferAttribute = Int16BufferAttribute;
  29019. exports.Int32Attribute = Int32Attribute;
  29020. exports.Int32BufferAttribute = Int32BufferAttribute;
  29021. exports.Int8Attribute = Int8Attribute;
  29022. exports.Int8BufferAttribute = Int8BufferAttribute;
  29023. exports.IntType = IntType;
  29024. exports.InterleavedBuffer = InterleavedBuffer;
  29025. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  29026. exports.Interpolant = Interpolant;
  29027. exports.InterpolateDiscrete = InterpolateDiscrete;
  29028. exports.InterpolateLinear = InterpolateLinear;
  29029. exports.InterpolateSmooth = InterpolateSmooth;
  29030. exports.InvertStencilOp = InvertStencilOp;
  29031. exports.JSONLoader = JSONLoader;
  29032. exports.KeepStencilOp = KeepStencilOp;
  29033. exports.KeyframeTrack = KeyframeTrack;
  29034. exports.LOD = LOD;
  29035. exports.LatheBufferGeometry = LatheGeometry;
  29036. exports.LatheGeometry = LatheGeometry;
  29037. exports.Layers = Layers;
  29038. exports.LensFlare = LensFlare;
  29039. exports.LessDepth = LessDepth;
  29040. exports.LessEqualDepth = LessEqualDepth;
  29041. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  29042. exports.LessStencilFunc = LessStencilFunc;
  29043. exports.Light = Light;
  29044. exports.LightProbe = LightProbe;
  29045. exports.Line = Line;
  29046. exports.Line3 = Line3;
  29047. exports.LineBasicMaterial = LineBasicMaterial;
  29048. exports.LineCurve = LineCurve;
  29049. exports.LineCurve3 = LineCurve3;
  29050. exports.LineDashedMaterial = LineDashedMaterial;
  29051. exports.LineLoop = LineLoop;
  29052. exports.LinePieces = LinePieces;
  29053. exports.LineSegments = LineSegments;
  29054. exports.LineStrip = LineStrip;
  29055. exports.LinearEncoding = LinearEncoding;
  29056. exports.LinearFilter = LinearFilter;
  29057. exports.LinearInterpolant = LinearInterpolant;
  29058. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  29059. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  29060. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  29061. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  29062. exports.LinearToneMapping = LinearToneMapping;
  29063. exports.Loader = Loader;
  29064. exports.LoaderUtils = LoaderUtils;
  29065. exports.LoadingManager = LoadingManager;
  29066. exports.LogLuvEncoding = LogLuvEncoding;
  29067. exports.LoopOnce = LoopOnce;
  29068. exports.LoopPingPong = LoopPingPong;
  29069. exports.LoopRepeat = LoopRepeat;
  29070. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  29071. exports.LuminanceFormat = LuminanceFormat;
  29072. exports.MOUSE = MOUSE;
  29073. exports.Material = Material;
  29074. exports.MaterialLoader = MaterialLoader;
  29075. exports.Math = MathUtils;
  29076. exports.MathUtils = MathUtils;
  29077. exports.Matrix3 = Matrix3;
  29078. exports.Matrix4 = Matrix4;
  29079. exports.MaxEquation = MaxEquation;
  29080. exports.Mesh = Mesh;
  29081. exports.MeshBasicMaterial = MeshBasicMaterial;
  29082. exports.MeshDepthMaterial = MeshDepthMaterial;
  29083. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  29084. exports.MeshFaceMaterial = MeshFaceMaterial;
  29085. exports.MeshLambertMaterial = MeshLambertMaterial;
  29086. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  29087. exports.MeshNormalMaterial = MeshNormalMaterial;
  29088. exports.MeshPhongMaterial = MeshPhongMaterial;
  29089. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  29090. exports.MeshStandardMaterial = MeshStandardMaterial;
  29091. exports.MeshToonMaterial = MeshToonMaterial;
  29092. exports.MinEquation = MinEquation;
  29093. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  29094. exports.MixOperation = MixOperation;
  29095. exports.MultiMaterial = MultiMaterial;
  29096. exports.MultiplyBlending = MultiplyBlending;
  29097. exports.MultiplyOperation = MultiplyOperation;
  29098. exports.NearestFilter = NearestFilter;
  29099. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  29100. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  29101. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  29102. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  29103. exports.NeverDepth = NeverDepth;
  29104. exports.NeverStencilFunc = NeverStencilFunc;
  29105. exports.NoBlending = NoBlending;
  29106. exports.NoColors = NoColors;
  29107. exports.NoToneMapping = NoToneMapping;
  29108. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  29109. exports.NormalBlending = NormalBlending;
  29110. exports.NotEqualDepth = NotEqualDepth;
  29111. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  29112. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  29113. exports.Object3D = Object3D;
  29114. exports.ObjectLoader = ObjectLoader;
  29115. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  29116. exports.OctahedronBufferGeometry = OctahedronGeometry;
  29117. exports.OctahedronGeometry = OctahedronGeometry;
  29118. exports.OneFactor = OneFactor;
  29119. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  29120. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  29121. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  29122. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  29123. exports.OrthographicCamera = OrthographicCamera;
  29124. exports.PCFShadowMap = PCFShadowMap;
  29125. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  29126. exports.PMREMGenerator = PMREMGenerator;
  29127. exports.ParametricBufferGeometry = ParametricGeometry;
  29128. exports.ParametricGeometry = ParametricGeometry;
  29129. exports.Particle = Particle;
  29130. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  29131. exports.ParticleSystem = ParticleSystem;
  29132. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  29133. exports.Path = Path;
  29134. exports.PerspectiveCamera = PerspectiveCamera;
  29135. exports.Plane = Plane;
  29136. exports.PlaneBufferGeometry = PlaneGeometry;
  29137. exports.PlaneGeometry = PlaneGeometry;
  29138. exports.PlaneHelper = PlaneHelper;
  29139. exports.PointCloud = PointCloud;
  29140. exports.PointCloudMaterial = PointCloudMaterial;
  29141. exports.PointLight = PointLight;
  29142. exports.PointLightHelper = PointLightHelper;
  29143. exports.Points = Points;
  29144. exports.PointsMaterial = PointsMaterial;
  29145. exports.PolarGridHelper = PolarGridHelper;
  29146. exports.PolyhedronBufferGeometry = PolyhedronGeometry;
  29147. exports.PolyhedronGeometry = PolyhedronGeometry;
  29148. exports.PositionalAudio = PositionalAudio;
  29149. exports.PropertyBinding = PropertyBinding;
  29150. exports.PropertyMixer = PropertyMixer;
  29151. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  29152. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  29153. exports.Quaternion = Quaternion;
  29154. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  29155. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  29156. exports.REVISION = REVISION;
  29157. exports.RGBADepthPacking = RGBADepthPacking;
  29158. exports.RGBAFormat = RGBAFormat;
  29159. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  29160. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  29161. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  29162. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  29163. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  29164. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  29165. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  29166. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  29167. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  29168. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  29169. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  29170. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  29171. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  29172. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  29173. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  29174. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  29175. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  29176. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  29177. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  29178. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  29179. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  29180. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  29181. exports.RGBDEncoding = RGBDEncoding;
  29182. exports.RGBEEncoding = RGBEEncoding;
  29183. exports.RGBEFormat = RGBEFormat;
  29184. exports.RGBFormat = RGBFormat;
  29185. exports.RGBIntegerFormat = RGBIntegerFormat;
  29186. exports.RGBM16Encoding = RGBM16Encoding;
  29187. exports.RGBM7Encoding = RGBM7Encoding;
  29188. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  29189. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  29190. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  29191. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  29192. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  29193. exports.RGFormat = RGFormat;
  29194. exports.RGIntegerFormat = RGIntegerFormat;
  29195. exports.RawShaderMaterial = RawShaderMaterial;
  29196. exports.Ray = Ray;
  29197. exports.Raycaster = Raycaster;
  29198. exports.RectAreaLight = RectAreaLight;
  29199. exports.RedFormat = RedFormat;
  29200. exports.RedIntegerFormat = RedIntegerFormat;
  29201. exports.ReinhardToneMapping = ReinhardToneMapping;
  29202. exports.RepeatWrapping = RepeatWrapping;
  29203. exports.ReplaceStencilOp = ReplaceStencilOp;
  29204. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  29205. exports.RingBufferGeometry = RingGeometry;
  29206. exports.RingGeometry = RingGeometry;
  29207. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  29208. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  29209. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  29210. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  29211. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  29212. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  29213. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  29214. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  29215. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  29216. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  29217. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  29218. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  29219. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  29220. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  29221. exports.Scene = Scene;
  29222. exports.SceneUtils = SceneUtils;
  29223. exports.ShaderChunk = ShaderChunk;
  29224. exports.ShaderLib = ShaderLib;
  29225. exports.ShaderMaterial = ShaderMaterial;
  29226. exports.ShadowMaterial = ShadowMaterial;
  29227. exports.Shape = Shape;
  29228. exports.ShapeBufferGeometry = ShapeGeometry;
  29229. exports.ShapeGeometry = ShapeGeometry;
  29230. exports.ShapePath = ShapePath;
  29231. exports.ShapeUtils = ShapeUtils;
  29232. exports.ShortType = ShortType;
  29233. exports.Skeleton = Skeleton;
  29234. exports.SkeletonHelper = SkeletonHelper;
  29235. exports.SkinnedMesh = SkinnedMesh;
  29236. exports.SmoothShading = SmoothShading;
  29237. exports.Sphere = Sphere;
  29238. exports.SphereBufferGeometry = SphereGeometry;
  29239. exports.SphereGeometry = SphereGeometry;
  29240. exports.Spherical = Spherical;
  29241. exports.SphericalHarmonics3 = SphericalHarmonics3;
  29242. exports.SplineCurve = SplineCurve;
  29243. exports.SpotLight = SpotLight;
  29244. exports.SpotLightHelper = SpotLightHelper;
  29245. exports.Sprite = Sprite;
  29246. exports.SpriteMaterial = SpriteMaterial;
  29247. exports.SrcAlphaFactor = SrcAlphaFactor;
  29248. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  29249. exports.SrcColorFactor = SrcColorFactor;
  29250. exports.StaticCopyUsage = StaticCopyUsage;
  29251. exports.StaticDrawUsage = StaticDrawUsage;
  29252. exports.StaticReadUsage = StaticReadUsage;
  29253. exports.StereoCamera = StereoCamera;
  29254. exports.StreamCopyUsage = StreamCopyUsage;
  29255. exports.StreamDrawUsage = StreamDrawUsage;
  29256. exports.StreamReadUsage = StreamReadUsage;
  29257. exports.StringKeyframeTrack = StringKeyframeTrack;
  29258. exports.SubtractEquation = SubtractEquation;
  29259. exports.SubtractiveBlending = SubtractiveBlending;
  29260. exports.TOUCH = TOUCH;
  29261. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  29262. exports.TetrahedronBufferGeometry = TetrahedronGeometry;
  29263. exports.TetrahedronGeometry = TetrahedronGeometry;
  29264. exports.TextBufferGeometry = TextGeometry;
  29265. exports.TextGeometry = TextGeometry;
  29266. exports.Texture = Texture;
  29267. exports.TextureLoader = TextureLoader;
  29268. exports.TorusBufferGeometry = TorusGeometry;
  29269. exports.TorusGeometry = TorusGeometry;
  29270. exports.TorusKnotBufferGeometry = TorusKnotGeometry;
  29271. exports.TorusKnotGeometry = TorusKnotGeometry;
  29272. exports.Triangle = Triangle;
  29273. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  29274. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  29275. exports.TrianglesDrawMode = TrianglesDrawMode;
  29276. exports.TubeBufferGeometry = TubeGeometry;
  29277. exports.TubeGeometry = TubeGeometry;
  29278. exports.UVMapping = UVMapping;
  29279. exports.Uint16Attribute = Uint16Attribute;
  29280. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  29281. exports.Uint32Attribute = Uint32Attribute;
  29282. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  29283. exports.Uint8Attribute = Uint8Attribute;
  29284. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  29285. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  29286. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  29287. exports.Uniform = Uniform;
  29288. exports.UniformsLib = UniformsLib;
  29289. exports.UniformsUtils = UniformsUtils;
  29290. exports.UnsignedByteType = UnsignedByteType;
  29291. exports.UnsignedInt248Type = UnsignedInt248Type;
  29292. exports.UnsignedIntType = UnsignedIntType;
  29293. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  29294. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  29295. exports.UnsignedShort565Type = UnsignedShort565Type;
  29296. exports.UnsignedShortType = UnsignedShortType;
  29297. exports.VSMShadowMap = VSMShadowMap;
  29298. exports.Vector2 = Vector2;
  29299. exports.Vector3 = Vector3;
  29300. exports.Vector4 = Vector4;
  29301. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  29302. exports.Vertex = Vertex;
  29303. exports.VertexColors = VertexColors;
  29304. exports.VideoTexture = VideoTexture;
  29305. exports.WebGL1Renderer = WebGL1Renderer;
  29306. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  29307. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  29308. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  29309. exports.WebGLRenderTarget = WebGLRenderTarget;
  29310. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  29311. exports.WebGLRenderer = WebGLRenderer;
  29312. exports.WebGLUtils = WebGLUtils;
  29313. exports.WireframeGeometry = WireframeGeometry;
  29314. exports.WireframeHelper = WireframeHelper;
  29315. exports.WrapAroundEnding = WrapAroundEnding;
  29316. exports.XHRLoader = XHRLoader;
  29317. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  29318. exports.ZeroFactor = ZeroFactor;
  29319. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  29320. exports.ZeroStencilOp = ZeroStencilOp;
  29321. exports.sRGBEncoding = sRGBEncoding;
  29322. Object.defineProperty(exports, '__esModule', { value: true });
  29323. })));