three.js 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200
  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 = '131dev';
  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. this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  1587. this.texture.image = {
  1588. width: width,
  1589. height: height,
  1590. depth: 1
  1591. };
  1592. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1593. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1594. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1595. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1596. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1597. }
  1598. setTexture(texture) {
  1599. texture.image = {
  1600. width: this.width,
  1601. height: this.height,
  1602. depth: this.depth
  1603. };
  1604. this.texture = texture;
  1605. }
  1606. setSize(width, height, depth = 1) {
  1607. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1608. this.width = width;
  1609. this.height = height;
  1610. this.depth = depth;
  1611. this.texture.image.width = width;
  1612. this.texture.image.height = height;
  1613. this.texture.image.depth = depth;
  1614. this.dispose();
  1615. }
  1616. this.viewport.set(0, 0, width, height);
  1617. this.scissor.set(0, 0, width, height);
  1618. }
  1619. clone() {
  1620. return new this.constructor().copy(this);
  1621. }
  1622. copy(source) {
  1623. this.width = source.width;
  1624. this.height = source.height;
  1625. this.depth = source.depth;
  1626. this.viewport.copy(source.viewport);
  1627. this.texture = source.texture.clone();
  1628. this.texture.image = { ...this.texture.image
  1629. }; // See #20328.
  1630. this.depthBuffer = source.depthBuffer;
  1631. this.stencilBuffer = source.stencilBuffer;
  1632. this.depthTexture = source.depthTexture;
  1633. return this;
  1634. }
  1635. dispose() {
  1636. this.dispatchEvent({
  1637. type: 'dispose'
  1638. });
  1639. }
  1640. }
  1641. WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
  1642. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1643. constructor(width, height, count) {
  1644. super(width, height);
  1645. const texture = this.texture;
  1646. this.texture = [];
  1647. for (let i = 0; i < count; i++) {
  1648. this.texture[i] = texture.clone();
  1649. }
  1650. }
  1651. setSize(width, height, depth = 1) {
  1652. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1653. this.width = width;
  1654. this.height = height;
  1655. this.depth = depth;
  1656. for (let i = 0, il = this.texture.length; i < il; i++) {
  1657. this.texture[i].image.width = width;
  1658. this.texture[i].image.height = height;
  1659. this.texture[i].image.depth = depth;
  1660. }
  1661. this.dispose();
  1662. }
  1663. this.viewport.set(0, 0, width, height);
  1664. this.scissor.set(0, 0, width, height);
  1665. return this;
  1666. }
  1667. copy(source) {
  1668. this.dispose();
  1669. this.width = source.width;
  1670. this.height = source.height;
  1671. this.depth = source.depth;
  1672. this.viewport.set(0, 0, this.width, this.height);
  1673. this.scissor.set(0, 0, this.width, this.height);
  1674. this.depthBuffer = source.depthBuffer;
  1675. this.stencilBuffer = source.stencilBuffer;
  1676. this.depthTexture = source.depthTexture;
  1677. this.texture.length = 0;
  1678. for (let i = 0, il = source.texture.length; i < il; i++) {
  1679. this.texture[i] = source.texture[i].clone();
  1680. }
  1681. return this;
  1682. }
  1683. }
  1684. WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true;
  1685. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  1686. constructor(width, height, options) {
  1687. super(width, height, options);
  1688. this.samples = 4;
  1689. }
  1690. copy(source) {
  1691. super.copy.call(this, source);
  1692. this.samples = source.samples;
  1693. return this;
  1694. }
  1695. }
  1696. WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true;
  1697. class Quaternion {
  1698. constructor(x = 0, y = 0, z = 0, w = 1) {
  1699. this._x = x;
  1700. this._y = y;
  1701. this._z = z;
  1702. this._w = w;
  1703. }
  1704. static slerp(qa, qb, qm, t) {
  1705. console.warn('THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.');
  1706. return qm.slerpQuaternions(qa, qb, t);
  1707. }
  1708. static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  1709. // fuzz-free, array-based Quaternion SLERP operation
  1710. let x0 = src0[srcOffset0 + 0],
  1711. y0 = src0[srcOffset0 + 1],
  1712. z0 = src0[srcOffset0 + 2],
  1713. w0 = src0[srcOffset0 + 3];
  1714. const x1 = src1[srcOffset1 + 0],
  1715. y1 = src1[srcOffset1 + 1],
  1716. z1 = src1[srcOffset1 + 2],
  1717. w1 = src1[srcOffset1 + 3];
  1718. if (t === 0) {
  1719. dst[dstOffset + 0] = x0;
  1720. dst[dstOffset + 1] = y0;
  1721. dst[dstOffset + 2] = z0;
  1722. dst[dstOffset + 3] = w0;
  1723. return;
  1724. }
  1725. if (t === 1) {
  1726. dst[dstOffset + 0] = x1;
  1727. dst[dstOffset + 1] = y1;
  1728. dst[dstOffset + 2] = z1;
  1729. dst[dstOffset + 3] = w1;
  1730. return;
  1731. }
  1732. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  1733. let s = 1 - t;
  1734. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1735. dir = cos >= 0 ? 1 : -1,
  1736. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  1737. if (sqrSin > Number.EPSILON) {
  1738. const sin = Math.sqrt(sqrSin),
  1739. len = Math.atan2(sin, cos * dir);
  1740. s = Math.sin(s * len) / sin;
  1741. t = Math.sin(t * len) / sin;
  1742. }
  1743. const tDir = t * dir;
  1744. x0 = x0 * s + x1 * tDir;
  1745. y0 = y0 * s + y1 * tDir;
  1746. z0 = z0 * s + z1 * tDir;
  1747. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  1748. if (s === 1 - t) {
  1749. const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  1750. x0 *= f;
  1751. y0 *= f;
  1752. z0 *= f;
  1753. w0 *= f;
  1754. }
  1755. }
  1756. dst[dstOffset] = x0;
  1757. dst[dstOffset + 1] = y0;
  1758. dst[dstOffset + 2] = z0;
  1759. dst[dstOffset + 3] = w0;
  1760. }
  1761. static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  1762. const x0 = src0[srcOffset0];
  1763. const y0 = src0[srcOffset0 + 1];
  1764. const z0 = src0[srcOffset0 + 2];
  1765. const w0 = src0[srcOffset0 + 3];
  1766. const x1 = src1[srcOffset1];
  1767. const y1 = src1[srcOffset1 + 1];
  1768. const z1 = src1[srcOffset1 + 2];
  1769. const w1 = src1[srcOffset1 + 3];
  1770. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1771. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1772. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1773. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1774. return dst;
  1775. }
  1776. get x() {
  1777. return this._x;
  1778. }
  1779. set x(value) {
  1780. this._x = value;
  1781. this._onChangeCallback();
  1782. }
  1783. get y() {
  1784. return this._y;
  1785. }
  1786. set y(value) {
  1787. this._y = value;
  1788. this._onChangeCallback();
  1789. }
  1790. get z() {
  1791. return this._z;
  1792. }
  1793. set z(value) {
  1794. this._z = value;
  1795. this._onChangeCallback();
  1796. }
  1797. get w() {
  1798. return this._w;
  1799. }
  1800. set w(value) {
  1801. this._w = value;
  1802. this._onChangeCallback();
  1803. }
  1804. set(x, y, z, w) {
  1805. this._x = x;
  1806. this._y = y;
  1807. this._z = z;
  1808. this._w = w;
  1809. this._onChangeCallback();
  1810. return this;
  1811. }
  1812. clone() {
  1813. return new this.constructor(this._x, this._y, this._z, this._w);
  1814. }
  1815. copy(quaternion) {
  1816. this._x = quaternion.x;
  1817. this._y = quaternion.y;
  1818. this._z = quaternion.z;
  1819. this._w = quaternion.w;
  1820. this._onChangeCallback();
  1821. return this;
  1822. }
  1823. setFromEuler(euler, update) {
  1824. if (!(euler && euler.isEuler)) {
  1825. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  1826. }
  1827. const x = euler._x,
  1828. y = euler._y,
  1829. z = euler._z,
  1830. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  1831. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1832. // content/SpinCalc.m
  1833. const cos = Math.cos;
  1834. const sin = Math.sin;
  1835. const c1 = cos(x / 2);
  1836. const c2 = cos(y / 2);
  1837. const c3 = cos(z / 2);
  1838. const s1 = sin(x / 2);
  1839. const s2 = sin(y / 2);
  1840. const s3 = sin(z / 2);
  1841. switch (order) {
  1842. case 'XYZ':
  1843. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1844. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1845. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1846. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1847. break;
  1848. case 'YXZ':
  1849. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1850. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1851. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1852. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1853. break;
  1854. case 'ZXY':
  1855. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1856. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1857. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1858. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1859. break;
  1860. case 'ZYX':
  1861. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1862. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1863. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1864. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1865. break;
  1866. case 'YZX':
  1867. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1868. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1869. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1870. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1871. break;
  1872. case 'XZY':
  1873. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1874. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1875. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1876. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1877. break;
  1878. default:
  1879. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  1880. }
  1881. if (update !== false) this._onChangeCallback();
  1882. return this;
  1883. }
  1884. setFromAxisAngle(axis, angle) {
  1885. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1886. // assumes axis is normalized
  1887. const halfAngle = angle / 2,
  1888. s = Math.sin(halfAngle);
  1889. this._x = axis.x * s;
  1890. this._y = axis.y * s;
  1891. this._z = axis.z * s;
  1892. this._w = Math.cos(halfAngle);
  1893. this._onChangeCallback();
  1894. return this;
  1895. }
  1896. setFromRotationMatrix(m) {
  1897. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1898. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1899. const te = m.elements,
  1900. m11 = te[0],
  1901. m12 = te[4],
  1902. m13 = te[8],
  1903. m21 = te[1],
  1904. m22 = te[5],
  1905. m23 = te[9],
  1906. m31 = te[2],
  1907. m32 = te[6],
  1908. m33 = te[10],
  1909. trace = m11 + m22 + m33;
  1910. if (trace > 0) {
  1911. const s = 0.5 / Math.sqrt(trace + 1.0);
  1912. this._w = 0.25 / s;
  1913. this._x = (m32 - m23) * s;
  1914. this._y = (m13 - m31) * s;
  1915. this._z = (m21 - m12) * s;
  1916. } else if (m11 > m22 && m11 > m33) {
  1917. const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1918. this._w = (m32 - m23) / s;
  1919. this._x = 0.25 * s;
  1920. this._y = (m12 + m21) / s;
  1921. this._z = (m13 + m31) / s;
  1922. } else if (m22 > m33) {
  1923. const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1924. this._w = (m13 - m31) / s;
  1925. this._x = (m12 + m21) / s;
  1926. this._y = 0.25 * s;
  1927. this._z = (m23 + m32) / s;
  1928. } else {
  1929. const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1930. this._w = (m21 - m12) / s;
  1931. this._x = (m13 + m31) / s;
  1932. this._y = (m23 + m32) / s;
  1933. this._z = 0.25 * s;
  1934. }
  1935. this._onChangeCallback();
  1936. return this;
  1937. }
  1938. setFromUnitVectors(vFrom, vTo) {
  1939. // assumes direction vectors vFrom and vTo are normalized
  1940. let r = vFrom.dot(vTo) + 1;
  1941. if (r < Number.EPSILON) {
  1942. // vFrom and vTo point in opposite directions
  1943. r = 0;
  1944. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  1945. this._x = -vFrom.y;
  1946. this._y = vFrom.x;
  1947. this._z = 0;
  1948. this._w = r;
  1949. } else {
  1950. this._x = 0;
  1951. this._y = -vFrom.z;
  1952. this._z = vFrom.y;
  1953. this._w = r;
  1954. }
  1955. } else {
  1956. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  1957. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  1958. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  1959. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  1960. this._w = r;
  1961. }
  1962. return this.normalize();
  1963. }
  1964. angleTo(q) {
  1965. return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1)));
  1966. }
  1967. rotateTowards(q, step) {
  1968. const angle = this.angleTo(q);
  1969. if (angle === 0) return this;
  1970. const t = Math.min(1, step / angle);
  1971. this.slerp(q, t);
  1972. return this;
  1973. }
  1974. identity() {
  1975. return this.set(0, 0, 0, 1);
  1976. }
  1977. invert() {
  1978. // quaternion is assumed to have unit length
  1979. return this.conjugate();
  1980. }
  1981. conjugate() {
  1982. this._x *= -1;
  1983. this._y *= -1;
  1984. this._z *= -1;
  1985. this._onChangeCallback();
  1986. return this;
  1987. }
  1988. dot(v) {
  1989. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1990. }
  1991. lengthSq() {
  1992. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1993. }
  1994. length() {
  1995. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  1996. }
  1997. normalize() {
  1998. let l = this.length();
  1999. if (l === 0) {
  2000. this._x = 0;
  2001. this._y = 0;
  2002. this._z = 0;
  2003. this._w = 1;
  2004. } else {
  2005. l = 1 / l;
  2006. this._x = this._x * l;
  2007. this._y = this._y * l;
  2008. this._z = this._z * l;
  2009. this._w = this._w * l;
  2010. }
  2011. this._onChangeCallback();
  2012. return this;
  2013. }
  2014. multiply(q, p) {
  2015. if (p !== undefined) {
  2016. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2017. return this.multiplyQuaternions(q, p);
  2018. }
  2019. return this.multiplyQuaternions(this, q);
  2020. }
  2021. premultiply(q) {
  2022. return this.multiplyQuaternions(q, this);
  2023. }
  2024. multiplyQuaternions(a, b) {
  2025. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2026. const qax = a._x,
  2027. qay = a._y,
  2028. qaz = a._z,
  2029. qaw = a._w;
  2030. const qbx = b._x,
  2031. qby = b._y,
  2032. qbz = b._z,
  2033. qbw = b._w;
  2034. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2035. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2036. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2037. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2038. this._onChangeCallback();
  2039. return this;
  2040. }
  2041. slerp(qb, t) {
  2042. if (t === 0) return this;
  2043. if (t === 1) return this.copy(qb);
  2044. const x = this._x,
  2045. y = this._y,
  2046. z = this._z,
  2047. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2048. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2049. if (cosHalfTheta < 0) {
  2050. this._w = -qb._w;
  2051. this._x = -qb._x;
  2052. this._y = -qb._y;
  2053. this._z = -qb._z;
  2054. cosHalfTheta = -cosHalfTheta;
  2055. } else {
  2056. this.copy(qb);
  2057. }
  2058. if (cosHalfTheta >= 1.0) {
  2059. this._w = w;
  2060. this._x = x;
  2061. this._y = y;
  2062. this._z = z;
  2063. return this;
  2064. }
  2065. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2066. if (sqrSinHalfTheta <= Number.EPSILON) {
  2067. const s = 1 - t;
  2068. this._w = s * w + t * this._w;
  2069. this._x = s * x + t * this._x;
  2070. this._y = s * y + t * this._y;
  2071. this._z = s * z + t * this._z;
  2072. this.normalize();
  2073. this._onChangeCallback();
  2074. return this;
  2075. }
  2076. const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2077. const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2078. const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2079. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2080. this._w = w * ratioA + this._w * ratioB;
  2081. this._x = x * ratioA + this._x * ratioB;
  2082. this._y = y * ratioA + this._y * ratioB;
  2083. this._z = z * ratioA + this._z * ratioB;
  2084. this._onChangeCallback();
  2085. return this;
  2086. }
  2087. slerpQuaternions(qa, qb, t) {
  2088. this.copy(qa).slerp(qb, t);
  2089. }
  2090. equals(quaternion) {
  2091. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2092. }
  2093. fromArray(array, offset = 0) {
  2094. this._x = array[offset];
  2095. this._y = array[offset + 1];
  2096. this._z = array[offset + 2];
  2097. this._w = array[offset + 3];
  2098. this._onChangeCallback();
  2099. return this;
  2100. }
  2101. toArray(array = [], offset = 0) {
  2102. array[offset] = this._x;
  2103. array[offset + 1] = this._y;
  2104. array[offset + 2] = this._z;
  2105. array[offset + 3] = this._w;
  2106. return array;
  2107. }
  2108. fromBufferAttribute(attribute, index) {
  2109. this._x = attribute.getX(index);
  2110. this._y = attribute.getY(index);
  2111. this._z = attribute.getZ(index);
  2112. this._w = attribute.getW(index);
  2113. return this;
  2114. }
  2115. _onChange(callback) {
  2116. this._onChangeCallback = callback;
  2117. return this;
  2118. }
  2119. _onChangeCallback() {}
  2120. }
  2121. Quaternion.prototype.isQuaternion = true;
  2122. class Vector3 {
  2123. constructor(x = 0, y = 0, z = 0) {
  2124. this.x = x;
  2125. this.y = y;
  2126. this.z = z;
  2127. }
  2128. set(x, y, z) {
  2129. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  2130. this.x = x;
  2131. this.y = y;
  2132. this.z = z;
  2133. return this;
  2134. }
  2135. setScalar(scalar) {
  2136. this.x = scalar;
  2137. this.y = scalar;
  2138. this.z = scalar;
  2139. return this;
  2140. }
  2141. setX(x) {
  2142. this.x = x;
  2143. return this;
  2144. }
  2145. setY(y) {
  2146. this.y = y;
  2147. return this;
  2148. }
  2149. setZ(z) {
  2150. this.z = z;
  2151. return this;
  2152. }
  2153. setComponent(index, value) {
  2154. switch (index) {
  2155. case 0:
  2156. this.x = value;
  2157. break;
  2158. case 1:
  2159. this.y = value;
  2160. break;
  2161. case 2:
  2162. this.z = value;
  2163. break;
  2164. default:
  2165. throw new Error('index is out of range: ' + index);
  2166. }
  2167. return this;
  2168. }
  2169. getComponent(index) {
  2170. switch (index) {
  2171. case 0:
  2172. return this.x;
  2173. case 1:
  2174. return this.y;
  2175. case 2:
  2176. return this.z;
  2177. default:
  2178. throw new Error('index is out of range: ' + index);
  2179. }
  2180. }
  2181. clone() {
  2182. return new this.constructor(this.x, this.y, this.z);
  2183. }
  2184. copy(v) {
  2185. this.x = v.x;
  2186. this.y = v.y;
  2187. this.z = v.z;
  2188. return this;
  2189. }
  2190. add(v, w) {
  2191. if (w !== undefined) {
  2192. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2193. return this.addVectors(v, w);
  2194. }
  2195. this.x += v.x;
  2196. this.y += v.y;
  2197. this.z += v.z;
  2198. return this;
  2199. }
  2200. addScalar(s) {
  2201. this.x += s;
  2202. this.y += s;
  2203. this.z += s;
  2204. return this;
  2205. }
  2206. addVectors(a, b) {
  2207. this.x = a.x + b.x;
  2208. this.y = a.y + b.y;
  2209. this.z = a.z + b.z;
  2210. return this;
  2211. }
  2212. addScaledVector(v, s) {
  2213. this.x += v.x * s;
  2214. this.y += v.y * s;
  2215. this.z += v.z * s;
  2216. return this;
  2217. }
  2218. sub(v, w) {
  2219. if (w !== undefined) {
  2220. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2221. return this.subVectors(v, w);
  2222. }
  2223. this.x -= v.x;
  2224. this.y -= v.y;
  2225. this.z -= v.z;
  2226. return this;
  2227. }
  2228. subScalar(s) {
  2229. this.x -= s;
  2230. this.y -= s;
  2231. this.z -= s;
  2232. return this;
  2233. }
  2234. subVectors(a, b) {
  2235. this.x = a.x - b.x;
  2236. this.y = a.y - b.y;
  2237. this.z = a.z - b.z;
  2238. return this;
  2239. }
  2240. multiply(v, w) {
  2241. if (w !== undefined) {
  2242. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2243. return this.multiplyVectors(v, w);
  2244. }
  2245. this.x *= v.x;
  2246. this.y *= v.y;
  2247. this.z *= v.z;
  2248. return this;
  2249. }
  2250. multiplyScalar(scalar) {
  2251. this.x *= scalar;
  2252. this.y *= scalar;
  2253. this.z *= scalar;
  2254. return this;
  2255. }
  2256. multiplyVectors(a, b) {
  2257. this.x = a.x * b.x;
  2258. this.y = a.y * b.y;
  2259. this.z = a.z * b.z;
  2260. return this;
  2261. }
  2262. applyEuler(euler) {
  2263. if (!(euler && euler.isEuler)) {
  2264. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2265. }
  2266. return this.applyQuaternion(_quaternion$4.setFromEuler(euler));
  2267. }
  2268. applyAxisAngle(axis, angle) {
  2269. return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle));
  2270. }
  2271. applyMatrix3(m) {
  2272. const x = this.x,
  2273. y = this.y,
  2274. z = this.z;
  2275. const e = m.elements;
  2276. this.x = e[0] * x + e[3] * y + e[6] * z;
  2277. this.y = e[1] * x + e[4] * y + e[7] * z;
  2278. this.z = e[2] * x + e[5] * y + e[8] * z;
  2279. return this;
  2280. }
  2281. applyNormalMatrix(m) {
  2282. return this.applyMatrix3(m).normalize();
  2283. }
  2284. applyMatrix4(m) {
  2285. const x = this.x,
  2286. y = this.y,
  2287. z = this.z;
  2288. const e = m.elements;
  2289. const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2290. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2291. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2292. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2293. return this;
  2294. }
  2295. applyQuaternion(q) {
  2296. const x = this.x,
  2297. y = this.y,
  2298. z = this.z;
  2299. const qx = q.x,
  2300. qy = q.y,
  2301. qz = q.z,
  2302. qw = q.w; // calculate quat * vector
  2303. const ix = qw * x + qy * z - qz * y;
  2304. const iy = qw * y + qz * x - qx * z;
  2305. const iz = qw * z + qx * y - qy * x;
  2306. const iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2307. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2308. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2309. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2310. return this;
  2311. }
  2312. project(camera) {
  2313. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2314. }
  2315. unproject(camera) {
  2316. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2317. }
  2318. transformDirection(m) {
  2319. // input: THREE.Matrix4 affine matrix
  2320. // vector interpreted as a direction
  2321. const x = this.x,
  2322. y = this.y,
  2323. z = this.z;
  2324. const e = m.elements;
  2325. this.x = e[0] * x + e[4] * y + e[8] * z;
  2326. this.y = e[1] * x + e[5] * y + e[9] * z;
  2327. this.z = e[2] * x + e[6] * y + e[10] * z;
  2328. return this.normalize();
  2329. }
  2330. divide(v) {
  2331. this.x /= v.x;
  2332. this.y /= v.y;
  2333. this.z /= v.z;
  2334. return this;
  2335. }
  2336. divideScalar(scalar) {
  2337. return this.multiplyScalar(1 / scalar);
  2338. }
  2339. min(v) {
  2340. this.x = Math.min(this.x, v.x);
  2341. this.y = Math.min(this.y, v.y);
  2342. this.z = Math.min(this.z, v.z);
  2343. return this;
  2344. }
  2345. max(v) {
  2346. this.x = Math.max(this.x, v.x);
  2347. this.y = Math.max(this.y, v.y);
  2348. this.z = Math.max(this.z, v.z);
  2349. return this;
  2350. }
  2351. clamp(min, max) {
  2352. // assumes min < max, componentwise
  2353. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2354. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2355. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2356. return this;
  2357. }
  2358. clampScalar(minVal, maxVal) {
  2359. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2360. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2361. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2362. return this;
  2363. }
  2364. clampLength(min, max) {
  2365. const length = this.length();
  2366. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2367. }
  2368. floor() {
  2369. this.x = Math.floor(this.x);
  2370. this.y = Math.floor(this.y);
  2371. this.z = Math.floor(this.z);
  2372. return this;
  2373. }
  2374. ceil() {
  2375. this.x = Math.ceil(this.x);
  2376. this.y = Math.ceil(this.y);
  2377. this.z = Math.ceil(this.z);
  2378. return this;
  2379. }
  2380. round() {
  2381. this.x = Math.round(this.x);
  2382. this.y = Math.round(this.y);
  2383. this.z = Math.round(this.z);
  2384. return this;
  2385. }
  2386. roundToZero() {
  2387. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2388. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2389. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2390. return this;
  2391. }
  2392. negate() {
  2393. this.x = -this.x;
  2394. this.y = -this.y;
  2395. this.z = -this.z;
  2396. return this;
  2397. }
  2398. dot(v) {
  2399. return this.x * v.x + this.y * v.y + this.z * v.z;
  2400. } // TODO lengthSquared?
  2401. lengthSq() {
  2402. return this.x * this.x + this.y * this.y + this.z * this.z;
  2403. }
  2404. length() {
  2405. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2406. }
  2407. manhattanLength() {
  2408. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2409. }
  2410. normalize() {
  2411. return this.divideScalar(this.length() || 1);
  2412. }
  2413. setLength(length) {
  2414. return this.normalize().multiplyScalar(length);
  2415. }
  2416. lerp(v, alpha) {
  2417. this.x += (v.x - this.x) * alpha;
  2418. this.y += (v.y - this.y) * alpha;
  2419. this.z += (v.z - this.z) * alpha;
  2420. return this;
  2421. }
  2422. lerpVectors(v1, v2, alpha) {
  2423. this.x = v1.x + (v2.x - v1.x) * alpha;
  2424. this.y = v1.y + (v2.y - v1.y) * alpha;
  2425. this.z = v1.z + (v2.z - v1.z) * alpha;
  2426. return this;
  2427. }
  2428. cross(v, w) {
  2429. if (w !== undefined) {
  2430. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2431. return this.crossVectors(v, w);
  2432. }
  2433. return this.crossVectors(this, v);
  2434. }
  2435. crossVectors(a, b) {
  2436. const ax = a.x,
  2437. ay = a.y,
  2438. az = a.z;
  2439. const bx = b.x,
  2440. by = b.y,
  2441. bz = b.z;
  2442. this.x = ay * bz - az * by;
  2443. this.y = az * bx - ax * bz;
  2444. this.z = ax * by - ay * bx;
  2445. return this;
  2446. }
  2447. projectOnVector(v) {
  2448. const denominator = v.lengthSq();
  2449. if (denominator === 0) return this.set(0, 0, 0);
  2450. const scalar = v.dot(this) / denominator;
  2451. return this.copy(v).multiplyScalar(scalar);
  2452. }
  2453. projectOnPlane(planeNormal) {
  2454. _vector$c.copy(this).projectOnVector(planeNormal);
  2455. return this.sub(_vector$c);
  2456. }
  2457. reflect(normal) {
  2458. // reflect incident vector off plane orthogonal to normal
  2459. // normal is assumed to have unit length
  2460. return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal)));
  2461. }
  2462. angleTo(v) {
  2463. const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  2464. if (denominator === 0) return Math.PI / 2;
  2465. const theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  2466. return Math.acos(clamp(theta, -1, 1));
  2467. }
  2468. distanceTo(v) {
  2469. return Math.sqrt(this.distanceToSquared(v));
  2470. }
  2471. distanceToSquared(v) {
  2472. const dx = this.x - v.x,
  2473. dy = this.y - v.y,
  2474. dz = this.z - v.z;
  2475. return dx * dx + dy * dy + dz * dz;
  2476. }
  2477. manhattanDistanceTo(v) {
  2478. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  2479. }
  2480. setFromSpherical(s) {
  2481. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  2482. }
  2483. setFromSphericalCoords(radius, phi, theta) {
  2484. const sinPhiRadius = Math.sin(phi) * radius;
  2485. this.x = sinPhiRadius * Math.sin(theta);
  2486. this.y = Math.cos(phi) * radius;
  2487. this.z = sinPhiRadius * Math.cos(theta);
  2488. return this;
  2489. }
  2490. setFromCylindrical(c) {
  2491. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  2492. }
  2493. setFromCylindricalCoords(radius, theta, y) {
  2494. this.x = radius * Math.sin(theta);
  2495. this.y = y;
  2496. this.z = radius * Math.cos(theta);
  2497. return this;
  2498. }
  2499. setFromMatrixPosition(m) {
  2500. const e = m.elements;
  2501. this.x = e[12];
  2502. this.y = e[13];
  2503. this.z = e[14];
  2504. return this;
  2505. }
  2506. setFromMatrixScale(m) {
  2507. const sx = this.setFromMatrixColumn(m, 0).length();
  2508. const sy = this.setFromMatrixColumn(m, 1).length();
  2509. const sz = this.setFromMatrixColumn(m, 2).length();
  2510. this.x = sx;
  2511. this.y = sy;
  2512. this.z = sz;
  2513. return this;
  2514. }
  2515. setFromMatrixColumn(m, index) {
  2516. return this.fromArray(m.elements, index * 4);
  2517. }
  2518. setFromMatrix3Column(m, index) {
  2519. return this.fromArray(m.elements, index * 3);
  2520. }
  2521. equals(v) {
  2522. return v.x === this.x && v.y === this.y && v.z === this.z;
  2523. }
  2524. fromArray(array, offset = 0) {
  2525. this.x = array[offset];
  2526. this.y = array[offset + 1];
  2527. this.z = array[offset + 2];
  2528. return this;
  2529. }
  2530. toArray(array = [], offset = 0) {
  2531. array[offset] = this.x;
  2532. array[offset + 1] = this.y;
  2533. array[offset + 2] = this.z;
  2534. return array;
  2535. }
  2536. fromBufferAttribute(attribute, index, offset) {
  2537. if (offset !== undefined) {
  2538. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  2539. }
  2540. this.x = attribute.getX(index);
  2541. this.y = attribute.getY(index);
  2542. this.z = attribute.getZ(index);
  2543. return this;
  2544. }
  2545. random() {
  2546. this.x = Math.random();
  2547. this.y = Math.random();
  2548. this.z = Math.random();
  2549. return this;
  2550. }
  2551. }
  2552. Vector3.prototype.isVector3 = true;
  2553. const _vector$c = /*@__PURE__*/new Vector3();
  2554. const _quaternion$4 = /*@__PURE__*/new Quaternion();
  2555. class Box3 {
  2556. constructor(min = new Vector3(+Infinity, +Infinity, +Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) {
  2557. this.min = min;
  2558. this.max = max;
  2559. }
  2560. set(min, max) {
  2561. this.min.copy(min);
  2562. this.max.copy(max);
  2563. return this;
  2564. }
  2565. setFromArray(array) {
  2566. let minX = +Infinity;
  2567. let minY = +Infinity;
  2568. let minZ = +Infinity;
  2569. let maxX = -Infinity;
  2570. let maxY = -Infinity;
  2571. let maxZ = -Infinity;
  2572. for (let i = 0, l = array.length; i < l; i += 3) {
  2573. const x = array[i];
  2574. const y = array[i + 1];
  2575. const z = array[i + 2];
  2576. if (x < minX) minX = x;
  2577. if (y < minY) minY = y;
  2578. if (z < minZ) minZ = z;
  2579. if (x > maxX) maxX = x;
  2580. if (y > maxY) maxY = y;
  2581. if (z > maxZ) maxZ = z;
  2582. }
  2583. this.min.set(minX, minY, minZ);
  2584. this.max.set(maxX, maxY, maxZ);
  2585. return this;
  2586. }
  2587. setFromBufferAttribute(attribute) {
  2588. let minX = +Infinity;
  2589. let minY = +Infinity;
  2590. let minZ = +Infinity;
  2591. let maxX = -Infinity;
  2592. let maxY = -Infinity;
  2593. let maxZ = -Infinity;
  2594. for (let i = 0, l = attribute.count; i < l; i++) {
  2595. const x = attribute.getX(i);
  2596. const y = attribute.getY(i);
  2597. const z = attribute.getZ(i);
  2598. if (x < minX) minX = x;
  2599. if (y < minY) minY = y;
  2600. if (z < minZ) minZ = z;
  2601. if (x > maxX) maxX = x;
  2602. if (y > maxY) maxY = y;
  2603. if (z > maxZ) maxZ = z;
  2604. }
  2605. this.min.set(minX, minY, minZ);
  2606. this.max.set(maxX, maxY, maxZ);
  2607. return this;
  2608. }
  2609. setFromPoints(points) {
  2610. this.makeEmpty();
  2611. for (let i = 0, il = points.length; i < il; i++) {
  2612. this.expandByPoint(points[i]);
  2613. }
  2614. return this;
  2615. }
  2616. setFromCenterAndSize(center, size) {
  2617. const halfSize = _vector$b.copy(size).multiplyScalar(0.5);
  2618. this.min.copy(center).sub(halfSize);
  2619. this.max.copy(center).add(halfSize);
  2620. return this;
  2621. }
  2622. setFromObject(object) {
  2623. this.makeEmpty();
  2624. return this.expandByObject(object);
  2625. }
  2626. clone() {
  2627. return new this.constructor().copy(this);
  2628. }
  2629. copy(box) {
  2630. this.min.copy(box.min);
  2631. this.max.copy(box.max);
  2632. return this;
  2633. }
  2634. makeEmpty() {
  2635. this.min.x = this.min.y = this.min.z = +Infinity;
  2636. this.max.x = this.max.y = this.max.z = -Infinity;
  2637. return this;
  2638. }
  2639. isEmpty() {
  2640. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2641. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  2642. }
  2643. getCenter(target) {
  2644. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  2645. }
  2646. getSize(target) {
  2647. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  2648. }
  2649. expandByPoint(point) {
  2650. this.min.min(point);
  2651. this.max.max(point);
  2652. return this;
  2653. }
  2654. expandByVector(vector) {
  2655. this.min.sub(vector);
  2656. this.max.add(vector);
  2657. return this;
  2658. }
  2659. expandByScalar(scalar) {
  2660. this.min.addScalar(-scalar);
  2661. this.max.addScalar(scalar);
  2662. return this;
  2663. }
  2664. expandByObject(object) {
  2665. // Computes the world-axis-aligned bounding box of an object (including its children),
  2666. // accounting for both the object's, and children's, world transforms
  2667. object.updateWorldMatrix(false, false);
  2668. const geometry = object.geometry;
  2669. if (geometry !== undefined) {
  2670. if (geometry.boundingBox === null) {
  2671. geometry.computeBoundingBox();
  2672. }
  2673. _box$3.copy(geometry.boundingBox);
  2674. _box$3.applyMatrix4(object.matrixWorld);
  2675. this.union(_box$3);
  2676. }
  2677. const children = object.children;
  2678. for (let i = 0, l = children.length; i < l; i++) {
  2679. this.expandByObject(children[i]);
  2680. }
  2681. return this;
  2682. }
  2683. containsPoint(point) {
  2684. 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;
  2685. }
  2686. containsBox(box) {
  2687. 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;
  2688. }
  2689. getParameter(point, target) {
  2690. // This can potentially have a divide by zero if the box
  2691. // has a size dimension of 0.
  2692. 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));
  2693. }
  2694. intersectsBox(box) {
  2695. // using 6 splitting planes to rule out intersections.
  2696. 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;
  2697. }
  2698. intersectsSphere(sphere) {
  2699. // Find the point on the AABB closest to the sphere center.
  2700. this.clampPoint(sphere.center, _vector$b); // If that point is inside the sphere, the AABB and sphere intersect.
  2701. return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  2702. }
  2703. intersectsPlane(plane) {
  2704. // We compute the minimum and maximum dot product values. If those values
  2705. // are on the same side (back or front) of the plane, then there is no intersection.
  2706. let min, max;
  2707. if (plane.normal.x > 0) {
  2708. min = plane.normal.x * this.min.x;
  2709. max = plane.normal.x * this.max.x;
  2710. } else {
  2711. min = plane.normal.x * this.max.x;
  2712. max = plane.normal.x * this.min.x;
  2713. }
  2714. if (plane.normal.y > 0) {
  2715. min += plane.normal.y * this.min.y;
  2716. max += plane.normal.y * this.max.y;
  2717. } else {
  2718. min += plane.normal.y * this.max.y;
  2719. max += plane.normal.y * this.min.y;
  2720. }
  2721. if (plane.normal.z > 0) {
  2722. min += plane.normal.z * this.min.z;
  2723. max += plane.normal.z * this.max.z;
  2724. } else {
  2725. min += plane.normal.z * this.max.z;
  2726. max += plane.normal.z * this.min.z;
  2727. }
  2728. return min <= -plane.constant && max >= -plane.constant;
  2729. }
  2730. intersectsTriangle(triangle) {
  2731. if (this.isEmpty()) {
  2732. return false;
  2733. } // compute box center and extents
  2734. this.getCenter(_center);
  2735. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  2736. _v0$2.subVectors(triangle.a, _center);
  2737. _v1$7.subVectors(triangle.b, _center);
  2738. _v2$3.subVectors(triangle.c, _center); // compute edge vectors for triangle
  2739. _f0.subVectors(_v1$7, _v0$2);
  2740. _f1.subVectors(_v2$3, _v1$7);
  2741. _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
  2742. // 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
  2743. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2744. 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];
  2745. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2746. return false;
  2747. } // test 3 face normals from the aabb
  2748. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  2749. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2750. return false;
  2751. } // finally testing the face normal of the triangle
  2752. // use already existing triangle edge vectors here
  2753. _triangleNormal.crossVectors(_f0, _f1);
  2754. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  2755. return satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents);
  2756. }
  2757. clampPoint(point, target) {
  2758. return target.copy(point).clamp(this.min, this.max);
  2759. }
  2760. distanceToPoint(point) {
  2761. const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max);
  2762. return clampedPoint.sub(point).length();
  2763. }
  2764. getBoundingSphere(target) {
  2765. this.getCenter(target.center);
  2766. target.radius = this.getSize(_vector$b).length() * 0.5;
  2767. return target;
  2768. }
  2769. intersect(box) {
  2770. this.min.max(box.min);
  2771. 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.
  2772. if (this.isEmpty()) this.makeEmpty();
  2773. return this;
  2774. }
  2775. union(box) {
  2776. this.min.min(box.min);
  2777. this.max.max(box.max);
  2778. return this;
  2779. }
  2780. applyMatrix4(matrix) {
  2781. // transform of empty box is an empty box.
  2782. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2783. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  2784. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  2785. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  2786. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  2787. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  2788. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  2789. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  2790. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  2791. this.setFromPoints(_points);
  2792. return this;
  2793. }
  2794. translate(offset) {
  2795. this.min.add(offset);
  2796. this.max.add(offset);
  2797. return this;
  2798. }
  2799. equals(box) {
  2800. return box.min.equals(this.min) && box.max.equals(this.max);
  2801. }
  2802. }
  2803. Box3.prototype.isBox3 = true;
  2804. 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()];
  2805. const _vector$b = /*@__PURE__*/new Vector3();
  2806. const _box$3 = /*@__PURE__*/new Box3(); // triangle centered vertices
  2807. const _v0$2 = /*@__PURE__*/new Vector3();
  2808. const _v1$7 = /*@__PURE__*/new Vector3();
  2809. const _v2$3 = /*@__PURE__*/new Vector3(); // triangle edge vectors
  2810. const _f0 = /*@__PURE__*/new Vector3();
  2811. const _f1 = /*@__PURE__*/new Vector3();
  2812. const _f2 = /*@__PURE__*/new Vector3();
  2813. const _center = /*@__PURE__*/new Vector3();
  2814. const _extents = /*@__PURE__*/new Vector3();
  2815. const _triangleNormal = /*@__PURE__*/new Vector3();
  2816. const _testAxis = /*@__PURE__*/new Vector3();
  2817. function satForAxes(axes, v0, v1, v2, extents) {
  2818. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  2819. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  2820. 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
  2821. const p0 = v0.dot(_testAxis);
  2822. const p1 = v1.dot(_testAxis);
  2823. const p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  2824. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  2825. // points of the projected triangle are outside the projected half-length of the aabb
  2826. // the axis is seperating and we can exit
  2827. return false;
  2828. }
  2829. }
  2830. return true;
  2831. }
  2832. const _box$2 = /*@__PURE__*/new Box3();
  2833. const _v1$6 = /*@__PURE__*/new Vector3();
  2834. const _toFarthestPoint = /*@__PURE__*/new Vector3();
  2835. const _toPoint = /*@__PURE__*/new Vector3();
  2836. class Sphere {
  2837. constructor(center = new Vector3(), radius = -1) {
  2838. this.center = center;
  2839. this.radius = radius;
  2840. }
  2841. set(center, radius) {
  2842. this.center.copy(center);
  2843. this.radius = radius;
  2844. return this;
  2845. }
  2846. setFromPoints(points, optionalCenter) {
  2847. const center = this.center;
  2848. if (optionalCenter !== undefined) {
  2849. center.copy(optionalCenter);
  2850. } else {
  2851. _box$2.setFromPoints(points).getCenter(center);
  2852. }
  2853. let maxRadiusSq = 0;
  2854. for (let i = 0, il = points.length; i < il; i++) {
  2855. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  2856. }
  2857. this.radius = Math.sqrt(maxRadiusSq);
  2858. return this;
  2859. }
  2860. copy(sphere) {
  2861. this.center.copy(sphere.center);
  2862. this.radius = sphere.radius;
  2863. return this;
  2864. }
  2865. isEmpty() {
  2866. return this.radius < 0;
  2867. }
  2868. makeEmpty() {
  2869. this.center.set(0, 0, 0);
  2870. this.radius = -1;
  2871. return this;
  2872. }
  2873. containsPoint(point) {
  2874. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  2875. }
  2876. distanceToPoint(point) {
  2877. return point.distanceTo(this.center) - this.radius;
  2878. }
  2879. intersectsSphere(sphere) {
  2880. const radiusSum = this.radius + sphere.radius;
  2881. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  2882. }
  2883. intersectsBox(box) {
  2884. return box.intersectsSphere(this);
  2885. }
  2886. intersectsPlane(plane) {
  2887. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  2888. }
  2889. clampPoint(point, target) {
  2890. const deltaLengthSq = this.center.distanceToSquared(point);
  2891. target.copy(point);
  2892. if (deltaLengthSq > this.radius * this.radius) {
  2893. target.sub(this.center).normalize();
  2894. target.multiplyScalar(this.radius).add(this.center);
  2895. }
  2896. return target;
  2897. }
  2898. getBoundingBox(target) {
  2899. if (this.isEmpty()) {
  2900. // Empty sphere produces empty bounding box
  2901. target.makeEmpty();
  2902. return target;
  2903. }
  2904. target.set(this.center, this.center);
  2905. target.expandByScalar(this.radius);
  2906. return target;
  2907. }
  2908. applyMatrix4(matrix) {
  2909. this.center.applyMatrix4(matrix);
  2910. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2911. return this;
  2912. }
  2913. translate(offset) {
  2914. this.center.add(offset);
  2915. return this;
  2916. }
  2917. expandByPoint(point) {
  2918. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  2919. _toPoint.subVectors(point, this.center);
  2920. const lengthSq = _toPoint.lengthSq();
  2921. if (lengthSq > this.radius * this.radius) {
  2922. const length = Math.sqrt(lengthSq);
  2923. const missingRadiusHalf = (length - this.radius) * 0.5; // Nudge this sphere towards the target point. Add half the missing distance to radius,
  2924. // and the other half to position. This gives a tighter enclosure, instead of if
  2925. // the whole missing distance were just added to radius.
  2926. this.center.add(_toPoint.multiplyScalar(missingRadiusHalf / length));
  2927. this.radius += missingRadiusHalf;
  2928. }
  2929. return this;
  2930. }
  2931. union(sphere) {
  2932. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  2933. // To enclose another sphere into this sphere, we only need to enclose two points:
  2934. // 1) Enclose the farthest point on the other sphere into this sphere.
  2935. // 2) Enclose the opposite point of the farthest point into this sphere.
  2936. _toFarthestPoint.subVectors(sphere.center, this.center).normalize().multiplyScalar(sphere.radius);
  2937. this.expandByPoint(_v1$6.copy(sphere.center).add(_toFarthestPoint));
  2938. this.expandByPoint(_v1$6.copy(sphere.center).sub(_toFarthestPoint));
  2939. return this;
  2940. }
  2941. equals(sphere) {
  2942. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  2943. }
  2944. clone() {
  2945. return new this.constructor().copy(this);
  2946. }
  2947. }
  2948. const _vector$a = /*@__PURE__*/new Vector3();
  2949. const _segCenter = /*@__PURE__*/new Vector3();
  2950. const _segDir = /*@__PURE__*/new Vector3();
  2951. const _diff = /*@__PURE__*/new Vector3();
  2952. const _edge1 = /*@__PURE__*/new Vector3();
  2953. const _edge2 = /*@__PURE__*/new Vector3();
  2954. const _normal$1 = /*@__PURE__*/new Vector3();
  2955. class Ray {
  2956. constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) {
  2957. this.origin = origin;
  2958. this.direction = direction;
  2959. }
  2960. set(origin, direction) {
  2961. this.origin.copy(origin);
  2962. this.direction.copy(direction);
  2963. return this;
  2964. }
  2965. copy(ray) {
  2966. this.origin.copy(ray.origin);
  2967. this.direction.copy(ray.direction);
  2968. return this;
  2969. }
  2970. at(t, target) {
  2971. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  2972. }
  2973. lookAt(v) {
  2974. this.direction.copy(v).sub(this.origin).normalize();
  2975. return this;
  2976. }
  2977. recast(t) {
  2978. this.origin.copy(this.at(t, _vector$a));
  2979. return this;
  2980. }
  2981. closestPointToPoint(point, target) {
  2982. target.subVectors(point, this.origin);
  2983. const directionDistance = target.dot(this.direction);
  2984. if (directionDistance < 0) {
  2985. return target.copy(this.origin);
  2986. }
  2987. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  2988. }
  2989. distanceToPoint(point) {
  2990. return Math.sqrt(this.distanceSqToPoint(point));
  2991. }
  2992. distanceSqToPoint(point) {
  2993. const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  2994. if (directionDistance < 0) {
  2995. return this.origin.distanceToSquared(point);
  2996. }
  2997. _vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  2998. return _vector$a.distanceToSquared(point);
  2999. }
  3000. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  3001. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3002. // It returns the min distance between the ray and the segment
  3003. // defined by v0 and v1
  3004. // It can also set two optional targets :
  3005. // - The closest point on the ray
  3006. // - The closest point on the segment
  3007. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  3008. _segDir.copy(v1).sub(v0).normalize();
  3009. _diff.copy(this.origin).sub(_segCenter);
  3010. const segExtent = v0.distanceTo(v1) * 0.5;
  3011. const a01 = -this.direction.dot(_segDir);
  3012. const b0 = _diff.dot(this.direction);
  3013. const b1 = -_diff.dot(_segDir);
  3014. const c = _diff.lengthSq();
  3015. const det = Math.abs(1 - a01 * a01);
  3016. let s0, s1, sqrDist, extDet;
  3017. if (det > 0) {
  3018. // The ray and segment are not parallel.
  3019. s0 = a01 * b1 - b0;
  3020. s1 = a01 * b0 - b1;
  3021. extDet = segExtent * det;
  3022. if (s0 >= 0) {
  3023. if (s1 >= -extDet) {
  3024. if (s1 <= extDet) {
  3025. // region 0
  3026. // Minimum at interior points of ray and segment.
  3027. const invDet = 1 / det;
  3028. s0 *= invDet;
  3029. s1 *= invDet;
  3030. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  3031. } else {
  3032. // region 1
  3033. s1 = segExtent;
  3034. s0 = Math.max(0, -(a01 * s1 + b0));
  3035. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3036. }
  3037. } else {
  3038. // region 5
  3039. s1 = -segExtent;
  3040. s0 = Math.max(0, -(a01 * s1 + b0));
  3041. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3042. }
  3043. } else {
  3044. if (s1 <= -extDet) {
  3045. // region 4
  3046. s0 = Math.max(0, -(-a01 * segExtent + b0));
  3047. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3048. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3049. } else if (s1 <= extDet) {
  3050. // region 3
  3051. s0 = 0;
  3052. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  3053. sqrDist = s1 * (s1 + 2 * b1) + c;
  3054. } else {
  3055. // region 2
  3056. s0 = Math.max(0, -(a01 * segExtent + b0));
  3057. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3058. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3059. }
  3060. }
  3061. } else {
  3062. // Ray and segment are parallel.
  3063. s1 = a01 > 0 ? -segExtent : segExtent;
  3064. s0 = Math.max(0, -(a01 * s1 + b0));
  3065. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3066. }
  3067. if (optionalPointOnRay) {
  3068. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  3069. }
  3070. if (optionalPointOnSegment) {
  3071. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  3072. }
  3073. return sqrDist;
  3074. }
  3075. intersectSphere(sphere, target) {
  3076. _vector$a.subVectors(sphere.center, this.origin);
  3077. const tca = _vector$a.dot(this.direction);
  3078. const d2 = _vector$a.dot(_vector$a) - tca * tca;
  3079. const radius2 = sphere.radius * sphere.radius;
  3080. if (d2 > radius2) return null;
  3081. const thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  3082. const t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  3083. const t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  3084. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  3085. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3086. // in order to always return an intersect point that is in front of the ray.
  3087. 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
  3088. return this.at(t0, target);
  3089. }
  3090. intersectsSphere(sphere) {
  3091. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  3092. }
  3093. distanceToPlane(plane) {
  3094. const denominator = plane.normal.dot(this.direction);
  3095. if (denominator === 0) {
  3096. // line is coplanar, return origin
  3097. if (plane.distanceToPoint(this.origin) === 0) {
  3098. return 0;
  3099. } // Null is preferable to undefined since undefined means.... it is undefined
  3100. return null;
  3101. }
  3102. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  3103. return t >= 0 ? t : null;
  3104. }
  3105. intersectPlane(plane, target) {
  3106. const t = this.distanceToPlane(plane);
  3107. if (t === null) {
  3108. return null;
  3109. }
  3110. return this.at(t, target);
  3111. }
  3112. intersectsPlane(plane) {
  3113. // check if the ray lies on the plane first
  3114. const distToPoint = plane.distanceToPoint(this.origin);
  3115. if (distToPoint === 0) {
  3116. return true;
  3117. }
  3118. const denominator = plane.normal.dot(this.direction);
  3119. if (denominator * distToPoint < 0) {
  3120. return true;
  3121. } // ray origin is behind the plane (and is pointing behind it)
  3122. return false;
  3123. }
  3124. intersectBox(box, target) {
  3125. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3126. const invdirx = 1 / this.direction.x,
  3127. invdiry = 1 / this.direction.y,
  3128. invdirz = 1 / this.direction.z;
  3129. const origin = this.origin;
  3130. if (invdirx >= 0) {
  3131. tmin = (box.min.x - origin.x) * invdirx;
  3132. tmax = (box.max.x - origin.x) * invdirx;
  3133. } else {
  3134. tmin = (box.max.x - origin.x) * invdirx;
  3135. tmax = (box.min.x - origin.x) * invdirx;
  3136. }
  3137. if (invdiry >= 0) {
  3138. tymin = (box.min.y - origin.y) * invdiry;
  3139. tymax = (box.max.y - origin.y) * invdiry;
  3140. } else {
  3141. tymin = (box.max.y - origin.y) * invdiry;
  3142. tymax = (box.min.y - origin.y) * invdiry;
  3143. }
  3144. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  3145. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3146. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  3147. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  3148. if (invdirz >= 0) {
  3149. tzmin = (box.min.z - origin.z) * invdirz;
  3150. tzmax = (box.max.z - origin.z) * invdirz;
  3151. } else {
  3152. tzmin = (box.max.z - origin.z) * invdirz;
  3153. tzmax = (box.min.z - origin.z) * invdirz;
  3154. }
  3155. if (tmin > tzmax || tzmin > tmax) return null;
  3156. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  3157. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  3158. if (tmax < 0) return null;
  3159. return this.at(tmin >= 0 ? tmin : tmax, target);
  3160. }
  3161. intersectsBox(box) {
  3162. return this.intersectBox(box, _vector$a) !== null;
  3163. }
  3164. intersectTriangle(a, b, c, backfaceCulling, target) {
  3165. // Compute the offset origin, edges, and normal.
  3166. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3167. _edge1.subVectors(b, a);
  3168. _edge2.subVectors(c, a);
  3169. _normal$1.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3170. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3171. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3172. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3173. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3174. let DdN = this.direction.dot(_normal$1);
  3175. let sign;
  3176. if (DdN > 0) {
  3177. if (backfaceCulling) return null;
  3178. sign = 1;
  3179. } else if (DdN < 0) {
  3180. sign = -1;
  3181. DdN = -DdN;
  3182. } else {
  3183. return null;
  3184. }
  3185. _diff.subVectors(this.origin, a);
  3186. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  3187. if (DdQxE2 < 0) {
  3188. return null;
  3189. }
  3190. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  3191. if (DdE1xQ < 0) {
  3192. return null;
  3193. } // b1+b2 > 1, no intersection
  3194. if (DdQxE2 + DdE1xQ > DdN) {
  3195. return null;
  3196. } // Line intersects triangle, check if ray does.
  3197. const QdN = -sign * _diff.dot(_normal$1); // t < 0, no intersection
  3198. if (QdN < 0) {
  3199. return null;
  3200. } // Ray intersects triangle.
  3201. return this.at(QdN / DdN, target);
  3202. }
  3203. applyMatrix4(matrix4) {
  3204. this.origin.applyMatrix4(matrix4);
  3205. this.direction.transformDirection(matrix4);
  3206. return this;
  3207. }
  3208. equals(ray) {
  3209. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  3210. }
  3211. clone() {
  3212. return new this.constructor().copy(this);
  3213. }
  3214. }
  3215. class Matrix4 {
  3216. constructor() {
  3217. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3218. if (arguments.length > 0) {
  3219. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  3220. }
  3221. }
  3222. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3223. const te = this.elements;
  3224. te[0] = n11;
  3225. te[4] = n12;
  3226. te[8] = n13;
  3227. te[12] = n14;
  3228. te[1] = n21;
  3229. te[5] = n22;
  3230. te[9] = n23;
  3231. te[13] = n24;
  3232. te[2] = n31;
  3233. te[6] = n32;
  3234. te[10] = n33;
  3235. te[14] = n34;
  3236. te[3] = n41;
  3237. te[7] = n42;
  3238. te[11] = n43;
  3239. te[15] = n44;
  3240. return this;
  3241. }
  3242. identity() {
  3243. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3244. return this;
  3245. }
  3246. clone() {
  3247. return new Matrix4().fromArray(this.elements);
  3248. }
  3249. copy(m) {
  3250. const te = this.elements;
  3251. const me = m.elements;
  3252. te[0] = me[0];
  3253. te[1] = me[1];
  3254. te[2] = me[2];
  3255. te[3] = me[3];
  3256. te[4] = me[4];
  3257. te[5] = me[5];
  3258. te[6] = me[6];
  3259. te[7] = me[7];
  3260. te[8] = me[8];
  3261. te[9] = me[9];
  3262. te[10] = me[10];
  3263. te[11] = me[11];
  3264. te[12] = me[12];
  3265. te[13] = me[13];
  3266. te[14] = me[14];
  3267. te[15] = me[15];
  3268. return this;
  3269. }
  3270. copyPosition(m) {
  3271. const te = this.elements,
  3272. me = m.elements;
  3273. te[12] = me[12];
  3274. te[13] = me[13];
  3275. te[14] = me[14];
  3276. return this;
  3277. }
  3278. setFromMatrix3(m) {
  3279. const me = m.elements;
  3280. 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);
  3281. return this;
  3282. }
  3283. extractBasis(xAxis, yAxis, zAxis) {
  3284. xAxis.setFromMatrixColumn(this, 0);
  3285. yAxis.setFromMatrixColumn(this, 1);
  3286. zAxis.setFromMatrixColumn(this, 2);
  3287. return this;
  3288. }
  3289. makeBasis(xAxis, yAxis, zAxis) {
  3290. 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);
  3291. return this;
  3292. }
  3293. extractRotation(m) {
  3294. // this method does not support reflection matrices
  3295. const te = this.elements;
  3296. const me = m.elements;
  3297. const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length();
  3298. const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length();
  3299. const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length();
  3300. te[0] = me[0] * scaleX;
  3301. te[1] = me[1] * scaleX;
  3302. te[2] = me[2] * scaleX;
  3303. te[3] = 0;
  3304. te[4] = me[4] * scaleY;
  3305. te[5] = me[5] * scaleY;
  3306. te[6] = me[6] * scaleY;
  3307. te[7] = 0;
  3308. te[8] = me[8] * scaleZ;
  3309. te[9] = me[9] * scaleZ;
  3310. te[10] = me[10] * scaleZ;
  3311. te[11] = 0;
  3312. te[12] = 0;
  3313. te[13] = 0;
  3314. te[14] = 0;
  3315. te[15] = 1;
  3316. return this;
  3317. }
  3318. makeRotationFromEuler(euler) {
  3319. if (!(euler && euler.isEuler)) {
  3320. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  3321. }
  3322. const te = this.elements;
  3323. const x = euler.x,
  3324. y = euler.y,
  3325. z = euler.z;
  3326. const a = Math.cos(x),
  3327. b = Math.sin(x);
  3328. const c = Math.cos(y),
  3329. d = Math.sin(y);
  3330. const e = Math.cos(z),
  3331. f = Math.sin(z);
  3332. if (euler.order === 'XYZ') {
  3333. const ae = a * e,
  3334. af = a * f,
  3335. be = b * e,
  3336. bf = b * f;
  3337. te[0] = c * e;
  3338. te[4] = -c * f;
  3339. te[8] = d;
  3340. te[1] = af + be * d;
  3341. te[5] = ae - bf * d;
  3342. te[9] = -b * c;
  3343. te[2] = bf - ae * d;
  3344. te[6] = be + af * d;
  3345. te[10] = a * c;
  3346. } else if (euler.order === 'YXZ') {
  3347. const ce = c * e,
  3348. cf = c * f,
  3349. de = d * e,
  3350. df = d * f;
  3351. te[0] = ce + df * b;
  3352. te[4] = de * b - cf;
  3353. te[8] = a * d;
  3354. te[1] = a * f;
  3355. te[5] = a * e;
  3356. te[9] = -b;
  3357. te[2] = cf * b - de;
  3358. te[6] = df + ce * b;
  3359. te[10] = a * c;
  3360. } else if (euler.order === 'ZXY') {
  3361. const ce = c * e,
  3362. cf = c * f,
  3363. de = d * e,
  3364. df = d * f;
  3365. te[0] = ce - df * b;
  3366. te[4] = -a * f;
  3367. te[8] = de + cf * b;
  3368. te[1] = cf + de * b;
  3369. te[5] = a * e;
  3370. te[9] = df - ce * b;
  3371. te[2] = -a * d;
  3372. te[6] = b;
  3373. te[10] = a * c;
  3374. } else if (euler.order === 'ZYX') {
  3375. const ae = a * e,
  3376. af = a * f,
  3377. be = b * e,
  3378. bf = b * f;
  3379. te[0] = c * e;
  3380. te[4] = be * d - af;
  3381. te[8] = ae * d + bf;
  3382. te[1] = c * f;
  3383. te[5] = bf * d + ae;
  3384. te[9] = af * d - be;
  3385. te[2] = -d;
  3386. te[6] = b * c;
  3387. te[10] = a * c;
  3388. } else if (euler.order === 'YZX') {
  3389. const ac = a * c,
  3390. ad = a * d,
  3391. bc = b * c,
  3392. bd = b * d;
  3393. te[0] = c * e;
  3394. te[4] = bd - ac * f;
  3395. te[8] = bc * f + ad;
  3396. te[1] = f;
  3397. te[5] = a * e;
  3398. te[9] = -b * e;
  3399. te[2] = -d * e;
  3400. te[6] = ad * f + bc;
  3401. te[10] = ac - bd * f;
  3402. } else if (euler.order === 'XZY') {
  3403. const ac = a * c,
  3404. ad = a * d,
  3405. bc = b * c,
  3406. bd = b * d;
  3407. te[0] = c * e;
  3408. te[4] = -f;
  3409. te[8] = d * e;
  3410. te[1] = ac * f + bd;
  3411. te[5] = a * e;
  3412. te[9] = ad * f - bc;
  3413. te[2] = bc * f - ad;
  3414. te[6] = b * e;
  3415. te[10] = bd * f + ac;
  3416. } // bottom row
  3417. te[3] = 0;
  3418. te[7] = 0;
  3419. te[11] = 0; // last column
  3420. te[12] = 0;
  3421. te[13] = 0;
  3422. te[14] = 0;
  3423. te[15] = 1;
  3424. return this;
  3425. }
  3426. makeRotationFromQuaternion(q) {
  3427. return this.compose(_zero, q, _one);
  3428. }
  3429. lookAt(eye, target, up) {
  3430. const te = this.elements;
  3431. _z.subVectors(eye, target);
  3432. if (_z.lengthSq() === 0) {
  3433. // eye and target are in the same position
  3434. _z.z = 1;
  3435. }
  3436. _z.normalize();
  3437. _x.crossVectors(up, _z);
  3438. if (_x.lengthSq() === 0) {
  3439. // up and z are parallel
  3440. if (Math.abs(up.z) === 1) {
  3441. _z.x += 0.0001;
  3442. } else {
  3443. _z.z += 0.0001;
  3444. }
  3445. _z.normalize();
  3446. _x.crossVectors(up, _z);
  3447. }
  3448. _x.normalize();
  3449. _y.crossVectors(_z, _x);
  3450. te[0] = _x.x;
  3451. te[4] = _y.x;
  3452. te[8] = _z.x;
  3453. te[1] = _x.y;
  3454. te[5] = _y.y;
  3455. te[9] = _z.y;
  3456. te[2] = _x.z;
  3457. te[6] = _y.z;
  3458. te[10] = _z.z;
  3459. return this;
  3460. }
  3461. multiply(m, n) {
  3462. if (n !== undefined) {
  3463. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  3464. return this.multiplyMatrices(m, n);
  3465. }
  3466. return this.multiplyMatrices(this, m);
  3467. }
  3468. premultiply(m) {
  3469. return this.multiplyMatrices(m, this);
  3470. }
  3471. multiplyMatrices(a, b) {
  3472. const ae = a.elements;
  3473. const be = b.elements;
  3474. const te = this.elements;
  3475. const a11 = ae[0],
  3476. a12 = ae[4],
  3477. a13 = ae[8],
  3478. a14 = ae[12];
  3479. const a21 = ae[1],
  3480. a22 = ae[5],
  3481. a23 = ae[9],
  3482. a24 = ae[13];
  3483. const a31 = ae[2],
  3484. a32 = ae[6],
  3485. a33 = ae[10],
  3486. a34 = ae[14];
  3487. const a41 = ae[3],
  3488. a42 = ae[7],
  3489. a43 = ae[11],
  3490. a44 = ae[15];
  3491. const b11 = be[0],
  3492. b12 = be[4],
  3493. b13 = be[8],
  3494. b14 = be[12];
  3495. const b21 = be[1],
  3496. b22 = be[5],
  3497. b23 = be[9],
  3498. b24 = be[13];
  3499. const b31 = be[2],
  3500. b32 = be[6],
  3501. b33 = be[10],
  3502. b34 = be[14];
  3503. const b41 = be[3],
  3504. b42 = be[7],
  3505. b43 = be[11],
  3506. b44 = be[15];
  3507. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3508. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3509. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3510. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3511. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3512. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3513. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3514. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3515. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3516. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3517. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3518. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3519. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3520. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3521. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3522. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3523. return this;
  3524. }
  3525. multiplyScalar(s) {
  3526. const te = this.elements;
  3527. te[0] *= s;
  3528. te[4] *= s;
  3529. te[8] *= s;
  3530. te[12] *= s;
  3531. te[1] *= s;
  3532. te[5] *= s;
  3533. te[9] *= s;
  3534. te[13] *= s;
  3535. te[2] *= s;
  3536. te[6] *= s;
  3537. te[10] *= s;
  3538. te[14] *= s;
  3539. te[3] *= s;
  3540. te[7] *= s;
  3541. te[11] *= s;
  3542. te[15] *= s;
  3543. return this;
  3544. }
  3545. determinant() {
  3546. const te = this.elements;
  3547. const n11 = te[0],
  3548. n12 = te[4],
  3549. n13 = te[8],
  3550. n14 = te[12];
  3551. const n21 = te[1],
  3552. n22 = te[5],
  3553. n23 = te[9],
  3554. n24 = te[13];
  3555. const n31 = te[2],
  3556. n32 = te[6],
  3557. n33 = te[10],
  3558. n34 = te[14];
  3559. const n41 = te[3],
  3560. n42 = te[7],
  3561. n43 = te[11],
  3562. n44 = te[15]; //TODO: make this more efficient
  3563. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3564. 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);
  3565. }
  3566. transpose() {
  3567. const te = this.elements;
  3568. let tmp;
  3569. tmp = te[1];
  3570. te[1] = te[4];
  3571. te[4] = tmp;
  3572. tmp = te[2];
  3573. te[2] = te[8];
  3574. te[8] = tmp;
  3575. tmp = te[6];
  3576. te[6] = te[9];
  3577. te[9] = tmp;
  3578. tmp = te[3];
  3579. te[3] = te[12];
  3580. te[12] = tmp;
  3581. tmp = te[7];
  3582. te[7] = te[13];
  3583. te[13] = tmp;
  3584. tmp = te[11];
  3585. te[11] = te[14];
  3586. te[14] = tmp;
  3587. return this;
  3588. }
  3589. setPosition(x, y, z) {
  3590. const te = this.elements;
  3591. if (x.isVector3) {
  3592. te[12] = x.x;
  3593. te[13] = x.y;
  3594. te[14] = x.z;
  3595. } else {
  3596. te[12] = x;
  3597. te[13] = y;
  3598. te[14] = z;
  3599. }
  3600. return this;
  3601. }
  3602. invert() {
  3603. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3604. const te = this.elements,
  3605. n11 = te[0],
  3606. n21 = te[1],
  3607. n31 = te[2],
  3608. n41 = te[3],
  3609. n12 = te[4],
  3610. n22 = te[5],
  3611. n32 = te[6],
  3612. n42 = te[7],
  3613. n13 = te[8],
  3614. n23 = te[9],
  3615. n33 = te[10],
  3616. n43 = te[11],
  3617. n14 = te[12],
  3618. n24 = te[13],
  3619. n34 = te[14],
  3620. n44 = te[15],
  3621. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3622. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3623. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3624. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3625. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3626. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  3627. const detInv = 1 / det;
  3628. te[0] = t11 * detInv;
  3629. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  3630. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  3631. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  3632. te[4] = t12 * detInv;
  3633. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  3634. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  3635. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  3636. te[8] = t13 * detInv;
  3637. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  3638. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  3639. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  3640. te[12] = t14 * detInv;
  3641. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  3642. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  3643. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  3644. return this;
  3645. }
  3646. scale(v) {
  3647. const te = this.elements;
  3648. const x = v.x,
  3649. y = v.y,
  3650. z = v.z;
  3651. te[0] *= x;
  3652. te[4] *= y;
  3653. te[8] *= z;
  3654. te[1] *= x;
  3655. te[5] *= y;
  3656. te[9] *= z;
  3657. te[2] *= x;
  3658. te[6] *= y;
  3659. te[10] *= z;
  3660. te[3] *= x;
  3661. te[7] *= y;
  3662. te[11] *= z;
  3663. return this;
  3664. }
  3665. getMaxScaleOnAxis() {
  3666. const te = this.elements;
  3667. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  3668. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  3669. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  3670. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  3671. }
  3672. makeTranslation(x, y, z) {
  3673. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  3674. return this;
  3675. }
  3676. makeRotationX(theta) {
  3677. const c = Math.cos(theta),
  3678. s = Math.sin(theta);
  3679. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  3680. return this;
  3681. }
  3682. makeRotationY(theta) {
  3683. const c = Math.cos(theta),
  3684. s = Math.sin(theta);
  3685. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  3686. return this;
  3687. }
  3688. makeRotationZ(theta) {
  3689. const c = Math.cos(theta),
  3690. s = Math.sin(theta);
  3691. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3692. return this;
  3693. }
  3694. makeRotationAxis(axis, angle) {
  3695. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3696. const c = Math.cos(angle);
  3697. const s = Math.sin(angle);
  3698. const t = 1 - c;
  3699. const x = axis.x,
  3700. y = axis.y,
  3701. z = axis.z;
  3702. const tx = t * x,
  3703. ty = t * y;
  3704. 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);
  3705. return this;
  3706. }
  3707. makeScale(x, y, z) {
  3708. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  3709. return this;
  3710. }
  3711. makeShear(xy, xz, yx, yz, zx, zy) {
  3712. this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1);
  3713. return this;
  3714. }
  3715. compose(position, quaternion, scale) {
  3716. const te = this.elements;
  3717. const x = quaternion._x,
  3718. y = quaternion._y,
  3719. z = quaternion._z,
  3720. w = quaternion._w;
  3721. const x2 = x + x,
  3722. y2 = y + y,
  3723. z2 = z + z;
  3724. const xx = x * x2,
  3725. xy = x * y2,
  3726. xz = x * z2;
  3727. const yy = y * y2,
  3728. yz = y * z2,
  3729. zz = z * z2;
  3730. const wx = w * x2,
  3731. wy = w * y2,
  3732. wz = w * z2;
  3733. const sx = scale.x,
  3734. sy = scale.y,
  3735. sz = scale.z;
  3736. te[0] = (1 - (yy + zz)) * sx;
  3737. te[1] = (xy + wz) * sx;
  3738. te[2] = (xz - wy) * sx;
  3739. te[3] = 0;
  3740. te[4] = (xy - wz) * sy;
  3741. te[5] = (1 - (xx + zz)) * sy;
  3742. te[6] = (yz + wx) * sy;
  3743. te[7] = 0;
  3744. te[8] = (xz + wy) * sz;
  3745. te[9] = (yz - wx) * sz;
  3746. te[10] = (1 - (xx + yy)) * sz;
  3747. te[11] = 0;
  3748. te[12] = position.x;
  3749. te[13] = position.y;
  3750. te[14] = position.z;
  3751. te[15] = 1;
  3752. return this;
  3753. }
  3754. decompose(position, quaternion, scale) {
  3755. const te = this.elements;
  3756. let sx = _v1$5.set(te[0], te[1], te[2]).length();
  3757. const sy = _v1$5.set(te[4], te[5], te[6]).length();
  3758. const sz = _v1$5.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  3759. const det = this.determinant();
  3760. if (det < 0) sx = -sx;
  3761. position.x = te[12];
  3762. position.y = te[13];
  3763. position.z = te[14]; // scale the rotation part
  3764. _m1$2.copy(this);
  3765. const invSX = 1 / sx;
  3766. const invSY = 1 / sy;
  3767. const invSZ = 1 / sz;
  3768. _m1$2.elements[0] *= invSX;
  3769. _m1$2.elements[1] *= invSX;
  3770. _m1$2.elements[2] *= invSX;
  3771. _m1$2.elements[4] *= invSY;
  3772. _m1$2.elements[5] *= invSY;
  3773. _m1$2.elements[6] *= invSY;
  3774. _m1$2.elements[8] *= invSZ;
  3775. _m1$2.elements[9] *= invSZ;
  3776. _m1$2.elements[10] *= invSZ;
  3777. quaternion.setFromRotationMatrix(_m1$2);
  3778. scale.x = sx;
  3779. scale.y = sy;
  3780. scale.z = sz;
  3781. return this;
  3782. }
  3783. makePerspective(left, right, top, bottom, near, far) {
  3784. if (far === undefined) {
  3785. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  3786. }
  3787. const te = this.elements;
  3788. const x = 2 * near / (right - left);
  3789. const y = 2 * near / (top - bottom);
  3790. const a = (right + left) / (right - left);
  3791. const b = (top + bottom) / (top - bottom);
  3792. const c = -(far + near) / (far - near);
  3793. const d = -2 * far * near / (far - near);
  3794. te[0] = x;
  3795. te[4] = 0;
  3796. te[8] = a;
  3797. te[12] = 0;
  3798. te[1] = 0;
  3799. te[5] = y;
  3800. te[9] = b;
  3801. te[13] = 0;
  3802. te[2] = 0;
  3803. te[6] = 0;
  3804. te[10] = c;
  3805. te[14] = d;
  3806. te[3] = 0;
  3807. te[7] = 0;
  3808. te[11] = -1;
  3809. te[15] = 0;
  3810. return this;
  3811. }
  3812. makeOrthographic(left, right, top, bottom, near, far) {
  3813. const te = this.elements;
  3814. const w = 1.0 / (right - left);
  3815. const h = 1.0 / (top - bottom);
  3816. const p = 1.0 / (far - near);
  3817. const x = (right + left) * w;
  3818. const y = (top + bottom) * h;
  3819. const z = (far + near) * p;
  3820. te[0] = 2 * w;
  3821. te[4] = 0;
  3822. te[8] = 0;
  3823. te[12] = -x;
  3824. te[1] = 0;
  3825. te[5] = 2 * h;
  3826. te[9] = 0;
  3827. te[13] = -y;
  3828. te[2] = 0;
  3829. te[6] = 0;
  3830. te[10] = -2 * p;
  3831. te[14] = -z;
  3832. te[3] = 0;
  3833. te[7] = 0;
  3834. te[11] = 0;
  3835. te[15] = 1;
  3836. return this;
  3837. }
  3838. equals(matrix) {
  3839. const te = this.elements;
  3840. const me = matrix.elements;
  3841. for (let i = 0; i < 16; i++) {
  3842. if (te[i] !== me[i]) return false;
  3843. }
  3844. return true;
  3845. }
  3846. fromArray(array, offset = 0) {
  3847. for (let i = 0; i < 16; i++) {
  3848. this.elements[i] = array[i + offset];
  3849. }
  3850. return this;
  3851. }
  3852. toArray(array = [], offset = 0) {
  3853. const te = this.elements;
  3854. array[offset] = te[0];
  3855. array[offset + 1] = te[1];
  3856. array[offset + 2] = te[2];
  3857. array[offset + 3] = te[3];
  3858. array[offset + 4] = te[4];
  3859. array[offset + 5] = te[5];
  3860. array[offset + 6] = te[6];
  3861. array[offset + 7] = te[7];
  3862. array[offset + 8] = te[8];
  3863. array[offset + 9] = te[9];
  3864. array[offset + 10] = te[10];
  3865. array[offset + 11] = te[11];
  3866. array[offset + 12] = te[12];
  3867. array[offset + 13] = te[13];
  3868. array[offset + 14] = te[14];
  3869. array[offset + 15] = te[15];
  3870. return array;
  3871. }
  3872. }
  3873. Matrix4.prototype.isMatrix4 = true;
  3874. const _v1$5 = /*@__PURE__*/new Vector3();
  3875. const _m1$2 = /*@__PURE__*/new Matrix4();
  3876. const _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  3877. const _one = /*@__PURE__*/new Vector3(1, 1, 1);
  3878. const _x = /*@__PURE__*/new Vector3();
  3879. const _y = /*@__PURE__*/new Vector3();
  3880. const _z = /*@__PURE__*/new Vector3();
  3881. const _matrix$1 = /*@__PURE__*/new Matrix4();
  3882. const _quaternion$3 = /*@__PURE__*/new Quaternion();
  3883. class Euler {
  3884. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  3885. this._x = x;
  3886. this._y = y;
  3887. this._z = z;
  3888. this._order = order;
  3889. }
  3890. get x() {
  3891. return this._x;
  3892. }
  3893. set x(value) {
  3894. this._x = value;
  3895. this._onChangeCallback();
  3896. }
  3897. get y() {
  3898. return this._y;
  3899. }
  3900. set y(value) {
  3901. this._y = value;
  3902. this._onChangeCallback();
  3903. }
  3904. get z() {
  3905. return this._z;
  3906. }
  3907. set z(value) {
  3908. this._z = value;
  3909. this._onChangeCallback();
  3910. }
  3911. get order() {
  3912. return this._order;
  3913. }
  3914. set order(value) {
  3915. this._order = value;
  3916. this._onChangeCallback();
  3917. }
  3918. set(x, y, z, order = this._order) {
  3919. this._x = x;
  3920. this._y = y;
  3921. this._z = z;
  3922. this._order = order;
  3923. this._onChangeCallback();
  3924. return this;
  3925. }
  3926. clone() {
  3927. return new this.constructor(this._x, this._y, this._z, this._order);
  3928. }
  3929. copy(euler) {
  3930. this._x = euler._x;
  3931. this._y = euler._y;
  3932. this._z = euler._z;
  3933. this._order = euler._order;
  3934. this._onChangeCallback();
  3935. return this;
  3936. }
  3937. setFromRotationMatrix(m, order = this._order, update = true) {
  3938. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3939. const te = m.elements;
  3940. const m11 = te[0],
  3941. m12 = te[4],
  3942. m13 = te[8];
  3943. const m21 = te[1],
  3944. m22 = te[5],
  3945. m23 = te[9];
  3946. const m31 = te[2],
  3947. m32 = te[6],
  3948. m33 = te[10];
  3949. switch (order) {
  3950. case 'XYZ':
  3951. this._y = Math.asin(clamp(m13, -1, 1));
  3952. if (Math.abs(m13) < 0.9999999) {
  3953. this._x = Math.atan2(-m23, m33);
  3954. this._z = Math.atan2(-m12, m11);
  3955. } else {
  3956. this._x = Math.atan2(m32, m22);
  3957. this._z = 0;
  3958. }
  3959. break;
  3960. case 'YXZ':
  3961. this._x = Math.asin(-clamp(m23, -1, 1));
  3962. if (Math.abs(m23) < 0.9999999) {
  3963. this._y = Math.atan2(m13, m33);
  3964. this._z = Math.atan2(m21, m22);
  3965. } else {
  3966. this._y = Math.atan2(-m31, m11);
  3967. this._z = 0;
  3968. }
  3969. break;
  3970. case 'ZXY':
  3971. this._x = Math.asin(clamp(m32, -1, 1));
  3972. if (Math.abs(m32) < 0.9999999) {
  3973. this._y = Math.atan2(-m31, m33);
  3974. this._z = Math.atan2(-m12, m22);
  3975. } else {
  3976. this._y = 0;
  3977. this._z = Math.atan2(m21, m11);
  3978. }
  3979. break;
  3980. case 'ZYX':
  3981. this._y = Math.asin(-clamp(m31, -1, 1));
  3982. if (Math.abs(m31) < 0.9999999) {
  3983. this._x = Math.atan2(m32, m33);
  3984. this._z = Math.atan2(m21, m11);
  3985. } else {
  3986. this._x = 0;
  3987. this._z = Math.atan2(-m12, m22);
  3988. }
  3989. break;
  3990. case 'YZX':
  3991. this._z = Math.asin(clamp(m21, -1, 1));
  3992. if (Math.abs(m21) < 0.9999999) {
  3993. this._x = Math.atan2(-m23, m22);
  3994. this._y = Math.atan2(-m31, m11);
  3995. } else {
  3996. this._x = 0;
  3997. this._y = Math.atan2(m13, m33);
  3998. }
  3999. break;
  4000. case 'XZY':
  4001. this._z = Math.asin(-clamp(m12, -1, 1));
  4002. if (Math.abs(m12) < 0.9999999) {
  4003. this._x = Math.atan2(m32, m22);
  4004. this._y = Math.atan2(m13, m11);
  4005. } else {
  4006. this._x = Math.atan2(-m23, m33);
  4007. this._y = 0;
  4008. }
  4009. break;
  4010. default:
  4011. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  4012. }
  4013. this._order = order;
  4014. if (update === true) this._onChangeCallback();
  4015. return this;
  4016. }
  4017. setFromQuaternion(q, order, update) {
  4018. _matrix$1.makeRotationFromQuaternion(q);
  4019. return this.setFromRotationMatrix(_matrix$1, order, update);
  4020. }
  4021. setFromVector3(v, order = this._order) {
  4022. return this.set(v.x, v.y, v.z, order);
  4023. }
  4024. reorder(newOrder) {
  4025. // WARNING: this discards revolution information -bhouston
  4026. _quaternion$3.setFromEuler(this);
  4027. return this.setFromQuaternion(_quaternion$3, newOrder);
  4028. }
  4029. equals(euler) {
  4030. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4031. }
  4032. fromArray(array) {
  4033. this._x = array[0];
  4034. this._y = array[1];
  4035. this._z = array[2];
  4036. if (array[3] !== undefined) this._order = array[3];
  4037. this._onChangeCallback();
  4038. return this;
  4039. }
  4040. toArray(array = [], offset = 0) {
  4041. array[offset] = this._x;
  4042. array[offset + 1] = this._y;
  4043. array[offset + 2] = this._z;
  4044. array[offset + 3] = this._order;
  4045. return array;
  4046. }
  4047. toVector3(optionalResult) {
  4048. if (optionalResult) {
  4049. return optionalResult.set(this._x, this._y, this._z);
  4050. } else {
  4051. return new Vector3(this._x, this._y, this._z);
  4052. }
  4053. }
  4054. _onChange(callback) {
  4055. this._onChangeCallback = callback;
  4056. return this;
  4057. }
  4058. _onChangeCallback() {}
  4059. }
  4060. Euler.prototype.isEuler = true;
  4061. Euler.DefaultOrder = 'XYZ';
  4062. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4063. class Layers {
  4064. constructor() {
  4065. this.mask = 1 | 0;
  4066. }
  4067. set(channel) {
  4068. this.mask = 1 << channel | 0;
  4069. }
  4070. enable(channel) {
  4071. this.mask |= 1 << channel | 0;
  4072. }
  4073. enableAll() {
  4074. this.mask = 0xffffffff | 0;
  4075. }
  4076. toggle(channel) {
  4077. this.mask ^= 1 << channel | 0;
  4078. }
  4079. disable(channel) {
  4080. this.mask &= ~(1 << channel | 0);
  4081. }
  4082. disableAll() {
  4083. this.mask = 0;
  4084. }
  4085. test(layers) {
  4086. return (this.mask & layers.mask) !== 0;
  4087. }
  4088. }
  4089. let _object3DId = 0;
  4090. const _v1$4 = /*@__PURE__*/new Vector3();
  4091. const _q1 = /*@__PURE__*/new Quaternion();
  4092. const _m1$1 = /*@__PURE__*/new Matrix4();
  4093. const _target = /*@__PURE__*/new Vector3();
  4094. const _position$3 = /*@__PURE__*/new Vector3();
  4095. const _scale$2 = /*@__PURE__*/new Vector3();
  4096. const _quaternion$2 = /*@__PURE__*/new Quaternion();
  4097. const _xAxis = /*@__PURE__*/new Vector3(1, 0, 0);
  4098. const _yAxis = /*@__PURE__*/new Vector3(0, 1, 0);
  4099. const _zAxis = /*@__PURE__*/new Vector3(0, 0, 1);
  4100. const _addedEvent = {
  4101. type: 'added'
  4102. };
  4103. const _removedEvent = {
  4104. type: 'removed'
  4105. };
  4106. class Object3D extends EventDispatcher {
  4107. constructor() {
  4108. super();
  4109. Object.defineProperty(this, 'id', {
  4110. value: _object3DId++
  4111. });
  4112. this.uuid = generateUUID();
  4113. this.name = '';
  4114. this.type = 'Object3D';
  4115. this.parent = null;
  4116. this.children = [];
  4117. this.up = Object3D.DefaultUp.clone();
  4118. const position = new Vector3();
  4119. const rotation = new Euler();
  4120. const quaternion = new Quaternion();
  4121. const scale = new Vector3(1, 1, 1);
  4122. function onRotationChange() {
  4123. quaternion.setFromEuler(rotation, false);
  4124. }
  4125. function onQuaternionChange() {
  4126. rotation.setFromQuaternion(quaternion, undefined, false);
  4127. }
  4128. rotation._onChange(onRotationChange);
  4129. quaternion._onChange(onQuaternionChange);
  4130. Object.defineProperties(this, {
  4131. position: {
  4132. configurable: true,
  4133. enumerable: true,
  4134. value: position
  4135. },
  4136. rotation: {
  4137. configurable: true,
  4138. enumerable: true,
  4139. value: rotation
  4140. },
  4141. quaternion: {
  4142. configurable: true,
  4143. enumerable: true,
  4144. value: quaternion
  4145. },
  4146. scale: {
  4147. configurable: true,
  4148. enumerable: true,
  4149. value: scale
  4150. },
  4151. modelViewMatrix: {
  4152. value: new Matrix4()
  4153. },
  4154. normalMatrix: {
  4155. value: new Matrix3()
  4156. }
  4157. });
  4158. this.matrix = new Matrix4();
  4159. this.matrixWorld = new Matrix4();
  4160. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4161. this.matrixWorldNeedsUpdate = false;
  4162. this.layers = new Layers();
  4163. this.visible = true;
  4164. this.castShadow = false;
  4165. this.receiveShadow = false;
  4166. this.frustumCulled = true;
  4167. this.renderOrder = 0;
  4168. this.animations = [];
  4169. this.userData = {};
  4170. }
  4171. onBeforeRender() {}
  4172. onAfterRender() {}
  4173. applyMatrix4(matrix) {
  4174. if (this.matrixAutoUpdate) this.updateMatrix();
  4175. this.matrix.premultiply(matrix);
  4176. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4177. }
  4178. applyQuaternion(q) {
  4179. this.quaternion.premultiply(q);
  4180. return this;
  4181. }
  4182. setRotationFromAxisAngle(axis, angle) {
  4183. // assumes axis is normalized
  4184. this.quaternion.setFromAxisAngle(axis, angle);
  4185. }
  4186. setRotationFromEuler(euler) {
  4187. this.quaternion.setFromEuler(euler, true);
  4188. }
  4189. setRotationFromMatrix(m) {
  4190. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4191. this.quaternion.setFromRotationMatrix(m);
  4192. }
  4193. setRotationFromQuaternion(q) {
  4194. // assumes q is normalized
  4195. this.quaternion.copy(q);
  4196. }
  4197. rotateOnAxis(axis, angle) {
  4198. // rotate object on axis in object space
  4199. // axis is assumed to be normalized
  4200. _q1.setFromAxisAngle(axis, angle);
  4201. this.quaternion.multiply(_q1);
  4202. return this;
  4203. }
  4204. rotateOnWorldAxis(axis, angle) {
  4205. // rotate object on axis in world space
  4206. // axis is assumed to be normalized
  4207. // method assumes no rotated parent
  4208. _q1.setFromAxisAngle(axis, angle);
  4209. this.quaternion.premultiply(_q1);
  4210. return this;
  4211. }
  4212. rotateX(angle) {
  4213. return this.rotateOnAxis(_xAxis, angle);
  4214. }
  4215. rotateY(angle) {
  4216. return this.rotateOnAxis(_yAxis, angle);
  4217. }
  4218. rotateZ(angle) {
  4219. return this.rotateOnAxis(_zAxis, angle);
  4220. }
  4221. translateOnAxis(axis, distance) {
  4222. // translate object by distance along axis in object space
  4223. // axis is assumed to be normalized
  4224. _v1$4.copy(axis).applyQuaternion(this.quaternion);
  4225. this.position.add(_v1$4.multiplyScalar(distance));
  4226. return this;
  4227. }
  4228. translateX(distance) {
  4229. return this.translateOnAxis(_xAxis, distance);
  4230. }
  4231. translateY(distance) {
  4232. return this.translateOnAxis(_yAxis, distance);
  4233. }
  4234. translateZ(distance) {
  4235. return this.translateOnAxis(_zAxis, distance);
  4236. }
  4237. localToWorld(vector) {
  4238. return vector.applyMatrix4(this.matrixWorld);
  4239. }
  4240. worldToLocal(vector) {
  4241. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  4242. }
  4243. lookAt(x, y, z) {
  4244. // This method does not support objects having non-uniformly-scaled parent(s)
  4245. if (x.isVector3) {
  4246. _target.copy(x);
  4247. } else {
  4248. _target.set(x, y, z);
  4249. }
  4250. const parent = this.parent;
  4251. this.updateWorldMatrix(true, false);
  4252. _position$3.setFromMatrixPosition(this.matrixWorld);
  4253. if (this.isCamera || this.isLight) {
  4254. _m1$1.lookAt(_position$3, _target, this.up);
  4255. } else {
  4256. _m1$1.lookAt(_target, _position$3, this.up);
  4257. }
  4258. this.quaternion.setFromRotationMatrix(_m1$1);
  4259. if (parent) {
  4260. _m1$1.extractRotation(parent.matrixWorld);
  4261. _q1.setFromRotationMatrix(_m1$1);
  4262. this.quaternion.premultiply(_q1.invert());
  4263. }
  4264. }
  4265. add(object) {
  4266. if (arguments.length > 1) {
  4267. for (let i = 0; i < arguments.length; i++) {
  4268. this.add(arguments[i]);
  4269. }
  4270. return this;
  4271. }
  4272. if (object === this) {
  4273. console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
  4274. return this;
  4275. }
  4276. if (object && object.isObject3D) {
  4277. if (object.parent !== null) {
  4278. object.parent.remove(object);
  4279. }
  4280. object.parent = this;
  4281. this.children.push(object);
  4282. object.dispatchEvent(_addedEvent);
  4283. } else {
  4284. console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
  4285. }
  4286. return this;
  4287. }
  4288. remove(object) {
  4289. if (arguments.length > 1) {
  4290. for (let i = 0; i < arguments.length; i++) {
  4291. this.remove(arguments[i]);
  4292. }
  4293. return this;
  4294. }
  4295. const index = this.children.indexOf(object);
  4296. if (index !== -1) {
  4297. object.parent = null;
  4298. this.children.splice(index, 1);
  4299. object.dispatchEvent(_removedEvent);
  4300. }
  4301. return this;
  4302. }
  4303. removeFromParent() {
  4304. const parent = this.parent;
  4305. if (parent !== null) {
  4306. parent.remove(this);
  4307. }
  4308. return this;
  4309. }
  4310. clear() {
  4311. for (let i = 0; i < this.children.length; i++) {
  4312. const object = this.children[i];
  4313. object.parent = null;
  4314. object.dispatchEvent(_removedEvent);
  4315. }
  4316. this.children.length = 0;
  4317. return this;
  4318. }
  4319. attach(object) {
  4320. // adds object as a child of this, while maintaining the object's world transform
  4321. this.updateWorldMatrix(true, false);
  4322. _m1$1.copy(this.matrixWorld).invert();
  4323. if (object.parent !== null) {
  4324. object.parent.updateWorldMatrix(true, false);
  4325. _m1$1.multiply(object.parent.matrixWorld);
  4326. }
  4327. object.applyMatrix4(_m1$1);
  4328. this.add(object);
  4329. object.updateWorldMatrix(false, true);
  4330. return this;
  4331. }
  4332. getObjectById(id) {
  4333. return this.getObjectByProperty('id', id);
  4334. }
  4335. getObjectByName(name) {
  4336. return this.getObjectByProperty('name', name);
  4337. }
  4338. getObjectByProperty(name, value) {
  4339. if (this[name] === value) return this;
  4340. for (let i = 0, l = this.children.length; i < l; i++) {
  4341. const child = this.children[i];
  4342. const object = child.getObjectByProperty(name, value);
  4343. if (object !== undefined) {
  4344. return object;
  4345. }
  4346. }
  4347. return undefined;
  4348. }
  4349. getWorldPosition(target) {
  4350. this.updateWorldMatrix(true, false);
  4351. return target.setFromMatrixPosition(this.matrixWorld);
  4352. }
  4353. getWorldQuaternion(target) {
  4354. this.updateWorldMatrix(true, false);
  4355. this.matrixWorld.decompose(_position$3, target, _scale$2);
  4356. return target;
  4357. }
  4358. getWorldScale(target) {
  4359. this.updateWorldMatrix(true, false);
  4360. this.matrixWorld.decompose(_position$3, _quaternion$2, target);
  4361. return target;
  4362. }
  4363. getWorldDirection(target) {
  4364. this.updateWorldMatrix(true, false);
  4365. const e = this.matrixWorld.elements;
  4366. return target.set(e[8], e[9], e[10]).normalize();
  4367. }
  4368. raycast() {}
  4369. traverse(callback) {
  4370. callback(this);
  4371. const children = this.children;
  4372. for (let i = 0, l = children.length; i < l; i++) {
  4373. children[i].traverse(callback);
  4374. }
  4375. }
  4376. traverseVisible(callback) {
  4377. if (this.visible === false) return;
  4378. callback(this);
  4379. const children = this.children;
  4380. for (let i = 0, l = children.length; i < l; i++) {
  4381. children[i].traverseVisible(callback);
  4382. }
  4383. }
  4384. traverseAncestors(callback) {
  4385. const parent = this.parent;
  4386. if (parent !== null) {
  4387. callback(parent);
  4388. parent.traverseAncestors(callback);
  4389. }
  4390. }
  4391. updateMatrix() {
  4392. this.matrix.compose(this.position, this.quaternion, this.scale);
  4393. this.matrixWorldNeedsUpdate = true;
  4394. }
  4395. updateMatrixWorld(force) {
  4396. if (this.matrixAutoUpdate) this.updateMatrix();
  4397. if (this.matrixWorldNeedsUpdate || force) {
  4398. if (this.parent === null) {
  4399. this.matrixWorld.copy(this.matrix);
  4400. } else {
  4401. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4402. }
  4403. this.matrixWorldNeedsUpdate = false;
  4404. force = true;
  4405. } // update children
  4406. const children = this.children;
  4407. for (let i = 0, l = children.length; i < l; i++) {
  4408. children[i].updateMatrixWorld(force);
  4409. }
  4410. }
  4411. updateWorldMatrix(updateParents, updateChildren) {
  4412. const parent = this.parent;
  4413. if (updateParents === true && parent !== null) {
  4414. parent.updateWorldMatrix(true, false);
  4415. }
  4416. if (this.matrixAutoUpdate) this.updateMatrix();
  4417. if (this.parent === null) {
  4418. this.matrixWorld.copy(this.matrix);
  4419. } else {
  4420. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4421. } // update children
  4422. if (updateChildren === true) {
  4423. const children = this.children;
  4424. for (let i = 0, l = children.length; i < l; i++) {
  4425. children[i].updateWorldMatrix(false, true);
  4426. }
  4427. }
  4428. }
  4429. toJSON(meta) {
  4430. // meta is a string when called from JSON.stringify
  4431. const isRootObject = meta === undefined || typeof meta === 'string';
  4432. const output = {}; // meta is a hash used to collect geometries, materials.
  4433. // not providing it implies that this is the root object
  4434. // being serialized.
  4435. if (isRootObject) {
  4436. // initialize meta obj
  4437. meta = {
  4438. geometries: {},
  4439. materials: {},
  4440. textures: {},
  4441. images: {},
  4442. shapes: {},
  4443. skeletons: {},
  4444. animations: {}
  4445. };
  4446. output.metadata = {
  4447. version: 4.5,
  4448. type: 'Object',
  4449. generator: 'Object3D.toJSON'
  4450. };
  4451. } // standard Object3D serialization
  4452. const object = {};
  4453. object.uuid = this.uuid;
  4454. object.type = this.type;
  4455. if (this.name !== '') object.name = this.name;
  4456. if (this.castShadow === true) object.castShadow = true;
  4457. if (this.receiveShadow === true) object.receiveShadow = true;
  4458. if (this.visible === false) object.visible = false;
  4459. if (this.frustumCulled === false) object.frustumCulled = false;
  4460. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  4461. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  4462. object.layers = this.layers.mask;
  4463. object.matrix = this.matrix.toArray();
  4464. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  4465. if (this.isInstancedMesh) {
  4466. object.type = 'InstancedMesh';
  4467. object.count = this.count;
  4468. object.instanceMatrix = this.instanceMatrix.toJSON();
  4469. if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON();
  4470. } //
  4471. function serialize(library, element) {
  4472. if (library[element.uuid] === undefined) {
  4473. library[element.uuid] = element.toJSON(meta);
  4474. }
  4475. return element.uuid;
  4476. }
  4477. if (this.isScene) {
  4478. if (this.background) {
  4479. if (this.background.isColor) {
  4480. object.background = this.background.toJSON();
  4481. } else if (this.background.isTexture) {
  4482. object.background = this.background.toJSON(meta).uuid;
  4483. }
  4484. }
  4485. if (this.environment && this.environment.isTexture) {
  4486. object.environment = this.environment.toJSON(meta).uuid;
  4487. }
  4488. } else if (this.isMesh || this.isLine || this.isPoints) {
  4489. object.geometry = serialize(meta.geometries, this.geometry);
  4490. const parameters = this.geometry.parameters;
  4491. if (parameters !== undefined && parameters.shapes !== undefined) {
  4492. const shapes = parameters.shapes;
  4493. if (Array.isArray(shapes)) {
  4494. for (let i = 0, l = shapes.length; i < l; i++) {
  4495. const shape = shapes[i];
  4496. serialize(meta.shapes, shape);
  4497. }
  4498. } else {
  4499. serialize(meta.shapes, shapes);
  4500. }
  4501. }
  4502. }
  4503. if (this.isSkinnedMesh) {
  4504. object.bindMode = this.bindMode;
  4505. object.bindMatrix = this.bindMatrix.toArray();
  4506. if (this.skeleton !== undefined) {
  4507. serialize(meta.skeletons, this.skeleton);
  4508. object.skeleton = this.skeleton.uuid;
  4509. }
  4510. }
  4511. if (this.material !== undefined) {
  4512. if (Array.isArray(this.material)) {
  4513. const uuids = [];
  4514. for (let i = 0, l = this.material.length; i < l; i++) {
  4515. uuids.push(serialize(meta.materials, this.material[i]));
  4516. }
  4517. object.material = uuids;
  4518. } else {
  4519. object.material = serialize(meta.materials, this.material);
  4520. }
  4521. } //
  4522. if (this.children.length > 0) {
  4523. object.children = [];
  4524. for (let i = 0; i < this.children.length; i++) {
  4525. object.children.push(this.children[i].toJSON(meta).object);
  4526. }
  4527. } //
  4528. if (this.animations.length > 0) {
  4529. object.animations = [];
  4530. for (let i = 0; i < this.animations.length; i++) {
  4531. const animation = this.animations[i];
  4532. object.animations.push(serialize(meta.animations, animation));
  4533. }
  4534. }
  4535. if (isRootObject) {
  4536. const geometries = extractFromCache(meta.geometries);
  4537. const materials = extractFromCache(meta.materials);
  4538. const textures = extractFromCache(meta.textures);
  4539. const images = extractFromCache(meta.images);
  4540. const shapes = extractFromCache(meta.shapes);
  4541. const skeletons = extractFromCache(meta.skeletons);
  4542. const animations = extractFromCache(meta.animations);
  4543. if (geometries.length > 0) output.geometries = geometries;
  4544. if (materials.length > 0) output.materials = materials;
  4545. if (textures.length > 0) output.textures = textures;
  4546. if (images.length > 0) output.images = images;
  4547. if (shapes.length > 0) output.shapes = shapes;
  4548. if (skeletons.length > 0) output.skeletons = skeletons;
  4549. if (animations.length > 0) output.animations = animations;
  4550. }
  4551. output.object = object;
  4552. return output; // extract data from the cache hash
  4553. // remove metadata on each item
  4554. // and return as array
  4555. function extractFromCache(cache) {
  4556. const values = [];
  4557. for (const key in cache) {
  4558. const data = cache[key];
  4559. delete data.metadata;
  4560. values.push(data);
  4561. }
  4562. return values;
  4563. }
  4564. }
  4565. clone(recursive) {
  4566. return new this.constructor().copy(this, recursive);
  4567. }
  4568. copy(source, recursive = true) {
  4569. this.name = source.name;
  4570. this.up.copy(source.up);
  4571. this.position.copy(source.position);
  4572. this.rotation.order = source.rotation.order;
  4573. this.quaternion.copy(source.quaternion);
  4574. this.scale.copy(source.scale);
  4575. this.matrix.copy(source.matrix);
  4576. this.matrixWorld.copy(source.matrixWorld);
  4577. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4578. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4579. this.layers.mask = source.layers.mask;
  4580. this.visible = source.visible;
  4581. this.castShadow = source.castShadow;
  4582. this.receiveShadow = source.receiveShadow;
  4583. this.frustumCulled = source.frustumCulled;
  4584. this.renderOrder = source.renderOrder;
  4585. this.userData = JSON.parse(JSON.stringify(source.userData));
  4586. if (recursive === true) {
  4587. for (let i = 0; i < source.children.length; i++) {
  4588. const child = source.children[i];
  4589. this.add(child.clone());
  4590. }
  4591. }
  4592. return this;
  4593. }
  4594. }
  4595. Object3D.DefaultUp = new Vector3(0, 1, 0);
  4596. Object3D.DefaultMatrixAutoUpdate = true;
  4597. Object3D.prototype.isObject3D = true;
  4598. const _v0$1 = /*@__PURE__*/new Vector3();
  4599. const _v1$3 = /*@__PURE__*/new Vector3();
  4600. const _v2$2 = /*@__PURE__*/new Vector3();
  4601. const _v3$1 = /*@__PURE__*/new Vector3();
  4602. const _vab = /*@__PURE__*/new Vector3();
  4603. const _vac = /*@__PURE__*/new Vector3();
  4604. const _vbc = /*@__PURE__*/new Vector3();
  4605. const _vap = /*@__PURE__*/new Vector3();
  4606. const _vbp = /*@__PURE__*/new Vector3();
  4607. const _vcp = /*@__PURE__*/new Vector3();
  4608. class Triangle {
  4609. constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) {
  4610. this.a = a;
  4611. this.b = b;
  4612. this.c = c;
  4613. }
  4614. static getNormal(a, b, c, target) {
  4615. target.subVectors(c, b);
  4616. _v0$1.subVectors(a, b);
  4617. target.cross(_v0$1);
  4618. const targetLengthSq = target.lengthSq();
  4619. if (targetLengthSq > 0) {
  4620. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  4621. }
  4622. return target.set(0, 0, 0);
  4623. } // static/instance method to calculate barycentric coordinates
  4624. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4625. static getBarycoord(point, a, b, c, target) {
  4626. _v0$1.subVectors(c, a);
  4627. _v1$3.subVectors(b, a);
  4628. _v2$2.subVectors(point, a);
  4629. const dot00 = _v0$1.dot(_v0$1);
  4630. const dot01 = _v0$1.dot(_v1$3);
  4631. const dot02 = _v0$1.dot(_v2$2);
  4632. const dot11 = _v1$3.dot(_v1$3);
  4633. const dot12 = _v1$3.dot(_v2$2);
  4634. const denom = dot00 * dot11 - dot01 * dot01; // collinear or singular triangle
  4635. if (denom === 0) {
  4636. // arbitrary location outside of triangle?
  4637. // not sure if this is the best idea, maybe should be returning undefined
  4638. return target.set(-2, -1, -1);
  4639. }
  4640. const invDenom = 1 / denom;
  4641. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  4642. const v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  4643. return target.set(1 - u - v, v, u);
  4644. }
  4645. static containsPoint(point, a, b, c) {
  4646. this.getBarycoord(point, a, b, c, _v3$1);
  4647. return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1;
  4648. }
  4649. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  4650. this.getBarycoord(point, p1, p2, p3, _v3$1);
  4651. target.set(0, 0);
  4652. target.addScaledVector(uv1, _v3$1.x);
  4653. target.addScaledVector(uv2, _v3$1.y);
  4654. target.addScaledVector(uv3, _v3$1.z);
  4655. return target;
  4656. }
  4657. static isFrontFacing(a, b, c, direction) {
  4658. _v0$1.subVectors(c, b);
  4659. _v1$3.subVectors(a, b); // strictly front facing
  4660. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  4661. }
  4662. set(a, b, c) {
  4663. this.a.copy(a);
  4664. this.b.copy(b);
  4665. this.c.copy(c);
  4666. return this;
  4667. }
  4668. setFromPointsAndIndices(points, i0, i1, i2) {
  4669. this.a.copy(points[i0]);
  4670. this.b.copy(points[i1]);
  4671. this.c.copy(points[i2]);
  4672. return this;
  4673. }
  4674. clone() {
  4675. return new this.constructor().copy(this);
  4676. }
  4677. copy(triangle) {
  4678. this.a.copy(triangle.a);
  4679. this.b.copy(triangle.b);
  4680. this.c.copy(triangle.c);
  4681. return this;
  4682. }
  4683. getArea() {
  4684. _v0$1.subVectors(this.c, this.b);
  4685. _v1$3.subVectors(this.a, this.b);
  4686. return _v0$1.cross(_v1$3).length() * 0.5;
  4687. }
  4688. getMidpoint(target) {
  4689. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  4690. }
  4691. getNormal(target) {
  4692. return Triangle.getNormal(this.a, this.b, this.c, target);
  4693. }
  4694. getPlane(target) {
  4695. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  4696. }
  4697. getBarycoord(point, target) {
  4698. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  4699. }
  4700. getUV(point, uv1, uv2, uv3, target) {
  4701. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  4702. }
  4703. containsPoint(point) {
  4704. return Triangle.containsPoint(point, this.a, this.b, this.c);
  4705. }
  4706. isFrontFacing(direction) {
  4707. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  4708. }
  4709. intersectsBox(box) {
  4710. return box.intersectsTriangle(this);
  4711. }
  4712. closestPointToPoint(p, target) {
  4713. const a = this.a,
  4714. b = this.b,
  4715. c = this.c;
  4716. let v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4717. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4718. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4719. // basically, we're distinguishing which of the voronoi regions of the triangle
  4720. // the point lies in with the minimum amount of redundant computation.
  4721. _vab.subVectors(b, a);
  4722. _vac.subVectors(c, a);
  4723. _vap.subVectors(p, a);
  4724. const d1 = _vab.dot(_vap);
  4725. const d2 = _vac.dot(_vap);
  4726. if (d1 <= 0 && d2 <= 0) {
  4727. // vertex region of A; barycentric coords (1, 0, 0)
  4728. return target.copy(a);
  4729. }
  4730. _vbp.subVectors(p, b);
  4731. const d3 = _vab.dot(_vbp);
  4732. const d4 = _vac.dot(_vbp);
  4733. if (d3 >= 0 && d4 <= d3) {
  4734. // vertex region of B; barycentric coords (0, 1, 0)
  4735. return target.copy(b);
  4736. }
  4737. const vc = d1 * d4 - d3 * d2;
  4738. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  4739. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  4740. return target.copy(a).addScaledVector(_vab, v);
  4741. }
  4742. _vcp.subVectors(p, c);
  4743. const d5 = _vab.dot(_vcp);
  4744. const d6 = _vac.dot(_vcp);
  4745. if (d6 >= 0 && d5 <= d6) {
  4746. // vertex region of C; barycentric coords (0, 0, 1)
  4747. return target.copy(c);
  4748. }
  4749. const vb = d5 * d2 - d1 * d6;
  4750. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  4751. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  4752. return target.copy(a).addScaledVector(_vac, w);
  4753. }
  4754. const va = d3 * d6 - d5 * d4;
  4755. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  4756. _vbc.subVectors(c, b);
  4757. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  4758. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  4759. } // face region
  4760. const denom = 1 / (va + vb + vc); // u = va * denom
  4761. v = vb * denom;
  4762. w = vc * denom;
  4763. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  4764. }
  4765. equals(triangle) {
  4766. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  4767. }
  4768. }
  4769. let materialId = 0;
  4770. class Material extends EventDispatcher {
  4771. constructor() {
  4772. super();
  4773. Object.defineProperty(this, 'id', {
  4774. value: materialId++
  4775. });
  4776. this.uuid = generateUUID();
  4777. this.name = '';
  4778. this.type = 'Material';
  4779. this.fog = true;
  4780. this.blending = NormalBlending;
  4781. this.side = FrontSide;
  4782. this.vertexColors = false;
  4783. this.opacity = 1;
  4784. this.transparent = false;
  4785. this.blendSrc = SrcAlphaFactor;
  4786. this.blendDst = OneMinusSrcAlphaFactor;
  4787. this.blendEquation = AddEquation;
  4788. this.blendSrcAlpha = null;
  4789. this.blendDstAlpha = null;
  4790. this.blendEquationAlpha = null;
  4791. this.depthFunc = LessEqualDepth;
  4792. this.depthTest = true;
  4793. this.depthWrite = true;
  4794. this.stencilWriteMask = 0xff;
  4795. this.stencilFunc = AlwaysStencilFunc;
  4796. this.stencilRef = 0;
  4797. this.stencilFuncMask = 0xff;
  4798. this.stencilFail = KeepStencilOp;
  4799. this.stencilZFail = KeepStencilOp;
  4800. this.stencilZPass = KeepStencilOp;
  4801. this.stencilWrite = false;
  4802. this.clippingPlanes = null;
  4803. this.clipIntersection = false;
  4804. this.clipShadows = false;
  4805. this.shadowSide = null;
  4806. this.colorWrite = true;
  4807. this.precision = null; // override the renderer's default precision for this material
  4808. this.polygonOffset = false;
  4809. this.polygonOffsetFactor = 0;
  4810. this.polygonOffsetUnits = 0;
  4811. this.dithering = false;
  4812. this.alphaTest = 0;
  4813. this.alphaToCoverage = false;
  4814. this.premultipliedAlpha = false;
  4815. this.visible = true;
  4816. this.toneMapped = true;
  4817. this.userData = {};
  4818. this.version = 0;
  4819. }
  4820. onBuild()
  4821. /* shaderobject, renderer */
  4822. {}
  4823. onBeforeCompile()
  4824. /* shaderobject, renderer */
  4825. {}
  4826. customProgramCacheKey() {
  4827. return this.onBeforeCompile.toString();
  4828. }
  4829. setValues(values) {
  4830. if (values === undefined) return;
  4831. for (const key in values) {
  4832. const newValue = values[key];
  4833. if (newValue === undefined) {
  4834. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  4835. continue;
  4836. } // for backward compatability if shading is set in the constructor
  4837. if (key === 'shading') {
  4838. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  4839. this.flatShading = newValue === FlatShading ? true : false;
  4840. continue;
  4841. }
  4842. const currentValue = this[key];
  4843. if (currentValue === undefined) {
  4844. console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
  4845. continue;
  4846. }
  4847. if (currentValue && currentValue.isColor) {
  4848. currentValue.set(newValue);
  4849. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  4850. currentValue.copy(newValue);
  4851. } else {
  4852. this[key] = newValue;
  4853. }
  4854. }
  4855. }
  4856. toJSON(meta) {
  4857. const isRoot = meta === undefined || typeof meta === 'string';
  4858. if (isRoot) {
  4859. meta = {
  4860. textures: {},
  4861. images: {}
  4862. };
  4863. }
  4864. const data = {
  4865. metadata: {
  4866. version: 4.5,
  4867. type: 'Material',
  4868. generator: 'Material.toJSON'
  4869. }
  4870. }; // standard Material serialization
  4871. data.uuid = this.uuid;
  4872. data.type = this.type;
  4873. if (this.name !== '') data.name = this.name;
  4874. if (this.color && this.color.isColor) data.color = this.color.getHex();
  4875. if (this.roughness !== undefined) data.roughness = this.roughness;
  4876. if (this.metalness !== undefined) data.metalness = this.metalness;
  4877. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  4878. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  4879. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  4880. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  4881. if (this.shininess !== undefined) data.shininess = this.shininess;
  4882. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  4883. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  4884. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  4885. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  4886. }
  4887. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  4888. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  4889. }
  4890. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  4891. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  4892. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  4893. }
  4894. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  4895. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  4896. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  4897. if (this.lightMap && this.lightMap.isTexture) {
  4898. data.lightMap = this.lightMap.toJSON(meta).uuid;
  4899. data.lightMapIntensity = this.lightMapIntensity;
  4900. }
  4901. if (this.aoMap && this.aoMap.isTexture) {
  4902. data.aoMap = this.aoMap.toJSON(meta).uuid;
  4903. data.aoMapIntensity = this.aoMapIntensity;
  4904. }
  4905. if (this.bumpMap && this.bumpMap.isTexture) {
  4906. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  4907. data.bumpScale = this.bumpScale;
  4908. }
  4909. if (this.normalMap && this.normalMap.isTexture) {
  4910. data.normalMap = this.normalMap.toJSON(meta).uuid;
  4911. data.normalMapType = this.normalMapType;
  4912. data.normalScale = this.normalScale.toArray();
  4913. }
  4914. if (this.displacementMap && this.displacementMap.isTexture) {
  4915. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  4916. data.displacementScale = this.displacementScale;
  4917. data.displacementBias = this.displacementBias;
  4918. }
  4919. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  4920. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  4921. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  4922. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  4923. if (this.envMap && this.envMap.isTexture) {
  4924. data.envMap = this.envMap.toJSON(meta).uuid;
  4925. if (this.combine !== undefined) data.combine = this.combine;
  4926. }
  4927. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  4928. if (this.reflectivity !== undefined) data.reflectivity = this.reflectivity;
  4929. if (this.refractionRatio !== undefined) data.refractionRatio = this.refractionRatio;
  4930. if (this.gradientMap && this.gradientMap.isTexture) {
  4931. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  4932. }
  4933. if (this.transmission !== undefined) data.transmission = this.transmission;
  4934. if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid;
  4935. if (this.thickness !== undefined) data.thickness = this.thickness;
  4936. if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid;
  4937. if (this.attenuationDistance !== undefined) data.attenuationDistance = this.attenuationDistance;
  4938. if (this.attenuationColor !== undefined) data.attenuationColor = this.attenuationColor.getHex();
  4939. if (this.size !== undefined) data.size = this.size;
  4940. if (this.shadowSide !== null) data.shadowSide = this.shadowSide;
  4941. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  4942. if (this.blending !== NormalBlending) data.blending = this.blending;
  4943. if (this.side !== FrontSide) data.side = this.side;
  4944. if (this.vertexColors) data.vertexColors = true;
  4945. if (this.opacity < 1) data.opacity = this.opacity;
  4946. if (this.transparent === true) data.transparent = this.transparent;
  4947. data.depthFunc = this.depthFunc;
  4948. data.depthTest = this.depthTest;
  4949. data.depthWrite = this.depthWrite;
  4950. data.colorWrite = this.colorWrite;
  4951. data.stencilWrite = this.stencilWrite;
  4952. data.stencilWriteMask = this.stencilWriteMask;
  4953. data.stencilFunc = this.stencilFunc;
  4954. data.stencilRef = this.stencilRef;
  4955. data.stencilFuncMask = this.stencilFuncMask;
  4956. data.stencilFail = this.stencilFail;
  4957. data.stencilZFail = this.stencilZFail;
  4958. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  4959. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  4960. if (this.polygonOffset === true) data.polygonOffset = true;
  4961. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  4962. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  4963. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  4964. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  4965. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  4966. if (this.scale !== undefined) data.scale = this.scale;
  4967. if (this.dithering === true) data.dithering = true;
  4968. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  4969. if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage;
  4970. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  4971. if (this.wireframe === true) data.wireframe = this.wireframe;
  4972. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  4973. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  4974. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  4975. if (this.flatShading === true) data.flatShading = this.flatShading;
  4976. if (this.visible === false) data.visible = false;
  4977. if (this.toneMapped === false) data.toneMapped = false;
  4978. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  4979. function extractFromCache(cache) {
  4980. const values = [];
  4981. for (const key in cache) {
  4982. const data = cache[key];
  4983. delete data.metadata;
  4984. values.push(data);
  4985. }
  4986. return values;
  4987. }
  4988. if (isRoot) {
  4989. const textures = extractFromCache(meta.textures);
  4990. const images = extractFromCache(meta.images);
  4991. if (textures.length > 0) data.textures = textures;
  4992. if (images.length > 0) data.images = images;
  4993. }
  4994. return data;
  4995. }
  4996. clone() {
  4997. return new this.constructor().copy(this);
  4998. }
  4999. copy(source) {
  5000. this.name = source.name;
  5001. this.fog = source.fog;
  5002. this.blending = source.blending;
  5003. this.side = source.side;
  5004. this.vertexColors = source.vertexColors;
  5005. this.opacity = source.opacity;
  5006. this.transparent = source.transparent;
  5007. this.blendSrc = source.blendSrc;
  5008. this.blendDst = source.blendDst;
  5009. this.blendEquation = source.blendEquation;
  5010. this.blendSrcAlpha = source.blendSrcAlpha;
  5011. this.blendDstAlpha = source.blendDstAlpha;
  5012. this.blendEquationAlpha = source.blendEquationAlpha;
  5013. this.depthFunc = source.depthFunc;
  5014. this.depthTest = source.depthTest;
  5015. this.depthWrite = source.depthWrite;
  5016. this.stencilWriteMask = source.stencilWriteMask;
  5017. this.stencilFunc = source.stencilFunc;
  5018. this.stencilRef = source.stencilRef;
  5019. this.stencilFuncMask = source.stencilFuncMask;
  5020. this.stencilFail = source.stencilFail;
  5021. this.stencilZFail = source.stencilZFail;
  5022. this.stencilZPass = source.stencilZPass;
  5023. this.stencilWrite = source.stencilWrite;
  5024. const srcPlanes = source.clippingPlanes;
  5025. let dstPlanes = null;
  5026. if (srcPlanes !== null) {
  5027. const n = srcPlanes.length;
  5028. dstPlanes = new Array(n);
  5029. for (let i = 0; i !== n; ++i) {
  5030. dstPlanes[i] = srcPlanes[i].clone();
  5031. }
  5032. }
  5033. this.clippingPlanes = dstPlanes;
  5034. this.clipIntersection = source.clipIntersection;
  5035. this.clipShadows = source.clipShadows;
  5036. this.shadowSide = source.shadowSide;
  5037. this.colorWrite = source.colorWrite;
  5038. this.precision = source.precision;
  5039. this.polygonOffset = source.polygonOffset;
  5040. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5041. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5042. this.dithering = source.dithering;
  5043. this.alphaTest = source.alphaTest;
  5044. this.alphaToCoverage = source.alphaToCoverage;
  5045. this.premultipliedAlpha = source.premultipliedAlpha;
  5046. this.visible = source.visible;
  5047. this.toneMapped = source.toneMapped;
  5048. this.userData = JSON.parse(JSON.stringify(source.userData));
  5049. return this;
  5050. }
  5051. dispose() {
  5052. this.dispatchEvent({
  5053. type: 'dispose'
  5054. });
  5055. }
  5056. set needsUpdate(value) {
  5057. if (value === true) this.version++;
  5058. }
  5059. }
  5060. Material.prototype.isMaterial = true;
  5061. const _colorKeywords = {
  5062. 'aliceblue': 0xF0F8FF,
  5063. 'antiquewhite': 0xFAEBD7,
  5064. 'aqua': 0x00FFFF,
  5065. 'aquamarine': 0x7FFFD4,
  5066. 'azure': 0xF0FFFF,
  5067. 'beige': 0xF5F5DC,
  5068. 'bisque': 0xFFE4C4,
  5069. 'black': 0x000000,
  5070. 'blanchedalmond': 0xFFEBCD,
  5071. 'blue': 0x0000FF,
  5072. 'blueviolet': 0x8A2BE2,
  5073. 'brown': 0xA52A2A,
  5074. 'burlywood': 0xDEB887,
  5075. 'cadetblue': 0x5F9EA0,
  5076. 'chartreuse': 0x7FFF00,
  5077. 'chocolate': 0xD2691E,
  5078. 'coral': 0xFF7F50,
  5079. 'cornflowerblue': 0x6495ED,
  5080. 'cornsilk': 0xFFF8DC,
  5081. 'crimson': 0xDC143C,
  5082. 'cyan': 0x00FFFF,
  5083. 'darkblue': 0x00008B,
  5084. 'darkcyan': 0x008B8B,
  5085. 'darkgoldenrod': 0xB8860B,
  5086. 'darkgray': 0xA9A9A9,
  5087. 'darkgreen': 0x006400,
  5088. 'darkgrey': 0xA9A9A9,
  5089. 'darkkhaki': 0xBDB76B,
  5090. 'darkmagenta': 0x8B008B,
  5091. 'darkolivegreen': 0x556B2F,
  5092. 'darkorange': 0xFF8C00,
  5093. 'darkorchid': 0x9932CC,
  5094. 'darkred': 0x8B0000,
  5095. 'darksalmon': 0xE9967A,
  5096. 'darkseagreen': 0x8FBC8F,
  5097. 'darkslateblue': 0x483D8B,
  5098. 'darkslategray': 0x2F4F4F,
  5099. 'darkslategrey': 0x2F4F4F,
  5100. 'darkturquoise': 0x00CED1,
  5101. 'darkviolet': 0x9400D3,
  5102. 'deeppink': 0xFF1493,
  5103. 'deepskyblue': 0x00BFFF,
  5104. 'dimgray': 0x696969,
  5105. 'dimgrey': 0x696969,
  5106. 'dodgerblue': 0x1E90FF,
  5107. 'firebrick': 0xB22222,
  5108. 'floralwhite': 0xFFFAF0,
  5109. 'forestgreen': 0x228B22,
  5110. 'fuchsia': 0xFF00FF,
  5111. 'gainsboro': 0xDCDCDC,
  5112. 'ghostwhite': 0xF8F8FF,
  5113. 'gold': 0xFFD700,
  5114. 'goldenrod': 0xDAA520,
  5115. 'gray': 0x808080,
  5116. 'green': 0x008000,
  5117. 'greenyellow': 0xADFF2F,
  5118. 'grey': 0x808080,
  5119. 'honeydew': 0xF0FFF0,
  5120. 'hotpink': 0xFF69B4,
  5121. 'indianred': 0xCD5C5C,
  5122. 'indigo': 0x4B0082,
  5123. 'ivory': 0xFFFFF0,
  5124. 'khaki': 0xF0E68C,
  5125. 'lavender': 0xE6E6FA,
  5126. 'lavenderblush': 0xFFF0F5,
  5127. 'lawngreen': 0x7CFC00,
  5128. 'lemonchiffon': 0xFFFACD,
  5129. 'lightblue': 0xADD8E6,
  5130. 'lightcoral': 0xF08080,
  5131. 'lightcyan': 0xE0FFFF,
  5132. 'lightgoldenrodyellow': 0xFAFAD2,
  5133. 'lightgray': 0xD3D3D3,
  5134. 'lightgreen': 0x90EE90,
  5135. 'lightgrey': 0xD3D3D3,
  5136. 'lightpink': 0xFFB6C1,
  5137. 'lightsalmon': 0xFFA07A,
  5138. 'lightseagreen': 0x20B2AA,
  5139. 'lightskyblue': 0x87CEFA,
  5140. 'lightslategray': 0x778899,
  5141. 'lightslategrey': 0x778899,
  5142. 'lightsteelblue': 0xB0C4DE,
  5143. 'lightyellow': 0xFFFFE0,
  5144. 'lime': 0x00FF00,
  5145. 'limegreen': 0x32CD32,
  5146. 'linen': 0xFAF0E6,
  5147. 'magenta': 0xFF00FF,
  5148. 'maroon': 0x800000,
  5149. 'mediumaquamarine': 0x66CDAA,
  5150. 'mediumblue': 0x0000CD,
  5151. 'mediumorchid': 0xBA55D3,
  5152. 'mediumpurple': 0x9370DB,
  5153. 'mediumseagreen': 0x3CB371,
  5154. 'mediumslateblue': 0x7B68EE,
  5155. 'mediumspringgreen': 0x00FA9A,
  5156. 'mediumturquoise': 0x48D1CC,
  5157. 'mediumvioletred': 0xC71585,
  5158. 'midnightblue': 0x191970,
  5159. 'mintcream': 0xF5FFFA,
  5160. 'mistyrose': 0xFFE4E1,
  5161. 'moccasin': 0xFFE4B5,
  5162. 'navajowhite': 0xFFDEAD,
  5163. 'navy': 0x000080,
  5164. 'oldlace': 0xFDF5E6,
  5165. 'olive': 0x808000,
  5166. 'olivedrab': 0x6B8E23,
  5167. 'orange': 0xFFA500,
  5168. 'orangered': 0xFF4500,
  5169. 'orchid': 0xDA70D6,
  5170. 'palegoldenrod': 0xEEE8AA,
  5171. 'palegreen': 0x98FB98,
  5172. 'paleturquoise': 0xAFEEEE,
  5173. 'palevioletred': 0xDB7093,
  5174. 'papayawhip': 0xFFEFD5,
  5175. 'peachpuff': 0xFFDAB9,
  5176. 'peru': 0xCD853F,
  5177. 'pink': 0xFFC0CB,
  5178. 'plum': 0xDDA0DD,
  5179. 'powderblue': 0xB0E0E6,
  5180. 'purple': 0x800080,
  5181. 'rebeccapurple': 0x663399,
  5182. 'red': 0xFF0000,
  5183. 'rosybrown': 0xBC8F8F,
  5184. 'royalblue': 0x4169E1,
  5185. 'saddlebrown': 0x8B4513,
  5186. 'salmon': 0xFA8072,
  5187. 'sandybrown': 0xF4A460,
  5188. 'seagreen': 0x2E8B57,
  5189. 'seashell': 0xFFF5EE,
  5190. 'sienna': 0xA0522D,
  5191. 'silver': 0xC0C0C0,
  5192. 'skyblue': 0x87CEEB,
  5193. 'slateblue': 0x6A5ACD,
  5194. 'slategray': 0x708090,
  5195. 'slategrey': 0x708090,
  5196. 'snow': 0xFFFAFA,
  5197. 'springgreen': 0x00FF7F,
  5198. 'steelblue': 0x4682B4,
  5199. 'tan': 0xD2B48C,
  5200. 'teal': 0x008080,
  5201. 'thistle': 0xD8BFD8,
  5202. 'tomato': 0xFF6347,
  5203. 'turquoise': 0x40E0D0,
  5204. 'violet': 0xEE82EE,
  5205. 'wheat': 0xF5DEB3,
  5206. 'white': 0xFFFFFF,
  5207. 'whitesmoke': 0xF5F5F5,
  5208. 'yellow': 0xFFFF00,
  5209. 'yellowgreen': 0x9ACD32
  5210. };
  5211. const _hslA = {
  5212. h: 0,
  5213. s: 0,
  5214. l: 0
  5215. };
  5216. const _hslB = {
  5217. h: 0,
  5218. s: 0,
  5219. l: 0
  5220. };
  5221. function hue2rgb(p, q, t) {
  5222. if (t < 0) t += 1;
  5223. if (t > 1) t -= 1;
  5224. if (t < 1 / 6) return p + (q - p) * 6 * t;
  5225. if (t < 1 / 2) return q;
  5226. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  5227. return p;
  5228. }
  5229. function SRGBToLinear(c) {
  5230. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  5231. }
  5232. function LinearToSRGB(c) {
  5233. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  5234. }
  5235. class Color {
  5236. constructor(r, g, b) {
  5237. if (g === undefined && b === undefined) {
  5238. // r is THREE.Color, hex or string
  5239. return this.set(r);
  5240. }
  5241. return this.setRGB(r, g, b);
  5242. }
  5243. set(value) {
  5244. if (value && value.isColor) {
  5245. this.copy(value);
  5246. } else if (typeof value === 'number') {
  5247. this.setHex(value);
  5248. } else if (typeof value === 'string') {
  5249. this.setStyle(value);
  5250. }
  5251. return this;
  5252. }
  5253. setScalar(scalar) {
  5254. this.r = scalar;
  5255. this.g = scalar;
  5256. this.b = scalar;
  5257. return this;
  5258. }
  5259. setHex(hex) {
  5260. hex = Math.floor(hex);
  5261. this.r = (hex >> 16 & 255) / 255;
  5262. this.g = (hex >> 8 & 255) / 255;
  5263. this.b = (hex & 255) / 255;
  5264. return this;
  5265. }
  5266. setRGB(r, g, b) {
  5267. this.r = r;
  5268. this.g = g;
  5269. this.b = b;
  5270. return this;
  5271. }
  5272. setHSL(h, s, l) {
  5273. // h,s,l ranges are in 0.0 - 1.0
  5274. h = euclideanModulo(h, 1);
  5275. s = clamp(s, 0, 1);
  5276. l = clamp(l, 0, 1);
  5277. if (s === 0) {
  5278. this.r = this.g = this.b = l;
  5279. } else {
  5280. const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  5281. const q = 2 * l - p;
  5282. this.r = hue2rgb(q, p, h + 1 / 3);
  5283. this.g = hue2rgb(q, p, h);
  5284. this.b = hue2rgb(q, p, h - 1 / 3);
  5285. }
  5286. return this;
  5287. }
  5288. setStyle(style) {
  5289. function handleAlpha(string) {
  5290. if (string === undefined) return;
  5291. if (parseFloat(string) < 1) {
  5292. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  5293. }
  5294. }
  5295. let m;
  5296. if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
  5297. // rgb / hsl
  5298. let color;
  5299. const name = m[1];
  5300. const components = m[2];
  5301. switch (name) {
  5302. case 'rgb':
  5303. case 'rgba':
  5304. if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5305. // rgb(255,0,0) rgba(255,0,0,0.5)
  5306. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  5307. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  5308. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  5309. handleAlpha(color[4]);
  5310. return this;
  5311. }
  5312. if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5313. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5314. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  5315. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  5316. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  5317. handleAlpha(color[4]);
  5318. return this;
  5319. }
  5320. break;
  5321. case 'hsl':
  5322. case 'hsla':
  5323. if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5324. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5325. const h = parseFloat(color[1]) / 360;
  5326. const s = parseInt(color[2], 10) / 100;
  5327. const l = parseInt(color[3], 10) / 100;
  5328. handleAlpha(color[4]);
  5329. return this.setHSL(h, s, l);
  5330. }
  5331. break;
  5332. }
  5333. } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
  5334. // hex color
  5335. const hex = m[1];
  5336. const size = hex.length;
  5337. if (size === 3) {
  5338. // #ff0
  5339. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  5340. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  5341. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  5342. return this;
  5343. } else if (size === 6) {
  5344. // #ff0000
  5345. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  5346. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  5347. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  5348. return this;
  5349. }
  5350. }
  5351. if (style && style.length > 0) {
  5352. return this.setColorName(style);
  5353. }
  5354. return this;
  5355. }
  5356. setColorName(style) {
  5357. // color keywords
  5358. const hex = _colorKeywords[style.toLowerCase()];
  5359. if (hex !== undefined) {
  5360. // red
  5361. this.setHex(hex);
  5362. } else {
  5363. // unknown color
  5364. console.warn('THREE.Color: Unknown color ' + style);
  5365. }
  5366. return this;
  5367. }
  5368. clone() {
  5369. return new this.constructor(this.r, this.g, this.b);
  5370. }
  5371. copy(color) {
  5372. this.r = color.r;
  5373. this.g = color.g;
  5374. this.b = color.b;
  5375. return this;
  5376. }
  5377. copyGammaToLinear(color, gammaFactor = 2.0) {
  5378. this.r = Math.pow(color.r, gammaFactor);
  5379. this.g = Math.pow(color.g, gammaFactor);
  5380. this.b = Math.pow(color.b, gammaFactor);
  5381. return this;
  5382. }
  5383. copyLinearToGamma(color, gammaFactor = 2.0) {
  5384. const safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  5385. this.r = Math.pow(color.r, safeInverse);
  5386. this.g = Math.pow(color.g, safeInverse);
  5387. this.b = Math.pow(color.b, safeInverse);
  5388. return this;
  5389. }
  5390. convertGammaToLinear(gammaFactor) {
  5391. this.copyGammaToLinear(this, gammaFactor);
  5392. return this;
  5393. }
  5394. convertLinearToGamma(gammaFactor) {
  5395. this.copyLinearToGamma(this, gammaFactor);
  5396. return this;
  5397. }
  5398. copySRGBToLinear(color) {
  5399. this.r = SRGBToLinear(color.r);
  5400. this.g = SRGBToLinear(color.g);
  5401. this.b = SRGBToLinear(color.b);
  5402. return this;
  5403. }
  5404. copyLinearToSRGB(color) {
  5405. this.r = LinearToSRGB(color.r);
  5406. this.g = LinearToSRGB(color.g);
  5407. this.b = LinearToSRGB(color.b);
  5408. return this;
  5409. }
  5410. convertSRGBToLinear() {
  5411. this.copySRGBToLinear(this);
  5412. return this;
  5413. }
  5414. convertLinearToSRGB() {
  5415. this.copyLinearToSRGB(this);
  5416. return this;
  5417. }
  5418. getHex() {
  5419. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  5420. }
  5421. getHexString() {
  5422. return ('000000' + this.getHex().toString(16)).slice(-6);
  5423. }
  5424. getHSL(target) {
  5425. // h,s,l ranges are in 0.0 - 1.0
  5426. const r = this.r,
  5427. g = this.g,
  5428. b = this.b;
  5429. const max = Math.max(r, g, b);
  5430. const min = Math.min(r, g, b);
  5431. let hue, saturation;
  5432. const lightness = (min + max) / 2.0;
  5433. if (min === max) {
  5434. hue = 0;
  5435. saturation = 0;
  5436. } else {
  5437. const delta = max - min;
  5438. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  5439. switch (max) {
  5440. case r:
  5441. hue = (g - b) / delta + (g < b ? 6 : 0);
  5442. break;
  5443. case g:
  5444. hue = (b - r) / delta + 2;
  5445. break;
  5446. case b:
  5447. hue = (r - g) / delta + 4;
  5448. break;
  5449. }
  5450. hue /= 6;
  5451. }
  5452. target.h = hue;
  5453. target.s = saturation;
  5454. target.l = lightness;
  5455. return target;
  5456. }
  5457. getStyle() {
  5458. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  5459. }
  5460. offsetHSL(h, s, l) {
  5461. this.getHSL(_hslA);
  5462. _hslA.h += h;
  5463. _hslA.s += s;
  5464. _hslA.l += l;
  5465. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  5466. return this;
  5467. }
  5468. add(color) {
  5469. this.r += color.r;
  5470. this.g += color.g;
  5471. this.b += color.b;
  5472. return this;
  5473. }
  5474. addColors(color1, color2) {
  5475. this.r = color1.r + color2.r;
  5476. this.g = color1.g + color2.g;
  5477. this.b = color1.b + color2.b;
  5478. return this;
  5479. }
  5480. addScalar(s) {
  5481. this.r += s;
  5482. this.g += s;
  5483. this.b += s;
  5484. return this;
  5485. }
  5486. sub(color) {
  5487. this.r = Math.max(0, this.r - color.r);
  5488. this.g = Math.max(0, this.g - color.g);
  5489. this.b = Math.max(0, this.b - color.b);
  5490. return this;
  5491. }
  5492. multiply(color) {
  5493. this.r *= color.r;
  5494. this.g *= color.g;
  5495. this.b *= color.b;
  5496. return this;
  5497. }
  5498. multiplyScalar(s) {
  5499. this.r *= s;
  5500. this.g *= s;
  5501. this.b *= s;
  5502. return this;
  5503. }
  5504. lerp(color, alpha) {
  5505. this.r += (color.r - this.r) * alpha;
  5506. this.g += (color.g - this.g) * alpha;
  5507. this.b += (color.b - this.b) * alpha;
  5508. return this;
  5509. }
  5510. lerpColors(color1, color2, alpha) {
  5511. this.r = color1.r + (color2.r - color1.r) * alpha;
  5512. this.g = color1.g + (color2.g - color1.g) * alpha;
  5513. this.b = color1.b + (color2.b - color1.b) * alpha;
  5514. return this;
  5515. }
  5516. lerpHSL(color, alpha) {
  5517. this.getHSL(_hslA);
  5518. color.getHSL(_hslB);
  5519. const h = lerp(_hslA.h, _hslB.h, alpha);
  5520. const s = lerp(_hslA.s, _hslB.s, alpha);
  5521. const l = lerp(_hslA.l, _hslB.l, alpha);
  5522. this.setHSL(h, s, l);
  5523. return this;
  5524. }
  5525. equals(c) {
  5526. return c.r === this.r && c.g === this.g && c.b === this.b;
  5527. }
  5528. fromArray(array, offset = 0) {
  5529. this.r = array[offset];
  5530. this.g = array[offset + 1];
  5531. this.b = array[offset + 2];
  5532. return this;
  5533. }
  5534. toArray(array = [], offset = 0) {
  5535. array[offset] = this.r;
  5536. array[offset + 1] = this.g;
  5537. array[offset + 2] = this.b;
  5538. return array;
  5539. }
  5540. fromBufferAttribute(attribute, index) {
  5541. this.r = attribute.getX(index);
  5542. this.g = attribute.getY(index);
  5543. this.b = attribute.getZ(index);
  5544. if (attribute.normalized === true) {
  5545. // assuming Uint8Array
  5546. this.r /= 255;
  5547. this.g /= 255;
  5548. this.b /= 255;
  5549. }
  5550. return this;
  5551. }
  5552. toJSON() {
  5553. return this.getHex();
  5554. }
  5555. }
  5556. Color.NAMES = _colorKeywords;
  5557. Color.prototype.isColor = true;
  5558. Color.prototype.r = 1;
  5559. Color.prototype.g = 1;
  5560. Color.prototype.b = 1;
  5561. /**
  5562. * parameters = {
  5563. * color: <hex>,
  5564. * opacity: <float>,
  5565. * map: new THREE.Texture( <Image> ),
  5566. *
  5567. * lightMap: new THREE.Texture( <Image> ),
  5568. * lightMapIntensity: <float>
  5569. *
  5570. * aoMap: new THREE.Texture( <Image> ),
  5571. * aoMapIntensity: <float>
  5572. *
  5573. * specularMap: new THREE.Texture( <Image> ),
  5574. *
  5575. * alphaMap: new THREE.Texture( <Image> ),
  5576. *
  5577. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  5578. * combine: THREE.Multiply,
  5579. * reflectivity: <float>,
  5580. * refractionRatio: <float>,
  5581. *
  5582. * depthTest: <bool>,
  5583. * depthWrite: <bool>,
  5584. *
  5585. * wireframe: <boolean>,
  5586. * wireframeLinewidth: <float>,
  5587. * }
  5588. */
  5589. class MeshBasicMaterial extends Material {
  5590. constructor(parameters) {
  5591. super();
  5592. this.type = 'MeshBasicMaterial';
  5593. this.color = new Color(0xffffff); // emissive
  5594. this.map = null;
  5595. this.lightMap = null;
  5596. this.lightMapIntensity = 1.0;
  5597. this.aoMap = null;
  5598. this.aoMapIntensity = 1.0;
  5599. this.specularMap = null;
  5600. this.alphaMap = null;
  5601. this.envMap = null;
  5602. this.combine = MultiplyOperation;
  5603. this.reflectivity = 1;
  5604. this.refractionRatio = 0.98;
  5605. this.wireframe = false;
  5606. this.wireframeLinewidth = 1;
  5607. this.wireframeLinecap = 'round';
  5608. this.wireframeLinejoin = 'round';
  5609. this.setValues(parameters);
  5610. }
  5611. copy(source) {
  5612. super.copy(source);
  5613. this.color.copy(source.color);
  5614. this.map = source.map;
  5615. this.lightMap = source.lightMap;
  5616. this.lightMapIntensity = source.lightMapIntensity;
  5617. this.aoMap = source.aoMap;
  5618. this.aoMapIntensity = source.aoMapIntensity;
  5619. this.specularMap = source.specularMap;
  5620. this.alphaMap = source.alphaMap;
  5621. this.envMap = source.envMap;
  5622. this.combine = source.combine;
  5623. this.reflectivity = source.reflectivity;
  5624. this.refractionRatio = source.refractionRatio;
  5625. this.wireframe = source.wireframe;
  5626. this.wireframeLinewidth = source.wireframeLinewidth;
  5627. this.wireframeLinecap = source.wireframeLinecap;
  5628. this.wireframeLinejoin = source.wireframeLinejoin;
  5629. return this;
  5630. }
  5631. }
  5632. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  5633. const _vector$9 = /*@__PURE__*/new Vector3();
  5634. const _vector2$1 = /*@__PURE__*/new Vector2();
  5635. class BufferAttribute {
  5636. constructor(array, itemSize, normalized) {
  5637. if (Array.isArray(array)) {
  5638. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  5639. }
  5640. this.name = '';
  5641. this.array = array;
  5642. this.itemSize = itemSize;
  5643. this.count = array !== undefined ? array.length / itemSize : 0;
  5644. this.normalized = normalized === true;
  5645. this.usage = StaticDrawUsage;
  5646. this.updateRange = {
  5647. offset: 0,
  5648. count: -1
  5649. };
  5650. this.version = 0;
  5651. }
  5652. onUploadCallback() {}
  5653. set needsUpdate(value) {
  5654. if (value === true) this.version++;
  5655. }
  5656. setUsage(value) {
  5657. this.usage = value;
  5658. return this;
  5659. }
  5660. copy(source) {
  5661. this.name = source.name;
  5662. this.array = new source.array.constructor(source.array);
  5663. this.itemSize = source.itemSize;
  5664. this.count = source.count;
  5665. this.normalized = source.normalized;
  5666. this.usage = source.usage;
  5667. return this;
  5668. }
  5669. copyAt(index1, attribute, index2) {
  5670. index1 *= this.itemSize;
  5671. index2 *= attribute.itemSize;
  5672. for (let i = 0, l = this.itemSize; i < l; i++) {
  5673. this.array[index1 + i] = attribute.array[index2 + i];
  5674. }
  5675. return this;
  5676. }
  5677. copyArray(array) {
  5678. this.array.set(array);
  5679. return this;
  5680. }
  5681. copyColorsArray(colors) {
  5682. const array = this.array;
  5683. let offset = 0;
  5684. for (let i = 0, l = colors.length; i < l; i++) {
  5685. let color = colors[i];
  5686. if (color === undefined) {
  5687. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  5688. color = new Color();
  5689. }
  5690. array[offset++] = color.r;
  5691. array[offset++] = color.g;
  5692. array[offset++] = color.b;
  5693. }
  5694. return this;
  5695. }
  5696. copyVector2sArray(vectors) {
  5697. const array = this.array;
  5698. let offset = 0;
  5699. for (let i = 0, l = vectors.length; i < l; i++) {
  5700. let vector = vectors[i];
  5701. if (vector === undefined) {
  5702. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  5703. vector = new Vector2();
  5704. }
  5705. array[offset++] = vector.x;
  5706. array[offset++] = vector.y;
  5707. }
  5708. return this;
  5709. }
  5710. copyVector3sArray(vectors) {
  5711. const array = this.array;
  5712. let offset = 0;
  5713. for (let i = 0, l = vectors.length; i < l; i++) {
  5714. let vector = vectors[i];
  5715. if (vector === undefined) {
  5716. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  5717. vector = new Vector3();
  5718. }
  5719. array[offset++] = vector.x;
  5720. array[offset++] = vector.y;
  5721. array[offset++] = vector.z;
  5722. }
  5723. return this;
  5724. }
  5725. copyVector4sArray(vectors) {
  5726. const array = this.array;
  5727. let offset = 0;
  5728. for (let i = 0, l = vectors.length; i < l; i++) {
  5729. let vector = vectors[i];
  5730. if (vector === undefined) {
  5731. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  5732. vector = new Vector4();
  5733. }
  5734. array[offset++] = vector.x;
  5735. array[offset++] = vector.y;
  5736. array[offset++] = vector.z;
  5737. array[offset++] = vector.w;
  5738. }
  5739. return this;
  5740. }
  5741. applyMatrix3(m) {
  5742. if (this.itemSize === 2) {
  5743. for (let i = 0, l = this.count; i < l; i++) {
  5744. _vector2$1.fromBufferAttribute(this, i);
  5745. _vector2$1.applyMatrix3(m);
  5746. this.setXY(i, _vector2$1.x, _vector2$1.y);
  5747. }
  5748. } else if (this.itemSize === 3) {
  5749. for (let i = 0, l = this.count; i < l; i++) {
  5750. _vector$9.fromBufferAttribute(this, i);
  5751. _vector$9.applyMatrix3(m);
  5752. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5753. }
  5754. }
  5755. return this;
  5756. }
  5757. applyMatrix4(m) {
  5758. for (let i = 0, l = this.count; i < l; i++) {
  5759. _vector$9.x = this.getX(i);
  5760. _vector$9.y = this.getY(i);
  5761. _vector$9.z = this.getZ(i);
  5762. _vector$9.applyMatrix4(m);
  5763. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5764. }
  5765. return this;
  5766. }
  5767. applyNormalMatrix(m) {
  5768. for (let i = 0, l = this.count; i < l; i++) {
  5769. _vector$9.x = this.getX(i);
  5770. _vector$9.y = this.getY(i);
  5771. _vector$9.z = this.getZ(i);
  5772. _vector$9.applyNormalMatrix(m);
  5773. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5774. }
  5775. return this;
  5776. }
  5777. transformDirection(m) {
  5778. for (let i = 0, l = this.count; i < l; i++) {
  5779. _vector$9.x = this.getX(i);
  5780. _vector$9.y = this.getY(i);
  5781. _vector$9.z = this.getZ(i);
  5782. _vector$9.transformDirection(m);
  5783. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5784. }
  5785. return this;
  5786. }
  5787. set(value, offset = 0) {
  5788. this.array.set(value, offset);
  5789. return this;
  5790. }
  5791. getX(index) {
  5792. return this.array[index * this.itemSize];
  5793. }
  5794. setX(index, x) {
  5795. this.array[index * this.itemSize] = x;
  5796. return this;
  5797. }
  5798. getY(index) {
  5799. return this.array[index * this.itemSize + 1];
  5800. }
  5801. setY(index, y) {
  5802. this.array[index * this.itemSize + 1] = y;
  5803. return this;
  5804. }
  5805. getZ(index) {
  5806. return this.array[index * this.itemSize + 2];
  5807. }
  5808. setZ(index, z) {
  5809. this.array[index * this.itemSize + 2] = z;
  5810. return this;
  5811. }
  5812. getW(index) {
  5813. return this.array[index * this.itemSize + 3];
  5814. }
  5815. setW(index, w) {
  5816. this.array[index * this.itemSize + 3] = w;
  5817. return this;
  5818. }
  5819. setXY(index, x, y) {
  5820. index *= this.itemSize;
  5821. this.array[index + 0] = x;
  5822. this.array[index + 1] = y;
  5823. return this;
  5824. }
  5825. setXYZ(index, x, y, z) {
  5826. index *= this.itemSize;
  5827. this.array[index + 0] = x;
  5828. this.array[index + 1] = y;
  5829. this.array[index + 2] = z;
  5830. return this;
  5831. }
  5832. setXYZW(index, x, y, z, w) {
  5833. index *= this.itemSize;
  5834. this.array[index + 0] = x;
  5835. this.array[index + 1] = y;
  5836. this.array[index + 2] = z;
  5837. this.array[index + 3] = w;
  5838. return this;
  5839. }
  5840. onUpload(callback) {
  5841. this.onUploadCallback = callback;
  5842. return this;
  5843. }
  5844. clone() {
  5845. return new this.constructor(this.array, this.itemSize).copy(this);
  5846. }
  5847. toJSON() {
  5848. const data = {
  5849. itemSize: this.itemSize,
  5850. type: this.array.constructor.name,
  5851. array: Array.prototype.slice.call(this.array),
  5852. normalized: this.normalized
  5853. };
  5854. if (this.name !== '') data.name = this.name;
  5855. if (this.usage !== StaticDrawUsage) data.usage = this.usage;
  5856. if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange;
  5857. return data;
  5858. }
  5859. }
  5860. BufferAttribute.prototype.isBufferAttribute = true; //
  5861. class Int8BufferAttribute extends BufferAttribute {
  5862. constructor(array, itemSize, normalized) {
  5863. super(new Int8Array(array), itemSize, normalized);
  5864. }
  5865. }
  5866. class Uint8BufferAttribute extends BufferAttribute {
  5867. constructor(array, itemSize, normalized) {
  5868. super(new Uint8Array(array), itemSize, normalized);
  5869. }
  5870. }
  5871. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5872. constructor(array, itemSize, normalized) {
  5873. super(new Uint8ClampedArray(array), itemSize, normalized);
  5874. }
  5875. }
  5876. class Int16BufferAttribute extends BufferAttribute {
  5877. constructor(array, itemSize, normalized) {
  5878. super(new Int16Array(array), itemSize, normalized);
  5879. }
  5880. }
  5881. class Uint16BufferAttribute extends BufferAttribute {
  5882. constructor(array, itemSize, normalized) {
  5883. super(new Uint16Array(array), itemSize, normalized);
  5884. }
  5885. }
  5886. class Int32BufferAttribute extends BufferAttribute {
  5887. constructor(array, itemSize, normalized) {
  5888. super(new Int32Array(array), itemSize, normalized);
  5889. }
  5890. }
  5891. class Uint32BufferAttribute extends BufferAttribute {
  5892. constructor(array, itemSize, normalized) {
  5893. super(new Uint32Array(array), itemSize, normalized);
  5894. }
  5895. }
  5896. class Float16BufferAttribute extends BufferAttribute {
  5897. constructor(array, itemSize, normalized) {
  5898. super(new Uint16Array(array), itemSize, normalized);
  5899. }
  5900. }
  5901. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  5902. class Float32BufferAttribute extends BufferAttribute {
  5903. constructor(array, itemSize, normalized) {
  5904. super(new Float32Array(array), itemSize, normalized);
  5905. }
  5906. }
  5907. class Float64BufferAttribute extends BufferAttribute {
  5908. constructor(array, itemSize, normalized) {
  5909. super(new Float64Array(array), itemSize, normalized);
  5910. }
  5911. } //
  5912. function arrayMax(array) {
  5913. if (array.length === 0) return -Infinity;
  5914. let max = array[0];
  5915. for (let i = 1, l = array.length; i < l; ++i) {
  5916. if (array[i] > max) max = array[i];
  5917. }
  5918. return max;
  5919. }
  5920. const TYPED_ARRAYS = {
  5921. Int8Array: Int8Array,
  5922. Uint8Array: Uint8Array,
  5923. Uint8ClampedArray: Uint8ClampedArray,
  5924. Int16Array: Int16Array,
  5925. Uint16Array: Uint16Array,
  5926. Int32Array: Int32Array,
  5927. Uint32Array: Uint32Array,
  5928. Float32Array: Float32Array,
  5929. Float64Array: Float64Array
  5930. };
  5931. function getTypedArray(type, buffer) {
  5932. return new TYPED_ARRAYS[type](buffer);
  5933. }
  5934. let _id = 0;
  5935. const _m1 = /*@__PURE__*/new Matrix4();
  5936. const _obj = /*@__PURE__*/new Object3D();
  5937. const _offset = /*@__PURE__*/new Vector3();
  5938. const _box$1 = /*@__PURE__*/new Box3();
  5939. const _boxMorphTargets = /*@__PURE__*/new Box3();
  5940. const _vector$8 = /*@__PURE__*/new Vector3();
  5941. class BufferGeometry extends EventDispatcher {
  5942. constructor() {
  5943. super();
  5944. Object.defineProperty(this, 'id', {
  5945. value: _id++
  5946. });
  5947. this.uuid = generateUUID();
  5948. this.name = '';
  5949. this.type = 'BufferGeometry';
  5950. this.index = null;
  5951. this.attributes = {};
  5952. this.morphAttributes = {};
  5953. this.morphTargetsRelative = false;
  5954. this.groups = [];
  5955. this.boundingBox = null;
  5956. this.boundingSphere = null;
  5957. this.drawRange = {
  5958. start: 0,
  5959. count: Infinity
  5960. };
  5961. this.userData = {};
  5962. }
  5963. getIndex() {
  5964. return this.index;
  5965. }
  5966. setIndex(index) {
  5967. if (Array.isArray(index)) {
  5968. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  5969. } else {
  5970. this.index = index;
  5971. }
  5972. return this;
  5973. }
  5974. getAttribute(name) {
  5975. return this.attributes[name];
  5976. }
  5977. setAttribute(name, attribute) {
  5978. this.attributes[name] = attribute;
  5979. return this;
  5980. }
  5981. deleteAttribute(name) {
  5982. delete this.attributes[name];
  5983. return this;
  5984. }
  5985. hasAttribute(name) {
  5986. return this.attributes[name] !== undefined;
  5987. }
  5988. addGroup(start, count, materialIndex = 0) {
  5989. this.groups.push({
  5990. start: start,
  5991. count: count,
  5992. materialIndex: materialIndex
  5993. });
  5994. }
  5995. clearGroups() {
  5996. this.groups = [];
  5997. }
  5998. setDrawRange(start, count) {
  5999. this.drawRange.start = start;
  6000. this.drawRange.count = count;
  6001. }
  6002. applyMatrix4(matrix) {
  6003. const position = this.attributes.position;
  6004. if (position !== undefined) {
  6005. position.applyMatrix4(matrix);
  6006. position.needsUpdate = true;
  6007. }
  6008. const normal = this.attributes.normal;
  6009. if (normal !== undefined) {
  6010. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6011. normal.applyNormalMatrix(normalMatrix);
  6012. normal.needsUpdate = true;
  6013. }
  6014. const tangent = this.attributes.tangent;
  6015. if (tangent !== undefined) {
  6016. tangent.transformDirection(matrix);
  6017. tangent.needsUpdate = true;
  6018. }
  6019. if (this.boundingBox !== null) {
  6020. this.computeBoundingBox();
  6021. }
  6022. if (this.boundingSphere !== null) {
  6023. this.computeBoundingSphere();
  6024. }
  6025. return this;
  6026. }
  6027. applyQuaternion(q) {
  6028. _m1.makeRotationFromQuaternion(q);
  6029. this.applyMatrix4(_m1);
  6030. return this;
  6031. }
  6032. rotateX(angle) {
  6033. // rotate geometry around world x-axis
  6034. _m1.makeRotationX(angle);
  6035. this.applyMatrix4(_m1);
  6036. return this;
  6037. }
  6038. rotateY(angle) {
  6039. // rotate geometry around world y-axis
  6040. _m1.makeRotationY(angle);
  6041. this.applyMatrix4(_m1);
  6042. return this;
  6043. }
  6044. rotateZ(angle) {
  6045. // rotate geometry around world z-axis
  6046. _m1.makeRotationZ(angle);
  6047. this.applyMatrix4(_m1);
  6048. return this;
  6049. }
  6050. translate(x, y, z) {
  6051. // translate geometry
  6052. _m1.makeTranslation(x, y, z);
  6053. this.applyMatrix4(_m1);
  6054. return this;
  6055. }
  6056. scale(x, y, z) {
  6057. // scale geometry
  6058. _m1.makeScale(x, y, z);
  6059. this.applyMatrix4(_m1);
  6060. return this;
  6061. }
  6062. lookAt(vector) {
  6063. _obj.lookAt(vector);
  6064. _obj.updateMatrix();
  6065. this.applyMatrix4(_obj.matrix);
  6066. return this;
  6067. }
  6068. center() {
  6069. this.computeBoundingBox();
  6070. this.boundingBox.getCenter(_offset).negate();
  6071. this.translate(_offset.x, _offset.y, _offset.z);
  6072. return this;
  6073. }
  6074. setFromPoints(points) {
  6075. const position = [];
  6076. for (let i = 0, l = points.length; i < l; i++) {
  6077. const point = points[i];
  6078. position.push(point.x, point.y, point.z || 0);
  6079. }
  6080. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6081. return this;
  6082. }
  6083. computeBoundingBox() {
  6084. if (this.boundingBox === null) {
  6085. this.boundingBox = new Box3();
  6086. }
  6087. const position = this.attributes.position;
  6088. const morphAttributesPosition = this.morphAttributes.position;
  6089. if (position && position.isGLBufferAttribute) {
  6090. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  6091. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  6092. return;
  6093. }
  6094. if (position !== undefined) {
  6095. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  6096. if (morphAttributesPosition) {
  6097. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6098. const morphAttribute = morphAttributesPosition[i];
  6099. _box$1.setFromBufferAttribute(morphAttribute);
  6100. if (this.morphTargetsRelative) {
  6101. _vector$8.addVectors(this.boundingBox.min, _box$1.min);
  6102. this.boundingBox.expandByPoint(_vector$8);
  6103. _vector$8.addVectors(this.boundingBox.max, _box$1.max);
  6104. this.boundingBox.expandByPoint(_vector$8);
  6105. } else {
  6106. this.boundingBox.expandByPoint(_box$1.min);
  6107. this.boundingBox.expandByPoint(_box$1.max);
  6108. }
  6109. }
  6110. }
  6111. } else {
  6112. this.boundingBox.makeEmpty();
  6113. }
  6114. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  6115. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  6116. }
  6117. }
  6118. computeBoundingSphere() {
  6119. if (this.boundingSphere === null) {
  6120. this.boundingSphere = new Sphere();
  6121. }
  6122. const position = this.attributes.position;
  6123. const morphAttributesPosition = this.morphAttributes.position;
  6124. if (position && position.isGLBufferAttribute) {
  6125. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  6126. this.boundingSphere.set(new Vector3(), Infinity);
  6127. return;
  6128. }
  6129. if (position) {
  6130. // first, find the center of the bounding sphere
  6131. const center = this.boundingSphere.center;
  6132. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  6133. if (morphAttributesPosition) {
  6134. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6135. const morphAttribute = morphAttributesPosition[i];
  6136. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  6137. if (this.morphTargetsRelative) {
  6138. _vector$8.addVectors(_box$1.min, _boxMorphTargets.min);
  6139. _box$1.expandByPoint(_vector$8);
  6140. _vector$8.addVectors(_box$1.max, _boxMorphTargets.max);
  6141. _box$1.expandByPoint(_vector$8);
  6142. } else {
  6143. _box$1.expandByPoint(_boxMorphTargets.min);
  6144. _box$1.expandByPoint(_boxMorphTargets.max);
  6145. }
  6146. }
  6147. }
  6148. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  6149. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6150. let maxRadiusSq = 0;
  6151. for (let i = 0, il = position.count; i < il; i++) {
  6152. _vector$8.fromBufferAttribute(position, i);
  6153. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6154. } // process morph attributes if present
  6155. if (morphAttributesPosition) {
  6156. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6157. const morphAttribute = morphAttributesPosition[i];
  6158. const morphTargetsRelative = this.morphTargetsRelative;
  6159. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  6160. _vector$8.fromBufferAttribute(morphAttribute, j);
  6161. if (morphTargetsRelative) {
  6162. _offset.fromBufferAttribute(position, j);
  6163. _vector$8.add(_offset);
  6164. }
  6165. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6166. }
  6167. }
  6168. }
  6169. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  6170. if (isNaN(this.boundingSphere.radius)) {
  6171. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  6172. }
  6173. }
  6174. }
  6175. computeFaceNormals() {// backwards compatibility
  6176. }
  6177. computeTangents() {
  6178. const index = this.index;
  6179. const attributes = this.attributes; // based on http://www.terathon.com/code/tangent.html
  6180. // (per vertex tangents)
  6181. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  6182. console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  6183. return;
  6184. }
  6185. const indices = index.array;
  6186. const positions = attributes.position.array;
  6187. const normals = attributes.normal.array;
  6188. const uvs = attributes.uv.array;
  6189. const nVertices = positions.length / 3;
  6190. if (attributes.tangent === undefined) {
  6191. this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
  6192. }
  6193. const tangents = attributes.tangent.array;
  6194. const tan1 = [],
  6195. tan2 = [];
  6196. for (let i = 0; i < nVertices; i++) {
  6197. tan1[i] = new Vector3();
  6198. tan2[i] = new Vector3();
  6199. }
  6200. const vA = new Vector3(),
  6201. vB = new Vector3(),
  6202. vC = new Vector3(),
  6203. uvA = new Vector2(),
  6204. uvB = new Vector2(),
  6205. uvC = new Vector2(),
  6206. sdir = new Vector3(),
  6207. tdir = new Vector3();
  6208. function handleTriangle(a, b, c) {
  6209. vA.fromArray(positions, a * 3);
  6210. vB.fromArray(positions, b * 3);
  6211. vC.fromArray(positions, c * 3);
  6212. uvA.fromArray(uvs, a * 2);
  6213. uvB.fromArray(uvs, b * 2);
  6214. uvC.fromArray(uvs, c * 2);
  6215. vB.sub(vA);
  6216. vC.sub(vA);
  6217. uvB.sub(uvA);
  6218. uvC.sub(uvA);
  6219. const r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  6220. if (!isFinite(r)) return;
  6221. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  6222. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  6223. tan1[a].add(sdir);
  6224. tan1[b].add(sdir);
  6225. tan1[c].add(sdir);
  6226. tan2[a].add(tdir);
  6227. tan2[b].add(tdir);
  6228. tan2[c].add(tdir);
  6229. }
  6230. let groups = this.groups;
  6231. if (groups.length === 0) {
  6232. groups = [{
  6233. start: 0,
  6234. count: indices.length
  6235. }];
  6236. }
  6237. for (let i = 0, il = groups.length; i < il; ++i) {
  6238. const group = groups[i];
  6239. const start = group.start;
  6240. const count = group.count;
  6241. for (let j = start, jl = start + count; j < jl; j += 3) {
  6242. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  6243. }
  6244. }
  6245. const tmp = new Vector3(),
  6246. tmp2 = new Vector3();
  6247. const n = new Vector3(),
  6248. n2 = new Vector3();
  6249. function handleVertex(v) {
  6250. n.fromArray(normals, v * 3);
  6251. n2.copy(n);
  6252. const t = tan1[v]; // Gram-Schmidt orthogonalize
  6253. tmp.copy(t);
  6254. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  6255. tmp2.crossVectors(n2, t);
  6256. const test = tmp2.dot(tan2[v]);
  6257. const w = test < 0.0 ? -1.0 : 1.0;
  6258. tangents[v * 4] = tmp.x;
  6259. tangents[v * 4 + 1] = tmp.y;
  6260. tangents[v * 4 + 2] = tmp.z;
  6261. tangents[v * 4 + 3] = w;
  6262. }
  6263. for (let i = 0, il = groups.length; i < il; ++i) {
  6264. const group = groups[i];
  6265. const start = group.start;
  6266. const count = group.count;
  6267. for (let j = start, jl = start + count; j < jl; j += 3) {
  6268. handleVertex(indices[j + 0]);
  6269. handleVertex(indices[j + 1]);
  6270. handleVertex(indices[j + 2]);
  6271. }
  6272. }
  6273. }
  6274. computeVertexNormals() {
  6275. const index = this.index;
  6276. const positionAttribute = this.getAttribute('position');
  6277. if (positionAttribute !== undefined) {
  6278. let normalAttribute = this.getAttribute('normal');
  6279. if (normalAttribute === undefined) {
  6280. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  6281. this.setAttribute('normal', normalAttribute);
  6282. } else {
  6283. // reset existing normals to zero
  6284. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  6285. normalAttribute.setXYZ(i, 0, 0, 0);
  6286. }
  6287. }
  6288. const pA = new Vector3(),
  6289. pB = new Vector3(),
  6290. pC = new Vector3();
  6291. const nA = new Vector3(),
  6292. nB = new Vector3(),
  6293. nC = new Vector3();
  6294. const cb = new Vector3(),
  6295. ab = new Vector3(); // indexed elements
  6296. if (index) {
  6297. for (let i = 0, il = index.count; i < il; i += 3) {
  6298. const vA = index.getX(i + 0);
  6299. const vB = index.getX(i + 1);
  6300. const vC = index.getX(i + 2);
  6301. pA.fromBufferAttribute(positionAttribute, vA);
  6302. pB.fromBufferAttribute(positionAttribute, vB);
  6303. pC.fromBufferAttribute(positionAttribute, vC);
  6304. cb.subVectors(pC, pB);
  6305. ab.subVectors(pA, pB);
  6306. cb.cross(ab);
  6307. nA.fromBufferAttribute(normalAttribute, vA);
  6308. nB.fromBufferAttribute(normalAttribute, vB);
  6309. nC.fromBufferAttribute(normalAttribute, vC);
  6310. nA.add(cb);
  6311. nB.add(cb);
  6312. nC.add(cb);
  6313. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  6314. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  6315. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  6316. }
  6317. } else {
  6318. // non-indexed elements (unconnected triangle soup)
  6319. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  6320. pA.fromBufferAttribute(positionAttribute, i + 0);
  6321. pB.fromBufferAttribute(positionAttribute, i + 1);
  6322. pC.fromBufferAttribute(positionAttribute, i + 2);
  6323. cb.subVectors(pC, pB);
  6324. ab.subVectors(pA, pB);
  6325. cb.cross(ab);
  6326. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  6327. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  6328. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  6329. }
  6330. }
  6331. this.normalizeNormals();
  6332. normalAttribute.needsUpdate = true;
  6333. }
  6334. }
  6335. merge(geometry, offset) {
  6336. if (!(geometry && geometry.isBufferGeometry)) {
  6337. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  6338. return;
  6339. }
  6340. if (offset === undefined) {
  6341. offset = 0;
  6342. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  6343. }
  6344. const attributes = this.attributes;
  6345. for (const key in attributes) {
  6346. if (geometry.attributes[key] === undefined) continue;
  6347. const attribute1 = attributes[key];
  6348. const attributeArray1 = attribute1.array;
  6349. const attribute2 = geometry.attributes[key];
  6350. const attributeArray2 = attribute2.array;
  6351. const attributeOffset = attribute2.itemSize * offset;
  6352. const length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  6353. for (let i = 0, j = attributeOffset; i < length; i++, j++) {
  6354. attributeArray1[j] = attributeArray2[i];
  6355. }
  6356. }
  6357. return this;
  6358. }
  6359. normalizeNormals() {
  6360. const normals = this.attributes.normal;
  6361. for (let i = 0, il = normals.count; i < il; i++) {
  6362. _vector$8.fromBufferAttribute(normals, i);
  6363. _vector$8.normalize();
  6364. normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z);
  6365. }
  6366. }
  6367. toNonIndexed() {
  6368. function convertBufferAttribute(attribute, indices) {
  6369. const array = attribute.array;
  6370. const itemSize = attribute.itemSize;
  6371. const normalized = attribute.normalized;
  6372. const array2 = new array.constructor(indices.length * itemSize);
  6373. let index = 0,
  6374. index2 = 0;
  6375. for (let i = 0, l = indices.length; i < l; i++) {
  6376. if (attribute.isInterleavedBufferAttribute) {
  6377. index = indices[i] * attribute.data.stride + attribute.offset;
  6378. } else {
  6379. index = indices[i] * itemSize;
  6380. }
  6381. for (let j = 0; j < itemSize; j++) {
  6382. array2[index2++] = array[index++];
  6383. }
  6384. }
  6385. return new BufferAttribute(array2, itemSize, normalized);
  6386. } //
  6387. if (this.index === null) {
  6388. console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
  6389. return this;
  6390. }
  6391. const geometry2 = new BufferGeometry();
  6392. const indices = this.index.array;
  6393. const attributes = this.attributes; // attributes
  6394. for (const name in attributes) {
  6395. const attribute = attributes[name];
  6396. const newAttribute = convertBufferAttribute(attribute, indices);
  6397. geometry2.setAttribute(name, newAttribute);
  6398. } // morph attributes
  6399. const morphAttributes = this.morphAttributes;
  6400. for (const name in morphAttributes) {
  6401. const morphArray = [];
  6402. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6403. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  6404. const attribute = morphAttribute[i];
  6405. const newAttribute = convertBufferAttribute(attribute, indices);
  6406. morphArray.push(newAttribute);
  6407. }
  6408. geometry2.morphAttributes[name] = morphArray;
  6409. }
  6410. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  6411. const groups = this.groups;
  6412. for (let i = 0, l = groups.length; i < l; i++) {
  6413. const group = groups[i];
  6414. geometry2.addGroup(group.start, group.count, group.materialIndex);
  6415. }
  6416. return geometry2;
  6417. }
  6418. toJSON() {
  6419. const data = {
  6420. metadata: {
  6421. version: 4.5,
  6422. type: 'BufferGeometry',
  6423. generator: 'BufferGeometry.toJSON'
  6424. }
  6425. }; // standard BufferGeometry serialization
  6426. data.uuid = this.uuid;
  6427. data.type = this.type;
  6428. if (this.name !== '') data.name = this.name;
  6429. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  6430. if (this.parameters !== undefined) {
  6431. const parameters = this.parameters;
  6432. for (const key in parameters) {
  6433. if (parameters[key] !== undefined) data[key] = parameters[key];
  6434. }
  6435. return data;
  6436. } // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6437. data.data = {
  6438. attributes: {}
  6439. };
  6440. const index = this.index;
  6441. if (index !== null) {
  6442. data.data.index = {
  6443. type: index.array.constructor.name,
  6444. array: Array.prototype.slice.call(index.array)
  6445. };
  6446. }
  6447. const attributes = this.attributes;
  6448. for (const key in attributes) {
  6449. const attribute = attributes[key];
  6450. data.data.attributes[key] = attribute.toJSON(data.data);
  6451. }
  6452. const morphAttributes = {};
  6453. let hasMorphAttributes = false;
  6454. for (const key in this.morphAttributes) {
  6455. const attributeArray = this.morphAttributes[key];
  6456. const array = [];
  6457. for (let i = 0, il = attributeArray.length; i < il; i++) {
  6458. const attribute = attributeArray[i];
  6459. array.push(attribute.toJSON(data.data));
  6460. }
  6461. if (array.length > 0) {
  6462. morphAttributes[key] = array;
  6463. hasMorphAttributes = true;
  6464. }
  6465. }
  6466. if (hasMorphAttributes) {
  6467. data.data.morphAttributes = morphAttributes;
  6468. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6469. }
  6470. const groups = this.groups;
  6471. if (groups.length > 0) {
  6472. data.data.groups = JSON.parse(JSON.stringify(groups));
  6473. }
  6474. const boundingSphere = this.boundingSphere;
  6475. if (boundingSphere !== null) {
  6476. data.data.boundingSphere = {
  6477. center: boundingSphere.center.toArray(),
  6478. radius: boundingSphere.radius
  6479. };
  6480. }
  6481. return data;
  6482. }
  6483. clone() {
  6484. /*
  6485. // Handle primitives
  6486. const parameters = this.parameters;
  6487. if ( parameters !== undefined ) {
  6488. const values = [];
  6489. for ( const key in parameters ) {
  6490. values.push( parameters[ key ] );
  6491. }
  6492. const geometry = Object.create( this.constructor.prototype );
  6493. this.constructor.apply( geometry, values );
  6494. return geometry;
  6495. }
  6496. return new this.constructor().copy( this );
  6497. */
  6498. return new BufferGeometry().copy(this);
  6499. }
  6500. copy(source) {
  6501. // reset
  6502. this.index = null;
  6503. this.attributes = {};
  6504. this.morphAttributes = {};
  6505. this.groups = [];
  6506. this.boundingBox = null;
  6507. this.boundingSphere = null; // used for storing cloned, shared data
  6508. const data = {}; // name
  6509. this.name = source.name; // index
  6510. const index = source.index;
  6511. if (index !== null) {
  6512. this.setIndex(index.clone(data));
  6513. } // attributes
  6514. const attributes = source.attributes;
  6515. for (const name in attributes) {
  6516. const attribute = attributes[name];
  6517. this.setAttribute(name, attribute.clone(data));
  6518. } // morph attributes
  6519. const morphAttributes = source.morphAttributes;
  6520. for (const name in morphAttributes) {
  6521. const array = [];
  6522. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6523. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  6524. array.push(morphAttribute[i].clone(data));
  6525. }
  6526. this.morphAttributes[name] = array;
  6527. }
  6528. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  6529. const groups = source.groups;
  6530. for (let i = 0, l = groups.length; i < l; i++) {
  6531. const group = groups[i];
  6532. this.addGroup(group.start, group.count, group.materialIndex);
  6533. } // bounding box
  6534. const boundingBox = source.boundingBox;
  6535. if (boundingBox !== null) {
  6536. this.boundingBox = boundingBox.clone();
  6537. } // bounding sphere
  6538. const boundingSphere = source.boundingSphere;
  6539. if (boundingSphere !== null) {
  6540. this.boundingSphere = boundingSphere.clone();
  6541. } // draw range
  6542. this.drawRange.start = source.drawRange.start;
  6543. this.drawRange.count = source.drawRange.count; // user data
  6544. this.userData = source.userData;
  6545. return this;
  6546. }
  6547. dispose() {
  6548. this.dispatchEvent({
  6549. type: 'dispose'
  6550. });
  6551. }
  6552. }
  6553. BufferGeometry.prototype.isBufferGeometry = true;
  6554. const _inverseMatrix$2 = /*@__PURE__*/new Matrix4();
  6555. const _ray$2 = /*@__PURE__*/new Ray();
  6556. const _sphere$3 = /*@__PURE__*/new Sphere();
  6557. const _vA$1 = /*@__PURE__*/new Vector3();
  6558. const _vB$1 = /*@__PURE__*/new Vector3();
  6559. const _vC$1 = /*@__PURE__*/new Vector3();
  6560. const _tempA = /*@__PURE__*/new Vector3();
  6561. const _tempB = /*@__PURE__*/new Vector3();
  6562. const _tempC = /*@__PURE__*/new Vector3();
  6563. const _morphA = /*@__PURE__*/new Vector3();
  6564. const _morphB = /*@__PURE__*/new Vector3();
  6565. const _morphC = /*@__PURE__*/new Vector3();
  6566. const _uvA$1 = /*@__PURE__*/new Vector2();
  6567. const _uvB$1 = /*@__PURE__*/new Vector2();
  6568. const _uvC$1 = /*@__PURE__*/new Vector2();
  6569. const _intersectionPoint = /*@__PURE__*/new Vector3();
  6570. const _intersectionPointWorld = /*@__PURE__*/new Vector3();
  6571. class Mesh extends Object3D {
  6572. constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) {
  6573. super();
  6574. this.type = 'Mesh';
  6575. this.geometry = geometry;
  6576. this.material = material;
  6577. this.updateMorphTargets();
  6578. }
  6579. copy(source) {
  6580. super.copy(source);
  6581. if (source.morphTargetInfluences !== undefined) {
  6582. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6583. }
  6584. if (source.morphTargetDictionary !== undefined) {
  6585. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  6586. }
  6587. this.material = source.material;
  6588. this.geometry = source.geometry;
  6589. return this;
  6590. }
  6591. updateMorphTargets() {
  6592. const geometry = this.geometry;
  6593. if (geometry.isBufferGeometry) {
  6594. const morphAttributes = geometry.morphAttributes;
  6595. const keys = Object.keys(morphAttributes);
  6596. if (keys.length > 0) {
  6597. const morphAttribute = morphAttributes[keys[0]];
  6598. if (morphAttribute !== undefined) {
  6599. this.morphTargetInfluences = [];
  6600. this.morphTargetDictionary = {};
  6601. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  6602. const name = morphAttribute[m].name || String(m);
  6603. this.morphTargetInfluences.push(0);
  6604. this.morphTargetDictionary[name] = m;
  6605. }
  6606. }
  6607. }
  6608. } else {
  6609. const morphTargets = geometry.morphTargets;
  6610. if (morphTargets !== undefined && morphTargets.length > 0) {
  6611. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6612. }
  6613. }
  6614. }
  6615. raycast(raycaster, intersects) {
  6616. const geometry = this.geometry;
  6617. const material = this.material;
  6618. const matrixWorld = this.matrixWorld;
  6619. if (material === undefined) return; // Checking boundingSphere distance to ray
  6620. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  6621. _sphere$3.copy(geometry.boundingSphere);
  6622. _sphere$3.applyMatrix4(matrixWorld);
  6623. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  6624. _inverseMatrix$2.copy(matrixWorld).invert();
  6625. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); // Check boundingBox before continuing
  6626. if (geometry.boundingBox !== null) {
  6627. if (_ray$2.intersectsBox(geometry.boundingBox) === false) return;
  6628. }
  6629. let intersection;
  6630. if (geometry.isBufferGeometry) {
  6631. const index = geometry.index;
  6632. const position = geometry.attributes.position;
  6633. const morphPosition = geometry.morphAttributes.position;
  6634. const morphTargetsRelative = geometry.morphTargetsRelative;
  6635. const uv = geometry.attributes.uv;
  6636. const uv2 = geometry.attributes.uv2;
  6637. const groups = geometry.groups;
  6638. const drawRange = geometry.drawRange;
  6639. if (index !== null) {
  6640. // indexed buffer geometry
  6641. if (Array.isArray(material)) {
  6642. for (let i = 0, il = groups.length; i < il; i++) {
  6643. const group = groups[i];
  6644. const groupMaterial = material[group.materialIndex];
  6645. const start = Math.max(group.start, drawRange.start);
  6646. const end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  6647. for (let j = start, jl = end; j < jl; j += 3) {
  6648. const a = index.getX(j);
  6649. const b = index.getX(j + 1);
  6650. const c = index.getX(j + 2);
  6651. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6652. if (intersection) {
  6653. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  6654. intersection.face.materialIndex = group.materialIndex;
  6655. intersects.push(intersection);
  6656. }
  6657. }
  6658. }
  6659. } else {
  6660. const start = Math.max(0, drawRange.start);
  6661. const end = Math.min(index.count, drawRange.start + drawRange.count);
  6662. for (let i = start, il = end; i < il; i += 3) {
  6663. const a = index.getX(i);
  6664. const b = index.getX(i + 1);
  6665. const c = index.getX(i + 2);
  6666. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6667. if (intersection) {
  6668. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  6669. intersects.push(intersection);
  6670. }
  6671. }
  6672. }
  6673. } else if (position !== undefined) {
  6674. // non-indexed buffer geometry
  6675. if (Array.isArray(material)) {
  6676. for (let i = 0, il = groups.length; i < il; i++) {
  6677. const group = groups[i];
  6678. const groupMaterial = material[group.materialIndex];
  6679. const start = Math.max(group.start, drawRange.start);
  6680. const end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  6681. for (let j = start, jl = end; j < jl; j += 3) {
  6682. const a = j;
  6683. const b = j + 1;
  6684. const c = j + 2;
  6685. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6686. if (intersection) {
  6687. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  6688. intersection.face.materialIndex = group.materialIndex;
  6689. intersects.push(intersection);
  6690. }
  6691. }
  6692. }
  6693. } else {
  6694. const start = Math.max(0, drawRange.start);
  6695. const end = Math.min(position.count, drawRange.start + drawRange.count);
  6696. for (let i = start, il = end; i < il; i += 3) {
  6697. const a = i;
  6698. const b = i + 1;
  6699. const c = i + 2;
  6700. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6701. if (intersection) {
  6702. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  6703. intersects.push(intersection);
  6704. }
  6705. }
  6706. }
  6707. }
  6708. } else if (geometry.isGeometry) {
  6709. console.error('THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6710. }
  6711. }
  6712. }
  6713. Mesh.prototype.isMesh = true;
  6714. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  6715. let intersect;
  6716. if (material.side === BackSide) {
  6717. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  6718. } else {
  6719. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  6720. }
  6721. if (intersect === null) return null;
  6722. _intersectionPointWorld.copy(point);
  6723. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  6724. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  6725. if (distance < raycaster.near || distance > raycaster.far) return null;
  6726. return {
  6727. distance: distance,
  6728. point: _intersectionPointWorld.clone(),
  6729. object: object
  6730. };
  6731. }
  6732. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  6733. _vA$1.fromBufferAttribute(position, a);
  6734. _vB$1.fromBufferAttribute(position, b);
  6735. _vC$1.fromBufferAttribute(position, c);
  6736. const morphInfluences = object.morphTargetInfluences;
  6737. if (morphPosition && morphInfluences) {
  6738. _morphA.set(0, 0, 0);
  6739. _morphB.set(0, 0, 0);
  6740. _morphC.set(0, 0, 0);
  6741. for (let i = 0, il = morphPosition.length; i < il; i++) {
  6742. const influence = morphInfluences[i];
  6743. const morphAttribute = morphPosition[i];
  6744. if (influence === 0) continue;
  6745. _tempA.fromBufferAttribute(morphAttribute, a);
  6746. _tempB.fromBufferAttribute(morphAttribute, b);
  6747. _tempC.fromBufferAttribute(morphAttribute, c);
  6748. if (morphTargetsRelative) {
  6749. _morphA.addScaledVector(_tempA, influence);
  6750. _morphB.addScaledVector(_tempB, influence);
  6751. _morphC.addScaledVector(_tempC, influence);
  6752. } else {
  6753. _morphA.addScaledVector(_tempA.sub(_vA$1), influence);
  6754. _morphB.addScaledVector(_tempB.sub(_vB$1), influence);
  6755. _morphC.addScaledVector(_tempC.sub(_vC$1), influence);
  6756. }
  6757. }
  6758. _vA$1.add(_morphA);
  6759. _vB$1.add(_morphB);
  6760. _vC$1.add(_morphC);
  6761. }
  6762. if (object.isSkinnedMesh) {
  6763. object.boneTransform(a, _vA$1);
  6764. object.boneTransform(b, _vB$1);
  6765. object.boneTransform(c, _vC$1);
  6766. }
  6767. const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
  6768. if (intersection) {
  6769. if (uv) {
  6770. _uvA$1.fromBufferAttribute(uv, a);
  6771. _uvB$1.fromBufferAttribute(uv, b);
  6772. _uvC$1.fromBufferAttribute(uv, c);
  6773. intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6774. }
  6775. if (uv2) {
  6776. _uvA$1.fromBufferAttribute(uv2, a);
  6777. _uvB$1.fromBufferAttribute(uv2, b);
  6778. _uvC$1.fromBufferAttribute(uv2, c);
  6779. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6780. }
  6781. const face = {
  6782. a: a,
  6783. b: b,
  6784. c: c,
  6785. normal: new Vector3(),
  6786. materialIndex: 0
  6787. };
  6788. Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
  6789. intersection.face = face;
  6790. }
  6791. return intersection;
  6792. }
  6793. class BoxGeometry extends BufferGeometry {
  6794. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  6795. super();
  6796. this.type = 'BoxGeometry';
  6797. this.parameters = {
  6798. width: width,
  6799. height: height,
  6800. depth: depth,
  6801. widthSegments: widthSegments,
  6802. heightSegments: heightSegments,
  6803. depthSegments: depthSegments
  6804. };
  6805. const scope = this; // segments
  6806. widthSegments = Math.floor(widthSegments);
  6807. heightSegments = Math.floor(heightSegments);
  6808. depthSegments = Math.floor(depthSegments); // buffers
  6809. const indices = [];
  6810. const vertices = [];
  6811. const normals = [];
  6812. const uvs = []; // helper variables
  6813. let numberOfVertices = 0;
  6814. let groupStart = 0; // build each side of the box geometry
  6815. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  6816. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  6817. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  6818. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  6819. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  6820. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  6821. // build geometry
  6822. this.setIndex(indices);
  6823. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  6824. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  6825. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  6826. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  6827. const segmentWidth = width / gridX;
  6828. const segmentHeight = height / gridY;
  6829. const widthHalf = width / 2;
  6830. const heightHalf = height / 2;
  6831. const depthHalf = depth / 2;
  6832. const gridX1 = gridX + 1;
  6833. const gridY1 = gridY + 1;
  6834. let vertexCounter = 0;
  6835. let groupCount = 0;
  6836. const vector = new Vector3(); // generate vertices, normals and uvs
  6837. for (let iy = 0; iy < gridY1; iy++) {
  6838. const y = iy * segmentHeight - heightHalf;
  6839. for (let ix = 0; ix < gridX1; ix++) {
  6840. const x = ix * segmentWidth - widthHalf; // set values to correct vector component
  6841. vector[u] = x * udir;
  6842. vector[v] = y * vdir;
  6843. vector[w] = depthHalf; // now apply vector to vertex buffer
  6844. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  6845. vector[u] = 0;
  6846. vector[v] = 0;
  6847. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  6848. normals.push(vector.x, vector.y, vector.z); // uvs
  6849. uvs.push(ix / gridX);
  6850. uvs.push(1 - iy / gridY); // counters
  6851. vertexCounter += 1;
  6852. }
  6853. } // indices
  6854. // 1. you need three indices to draw a single face
  6855. // 2. a single segment consists of two faces
  6856. // 3. so we need to generate six (2*3) indices per segment
  6857. for (let iy = 0; iy < gridY; iy++) {
  6858. for (let ix = 0; ix < gridX; ix++) {
  6859. const a = numberOfVertices + ix + gridX1 * iy;
  6860. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  6861. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  6862. const d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  6863. indices.push(a, b, d);
  6864. indices.push(b, c, d); // increase counter
  6865. groupCount += 6;
  6866. }
  6867. } // add a group to the geometry. this will ensure multi material support
  6868. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  6869. groupStart += groupCount; // update total number of vertices
  6870. numberOfVertices += vertexCounter;
  6871. }
  6872. }
  6873. static fromJSON(data) {
  6874. return new BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  6875. }
  6876. }
  6877. /**
  6878. * Uniform Utilities
  6879. */
  6880. function cloneUniforms(src) {
  6881. const dst = {};
  6882. for (const u in src) {
  6883. dst[u] = {};
  6884. for (const p in src[u]) {
  6885. const property = src[u][p];
  6886. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
  6887. dst[u][p] = property.clone();
  6888. } else if (Array.isArray(property)) {
  6889. dst[u][p] = property.slice();
  6890. } else {
  6891. dst[u][p] = property;
  6892. }
  6893. }
  6894. }
  6895. return dst;
  6896. }
  6897. function mergeUniforms(uniforms) {
  6898. const merged = {};
  6899. for (let u = 0; u < uniforms.length; u++) {
  6900. const tmp = cloneUniforms(uniforms[u]);
  6901. for (const p in tmp) {
  6902. merged[p] = tmp[p];
  6903. }
  6904. }
  6905. return merged;
  6906. } // Legacy
  6907. const UniformsUtils = {
  6908. clone: cloneUniforms,
  6909. merge: mergeUniforms
  6910. };
  6911. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6912. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6913. /**
  6914. * parameters = {
  6915. * defines: { "label" : "value" },
  6916. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  6917. *
  6918. * fragmentShader: <string>,
  6919. * vertexShader: <string>,
  6920. *
  6921. * wireframe: <boolean>,
  6922. * wireframeLinewidth: <float>,
  6923. *
  6924. * lights: <bool>
  6925. * }
  6926. */
  6927. class ShaderMaterial extends Material {
  6928. constructor(parameters) {
  6929. super();
  6930. this.type = 'ShaderMaterial';
  6931. this.defines = {};
  6932. this.uniforms = {};
  6933. this.vertexShader = default_vertex;
  6934. this.fragmentShader = default_fragment;
  6935. this.linewidth = 1;
  6936. this.wireframe = false;
  6937. this.wireframeLinewidth = 1;
  6938. this.fog = false; // set to use scene fog
  6939. this.lights = false; // set to use scene lights
  6940. this.clipping = false; // set to use user-defined clipping planes
  6941. this.extensions = {
  6942. derivatives: false,
  6943. // set to use derivatives
  6944. fragDepth: false,
  6945. // set to use fragment depth values
  6946. drawBuffers: false,
  6947. // set to use draw buffers
  6948. shaderTextureLOD: false // set to use shader texture LOD
  6949. }; // When rendered geometry doesn't include these attributes but the material does,
  6950. // use these default values in WebGL. This avoids errors when buffer data is missing.
  6951. this.defaultAttributeValues = {
  6952. 'color': [1, 1, 1],
  6953. 'uv': [0, 0],
  6954. 'uv2': [0, 0]
  6955. };
  6956. this.index0AttributeName = undefined;
  6957. this.uniformsNeedUpdate = false;
  6958. this.glslVersion = null;
  6959. if (parameters !== undefined) {
  6960. if (parameters.attributes !== undefined) {
  6961. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  6962. }
  6963. this.setValues(parameters);
  6964. }
  6965. }
  6966. copy(source) {
  6967. super.copy(source);
  6968. this.fragmentShader = source.fragmentShader;
  6969. this.vertexShader = source.vertexShader;
  6970. this.uniforms = cloneUniforms(source.uniforms);
  6971. this.defines = Object.assign({}, source.defines);
  6972. this.wireframe = source.wireframe;
  6973. this.wireframeLinewidth = source.wireframeLinewidth;
  6974. this.lights = source.lights;
  6975. this.clipping = source.clipping;
  6976. this.extensions = Object.assign({}, source.extensions);
  6977. this.glslVersion = source.glslVersion;
  6978. return this;
  6979. }
  6980. toJSON(meta) {
  6981. const data = super.toJSON(meta);
  6982. data.glslVersion = this.glslVersion;
  6983. data.uniforms = {};
  6984. for (const name in this.uniforms) {
  6985. const uniform = this.uniforms[name];
  6986. const value = uniform.value;
  6987. if (value && value.isTexture) {
  6988. data.uniforms[name] = {
  6989. type: 't',
  6990. value: value.toJSON(meta).uuid
  6991. };
  6992. } else if (value && value.isColor) {
  6993. data.uniforms[name] = {
  6994. type: 'c',
  6995. value: value.getHex()
  6996. };
  6997. } else if (value && value.isVector2) {
  6998. data.uniforms[name] = {
  6999. type: 'v2',
  7000. value: value.toArray()
  7001. };
  7002. } else if (value && value.isVector3) {
  7003. data.uniforms[name] = {
  7004. type: 'v3',
  7005. value: value.toArray()
  7006. };
  7007. } else if (value && value.isVector4) {
  7008. data.uniforms[name] = {
  7009. type: 'v4',
  7010. value: value.toArray()
  7011. };
  7012. } else if (value && value.isMatrix3) {
  7013. data.uniforms[name] = {
  7014. type: 'm3',
  7015. value: value.toArray()
  7016. };
  7017. } else if (value && value.isMatrix4) {
  7018. data.uniforms[name] = {
  7019. type: 'm4',
  7020. value: value.toArray()
  7021. };
  7022. } else {
  7023. data.uniforms[name] = {
  7024. value: value
  7025. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7026. }
  7027. }
  7028. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  7029. data.vertexShader = this.vertexShader;
  7030. data.fragmentShader = this.fragmentShader;
  7031. const extensions = {};
  7032. for (const key in this.extensions) {
  7033. if (this.extensions[key] === true) extensions[key] = true;
  7034. }
  7035. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  7036. return data;
  7037. }
  7038. }
  7039. ShaderMaterial.prototype.isShaderMaterial = true;
  7040. class Camera extends Object3D {
  7041. constructor() {
  7042. super();
  7043. this.type = 'Camera';
  7044. this.matrixWorldInverse = new Matrix4();
  7045. this.projectionMatrix = new Matrix4();
  7046. this.projectionMatrixInverse = new Matrix4();
  7047. }
  7048. copy(source, recursive) {
  7049. super.copy(source, recursive);
  7050. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  7051. this.projectionMatrix.copy(source.projectionMatrix);
  7052. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  7053. return this;
  7054. }
  7055. getWorldDirection(target) {
  7056. this.updateWorldMatrix(true, false);
  7057. const e = this.matrixWorld.elements;
  7058. return target.set(-e[8], -e[9], -e[10]).normalize();
  7059. }
  7060. updateMatrixWorld(force) {
  7061. super.updateMatrixWorld(force);
  7062. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7063. }
  7064. updateWorldMatrix(updateParents, updateChildren) {
  7065. super.updateWorldMatrix(updateParents, updateChildren);
  7066. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7067. }
  7068. clone() {
  7069. return new this.constructor().copy(this);
  7070. }
  7071. }
  7072. Camera.prototype.isCamera = true;
  7073. class PerspectiveCamera extends Camera {
  7074. constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  7075. super();
  7076. this.type = 'PerspectiveCamera';
  7077. this.fov = fov;
  7078. this.zoom = 1;
  7079. this.near = near;
  7080. this.far = far;
  7081. this.focus = 10;
  7082. this.aspect = aspect;
  7083. this.view = null;
  7084. this.filmGauge = 35; // width of the film (default in millimeters)
  7085. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7086. this.updateProjectionMatrix();
  7087. }
  7088. copy(source, recursive) {
  7089. super.copy(source, recursive);
  7090. this.fov = source.fov;
  7091. this.zoom = source.zoom;
  7092. this.near = source.near;
  7093. this.far = source.far;
  7094. this.focus = source.focus;
  7095. this.aspect = source.aspect;
  7096. this.view = source.view === null ? null : Object.assign({}, source.view);
  7097. this.filmGauge = source.filmGauge;
  7098. this.filmOffset = source.filmOffset;
  7099. return this;
  7100. }
  7101. /**
  7102. * Sets the FOV by focal length in respect to the current .filmGauge.
  7103. *
  7104. * The default film gauge is 35, so that the focal length can be specified for
  7105. * a 35mm (full frame) camera.
  7106. *
  7107. * Values for focal length and film gauge must have the same unit.
  7108. */
  7109. setFocalLength(focalLength) {
  7110. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7111. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7112. this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope);
  7113. this.updateProjectionMatrix();
  7114. }
  7115. /**
  7116. * Calculates the focal length from the current .fov and .filmGauge.
  7117. */
  7118. getFocalLength() {
  7119. const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov);
  7120. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7121. }
  7122. getEffectiveFOV() {
  7123. return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom);
  7124. }
  7125. getFilmWidth() {
  7126. // film not completely covered in portrait format (aspect < 1)
  7127. return this.filmGauge * Math.min(this.aspect, 1);
  7128. }
  7129. getFilmHeight() {
  7130. // film not completely covered in landscape format (aspect > 1)
  7131. return this.filmGauge / Math.max(this.aspect, 1);
  7132. }
  7133. /**
  7134. * Sets an offset in a larger frustum. This is useful for multi-window or
  7135. * multi-monitor/multi-machine setups.
  7136. *
  7137. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7138. * the monitors are in grid like this
  7139. *
  7140. * +---+---+---+
  7141. * | A | B | C |
  7142. * +---+---+---+
  7143. * | D | E | F |
  7144. * +---+---+---+
  7145. *
  7146. * then for each monitor you would call it like this
  7147. *
  7148. * const w = 1920;
  7149. * const h = 1080;
  7150. * const fullWidth = w * 3;
  7151. * const fullHeight = h * 2;
  7152. *
  7153. * --A--
  7154. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7155. * --B--
  7156. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7157. * --C--
  7158. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7159. * --D--
  7160. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7161. * --E--
  7162. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7163. * --F--
  7164. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7165. *
  7166. * Note there is no reason monitors have to be the same size or in a grid.
  7167. */
  7168. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  7169. this.aspect = fullWidth / fullHeight;
  7170. if (this.view === null) {
  7171. this.view = {
  7172. enabled: true,
  7173. fullWidth: 1,
  7174. fullHeight: 1,
  7175. offsetX: 0,
  7176. offsetY: 0,
  7177. width: 1,
  7178. height: 1
  7179. };
  7180. }
  7181. this.view.enabled = true;
  7182. this.view.fullWidth = fullWidth;
  7183. this.view.fullHeight = fullHeight;
  7184. this.view.offsetX = x;
  7185. this.view.offsetY = y;
  7186. this.view.width = width;
  7187. this.view.height = height;
  7188. this.updateProjectionMatrix();
  7189. }
  7190. clearViewOffset() {
  7191. if (this.view !== null) {
  7192. this.view.enabled = false;
  7193. }
  7194. this.updateProjectionMatrix();
  7195. }
  7196. updateProjectionMatrix() {
  7197. const near = this.near;
  7198. let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom;
  7199. let height = 2 * top;
  7200. let width = this.aspect * height;
  7201. let left = -0.5 * width;
  7202. const view = this.view;
  7203. if (this.view !== null && this.view.enabled) {
  7204. const fullWidth = view.fullWidth,
  7205. fullHeight = view.fullHeight;
  7206. left += view.offsetX * width / fullWidth;
  7207. top -= view.offsetY * height / fullHeight;
  7208. width *= view.width / fullWidth;
  7209. height *= view.height / fullHeight;
  7210. }
  7211. const skew = this.filmOffset;
  7212. if (skew !== 0) left += near * skew / this.getFilmWidth();
  7213. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  7214. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  7215. }
  7216. toJSON(meta) {
  7217. const data = super.toJSON(meta);
  7218. data.object.fov = this.fov;
  7219. data.object.zoom = this.zoom;
  7220. data.object.near = this.near;
  7221. data.object.far = this.far;
  7222. data.object.focus = this.focus;
  7223. data.object.aspect = this.aspect;
  7224. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  7225. data.object.filmGauge = this.filmGauge;
  7226. data.object.filmOffset = this.filmOffset;
  7227. return data;
  7228. }
  7229. }
  7230. PerspectiveCamera.prototype.isPerspectiveCamera = true;
  7231. const fov = 90,
  7232. aspect = 1;
  7233. class CubeCamera extends Object3D {
  7234. constructor(near, far, renderTarget) {
  7235. super();
  7236. this.type = 'CubeCamera';
  7237. if (renderTarget.isWebGLCubeRenderTarget !== true) {
  7238. console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
  7239. return;
  7240. }
  7241. this.renderTarget = renderTarget;
  7242. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  7243. cameraPX.layers = this.layers;
  7244. cameraPX.up.set(0, -1, 0);
  7245. cameraPX.lookAt(new Vector3(1, 0, 0));
  7246. this.add(cameraPX);
  7247. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  7248. cameraNX.layers = this.layers;
  7249. cameraNX.up.set(0, -1, 0);
  7250. cameraNX.lookAt(new Vector3(-1, 0, 0));
  7251. this.add(cameraNX);
  7252. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  7253. cameraPY.layers = this.layers;
  7254. cameraPY.up.set(0, 0, 1);
  7255. cameraPY.lookAt(new Vector3(0, 1, 0));
  7256. this.add(cameraPY);
  7257. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  7258. cameraNY.layers = this.layers;
  7259. cameraNY.up.set(0, 0, -1);
  7260. cameraNY.lookAt(new Vector3(0, -1, 0));
  7261. this.add(cameraNY);
  7262. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  7263. cameraPZ.layers = this.layers;
  7264. cameraPZ.up.set(0, -1, 0);
  7265. cameraPZ.lookAt(new Vector3(0, 0, 1));
  7266. this.add(cameraPZ);
  7267. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  7268. cameraNZ.layers = this.layers;
  7269. cameraNZ.up.set(0, -1, 0);
  7270. cameraNZ.lookAt(new Vector3(0, 0, -1));
  7271. this.add(cameraNZ);
  7272. }
  7273. update(renderer, scene) {
  7274. if (this.parent === null) this.updateMatrixWorld();
  7275. const renderTarget = this.renderTarget;
  7276. const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children;
  7277. const currentXrEnabled = renderer.xr.enabled;
  7278. const currentRenderTarget = renderer.getRenderTarget();
  7279. renderer.xr.enabled = false;
  7280. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7281. renderTarget.texture.generateMipmaps = false;
  7282. renderer.setRenderTarget(renderTarget, 0);
  7283. renderer.render(scene, cameraPX);
  7284. renderer.setRenderTarget(renderTarget, 1);
  7285. renderer.render(scene, cameraNX);
  7286. renderer.setRenderTarget(renderTarget, 2);
  7287. renderer.render(scene, cameraPY);
  7288. renderer.setRenderTarget(renderTarget, 3);
  7289. renderer.render(scene, cameraNY);
  7290. renderer.setRenderTarget(renderTarget, 4);
  7291. renderer.render(scene, cameraPZ);
  7292. renderTarget.texture.generateMipmaps = generateMipmaps;
  7293. renderer.setRenderTarget(renderTarget, 5);
  7294. renderer.render(scene, cameraNZ);
  7295. renderer.setRenderTarget(currentRenderTarget);
  7296. renderer.xr.enabled = currentXrEnabled;
  7297. }
  7298. }
  7299. class CubeTexture extends Texture {
  7300. constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  7301. images = images !== undefined ? images : [];
  7302. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7303. format = format !== undefined ? format : RGBFormat;
  7304. super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding); // Why CubeTexture._needsFlipEnvMap is necessary:
  7305. //
  7306. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7307. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7308. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7309. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7310. // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false)
  7311. // when using WebGLCubeRenderTarget.texture as a cube texture.
  7312. this._needsFlipEnvMap = true;
  7313. this.flipY = false;
  7314. }
  7315. get images() {
  7316. return this.image;
  7317. }
  7318. set images(value) {
  7319. this.image = value;
  7320. }
  7321. }
  7322. CubeTexture.prototype.isCubeTexture = true;
  7323. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7324. constructor(size, options, dummy) {
  7325. if (Number.isInteger(options)) {
  7326. console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
  7327. options = dummy;
  7328. }
  7329. super(size, size, options);
  7330. options = options || {};
  7331. this.texture = new CubeTexture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  7332. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7333. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7334. this.texture._needsFlipEnvMap = false;
  7335. }
  7336. fromEquirectangularTexture(renderer, texture) {
  7337. this.texture.type = texture.type;
  7338. this.texture.format = RGBAFormat; // see #18859
  7339. this.texture.encoding = texture.encoding;
  7340. this.texture.generateMipmaps = texture.generateMipmaps;
  7341. this.texture.minFilter = texture.minFilter;
  7342. this.texture.magFilter = texture.magFilter;
  7343. const shader = {
  7344. uniforms: {
  7345. tEquirect: {
  7346. value: null
  7347. }
  7348. },
  7349. vertexShader:
  7350. /* glsl */
  7351. `
  7352. varying vec3 vWorldDirection;
  7353. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7354. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7355. }
  7356. void main() {
  7357. vWorldDirection = transformDirection( position, modelMatrix );
  7358. #include <begin_vertex>
  7359. #include <project_vertex>
  7360. }
  7361. `,
  7362. fragmentShader:
  7363. /* glsl */
  7364. `
  7365. uniform sampler2D tEquirect;
  7366. varying vec3 vWorldDirection;
  7367. #include <common>
  7368. void main() {
  7369. vec3 direction = normalize( vWorldDirection );
  7370. vec2 sampleUV = equirectUv( direction );
  7371. gl_FragColor = texture2D( tEquirect, sampleUV );
  7372. }
  7373. `
  7374. };
  7375. const geometry = new BoxGeometry(5, 5, 5);
  7376. const material = new ShaderMaterial({
  7377. name: 'CubemapFromEquirect',
  7378. uniforms: cloneUniforms(shader.uniforms),
  7379. vertexShader: shader.vertexShader,
  7380. fragmentShader: shader.fragmentShader,
  7381. side: BackSide,
  7382. blending: NoBlending
  7383. });
  7384. material.uniforms.tEquirect.value = texture;
  7385. const mesh = new Mesh(geometry, material);
  7386. const currentMinFilter = texture.minFilter; // Avoid blurred poles
  7387. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  7388. const camera = new CubeCamera(1, 10, this);
  7389. camera.update(renderer, mesh);
  7390. texture.minFilter = currentMinFilter;
  7391. mesh.geometry.dispose();
  7392. mesh.material.dispose();
  7393. return this;
  7394. }
  7395. clear(renderer, color, depth, stencil) {
  7396. const currentRenderTarget = renderer.getRenderTarget();
  7397. for (let i = 0; i < 6; i++) {
  7398. renderer.setRenderTarget(this, i);
  7399. renderer.clear(color, depth, stencil);
  7400. }
  7401. renderer.setRenderTarget(currentRenderTarget);
  7402. }
  7403. }
  7404. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  7405. const _vector1 = /*@__PURE__*/new Vector3();
  7406. const _vector2 = /*@__PURE__*/new Vector3();
  7407. const _normalMatrix = /*@__PURE__*/new Matrix3();
  7408. class Plane {
  7409. constructor(normal = new Vector3(1, 0, 0), constant = 0) {
  7410. // normal is assumed to be normalized
  7411. this.normal = normal;
  7412. this.constant = constant;
  7413. }
  7414. set(normal, constant) {
  7415. this.normal.copy(normal);
  7416. this.constant = constant;
  7417. return this;
  7418. }
  7419. setComponents(x, y, z, w) {
  7420. this.normal.set(x, y, z);
  7421. this.constant = w;
  7422. return this;
  7423. }
  7424. setFromNormalAndCoplanarPoint(normal, point) {
  7425. this.normal.copy(normal);
  7426. this.constant = -point.dot(this.normal);
  7427. return this;
  7428. }
  7429. setFromCoplanarPoints(a, b, c) {
  7430. const normal = _vector1.subVectors(c, b).cross(_vector2.subVectors(a, b)).normalize(); // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7431. this.setFromNormalAndCoplanarPoint(normal, a);
  7432. return this;
  7433. }
  7434. copy(plane) {
  7435. this.normal.copy(plane.normal);
  7436. this.constant = plane.constant;
  7437. return this;
  7438. }
  7439. normalize() {
  7440. // Note: will lead to a divide by zero if the plane is invalid.
  7441. const inverseNormalLength = 1.0 / this.normal.length();
  7442. this.normal.multiplyScalar(inverseNormalLength);
  7443. this.constant *= inverseNormalLength;
  7444. return this;
  7445. }
  7446. negate() {
  7447. this.constant *= -1;
  7448. this.normal.negate();
  7449. return this;
  7450. }
  7451. distanceToPoint(point) {
  7452. return this.normal.dot(point) + this.constant;
  7453. }
  7454. distanceToSphere(sphere) {
  7455. return this.distanceToPoint(sphere.center) - sphere.radius;
  7456. }
  7457. projectPoint(point, target) {
  7458. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  7459. }
  7460. intersectLine(line, target) {
  7461. const direction = line.delta(_vector1);
  7462. const denominator = this.normal.dot(direction);
  7463. if (denominator === 0) {
  7464. // line is coplanar, return origin
  7465. if (this.distanceToPoint(line.start) === 0) {
  7466. return target.copy(line.start);
  7467. } // Unsure if this is the correct method to handle this case.
  7468. return null;
  7469. }
  7470. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  7471. if (t < 0 || t > 1) {
  7472. return null;
  7473. }
  7474. return target.copy(direction).multiplyScalar(t).add(line.start);
  7475. }
  7476. intersectsLine(line) {
  7477. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7478. const startSign = this.distanceToPoint(line.start);
  7479. const endSign = this.distanceToPoint(line.end);
  7480. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  7481. }
  7482. intersectsBox(box) {
  7483. return box.intersectsPlane(this);
  7484. }
  7485. intersectsSphere(sphere) {
  7486. return sphere.intersectsPlane(this);
  7487. }
  7488. coplanarPoint(target) {
  7489. return target.copy(this.normal).multiplyScalar(-this.constant);
  7490. }
  7491. applyMatrix4(matrix, optionalNormalMatrix) {
  7492. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  7493. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  7494. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  7495. this.constant = -referencePoint.dot(normal);
  7496. return this;
  7497. }
  7498. translate(offset) {
  7499. this.constant -= offset.dot(this.normal);
  7500. return this;
  7501. }
  7502. equals(plane) {
  7503. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  7504. }
  7505. clone() {
  7506. return new this.constructor().copy(this);
  7507. }
  7508. }
  7509. Plane.prototype.isPlane = true;
  7510. const _sphere$2 = /*@__PURE__*/new Sphere();
  7511. const _vector$7 = /*@__PURE__*/new Vector3();
  7512. class Frustum {
  7513. constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) {
  7514. this.planes = [p0, p1, p2, p3, p4, p5];
  7515. }
  7516. set(p0, p1, p2, p3, p4, p5) {
  7517. const planes = this.planes;
  7518. planes[0].copy(p0);
  7519. planes[1].copy(p1);
  7520. planes[2].copy(p2);
  7521. planes[3].copy(p3);
  7522. planes[4].copy(p4);
  7523. planes[5].copy(p5);
  7524. return this;
  7525. }
  7526. copy(frustum) {
  7527. const planes = this.planes;
  7528. for (let i = 0; i < 6; i++) {
  7529. planes[i].copy(frustum.planes[i]);
  7530. }
  7531. return this;
  7532. }
  7533. setFromProjectionMatrix(m) {
  7534. const planes = this.planes;
  7535. const me = m.elements;
  7536. const me0 = me[0],
  7537. me1 = me[1],
  7538. me2 = me[2],
  7539. me3 = me[3];
  7540. const me4 = me[4],
  7541. me5 = me[5],
  7542. me6 = me[6],
  7543. me7 = me[7];
  7544. const me8 = me[8],
  7545. me9 = me[9],
  7546. me10 = me[10],
  7547. me11 = me[11];
  7548. const me12 = me[12],
  7549. me13 = me[13],
  7550. me14 = me[14],
  7551. me15 = me[15];
  7552. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  7553. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  7554. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  7555. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  7556. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  7557. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  7558. return this;
  7559. }
  7560. intersectsObject(object) {
  7561. const geometry = object.geometry;
  7562. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7563. _sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  7564. return this.intersectsSphere(_sphere$2);
  7565. }
  7566. intersectsSprite(sprite) {
  7567. _sphere$2.center.set(0, 0, 0);
  7568. _sphere$2.radius = 0.7071067811865476;
  7569. _sphere$2.applyMatrix4(sprite.matrixWorld);
  7570. return this.intersectsSphere(_sphere$2);
  7571. }
  7572. intersectsSphere(sphere) {
  7573. const planes = this.planes;
  7574. const center = sphere.center;
  7575. const negRadius = -sphere.radius;
  7576. for (let i = 0; i < 6; i++) {
  7577. const distance = planes[i].distanceToPoint(center);
  7578. if (distance < negRadius) {
  7579. return false;
  7580. }
  7581. }
  7582. return true;
  7583. }
  7584. intersectsBox(box) {
  7585. const planes = this.planes;
  7586. for (let i = 0; i < 6; i++) {
  7587. const plane = planes[i]; // corner at max distance
  7588. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7589. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7590. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7591. if (plane.distanceToPoint(_vector$7) < 0) {
  7592. return false;
  7593. }
  7594. }
  7595. return true;
  7596. }
  7597. containsPoint(point) {
  7598. const planes = this.planes;
  7599. for (let i = 0; i < 6; i++) {
  7600. if (planes[i].distanceToPoint(point) < 0) {
  7601. return false;
  7602. }
  7603. }
  7604. return true;
  7605. }
  7606. clone() {
  7607. return new this.constructor().copy(this);
  7608. }
  7609. }
  7610. function WebGLAnimation() {
  7611. let context = null;
  7612. let isAnimating = false;
  7613. let animationLoop = null;
  7614. let requestId = null;
  7615. function onAnimationFrame(time, frame) {
  7616. animationLoop(time, frame);
  7617. requestId = context.requestAnimationFrame(onAnimationFrame);
  7618. }
  7619. return {
  7620. start: function () {
  7621. if (isAnimating === true) return;
  7622. if (animationLoop === null) return;
  7623. requestId = context.requestAnimationFrame(onAnimationFrame);
  7624. isAnimating = true;
  7625. },
  7626. stop: function () {
  7627. context.cancelAnimationFrame(requestId);
  7628. isAnimating = false;
  7629. },
  7630. setAnimationLoop: function (callback) {
  7631. animationLoop = callback;
  7632. },
  7633. setContext: function (value) {
  7634. context = value;
  7635. }
  7636. };
  7637. }
  7638. function WebGLAttributes(gl, capabilities) {
  7639. const isWebGL2 = capabilities.isWebGL2;
  7640. const buffers = new WeakMap();
  7641. function createBuffer(attribute, bufferType) {
  7642. const array = attribute.array;
  7643. const usage = attribute.usage;
  7644. const buffer = gl.createBuffer();
  7645. gl.bindBuffer(bufferType, buffer);
  7646. gl.bufferData(bufferType, array, usage);
  7647. attribute.onUploadCallback();
  7648. let type = gl.FLOAT;
  7649. if (array instanceof Float32Array) {
  7650. type = gl.FLOAT;
  7651. } else if (array instanceof Float64Array) {
  7652. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  7653. } else if (array instanceof Uint16Array) {
  7654. if (attribute.isFloat16BufferAttribute) {
  7655. if (isWebGL2) {
  7656. type = gl.HALF_FLOAT;
  7657. } else {
  7658. console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  7659. }
  7660. } else {
  7661. type = gl.UNSIGNED_SHORT;
  7662. }
  7663. } else if (array instanceof Int16Array) {
  7664. type = gl.SHORT;
  7665. } else if (array instanceof Uint32Array) {
  7666. type = gl.UNSIGNED_INT;
  7667. } else if (array instanceof Int32Array) {
  7668. type = gl.INT;
  7669. } else if (array instanceof Int8Array) {
  7670. type = gl.BYTE;
  7671. } else if (array instanceof Uint8Array) {
  7672. type = gl.UNSIGNED_BYTE;
  7673. } else if (array instanceof Uint8ClampedArray) {
  7674. type = gl.UNSIGNED_BYTE;
  7675. }
  7676. return {
  7677. buffer: buffer,
  7678. type: type,
  7679. bytesPerElement: array.BYTES_PER_ELEMENT,
  7680. version: attribute.version
  7681. };
  7682. }
  7683. function updateBuffer(buffer, attribute, bufferType) {
  7684. const array = attribute.array;
  7685. const updateRange = attribute.updateRange;
  7686. gl.bindBuffer(bufferType, buffer);
  7687. if (updateRange.count === -1) {
  7688. // Not using update ranges
  7689. gl.bufferSubData(bufferType, 0, array);
  7690. } else {
  7691. if (isWebGL2) {
  7692. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  7693. } else {
  7694. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  7695. }
  7696. updateRange.count = -1; // reset range
  7697. }
  7698. } //
  7699. function get(attribute) {
  7700. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7701. return buffers.get(attribute);
  7702. }
  7703. function remove(attribute) {
  7704. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7705. const data = buffers.get(attribute);
  7706. if (data) {
  7707. gl.deleteBuffer(data.buffer);
  7708. buffers.delete(attribute);
  7709. }
  7710. }
  7711. function update(attribute, bufferType) {
  7712. if (attribute.isGLBufferAttribute) {
  7713. const cached = buffers.get(attribute);
  7714. if (!cached || cached.version < attribute.version) {
  7715. buffers.set(attribute, {
  7716. buffer: attribute.buffer,
  7717. type: attribute.type,
  7718. bytesPerElement: attribute.elementSize,
  7719. version: attribute.version
  7720. });
  7721. }
  7722. return;
  7723. }
  7724. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7725. const data = buffers.get(attribute);
  7726. if (data === undefined) {
  7727. buffers.set(attribute, createBuffer(attribute, bufferType));
  7728. } else if (data.version < attribute.version) {
  7729. updateBuffer(data.buffer, attribute, bufferType);
  7730. data.version = attribute.version;
  7731. }
  7732. }
  7733. return {
  7734. get: get,
  7735. remove: remove,
  7736. update: update
  7737. };
  7738. }
  7739. class PlaneGeometry extends BufferGeometry {
  7740. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  7741. super();
  7742. this.type = 'PlaneGeometry';
  7743. this.parameters = {
  7744. width: width,
  7745. height: height,
  7746. widthSegments: widthSegments,
  7747. heightSegments: heightSegments
  7748. };
  7749. const width_half = width / 2;
  7750. const height_half = height / 2;
  7751. const gridX = Math.floor(widthSegments);
  7752. const gridY = Math.floor(heightSegments);
  7753. const gridX1 = gridX + 1;
  7754. const gridY1 = gridY + 1;
  7755. const segment_width = width / gridX;
  7756. const segment_height = height / gridY; //
  7757. const indices = [];
  7758. const vertices = [];
  7759. const normals = [];
  7760. const uvs = [];
  7761. for (let iy = 0; iy < gridY1; iy++) {
  7762. const y = iy * segment_height - height_half;
  7763. for (let ix = 0; ix < gridX1; ix++) {
  7764. const x = ix * segment_width - width_half;
  7765. vertices.push(x, -y, 0);
  7766. normals.push(0, 0, 1);
  7767. uvs.push(ix / gridX);
  7768. uvs.push(1 - iy / gridY);
  7769. }
  7770. }
  7771. for (let iy = 0; iy < gridY; iy++) {
  7772. for (let ix = 0; ix < gridX; ix++) {
  7773. const a = ix + gridX1 * iy;
  7774. const b = ix + gridX1 * (iy + 1);
  7775. const c = ix + 1 + gridX1 * (iy + 1);
  7776. const d = ix + 1 + gridX1 * iy;
  7777. indices.push(a, b, d);
  7778. indices.push(b, c, d);
  7779. }
  7780. }
  7781. this.setIndex(indices);
  7782. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7783. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7784. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7785. }
  7786. static fromJSON(data) {
  7787. return new PlaneGeometry(data.width, data.height, data.widthSegments, data.heightSegments);
  7788. }
  7789. }
  7790. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7791. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7792. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  7793. 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";
  7794. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7795. var begin_vertex = "vec3 transformed = vec3( position );";
  7796. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7797. 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";
  7798. 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";
  7799. 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";
  7800. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7801. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7802. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7803. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7804. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7805. 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";
  7806. 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";
  7807. 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}";
  7808. 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";
  7809. 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";
  7810. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7811. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7812. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7813. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7814. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7815. 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}";
  7816. 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";
  7817. 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";
  7818. 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";
  7819. 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";
  7820. 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";
  7821. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif";
  7822. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  7823. 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";
  7824. 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";
  7825. 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}";
  7826. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  7827. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7828. 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";
  7829. 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";
  7830. 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";
  7831. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7832. 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)";
  7833. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7834. 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)";
  7835. 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 ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, 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";
  7836. 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}";
  7837. 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";
  7838. 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";
  7839. 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";
  7840. 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";
  7841. 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";
  7842. 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";
  7843. 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";
  7844. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  7845. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7846. 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";
  7847. 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";
  7848. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7849. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7850. 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";
  7851. 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";
  7852. 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";
  7853. 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;";
  7854. 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";
  7855. 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";
  7856. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7857. 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";
  7858. 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";
  7859. 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}";
  7860. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7861. 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;";
  7862. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7863. 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";
  7864. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7865. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7866. 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";
  7867. 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";
  7868. 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";
  7869. 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}";
  7870. 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";
  7871. 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";
  7872. 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";
  7873. 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";
  7874. 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";
  7875. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7876. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7877. 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; }";
  7878. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tfloat transmissionFactor = transmission;\n\tfloat thicknessFactor = thickness;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\ttransmissionFactor *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tthicknessFactor *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition.xyz / vWorldPosition.w;\n\tvec3 v = normalize( cameraPosition - pos );\n\tfloat ior = ( 1.0 + 0.4 * reflectivity ) / ( 1.0 - 0.4 * reflectivity );\n\tvec3 transmission = transmissionFactor * getIBLVolumeRefraction(\n\t\tnormal, v, roughnessFactor, material.diffuseColor, material.specularColor,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationColor, attenuationDistance );\n\ttotalDiffuse = mix( totalDiffuse, transmission, transmissionFactor );\n#endif";
  7879. 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, float perceptualRoughness, vec3 baseColor, vec3 specularColor,\n\t\tvec3 position, mat4 modelMatrix, mat4 viewMatrix, mat4 projMatrix, float ior, float thickness,\n\t\tvec3 attenuationColor, float attenuationDistance) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay(n, v, thickness, ior, modelMatrix);\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4(refractedRayExit, 1.0);\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec3 transmittedLight = getTransmissionSample(refractionCoords, perceptualRoughness, ior);\n\t\tvec3 attenuatedColor = applyVolumeAttenuation(transmittedLight, length(transmissionRay), attenuationColor, attenuationDistance);\n\t\treturn (1.0 - specularColor) * attenuatedColor * baseColor;\n\t}\n#endif";
  7880. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7881. 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";
  7882. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7883. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7884. 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";
  7885. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7886. 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";
  7887. 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}";
  7888. 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}";
  7889. 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}";
  7890. 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}";
  7891. 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}";
  7892. 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}";
  7893. 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}";
  7894. 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}";
  7895. 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}";
  7896. 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}";
  7897. 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}";
  7898. 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}";
  7899. 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}";
  7900. var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  7901. 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}";
  7902. 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}";
  7903. 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}";
  7904. 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}";
  7905. 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}";
  7906. 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}";
  7907. 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}";
  7908. 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}";
  7909. 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#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\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}";
  7910. 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}";
  7911. 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}";
  7912. 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}";
  7913. 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}";
  7914. 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}";
  7915. 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}";
  7916. 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}";
  7917. 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}";
  7918. 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}";
  7919. const ShaderChunk = {
  7920. alphamap_fragment: alphamap_fragment,
  7921. alphamap_pars_fragment: alphamap_pars_fragment,
  7922. alphatest_fragment: alphatest_fragment,
  7923. aomap_fragment: aomap_fragment,
  7924. aomap_pars_fragment: aomap_pars_fragment,
  7925. begin_vertex: begin_vertex,
  7926. beginnormal_vertex: beginnormal_vertex,
  7927. bsdfs: bsdfs,
  7928. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7929. clipping_planes_fragment: clipping_planes_fragment,
  7930. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7931. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7932. clipping_planes_vertex: clipping_planes_vertex,
  7933. color_fragment: color_fragment,
  7934. color_pars_fragment: color_pars_fragment,
  7935. color_pars_vertex: color_pars_vertex,
  7936. color_vertex: color_vertex,
  7937. common: common,
  7938. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7939. defaultnormal_vertex: defaultnormal_vertex,
  7940. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7941. displacementmap_vertex: displacementmap_vertex,
  7942. emissivemap_fragment: emissivemap_fragment,
  7943. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7944. encodings_fragment: encodings_fragment,
  7945. encodings_pars_fragment: encodings_pars_fragment,
  7946. envmap_fragment: envmap_fragment,
  7947. envmap_common_pars_fragment: envmap_common_pars_fragment,
  7948. envmap_pars_fragment: envmap_pars_fragment,
  7949. envmap_pars_vertex: envmap_pars_vertex,
  7950. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  7951. envmap_vertex: envmap_vertex,
  7952. fog_vertex: fog_vertex,
  7953. fog_pars_vertex: fog_pars_vertex,
  7954. fog_fragment: fog_fragment,
  7955. fog_pars_fragment: fog_pars_fragment,
  7956. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7957. lightmap_fragment: lightmap_fragment,
  7958. lightmap_pars_fragment: lightmap_pars_fragment,
  7959. lights_lambert_vertex: lights_lambert_vertex,
  7960. lights_pars_begin: lights_pars_begin,
  7961. lights_toon_fragment: lights_toon_fragment,
  7962. lights_toon_pars_fragment: lights_toon_pars_fragment,
  7963. lights_phong_fragment: lights_phong_fragment,
  7964. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7965. lights_physical_fragment: lights_physical_fragment,
  7966. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7967. lights_fragment_begin: lights_fragment_begin,
  7968. lights_fragment_maps: lights_fragment_maps,
  7969. lights_fragment_end: lights_fragment_end,
  7970. logdepthbuf_fragment: logdepthbuf_fragment,
  7971. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7972. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7973. logdepthbuf_vertex: logdepthbuf_vertex,
  7974. map_fragment: map_fragment,
  7975. map_pars_fragment: map_pars_fragment,
  7976. map_particle_fragment: map_particle_fragment,
  7977. map_particle_pars_fragment: map_particle_pars_fragment,
  7978. metalnessmap_fragment: metalnessmap_fragment,
  7979. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7980. morphnormal_vertex: morphnormal_vertex,
  7981. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7982. morphtarget_vertex: morphtarget_vertex,
  7983. normal_fragment_begin: normal_fragment_begin,
  7984. normal_fragment_maps: normal_fragment_maps,
  7985. normalmap_pars_fragment: normalmap_pars_fragment,
  7986. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  7987. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  7988. clearcoat_pars_fragment: clearcoat_pars_fragment,
  7989. packing: packing,
  7990. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  7991. project_vertex: project_vertex,
  7992. dithering_fragment: dithering_fragment,
  7993. dithering_pars_fragment: dithering_pars_fragment,
  7994. roughnessmap_fragment: roughnessmap_fragment,
  7995. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  7996. shadowmap_pars_fragment: shadowmap_pars_fragment,
  7997. shadowmap_pars_vertex: shadowmap_pars_vertex,
  7998. shadowmap_vertex: shadowmap_vertex,
  7999. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8000. skinbase_vertex: skinbase_vertex,
  8001. skinning_pars_vertex: skinning_pars_vertex,
  8002. skinning_vertex: skinning_vertex,
  8003. skinnormal_vertex: skinnormal_vertex,
  8004. specularmap_fragment: specularmap_fragment,
  8005. specularmap_pars_fragment: specularmap_pars_fragment,
  8006. tonemapping_fragment: tonemapping_fragment,
  8007. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8008. transmission_fragment: transmission_fragment,
  8009. transmission_pars_fragment: transmission_pars_fragment,
  8010. uv_pars_fragment: uv_pars_fragment,
  8011. uv_pars_vertex: uv_pars_vertex,
  8012. uv_vertex: uv_vertex,
  8013. uv2_pars_fragment: uv2_pars_fragment,
  8014. uv2_pars_vertex: uv2_pars_vertex,
  8015. uv2_vertex: uv2_vertex,
  8016. worldpos_vertex: worldpos_vertex,
  8017. background_frag: background_frag,
  8018. background_vert: background_vert,
  8019. cube_frag: cube_frag,
  8020. cube_vert: cube_vert,
  8021. depth_frag: depth_frag,
  8022. depth_vert: depth_vert,
  8023. distanceRGBA_frag: distanceRGBA_frag,
  8024. distanceRGBA_vert: distanceRGBA_vert,
  8025. equirect_frag: equirect_frag,
  8026. equirect_vert: equirect_vert,
  8027. linedashed_frag: linedashed_frag,
  8028. linedashed_vert: linedashed_vert,
  8029. meshbasic_frag: meshbasic_frag,
  8030. meshbasic_vert: meshbasic_vert,
  8031. meshlambert_frag: meshlambert_frag,
  8032. meshlambert_vert: meshlambert_vert,
  8033. meshmatcap_frag: meshmatcap_frag,
  8034. meshmatcap_vert: meshmatcap_vert,
  8035. meshtoon_frag: meshtoon_frag,
  8036. meshtoon_vert: meshtoon_vert,
  8037. meshphong_frag: meshphong_frag,
  8038. meshphong_vert: meshphong_vert,
  8039. meshphysical_frag: meshphysical_frag,
  8040. meshphysical_vert: meshphysical_vert,
  8041. normal_frag: normal_frag,
  8042. normal_vert: normal_vert,
  8043. points_frag: points_frag,
  8044. points_vert: points_vert,
  8045. shadow_frag: shadow_frag,
  8046. shadow_vert: shadow_vert,
  8047. sprite_frag: sprite_frag,
  8048. sprite_vert: sprite_vert
  8049. };
  8050. /**
  8051. * Uniforms library for shared webgl shaders
  8052. */
  8053. const UniformsLib = {
  8054. common: {
  8055. diffuse: {
  8056. value: new Color(0xffffff)
  8057. },
  8058. opacity: {
  8059. value: 1.0
  8060. },
  8061. map: {
  8062. value: null
  8063. },
  8064. uvTransform: {
  8065. value: new Matrix3()
  8066. },
  8067. uv2Transform: {
  8068. value: new Matrix3()
  8069. },
  8070. alphaMap: {
  8071. value: null
  8072. }
  8073. },
  8074. specularmap: {
  8075. specularMap: {
  8076. value: null
  8077. }
  8078. },
  8079. envmap: {
  8080. envMap: {
  8081. value: null
  8082. },
  8083. flipEnvMap: {
  8084. value: -1
  8085. },
  8086. reflectivity: {
  8087. value: 1.0
  8088. },
  8089. refractionRatio: {
  8090. value: 0.98
  8091. },
  8092. maxMipLevel: {
  8093. value: 0
  8094. }
  8095. },
  8096. aomap: {
  8097. aoMap: {
  8098. value: null
  8099. },
  8100. aoMapIntensity: {
  8101. value: 1
  8102. }
  8103. },
  8104. lightmap: {
  8105. lightMap: {
  8106. value: null
  8107. },
  8108. lightMapIntensity: {
  8109. value: 1
  8110. }
  8111. },
  8112. emissivemap: {
  8113. emissiveMap: {
  8114. value: null
  8115. }
  8116. },
  8117. bumpmap: {
  8118. bumpMap: {
  8119. value: null
  8120. },
  8121. bumpScale: {
  8122. value: 1
  8123. }
  8124. },
  8125. normalmap: {
  8126. normalMap: {
  8127. value: null
  8128. },
  8129. normalScale: {
  8130. value: new Vector2(1, 1)
  8131. }
  8132. },
  8133. displacementmap: {
  8134. displacementMap: {
  8135. value: null
  8136. },
  8137. displacementScale: {
  8138. value: 1
  8139. },
  8140. displacementBias: {
  8141. value: 0
  8142. }
  8143. },
  8144. roughnessmap: {
  8145. roughnessMap: {
  8146. value: null
  8147. }
  8148. },
  8149. metalnessmap: {
  8150. metalnessMap: {
  8151. value: null
  8152. }
  8153. },
  8154. gradientmap: {
  8155. gradientMap: {
  8156. value: null
  8157. }
  8158. },
  8159. fog: {
  8160. fogDensity: {
  8161. value: 0.00025
  8162. },
  8163. fogNear: {
  8164. value: 1
  8165. },
  8166. fogFar: {
  8167. value: 2000
  8168. },
  8169. fogColor: {
  8170. value: new Color(0xffffff)
  8171. }
  8172. },
  8173. lights: {
  8174. ambientLightColor: {
  8175. value: []
  8176. },
  8177. lightProbe: {
  8178. value: []
  8179. },
  8180. directionalLights: {
  8181. value: [],
  8182. properties: {
  8183. direction: {},
  8184. color: {}
  8185. }
  8186. },
  8187. directionalLightShadows: {
  8188. value: [],
  8189. properties: {
  8190. shadowBias: {},
  8191. shadowNormalBias: {},
  8192. shadowRadius: {},
  8193. shadowMapSize: {}
  8194. }
  8195. },
  8196. directionalShadowMap: {
  8197. value: []
  8198. },
  8199. directionalShadowMatrix: {
  8200. value: []
  8201. },
  8202. spotLights: {
  8203. value: [],
  8204. properties: {
  8205. color: {},
  8206. position: {},
  8207. direction: {},
  8208. distance: {},
  8209. coneCos: {},
  8210. penumbraCos: {},
  8211. decay: {}
  8212. }
  8213. },
  8214. spotLightShadows: {
  8215. value: [],
  8216. properties: {
  8217. shadowBias: {},
  8218. shadowNormalBias: {},
  8219. shadowRadius: {},
  8220. shadowMapSize: {}
  8221. }
  8222. },
  8223. spotShadowMap: {
  8224. value: []
  8225. },
  8226. spotShadowMatrix: {
  8227. value: []
  8228. },
  8229. pointLights: {
  8230. value: [],
  8231. properties: {
  8232. color: {},
  8233. position: {},
  8234. decay: {},
  8235. distance: {}
  8236. }
  8237. },
  8238. pointLightShadows: {
  8239. value: [],
  8240. properties: {
  8241. shadowBias: {},
  8242. shadowNormalBias: {},
  8243. shadowRadius: {},
  8244. shadowMapSize: {},
  8245. shadowCameraNear: {},
  8246. shadowCameraFar: {}
  8247. }
  8248. },
  8249. pointShadowMap: {
  8250. value: []
  8251. },
  8252. pointShadowMatrix: {
  8253. value: []
  8254. },
  8255. hemisphereLights: {
  8256. value: [],
  8257. properties: {
  8258. direction: {},
  8259. skyColor: {},
  8260. groundColor: {}
  8261. }
  8262. },
  8263. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8264. rectAreaLights: {
  8265. value: [],
  8266. properties: {
  8267. color: {},
  8268. position: {},
  8269. width: {},
  8270. height: {}
  8271. }
  8272. },
  8273. ltc_1: {
  8274. value: null
  8275. },
  8276. ltc_2: {
  8277. value: null
  8278. }
  8279. },
  8280. points: {
  8281. diffuse: {
  8282. value: new Color(0xffffff)
  8283. },
  8284. opacity: {
  8285. value: 1.0
  8286. },
  8287. size: {
  8288. value: 1.0
  8289. },
  8290. scale: {
  8291. value: 1.0
  8292. },
  8293. map: {
  8294. value: null
  8295. },
  8296. alphaMap: {
  8297. value: null
  8298. },
  8299. uvTransform: {
  8300. value: new Matrix3()
  8301. }
  8302. },
  8303. sprite: {
  8304. diffuse: {
  8305. value: new Color(0xffffff)
  8306. },
  8307. opacity: {
  8308. value: 1.0
  8309. },
  8310. center: {
  8311. value: new Vector2(0.5, 0.5)
  8312. },
  8313. rotation: {
  8314. value: 0.0
  8315. },
  8316. map: {
  8317. value: null
  8318. },
  8319. alphaMap: {
  8320. value: null
  8321. },
  8322. uvTransform: {
  8323. value: new Matrix3()
  8324. }
  8325. }
  8326. };
  8327. const ShaderLib = {
  8328. basic: {
  8329. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  8330. vertexShader: ShaderChunk.meshbasic_vert,
  8331. fragmentShader: ShaderChunk.meshbasic_frag
  8332. },
  8333. lambert: {
  8334. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  8335. emissive: {
  8336. value: new Color(0x000000)
  8337. }
  8338. }]),
  8339. vertexShader: ShaderChunk.meshlambert_vert,
  8340. fragmentShader: ShaderChunk.meshlambert_frag
  8341. },
  8342. phong: {
  8343. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  8344. emissive: {
  8345. value: new Color(0x000000)
  8346. },
  8347. specular: {
  8348. value: new Color(0x111111)
  8349. },
  8350. shininess: {
  8351. value: 30
  8352. }
  8353. }]),
  8354. vertexShader: ShaderChunk.meshphong_vert,
  8355. fragmentShader: ShaderChunk.meshphong_frag
  8356. },
  8357. standard: {
  8358. 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, {
  8359. emissive: {
  8360. value: new Color(0x000000)
  8361. },
  8362. roughness: {
  8363. value: 1.0
  8364. },
  8365. metalness: {
  8366. value: 0.0
  8367. },
  8368. envMapIntensity: {
  8369. value: 1
  8370. } // temporary
  8371. }]),
  8372. vertexShader: ShaderChunk.meshphysical_vert,
  8373. fragmentShader: ShaderChunk.meshphysical_frag
  8374. },
  8375. toon: {
  8376. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  8377. emissive: {
  8378. value: new Color(0x000000)
  8379. }
  8380. }]),
  8381. vertexShader: ShaderChunk.meshtoon_vert,
  8382. fragmentShader: ShaderChunk.meshtoon_frag
  8383. },
  8384. matcap: {
  8385. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  8386. matcap: {
  8387. value: null
  8388. }
  8389. }]),
  8390. vertexShader: ShaderChunk.meshmatcap_vert,
  8391. fragmentShader: ShaderChunk.meshmatcap_frag
  8392. },
  8393. points: {
  8394. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  8395. vertexShader: ShaderChunk.points_vert,
  8396. fragmentShader: ShaderChunk.points_frag
  8397. },
  8398. dashed: {
  8399. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  8400. scale: {
  8401. value: 1
  8402. },
  8403. dashSize: {
  8404. value: 1
  8405. },
  8406. totalSize: {
  8407. value: 2
  8408. }
  8409. }]),
  8410. vertexShader: ShaderChunk.linedashed_vert,
  8411. fragmentShader: ShaderChunk.linedashed_frag
  8412. },
  8413. depth: {
  8414. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  8415. vertexShader: ShaderChunk.depth_vert,
  8416. fragmentShader: ShaderChunk.depth_frag
  8417. },
  8418. normal: {
  8419. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  8420. opacity: {
  8421. value: 1.0
  8422. }
  8423. }]),
  8424. vertexShader: ShaderChunk.normal_vert,
  8425. fragmentShader: ShaderChunk.normal_frag
  8426. },
  8427. sprite: {
  8428. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  8429. vertexShader: ShaderChunk.sprite_vert,
  8430. fragmentShader: ShaderChunk.sprite_frag
  8431. },
  8432. background: {
  8433. uniforms: {
  8434. uvTransform: {
  8435. value: new Matrix3()
  8436. },
  8437. t2D: {
  8438. value: null
  8439. }
  8440. },
  8441. vertexShader: ShaderChunk.background_vert,
  8442. fragmentShader: ShaderChunk.background_frag
  8443. },
  8444. /* -------------------------------------------------------------------------
  8445. // Cube map shader
  8446. ------------------------------------------------------------------------- */
  8447. cube: {
  8448. uniforms: mergeUniforms([UniformsLib.envmap, {
  8449. opacity: {
  8450. value: 1.0
  8451. }
  8452. }]),
  8453. vertexShader: ShaderChunk.cube_vert,
  8454. fragmentShader: ShaderChunk.cube_frag
  8455. },
  8456. equirect: {
  8457. uniforms: {
  8458. tEquirect: {
  8459. value: null
  8460. }
  8461. },
  8462. vertexShader: ShaderChunk.equirect_vert,
  8463. fragmentShader: ShaderChunk.equirect_frag
  8464. },
  8465. distanceRGBA: {
  8466. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  8467. referencePosition: {
  8468. value: new Vector3()
  8469. },
  8470. nearDistance: {
  8471. value: 1
  8472. },
  8473. farDistance: {
  8474. value: 1000
  8475. }
  8476. }]),
  8477. vertexShader: ShaderChunk.distanceRGBA_vert,
  8478. fragmentShader: ShaderChunk.distanceRGBA_frag
  8479. },
  8480. shadow: {
  8481. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  8482. color: {
  8483. value: new Color(0x00000)
  8484. },
  8485. opacity: {
  8486. value: 1.0
  8487. }
  8488. }]),
  8489. vertexShader: ShaderChunk.shadow_vert,
  8490. fragmentShader: ShaderChunk.shadow_frag
  8491. }
  8492. };
  8493. ShaderLib.physical = {
  8494. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  8495. clearcoat: {
  8496. value: 0
  8497. },
  8498. clearcoatMap: {
  8499. value: null
  8500. },
  8501. clearcoatRoughness: {
  8502. value: 0
  8503. },
  8504. clearcoatRoughnessMap: {
  8505. value: null
  8506. },
  8507. clearcoatNormalScale: {
  8508. value: new Vector2(1, 1)
  8509. },
  8510. clearcoatNormalMap: {
  8511. value: null
  8512. },
  8513. sheen: {
  8514. value: new Color(0x000000)
  8515. },
  8516. transmission: {
  8517. value: 0
  8518. },
  8519. transmissionMap: {
  8520. value: null
  8521. },
  8522. transmissionSamplerSize: {
  8523. value: new Vector2()
  8524. },
  8525. transmissionSamplerMap: {
  8526. value: null
  8527. },
  8528. thickness: {
  8529. value: 0
  8530. },
  8531. thicknessMap: {
  8532. value: null
  8533. },
  8534. attenuationDistance: {
  8535. value: 0
  8536. },
  8537. attenuationColor: {
  8538. value: new Color(0x000000)
  8539. }
  8540. }]),
  8541. vertexShader: ShaderChunk.meshphysical_vert,
  8542. fragmentShader: ShaderChunk.meshphysical_frag
  8543. };
  8544. function WebGLBackground(renderer, cubemaps, state, objects, premultipliedAlpha) {
  8545. const clearColor = new Color(0x000000);
  8546. let clearAlpha = 0;
  8547. let planeMesh;
  8548. let boxMesh;
  8549. let currentBackground = null;
  8550. let currentBackgroundVersion = 0;
  8551. let currentTonemapping = null;
  8552. function render(renderList, scene) {
  8553. let forceClear = false;
  8554. let background = scene.isScene === true ? scene.background : null;
  8555. if (background && background.isTexture) {
  8556. background = cubemaps.get(background);
  8557. } // Ignore background in AR
  8558. // TODO: Reconsider this.
  8559. const xr = renderer.xr;
  8560. const session = xr.getSession && xr.getSession();
  8561. if (session && session.environmentBlendMode === 'additive') {
  8562. background = null;
  8563. }
  8564. if (background === null) {
  8565. setClear(clearColor, clearAlpha);
  8566. } else if (background && background.isColor) {
  8567. setClear(background, 1);
  8568. forceClear = true;
  8569. }
  8570. if (renderer.autoClear || forceClear) {
  8571. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  8572. }
  8573. if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
  8574. if (boxMesh === undefined) {
  8575. boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
  8576. name: 'BackgroundCubeMaterial',
  8577. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  8578. vertexShader: ShaderLib.cube.vertexShader,
  8579. fragmentShader: ShaderLib.cube.fragmentShader,
  8580. side: BackSide,
  8581. depthTest: false,
  8582. depthWrite: false,
  8583. fog: false
  8584. }));
  8585. boxMesh.geometry.deleteAttribute('normal');
  8586. boxMesh.geometry.deleteAttribute('uv');
  8587. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  8588. this.matrixWorld.copyPosition(camera.matrixWorld);
  8589. }; // enable code injection for non-built-in material
  8590. Object.defineProperty(boxMesh.material, 'envMap', {
  8591. get: function () {
  8592. return this.uniforms.envMap.value;
  8593. }
  8594. });
  8595. objects.update(boxMesh);
  8596. }
  8597. boxMesh.material.uniforms.envMap.value = background;
  8598. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background._needsFlipEnvMap ? -1 : 1;
  8599. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8600. boxMesh.material.needsUpdate = true;
  8601. currentBackground = background;
  8602. currentBackgroundVersion = background.version;
  8603. currentTonemapping = renderer.toneMapping;
  8604. } // push to the pre-sorted opaque render list
  8605. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  8606. } else if (background && background.isTexture) {
  8607. if (planeMesh === undefined) {
  8608. planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
  8609. name: 'BackgroundMaterial',
  8610. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  8611. vertexShader: ShaderLib.background.vertexShader,
  8612. fragmentShader: ShaderLib.background.fragmentShader,
  8613. side: FrontSide,
  8614. depthTest: false,
  8615. depthWrite: false,
  8616. fog: false
  8617. }));
  8618. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  8619. Object.defineProperty(planeMesh.material, 'map', {
  8620. get: function () {
  8621. return this.uniforms.t2D.value;
  8622. }
  8623. });
  8624. objects.update(planeMesh);
  8625. }
  8626. planeMesh.material.uniforms.t2D.value = background;
  8627. if (background.matrixAutoUpdate === true) {
  8628. background.updateMatrix();
  8629. }
  8630. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  8631. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8632. planeMesh.material.needsUpdate = true;
  8633. currentBackground = background;
  8634. currentBackgroundVersion = background.version;
  8635. currentTonemapping = renderer.toneMapping;
  8636. } // push to the pre-sorted opaque render list
  8637. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  8638. }
  8639. }
  8640. function setClear(color, alpha) {
  8641. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  8642. }
  8643. return {
  8644. getClearColor: function () {
  8645. return clearColor;
  8646. },
  8647. setClearColor: function (color, alpha = 1) {
  8648. clearColor.set(color);
  8649. clearAlpha = alpha;
  8650. setClear(clearColor, clearAlpha);
  8651. },
  8652. getClearAlpha: function () {
  8653. return clearAlpha;
  8654. },
  8655. setClearAlpha: function (alpha) {
  8656. clearAlpha = alpha;
  8657. setClear(clearColor, clearAlpha);
  8658. },
  8659. render: render
  8660. };
  8661. }
  8662. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  8663. const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  8664. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  8665. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8666. const bindingStates = {};
  8667. const defaultState = createBindingState(null);
  8668. let currentState = defaultState;
  8669. function setup(object, material, program, geometry, index) {
  8670. let updateBuffers = false;
  8671. if (vaoAvailable) {
  8672. const state = getBindingState(geometry, program, material);
  8673. if (currentState !== state) {
  8674. currentState = state;
  8675. bindVertexArrayObject(currentState.object);
  8676. }
  8677. updateBuffers = needsUpdate(geometry, index);
  8678. if (updateBuffers) saveCache(geometry, index);
  8679. } else {
  8680. const wireframe = material.wireframe === true;
  8681. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  8682. currentState.geometry = geometry.id;
  8683. currentState.program = program.id;
  8684. currentState.wireframe = wireframe;
  8685. updateBuffers = true;
  8686. }
  8687. }
  8688. if (object.isInstancedMesh === true) {
  8689. updateBuffers = true;
  8690. }
  8691. if (index !== null) {
  8692. attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
  8693. }
  8694. if (updateBuffers) {
  8695. setupVertexAttributes(object, material, program, geometry);
  8696. if (index !== null) {
  8697. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
  8698. }
  8699. }
  8700. }
  8701. function createVertexArrayObject() {
  8702. if (capabilities.isWebGL2) return gl.createVertexArray();
  8703. return extension.createVertexArrayOES();
  8704. }
  8705. function bindVertexArrayObject(vao) {
  8706. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  8707. return extension.bindVertexArrayOES(vao);
  8708. }
  8709. function deleteVertexArrayObject(vao) {
  8710. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  8711. return extension.deleteVertexArrayOES(vao);
  8712. }
  8713. function getBindingState(geometry, program, material) {
  8714. const wireframe = material.wireframe === true;
  8715. let programMap = bindingStates[geometry.id];
  8716. if (programMap === undefined) {
  8717. programMap = {};
  8718. bindingStates[geometry.id] = programMap;
  8719. }
  8720. let stateMap = programMap[program.id];
  8721. if (stateMap === undefined) {
  8722. stateMap = {};
  8723. programMap[program.id] = stateMap;
  8724. }
  8725. let state = stateMap[wireframe];
  8726. if (state === undefined) {
  8727. state = createBindingState(createVertexArrayObject());
  8728. stateMap[wireframe] = state;
  8729. }
  8730. return state;
  8731. }
  8732. function createBindingState(vao) {
  8733. const newAttributes = [];
  8734. const enabledAttributes = [];
  8735. const attributeDivisors = [];
  8736. for (let i = 0; i < maxVertexAttributes; i++) {
  8737. newAttributes[i] = 0;
  8738. enabledAttributes[i] = 0;
  8739. attributeDivisors[i] = 0;
  8740. }
  8741. return {
  8742. // for backward compatibility on non-VAO support browser
  8743. geometry: null,
  8744. program: null,
  8745. wireframe: false,
  8746. newAttributes: newAttributes,
  8747. enabledAttributes: enabledAttributes,
  8748. attributeDivisors: attributeDivisors,
  8749. object: vao,
  8750. attributes: {},
  8751. index: null
  8752. };
  8753. }
  8754. function needsUpdate(geometry, index) {
  8755. const cachedAttributes = currentState.attributes;
  8756. const geometryAttributes = geometry.attributes;
  8757. let attributesNum = 0;
  8758. for (const key in geometryAttributes) {
  8759. const cachedAttribute = cachedAttributes[key];
  8760. const geometryAttribute = geometryAttributes[key];
  8761. if (cachedAttribute === undefined) return true;
  8762. if (cachedAttribute.attribute !== geometryAttribute) return true;
  8763. if (cachedAttribute.data !== geometryAttribute.data) return true;
  8764. attributesNum++;
  8765. }
  8766. if (currentState.attributesNum !== attributesNum) return true;
  8767. if (currentState.index !== index) return true;
  8768. return false;
  8769. }
  8770. function saveCache(geometry, index) {
  8771. const cache = {};
  8772. const attributes = geometry.attributes;
  8773. let attributesNum = 0;
  8774. for (const key in attributes) {
  8775. const attribute = attributes[key];
  8776. const data = {};
  8777. data.attribute = attribute;
  8778. if (attribute.data) {
  8779. data.data = attribute.data;
  8780. }
  8781. cache[key] = data;
  8782. attributesNum++;
  8783. }
  8784. currentState.attributes = cache;
  8785. currentState.attributesNum = attributesNum;
  8786. currentState.index = index;
  8787. }
  8788. function initAttributes() {
  8789. const newAttributes = currentState.newAttributes;
  8790. for (let i = 0, il = newAttributes.length; i < il; i++) {
  8791. newAttributes[i] = 0;
  8792. }
  8793. }
  8794. function enableAttribute(attribute) {
  8795. enableAttributeAndDivisor(attribute, 0);
  8796. }
  8797. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  8798. const newAttributes = currentState.newAttributes;
  8799. const enabledAttributes = currentState.enabledAttributes;
  8800. const attributeDivisors = currentState.attributeDivisors;
  8801. newAttributes[attribute] = 1;
  8802. if (enabledAttributes[attribute] === 0) {
  8803. gl.enableVertexAttribArray(attribute);
  8804. enabledAttributes[attribute] = 1;
  8805. }
  8806. if (attributeDivisors[attribute] !== meshPerAttribute) {
  8807. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  8808. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  8809. attributeDivisors[attribute] = meshPerAttribute;
  8810. }
  8811. }
  8812. function disableUnusedAttributes() {
  8813. const newAttributes = currentState.newAttributes;
  8814. const enabledAttributes = currentState.enabledAttributes;
  8815. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  8816. if (enabledAttributes[i] !== newAttributes[i]) {
  8817. gl.disableVertexAttribArray(i);
  8818. enabledAttributes[i] = 0;
  8819. }
  8820. }
  8821. }
  8822. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  8823. if (capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT)) {
  8824. gl.vertexAttribIPointer(index, size, type, stride, offset);
  8825. } else {
  8826. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  8827. }
  8828. }
  8829. function setupVertexAttributes(object, material, program, geometry) {
  8830. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  8831. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  8832. }
  8833. initAttributes();
  8834. const geometryAttributes = geometry.attributes;
  8835. const programAttributes = program.getAttributes();
  8836. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8837. for (const name in programAttributes) {
  8838. const programAttribute = programAttributes[name];
  8839. if (programAttribute >= 0) {
  8840. const geometryAttribute = geometryAttributes[name];
  8841. if (geometryAttribute !== undefined) {
  8842. const normalized = geometryAttribute.normalized;
  8843. const size = geometryAttribute.itemSize;
  8844. const attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  8845. if (attribute === undefined) continue;
  8846. const buffer = attribute.buffer;
  8847. const type = attribute.type;
  8848. const bytesPerElement = attribute.bytesPerElement;
  8849. if (geometryAttribute.isInterleavedBufferAttribute) {
  8850. const data = geometryAttribute.data;
  8851. const stride = data.stride;
  8852. const offset = geometryAttribute.offset;
  8853. if (data && data.isInstancedInterleavedBuffer) {
  8854. enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  8855. if (geometry._maxInstanceCount === undefined) {
  8856. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8857. }
  8858. } else {
  8859. enableAttribute(programAttribute);
  8860. }
  8861. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8862. vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  8863. } else {
  8864. if (geometryAttribute.isInstancedBufferAttribute) {
  8865. enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  8866. if (geometry._maxInstanceCount === undefined) {
  8867. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8868. }
  8869. } else {
  8870. enableAttribute(programAttribute);
  8871. }
  8872. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8873. vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  8874. }
  8875. } else if (name === 'instanceMatrix') {
  8876. const attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  8877. if (attribute === undefined) continue;
  8878. const buffer = attribute.buffer;
  8879. const type = attribute.type;
  8880. enableAttributeAndDivisor(programAttribute + 0, 1);
  8881. enableAttributeAndDivisor(programAttribute + 1, 1);
  8882. enableAttributeAndDivisor(programAttribute + 2, 1);
  8883. enableAttributeAndDivisor(programAttribute + 3, 1);
  8884. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8885. gl.vertexAttribPointer(programAttribute + 0, 4, type, false, 64, 0);
  8886. gl.vertexAttribPointer(programAttribute + 1, 4, type, false, 64, 16);
  8887. gl.vertexAttribPointer(programAttribute + 2, 4, type, false, 64, 32);
  8888. gl.vertexAttribPointer(programAttribute + 3, 4, type, false, 64, 48);
  8889. } else if (name === 'instanceColor') {
  8890. const attribute = attributes.get(object.instanceColor); // TODO Attribute may not be available on context restore
  8891. if (attribute === undefined) continue;
  8892. const buffer = attribute.buffer;
  8893. const type = attribute.type;
  8894. enableAttributeAndDivisor(programAttribute, 1);
  8895. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8896. gl.vertexAttribPointer(programAttribute, 3, type, false, 12, 0);
  8897. } else if (materialDefaultAttributeValues !== undefined) {
  8898. const value = materialDefaultAttributeValues[name];
  8899. if (value !== undefined) {
  8900. switch (value.length) {
  8901. case 2:
  8902. gl.vertexAttrib2fv(programAttribute, value);
  8903. break;
  8904. case 3:
  8905. gl.vertexAttrib3fv(programAttribute, value);
  8906. break;
  8907. case 4:
  8908. gl.vertexAttrib4fv(programAttribute, value);
  8909. break;
  8910. default:
  8911. gl.vertexAttrib1fv(programAttribute, value);
  8912. }
  8913. }
  8914. }
  8915. }
  8916. }
  8917. disableUnusedAttributes();
  8918. }
  8919. function dispose() {
  8920. reset();
  8921. for (const geometryId in bindingStates) {
  8922. const programMap = bindingStates[geometryId];
  8923. for (const programId in programMap) {
  8924. const stateMap = programMap[programId];
  8925. for (const wireframe in stateMap) {
  8926. deleteVertexArrayObject(stateMap[wireframe].object);
  8927. delete stateMap[wireframe];
  8928. }
  8929. delete programMap[programId];
  8930. }
  8931. delete bindingStates[geometryId];
  8932. }
  8933. }
  8934. function releaseStatesOfGeometry(geometry) {
  8935. if (bindingStates[geometry.id] === undefined) return;
  8936. const programMap = bindingStates[geometry.id];
  8937. for (const programId in programMap) {
  8938. const stateMap = programMap[programId];
  8939. for (const wireframe in stateMap) {
  8940. deleteVertexArrayObject(stateMap[wireframe].object);
  8941. delete stateMap[wireframe];
  8942. }
  8943. delete programMap[programId];
  8944. }
  8945. delete bindingStates[geometry.id];
  8946. }
  8947. function releaseStatesOfProgram(program) {
  8948. for (const geometryId in bindingStates) {
  8949. const programMap = bindingStates[geometryId];
  8950. if (programMap[program.id] === undefined) continue;
  8951. const stateMap = programMap[program.id];
  8952. for (const wireframe in stateMap) {
  8953. deleteVertexArrayObject(stateMap[wireframe].object);
  8954. delete stateMap[wireframe];
  8955. }
  8956. delete programMap[program.id];
  8957. }
  8958. }
  8959. function reset() {
  8960. resetDefaultState();
  8961. if (currentState === defaultState) return;
  8962. currentState = defaultState;
  8963. bindVertexArrayObject(currentState.object);
  8964. } // for backward-compatilibity
  8965. function resetDefaultState() {
  8966. defaultState.geometry = null;
  8967. defaultState.program = null;
  8968. defaultState.wireframe = false;
  8969. }
  8970. return {
  8971. setup: setup,
  8972. reset: reset,
  8973. resetDefaultState: resetDefaultState,
  8974. dispose: dispose,
  8975. releaseStatesOfGeometry: releaseStatesOfGeometry,
  8976. releaseStatesOfProgram: releaseStatesOfProgram,
  8977. initAttributes: initAttributes,
  8978. enableAttribute: enableAttribute,
  8979. disableUnusedAttributes: disableUnusedAttributes
  8980. };
  8981. }
  8982. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  8983. const isWebGL2 = capabilities.isWebGL2;
  8984. let mode;
  8985. function setMode(value) {
  8986. mode = value;
  8987. }
  8988. function render(start, count) {
  8989. gl.drawArrays(mode, start, count);
  8990. info.update(count, mode, 1);
  8991. }
  8992. function renderInstances(start, count, primcount) {
  8993. if (primcount === 0) return;
  8994. let extension, methodName;
  8995. if (isWebGL2) {
  8996. extension = gl;
  8997. methodName = 'drawArraysInstanced';
  8998. } else {
  8999. extension = extensions.get('ANGLE_instanced_arrays');
  9000. methodName = 'drawArraysInstancedANGLE';
  9001. if (extension === null) {
  9002. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9003. return;
  9004. }
  9005. }
  9006. extension[methodName](mode, start, count, primcount);
  9007. info.update(count, mode, primcount);
  9008. } //
  9009. this.setMode = setMode;
  9010. this.render = render;
  9011. this.renderInstances = renderInstances;
  9012. }
  9013. function WebGLCapabilities(gl, extensions, parameters) {
  9014. let maxAnisotropy;
  9015. function getMaxAnisotropy() {
  9016. if (maxAnisotropy !== undefined) return maxAnisotropy;
  9017. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  9018. const extension = extensions.get('EXT_texture_filter_anisotropic');
  9019. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  9020. } else {
  9021. maxAnisotropy = 0;
  9022. }
  9023. return maxAnisotropy;
  9024. }
  9025. function getMaxPrecision(precision) {
  9026. if (precision === 'highp') {
  9027. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
  9028. return 'highp';
  9029. }
  9030. precision = 'mediump';
  9031. }
  9032. if (precision === 'mediump') {
  9033. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
  9034. return 'mediump';
  9035. }
  9036. }
  9037. return 'lowp';
  9038. }
  9039. /* eslint-disable no-undef */
  9040. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  9041. /* eslint-enable no-undef */
  9042. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9043. const maxPrecision = getMaxPrecision(precision);
  9044. if (maxPrecision !== precision) {
  9045. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  9046. precision = maxPrecision;
  9047. }
  9048. const drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers');
  9049. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9050. const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  9051. const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9052. const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  9053. const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9054. const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  9055. const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
  9056. const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
  9057. const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9058. const vertexTextures = maxVertexTextures > 0;
  9059. const floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float');
  9060. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9061. const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
  9062. return {
  9063. isWebGL2: isWebGL2,
  9064. drawBuffers: drawBuffers,
  9065. getMaxAnisotropy: getMaxAnisotropy,
  9066. getMaxPrecision: getMaxPrecision,
  9067. precision: precision,
  9068. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9069. maxTextures: maxTextures,
  9070. maxVertexTextures: maxVertexTextures,
  9071. maxTextureSize: maxTextureSize,
  9072. maxCubemapSize: maxCubemapSize,
  9073. maxAttributes: maxAttributes,
  9074. maxVertexUniforms: maxVertexUniforms,
  9075. maxVaryings: maxVaryings,
  9076. maxFragmentUniforms: maxFragmentUniforms,
  9077. vertexTextures: vertexTextures,
  9078. floatFragmentTextures: floatFragmentTextures,
  9079. floatVertexTextures: floatVertexTextures,
  9080. maxSamples: maxSamples
  9081. };
  9082. }
  9083. function WebGLClipping(properties) {
  9084. const scope = this;
  9085. let globalState = null,
  9086. numGlobalPlanes = 0,
  9087. localClippingEnabled = false,
  9088. renderingShadows = false;
  9089. const plane = new Plane(),
  9090. viewNormalMatrix = new Matrix3(),
  9091. uniform = {
  9092. value: null,
  9093. needsUpdate: false
  9094. };
  9095. this.uniform = uniform;
  9096. this.numPlanes = 0;
  9097. this.numIntersection = 0;
  9098. this.init = function (planes, enableLocalClipping, camera) {
  9099. const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  9100. // run another frame in order to reset the state:
  9101. numGlobalPlanes !== 0 || localClippingEnabled;
  9102. localClippingEnabled = enableLocalClipping;
  9103. globalState = projectPlanes(planes, camera, 0);
  9104. numGlobalPlanes = planes.length;
  9105. return enabled;
  9106. };
  9107. this.beginShadows = function () {
  9108. renderingShadows = true;
  9109. projectPlanes(null);
  9110. };
  9111. this.endShadows = function () {
  9112. renderingShadows = false;
  9113. resetGlobalState();
  9114. };
  9115. this.setState = function (material, camera, useCache) {
  9116. const planes = material.clippingPlanes,
  9117. clipIntersection = material.clipIntersection,
  9118. clipShadows = material.clipShadows;
  9119. const materialProperties = properties.get(material);
  9120. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  9121. // there's no local clipping
  9122. if (renderingShadows) {
  9123. // there's no global clipping
  9124. projectPlanes(null);
  9125. } else {
  9126. resetGlobalState();
  9127. }
  9128. } else {
  9129. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9130. lGlobal = nGlobal * 4;
  9131. let dstArray = materialProperties.clippingState || null;
  9132. uniform.value = dstArray; // ensure unique state
  9133. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  9134. for (let i = 0; i !== lGlobal; ++i) {
  9135. dstArray[i] = globalState[i];
  9136. }
  9137. materialProperties.clippingState = dstArray;
  9138. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9139. this.numPlanes += nGlobal;
  9140. }
  9141. };
  9142. function resetGlobalState() {
  9143. if (uniform.value !== globalState) {
  9144. uniform.value = globalState;
  9145. uniform.needsUpdate = numGlobalPlanes > 0;
  9146. }
  9147. scope.numPlanes = numGlobalPlanes;
  9148. scope.numIntersection = 0;
  9149. }
  9150. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  9151. const nPlanes = planes !== null ? planes.length : 0;
  9152. let dstArray = null;
  9153. if (nPlanes !== 0) {
  9154. dstArray = uniform.value;
  9155. if (skipTransform !== true || dstArray === null) {
  9156. const flatSize = dstOffset + nPlanes * 4,
  9157. viewMatrix = camera.matrixWorldInverse;
  9158. viewNormalMatrix.getNormalMatrix(viewMatrix);
  9159. if (dstArray === null || dstArray.length < flatSize) {
  9160. dstArray = new Float32Array(flatSize);
  9161. }
  9162. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  9163. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  9164. plane.normal.toArray(dstArray, i4);
  9165. dstArray[i4 + 3] = plane.constant;
  9166. }
  9167. }
  9168. uniform.value = dstArray;
  9169. uniform.needsUpdate = true;
  9170. }
  9171. scope.numPlanes = nPlanes;
  9172. scope.numIntersection = 0;
  9173. return dstArray;
  9174. }
  9175. }
  9176. function WebGLCubeMaps(renderer) {
  9177. let cubemaps = new WeakMap();
  9178. function mapTextureMapping(texture, mapping) {
  9179. if (mapping === EquirectangularReflectionMapping) {
  9180. texture.mapping = CubeReflectionMapping;
  9181. } else if (mapping === EquirectangularRefractionMapping) {
  9182. texture.mapping = CubeRefractionMapping;
  9183. }
  9184. return texture;
  9185. }
  9186. function get(texture) {
  9187. if (texture && texture.isTexture) {
  9188. const mapping = texture.mapping;
  9189. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  9190. if (cubemaps.has(texture)) {
  9191. const cubemap = cubemaps.get(texture).texture;
  9192. return mapTextureMapping(cubemap, texture.mapping);
  9193. } else {
  9194. const image = texture.image;
  9195. if (image && image.height > 0) {
  9196. const currentRenderTarget = renderer.getRenderTarget();
  9197. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  9198. renderTarget.fromEquirectangularTexture(renderer, texture);
  9199. cubemaps.set(texture, renderTarget);
  9200. renderer.setRenderTarget(currentRenderTarget);
  9201. texture.addEventListener('dispose', onTextureDispose);
  9202. return mapTextureMapping(renderTarget.texture, texture.mapping);
  9203. } else {
  9204. // image not yet ready. try the conversion next frame
  9205. return null;
  9206. }
  9207. }
  9208. }
  9209. }
  9210. return texture;
  9211. }
  9212. function onTextureDispose(event) {
  9213. const texture = event.target;
  9214. texture.removeEventListener('dispose', onTextureDispose);
  9215. const cubemap = cubemaps.get(texture);
  9216. if (cubemap !== undefined) {
  9217. cubemaps.delete(texture);
  9218. cubemap.dispose();
  9219. }
  9220. }
  9221. function dispose() {
  9222. cubemaps = new WeakMap();
  9223. }
  9224. return {
  9225. get: get,
  9226. dispose: dispose
  9227. };
  9228. }
  9229. function WebGLExtensions(gl) {
  9230. const extensions = {};
  9231. function getExtension(name) {
  9232. if (extensions[name] !== undefined) {
  9233. return extensions[name];
  9234. }
  9235. let extension;
  9236. switch (name) {
  9237. case 'WEBGL_depth_texture':
  9238. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  9239. break;
  9240. case 'EXT_texture_filter_anisotropic':
  9241. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  9242. break;
  9243. case 'WEBGL_compressed_texture_s3tc':
  9244. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  9245. break;
  9246. case 'WEBGL_compressed_texture_pvrtc':
  9247. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  9248. break;
  9249. default:
  9250. extension = gl.getExtension(name);
  9251. }
  9252. extensions[name] = extension;
  9253. return extension;
  9254. }
  9255. return {
  9256. has: function (name) {
  9257. return getExtension(name) !== null;
  9258. },
  9259. init: function (capabilities) {
  9260. if (capabilities.isWebGL2) {
  9261. getExtension('EXT_color_buffer_float');
  9262. } else {
  9263. getExtension('WEBGL_depth_texture');
  9264. getExtension('OES_texture_float');
  9265. getExtension('OES_texture_half_float');
  9266. getExtension('OES_texture_half_float_linear');
  9267. getExtension('OES_standard_derivatives');
  9268. getExtension('OES_element_index_uint');
  9269. getExtension('OES_vertex_array_object');
  9270. getExtension('ANGLE_instanced_arrays');
  9271. }
  9272. getExtension('OES_texture_float_linear');
  9273. getExtension('EXT_color_buffer_half_float');
  9274. },
  9275. get: function (name) {
  9276. const extension = getExtension(name);
  9277. if (extension === null) {
  9278. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  9279. }
  9280. return extension;
  9281. }
  9282. };
  9283. }
  9284. function WebGLGeometries(gl, attributes, info, bindingStates) {
  9285. const geometries = {};
  9286. const wireframeAttributes = new WeakMap();
  9287. function onGeometryDispose(event) {
  9288. const geometry = event.target;
  9289. if (geometry.index !== null) {
  9290. attributes.remove(geometry.index);
  9291. }
  9292. for (const name in geometry.attributes) {
  9293. attributes.remove(geometry.attributes[name]);
  9294. }
  9295. geometry.removeEventListener('dispose', onGeometryDispose);
  9296. delete geometries[geometry.id];
  9297. const attribute = wireframeAttributes.get(geometry);
  9298. if (attribute) {
  9299. attributes.remove(attribute);
  9300. wireframeAttributes.delete(geometry);
  9301. }
  9302. bindingStates.releaseStatesOfGeometry(geometry);
  9303. if (geometry.isInstancedBufferGeometry === true) {
  9304. delete geometry._maxInstanceCount;
  9305. } //
  9306. info.memory.geometries--;
  9307. }
  9308. function get(object, geometry) {
  9309. if (geometries[geometry.id] === true) return geometry;
  9310. geometry.addEventListener('dispose', onGeometryDispose);
  9311. geometries[geometry.id] = true;
  9312. info.memory.geometries++;
  9313. return geometry;
  9314. }
  9315. function update(geometry) {
  9316. const geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  9317. for (const name in geometryAttributes) {
  9318. attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
  9319. } // morph targets
  9320. const morphAttributes = geometry.morphAttributes;
  9321. for (const name in morphAttributes) {
  9322. const array = morphAttributes[name];
  9323. for (let i = 0, l = array.length; i < l; i++) {
  9324. attributes.update(array[i], gl.ARRAY_BUFFER);
  9325. }
  9326. }
  9327. }
  9328. function updateWireframeAttribute(geometry) {
  9329. const indices = [];
  9330. const geometryIndex = geometry.index;
  9331. const geometryPosition = geometry.attributes.position;
  9332. let version = 0;
  9333. if (geometryIndex !== null) {
  9334. const array = geometryIndex.array;
  9335. version = geometryIndex.version;
  9336. for (let i = 0, l = array.length; i < l; i += 3) {
  9337. const a = array[i + 0];
  9338. const b = array[i + 1];
  9339. const c = array[i + 2];
  9340. indices.push(a, b, b, c, c, a);
  9341. }
  9342. } else {
  9343. const array = geometryPosition.array;
  9344. version = geometryPosition.version;
  9345. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  9346. const a = i + 0;
  9347. const b = i + 1;
  9348. const c = i + 2;
  9349. indices.push(a, b, b, c, c, a);
  9350. }
  9351. }
  9352. const attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  9353. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  9354. //
  9355. const previousAttribute = wireframeAttributes.get(geometry);
  9356. if (previousAttribute) attributes.remove(previousAttribute); //
  9357. wireframeAttributes.set(geometry, attribute);
  9358. }
  9359. function getWireframeAttribute(geometry) {
  9360. const currentAttribute = wireframeAttributes.get(geometry);
  9361. if (currentAttribute) {
  9362. const geometryIndex = geometry.index;
  9363. if (geometryIndex !== null) {
  9364. // if the attribute is obsolete, create a new one
  9365. if (currentAttribute.version < geometryIndex.version) {
  9366. updateWireframeAttribute(geometry);
  9367. }
  9368. }
  9369. } else {
  9370. updateWireframeAttribute(geometry);
  9371. }
  9372. return wireframeAttributes.get(geometry);
  9373. }
  9374. return {
  9375. get: get,
  9376. update: update,
  9377. getWireframeAttribute: getWireframeAttribute
  9378. };
  9379. }
  9380. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  9381. const isWebGL2 = capabilities.isWebGL2;
  9382. let mode;
  9383. function setMode(value) {
  9384. mode = value;
  9385. }
  9386. let type, bytesPerElement;
  9387. function setIndex(value) {
  9388. type = value.type;
  9389. bytesPerElement = value.bytesPerElement;
  9390. }
  9391. function render(start, count) {
  9392. gl.drawElements(mode, count, type, start * bytesPerElement);
  9393. info.update(count, mode, 1);
  9394. }
  9395. function renderInstances(start, count, primcount) {
  9396. if (primcount === 0) return;
  9397. let extension, methodName;
  9398. if (isWebGL2) {
  9399. extension = gl;
  9400. methodName = 'drawElementsInstanced';
  9401. } else {
  9402. extension = extensions.get('ANGLE_instanced_arrays');
  9403. methodName = 'drawElementsInstancedANGLE';
  9404. if (extension === null) {
  9405. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9406. return;
  9407. }
  9408. }
  9409. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  9410. info.update(count, mode, primcount);
  9411. } //
  9412. this.setMode = setMode;
  9413. this.setIndex = setIndex;
  9414. this.render = render;
  9415. this.renderInstances = renderInstances;
  9416. }
  9417. function WebGLInfo(gl) {
  9418. const memory = {
  9419. geometries: 0,
  9420. textures: 0
  9421. };
  9422. const render = {
  9423. frame: 0,
  9424. calls: 0,
  9425. triangles: 0,
  9426. points: 0,
  9427. lines: 0
  9428. };
  9429. function update(count, mode, instanceCount) {
  9430. render.calls++;
  9431. switch (mode) {
  9432. case gl.TRIANGLES:
  9433. render.triangles += instanceCount * (count / 3);
  9434. break;
  9435. case gl.LINES:
  9436. render.lines += instanceCount * (count / 2);
  9437. break;
  9438. case gl.LINE_STRIP:
  9439. render.lines += instanceCount * (count - 1);
  9440. break;
  9441. case gl.LINE_LOOP:
  9442. render.lines += instanceCount * count;
  9443. break;
  9444. case gl.POINTS:
  9445. render.points += instanceCount * count;
  9446. break;
  9447. default:
  9448. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  9449. break;
  9450. }
  9451. }
  9452. function reset() {
  9453. render.frame++;
  9454. render.calls = 0;
  9455. render.triangles = 0;
  9456. render.points = 0;
  9457. render.lines = 0;
  9458. }
  9459. return {
  9460. memory: memory,
  9461. render: render,
  9462. programs: null,
  9463. autoReset: true,
  9464. reset: reset,
  9465. update: update
  9466. };
  9467. }
  9468. function numericalSort(a, b) {
  9469. return a[0] - b[0];
  9470. }
  9471. function absNumericalSort(a, b) {
  9472. return Math.abs(b[1]) - Math.abs(a[1]);
  9473. }
  9474. function WebGLMorphtargets(gl) {
  9475. const influencesList = {};
  9476. const morphInfluences = new Float32Array(8);
  9477. const workInfluences = [];
  9478. for (let i = 0; i < 8; i++) {
  9479. workInfluences[i] = [i, 0];
  9480. }
  9481. function update(object, geometry, material, program) {
  9482. const objectInfluences = object.morphTargetInfluences; // When object doesn't have morph target influences defined, we treat it as a 0-length array
  9483. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  9484. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  9485. let influences = influencesList[geometry.id];
  9486. if (influences === undefined || influences.length !== length) {
  9487. // initialise list
  9488. influences = [];
  9489. for (let i = 0; i < length; i++) {
  9490. influences[i] = [i, 0];
  9491. }
  9492. influencesList[geometry.id] = influences;
  9493. } // Collect influences
  9494. for (let i = 0; i < length; i++) {
  9495. const influence = influences[i];
  9496. influence[0] = i;
  9497. influence[1] = objectInfluences[i];
  9498. }
  9499. influences.sort(absNumericalSort);
  9500. for (let i = 0; i < 8; i++) {
  9501. if (i < length && influences[i][1]) {
  9502. workInfluences[i][0] = influences[i][0];
  9503. workInfluences[i][1] = influences[i][1];
  9504. } else {
  9505. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  9506. workInfluences[i][1] = 0;
  9507. }
  9508. }
  9509. workInfluences.sort(numericalSort);
  9510. const morphTargets = geometry.morphAttributes.position;
  9511. const morphNormals = geometry.morphAttributes.normal;
  9512. let morphInfluencesSum = 0;
  9513. for (let i = 0; i < 8; i++) {
  9514. const influence = workInfluences[i];
  9515. const index = influence[0];
  9516. const value = influence[1];
  9517. if (index !== Number.MAX_SAFE_INTEGER && value) {
  9518. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  9519. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  9520. }
  9521. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  9522. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  9523. }
  9524. morphInfluences[i] = value;
  9525. morphInfluencesSum += value;
  9526. } else {
  9527. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  9528. geometry.deleteAttribute('morphTarget' + i);
  9529. }
  9530. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  9531. geometry.deleteAttribute('morphNormal' + i);
  9532. }
  9533. morphInfluences[i] = 0;
  9534. }
  9535. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  9536. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  9537. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  9538. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  9539. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  9540. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  9541. }
  9542. return {
  9543. update: update
  9544. };
  9545. }
  9546. function WebGLObjects(gl, geometries, attributes, info) {
  9547. let updateMap = new WeakMap();
  9548. function update(object) {
  9549. const frame = info.render.frame;
  9550. const geometry = object.geometry;
  9551. const buffergeometry = geometries.get(object, geometry); // Update once per frame
  9552. if (updateMap.get(buffergeometry) !== frame) {
  9553. geometries.update(buffergeometry);
  9554. updateMap.set(buffergeometry, frame);
  9555. }
  9556. if (object.isInstancedMesh) {
  9557. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  9558. object.addEventListener('dispose', onInstancedMeshDispose);
  9559. }
  9560. attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
  9561. if (object.instanceColor !== null) {
  9562. attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
  9563. }
  9564. }
  9565. return buffergeometry;
  9566. }
  9567. function dispose() {
  9568. updateMap = new WeakMap();
  9569. }
  9570. function onInstancedMeshDispose(event) {
  9571. const instancedMesh = event.target;
  9572. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  9573. attributes.remove(instancedMesh.instanceMatrix);
  9574. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  9575. }
  9576. return {
  9577. update: update,
  9578. dispose: dispose
  9579. };
  9580. }
  9581. class DataTexture2DArray extends Texture {
  9582. constructor(data = null, width = 1, height = 1, depth = 1) {
  9583. super(null);
  9584. this.image = {
  9585. data,
  9586. width,
  9587. height,
  9588. depth
  9589. };
  9590. this.magFilter = NearestFilter;
  9591. this.minFilter = NearestFilter;
  9592. this.wrapR = ClampToEdgeWrapping;
  9593. this.generateMipmaps = false;
  9594. this.flipY = false;
  9595. this.unpackAlignment = 1;
  9596. this.needsUpdate = true;
  9597. }
  9598. }
  9599. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  9600. class DataTexture3D extends Texture {
  9601. constructor(data = null, width = 1, height = 1, depth = 1) {
  9602. // We're going to add .setXXX() methods for setting properties later.
  9603. // Users can still set in DataTexture3D directly.
  9604. //
  9605. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  9606. // texture.anisotropy = 16;
  9607. //
  9608. // See #14839
  9609. super(null);
  9610. this.image = {
  9611. data,
  9612. width,
  9613. height,
  9614. depth
  9615. };
  9616. this.magFilter = NearestFilter;
  9617. this.minFilter = NearestFilter;
  9618. this.wrapR = ClampToEdgeWrapping;
  9619. this.generateMipmaps = false;
  9620. this.flipY = false;
  9621. this.unpackAlignment = 1;
  9622. this.needsUpdate = true;
  9623. }
  9624. }
  9625. DataTexture3D.prototype.isDataTexture3D = true;
  9626. /**
  9627. * Uniforms of a program.
  9628. * Those form a tree structure with a special top-level container for the root,
  9629. * which you get by calling 'new WebGLUniforms( gl, program )'.
  9630. *
  9631. *
  9632. * Properties of inner nodes including the top-level container:
  9633. *
  9634. * .seq - array of nested uniforms
  9635. * .map - nested uniforms by name
  9636. *
  9637. *
  9638. * Methods of all nodes except the top-level container:
  9639. *
  9640. * .setValue( gl, value, [textures] )
  9641. *
  9642. * uploads a uniform value(s)
  9643. * the 'textures' parameter is needed for sampler uniforms
  9644. *
  9645. *
  9646. * Static methods of the top-level container (textures factorizations):
  9647. *
  9648. * .upload( gl, seq, values, textures )
  9649. *
  9650. * sets uniforms in 'seq' to 'values[id].value'
  9651. *
  9652. * .seqWithValue( seq, values ) : filteredSeq
  9653. *
  9654. * filters 'seq' entries with corresponding entry in values
  9655. *
  9656. *
  9657. * Methods of the top-level container (textures factorizations):
  9658. *
  9659. * .setValue( gl, name, value, textures )
  9660. *
  9661. * sets uniform with name 'name' to 'value'
  9662. *
  9663. * .setOptional( gl, obj, prop )
  9664. *
  9665. * like .set for an optional property of the object
  9666. *
  9667. */
  9668. const emptyTexture = new Texture();
  9669. const emptyTexture2dArray = new DataTexture2DArray();
  9670. const emptyTexture3d = new DataTexture3D();
  9671. const emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  9672. // Array Caches (provide typed arrays for temporary by size)
  9673. const arrayCacheF32 = [];
  9674. const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  9675. const mat4array = new Float32Array(16);
  9676. const mat3array = new Float32Array(9);
  9677. const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  9678. function flatten(array, nBlocks, blockSize) {
  9679. const firstElem = array[0];
  9680. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  9681. // see http://jacksondunstan.com/articles/983
  9682. const n = nBlocks * blockSize;
  9683. let r = arrayCacheF32[n];
  9684. if (r === undefined) {
  9685. r = new Float32Array(n);
  9686. arrayCacheF32[n] = r;
  9687. }
  9688. if (nBlocks !== 0) {
  9689. firstElem.toArray(r, 0);
  9690. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  9691. offset += blockSize;
  9692. array[i].toArray(r, offset);
  9693. }
  9694. }
  9695. return r;
  9696. }
  9697. function arraysEqual(a, b) {
  9698. if (a.length !== b.length) return false;
  9699. for (let i = 0, l = a.length; i < l; i++) {
  9700. if (a[i] !== b[i]) return false;
  9701. }
  9702. return true;
  9703. }
  9704. function copyArray(a, b) {
  9705. for (let i = 0, l = b.length; i < l; i++) {
  9706. a[i] = b[i];
  9707. }
  9708. } // Texture unit allocation
  9709. function allocTexUnits(textures, n) {
  9710. let r = arrayCacheI32[n];
  9711. if (r === undefined) {
  9712. r = new Int32Array(n);
  9713. arrayCacheI32[n] = r;
  9714. }
  9715. for (let i = 0; i !== n; ++i) {
  9716. r[i] = textures.allocateTextureUnit();
  9717. }
  9718. return r;
  9719. } // --- Setters ---
  9720. // Note: Defining these methods externally, because they come in a bunch
  9721. // and this way their names minify.
  9722. // Single scalar
  9723. function setValueV1f(gl, v) {
  9724. const cache = this.cache;
  9725. if (cache[0] === v) return;
  9726. gl.uniform1f(this.addr, v);
  9727. cache[0] = v;
  9728. } // Single float vector (from flat array or THREE.VectorN)
  9729. function setValueV2f(gl, v) {
  9730. const cache = this.cache;
  9731. if (v.x !== undefined) {
  9732. if (cache[0] !== v.x || cache[1] !== v.y) {
  9733. gl.uniform2f(this.addr, v.x, v.y);
  9734. cache[0] = v.x;
  9735. cache[1] = v.y;
  9736. }
  9737. } else {
  9738. if (arraysEqual(cache, v)) return;
  9739. gl.uniform2fv(this.addr, v);
  9740. copyArray(cache, v);
  9741. }
  9742. }
  9743. function setValueV3f(gl, v) {
  9744. const cache = this.cache;
  9745. if (v.x !== undefined) {
  9746. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  9747. gl.uniform3f(this.addr, v.x, v.y, v.z);
  9748. cache[0] = v.x;
  9749. cache[1] = v.y;
  9750. cache[2] = v.z;
  9751. }
  9752. } else if (v.r !== undefined) {
  9753. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  9754. gl.uniform3f(this.addr, v.r, v.g, v.b);
  9755. cache[0] = v.r;
  9756. cache[1] = v.g;
  9757. cache[2] = v.b;
  9758. }
  9759. } else {
  9760. if (arraysEqual(cache, v)) return;
  9761. gl.uniform3fv(this.addr, v);
  9762. copyArray(cache, v);
  9763. }
  9764. }
  9765. function setValueV4f(gl, v) {
  9766. const cache = this.cache;
  9767. if (v.x !== undefined) {
  9768. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  9769. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  9770. cache[0] = v.x;
  9771. cache[1] = v.y;
  9772. cache[2] = v.z;
  9773. cache[3] = v.w;
  9774. }
  9775. } else {
  9776. if (arraysEqual(cache, v)) return;
  9777. gl.uniform4fv(this.addr, v);
  9778. copyArray(cache, v);
  9779. }
  9780. } // Single matrix (from flat array or THREE.MatrixN)
  9781. function setValueM2(gl, v) {
  9782. const cache = this.cache;
  9783. const elements = v.elements;
  9784. if (elements === undefined) {
  9785. if (arraysEqual(cache, v)) return;
  9786. gl.uniformMatrix2fv(this.addr, false, v);
  9787. copyArray(cache, v);
  9788. } else {
  9789. if (arraysEqual(cache, elements)) return;
  9790. mat2array.set(elements);
  9791. gl.uniformMatrix2fv(this.addr, false, mat2array);
  9792. copyArray(cache, elements);
  9793. }
  9794. }
  9795. function setValueM3(gl, v) {
  9796. const cache = this.cache;
  9797. const elements = v.elements;
  9798. if (elements === undefined) {
  9799. if (arraysEqual(cache, v)) return;
  9800. gl.uniformMatrix3fv(this.addr, false, v);
  9801. copyArray(cache, v);
  9802. } else {
  9803. if (arraysEqual(cache, elements)) return;
  9804. mat3array.set(elements);
  9805. gl.uniformMatrix3fv(this.addr, false, mat3array);
  9806. copyArray(cache, elements);
  9807. }
  9808. }
  9809. function setValueM4(gl, v) {
  9810. const cache = this.cache;
  9811. const elements = v.elements;
  9812. if (elements === undefined) {
  9813. if (arraysEqual(cache, v)) return;
  9814. gl.uniformMatrix4fv(this.addr, false, v);
  9815. copyArray(cache, v);
  9816. } else {
  9817. if (arraysEqual(cache, elements)) return;
  9818. mat4array.set(elements);
  9819. gl.uniformMatrix4fv(this.addr, false, mat4array);
  9820. copyArray(cache, elements);
  9821. }
  9822. } // Single integer / boolean
  9823. function setValueV1i(gl, v) {
  9824. const cache = this.cache;
  9825. if (cache[0] === v) return;
  9826. gl.uniform1i(this.addr, v);
  9827. cache[0] = v;
  9828. } // Single integer / boolean vector (from flat array)
  9829. function setValueV2i(gl, v) {
  9830. const cache = this.cache;
  9831. if (arraysEqual(cache, v)) return;
  9832. gl.uniform2iv(this.addr, v);
  9833. copyArray(cache, v);
  9834. }
  9835. function setValueV3i(gl, v) {
  9836. const cache = this.cache;
  9837. if (arraysEqual(cache, v)) return;
  9838. gl.uniform3iv(this.addr, v);
  9839. copyArray(cache, v);
  9840. }
  9841. function setValueV4i(gl, v) {
  9842. const cache = this.cache;
  9843. if (arraysEqual(cache, v)) return;
  9844. gl.uniform4iv(this.addr, v);
  9845. copyArray(cache, v);
  9846. } // Single unsigned integer
  9847. function setValueV1ui(gl, v) {
  9848. const cache = this.cache;
  9849. if (cache[0] === v) return;
  9850. gl.uniform1ui(this.addr, v);
  9851. cache[0] = v;
  9852. } // Single unsigned integer vector (from flat array)
  9853. function setValueV2ui(gl, v) {
  9854. const cache = this.cache;
  9855. if (arraysEqual(cache, v)) return;
  9856. gl.uniform2uiv(this.addr, v);
  9857. copyArray(cache, v);
  9858. }
  9859. function setValueV3ui(gl, v) {
  9860. const cache = this.cache;
  9861. if (arraysEqual(cache, v)) return;
  9862. gl.uniform3uiv(this.addr, v);
  9863. copyArray(cache, v);
  9864. }
  9865. function setValueV4ui(gl, v) {
  9866. const cache = this.cache;
  9867. if (arraysEqual(cache, v)) return;
  9868. gl.uniform4uiv(this.addr, v);
  9869. copyArray(cache, v);
  9870. } // Single texture (2D / Cube)
  9871. function setValueT1(gl, v, textures) {
  9872. const cache = this.cache;
  9873. const unit = textures.allocateTextureUnit();
  9874. if (cache[0] !== unit) {
  9875. gl.uniform1i(this.addr, unit);
  9876. cache[0] = unit;
  9877. }
  9878. textures.safeSetTexture2D(v || emptyTexture, unit);
  9879. }
  9880. function setValueT3D1(gl, v, textures) {
  9881. const cache = this.cache;
  9882. const unit = textures.allocateTextureUnit();
  9883. if (cache[0] !== unit) {
  9884. gl.uniform1i(this.addr, unit);
  9885. cache[0] = unit;
  9886. }
  9887. textures.setTexture3D(v || emptyTexture3d, unit);
  9888. }
  9889. function setValueT6(gl, v, textures) {
  9890. const cache = this.cache;
  9891. const unit = textures.allocateTextureUnit();
  9892. if (cache[0] !== unit) {
  9893. gl.uniform1i(this.addr, unit);
  9894. cache[0] = unit;
  9895. }
  9896. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  9897. }
  9898. function setValueT2DArray1(gl, v, textures) {
  9899. const cache = this.cache;
  9900. const unit = textures.allocateTextureUnit();
  9901. if (cache[0] !== unit) {
  9902. gl.uniform1i(this.addr, unit);
  9903. cache[0] = unit;
  9904. }
  9905. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  9906. } // Helper to pick the right setter for the singular case
  9907. function getSingularSetter(type) {
  9908. switch (type) {
  9909. case 0x1406:
  9910. return setValueV1f;
  9911. // FLOAT
  9912. case 0x8b50:
  9913. return setValueV2f;
  9914. // _VEC2
  9915. case 0x8b51:
  9916. return setValueV3f;
  9917. // _VEC3
  9918. case 0x8b52:
  9919. return setValueV4f;
  9920. // _VEC4
  9921. case 0x8b5a:
  9922. return setValueM2;
  9923. // _MAT2
  9924. case 0x8b5b:
  9925. return setValueM3;
  9926. // _MAT3
  9927. case 0x8b5c:
  9928. return setValueM4;
  9929. // _MAT4
  9930. case 0x1404:
  9931. case 0x8b56:
  9932. return setValueV1i;
  9933. // INT, BOOL
  9934. case 0x8b53:
  9935. case 0x8b57:
  9936. return setValueV2i;
  9937. // _VEC2
  9938. case 0x8b54:
  9939. case 0x8b58:
  9940. return setValueV3i;
  9941. // _VEC3
  9942. case 0x8b55:
  9943. case 0x8b59:
  9944. return setValueV4i;
  9945. // _VEC4
  9946. case 0x1405:
  9947. return setValueV1ui;
  9948. // UINT
  9949. case 0x8dc6:
  9950. return setValueV2ui;
  9951. // _VEC2
  9952. case 0x8dc7:
  9953. return setValueV3ui;
  9954. // _VEC3
  9955. case 0x8dc8:
  9956. return setValueV4ui;
  9957. // _VEC4
  9958. case 0x8b5e: // SAMPLER_2D
  9959. case 0x8d66: // SAMPLER_EXTERNAL_OES
  9960. case 0x8dca: // INT_SAMPLER_2D
  9961. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  9962. case 0x8b62:
  9963. // SAMPLER_2D_SHADOW
  9964. return setValueT1;
  9965. case 0x8b5f: // SAMPLER_3D
  9966. case 0x8dcb: // INT_SAMPLER_3D
  9967. case 0x8dd3:
  9968. // UNSIGNED_INT_SAMPLER_3D
  9969. return setValueT3D1;
  9970. case 0x8b60: // SAMPLER_CUBE
  9971. case 0x8dcc: // INT_SAMPLER_CUBE
  9972. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  9973. case 0x8dc5:
  9974. // SAMPLER_CUBE_SHADOW
  9975. return setValueT6;
  9976. case 0x8dc1: // SAMPLER_2D_ARRAY
  9977. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  9978. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  9979. case 0x8dc4:
  9980. // SAMPLER_2D_ARRAY_SHADOW
  9981. return setValueT2DArray1;
  9982. }
  9983. } // Array of scalars
  9984. function setValueV1fArray(gl, v) {
  9985. gl.uniform1fv(this.addr, v);
  9986. } // Array of vectors (from flat array or array of THREE.VectorN)
  9987. function setValueV2fArray(gl, v) {
  9988. const data = flatten(v, this.size, 2);
  9989. gl.uniform2fv(this.addr, data);
  9990. }
  9991. function setValueV3fArray(gl, v) {
  9992. const data = flatten(v, this.size, 3);
  9993. gl.uniform3fv(this.addr, data);
  9994. }
  9995. function setValueV4fArray(gl, v) {
  9996. const data = flatten(v, this.size, 4);
  9997. gl.uniform4fv(this.addr, data);
  9998. } // Array of matrices (from flat array or array of THREE.MatrixN)
  9999. function setValueM2Array(gl, v) {
  10000. const data = flatten(v, this.size, 4);
  10001. gl.uniformMatrix2fv(this.addr, false, data);
  10002. }
  10003. function setValueM3Array(gl, v) {
  10004. const data = flatten(v, this.size, 9);
  10005. gl.uniformMatrix3fv(this.addr, false, data);
  10006. }
  10007. function setValueM4Array(gl, v) {
  10008. const data = flatten(v, this.size, 16);
  10009. gl.uniformMatrix4fv(this.addr, false, data);
  10010. } // Array of integer / boolean
  10011. function setValueV1iArray(gl, v) {
  10012. gl.uniform1iv(this.addr, v);
  10013. } // Array of integer / boolean vectors (from flat array)
  10014. function setValueV2iArray(gl, v) {
  10015. gl.uniform2iv(this.addr, v);
  10016. }
  10017. function setValueV3iArray(gl, v) {
  10018. gl.uniform3iv(this.addr, v);
  10019. }
  10020. function setValueV4iArray(gl, v) {
  10021. gl.uniform4iv(this.addr, v);
  10022. } // Array of unsigned integer
  10023. function setValueV1uiArray(gl, v) {
  10024. gl.uniform1uiv(this.addr, v);
  10025. } // Array of unsigned integer vectors (from flat array)
  10026. function setValueV2uiArray(gl, v) {
  10027. gl.uniform2uiv(this.addr, v);
  10028. }
  10029. function setValueV3uiArray(gl, v) {
  10030. gl.uniform3uiv(this.addr, v);
  10031. }
  10032. function setValueV4uiArray(gl, v) {
  10033. gl.uniform4uiv(this.addr, v);
  10034. } // Array of textures (2D / Cube)
  10035. function setValueT1Array(gl, v, textures) {
  10036. const n = v.length;
  10037. const units = allocTexUnits(textures, n);
  10038. gl.uniform1iv(this.addr, units);
  10039. for (let i = 0; i !== n; ++i) {
  10040. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  10041. }
  10042. }
  10043. function setValueT6Array(gl, v, textures) {
  10044. const n = v.length;
  10045. const units = allocTexUnits(textures, n);
  10046. gl.uniform1iv(this.addr, units);
  10047. for (let i = 0; i !== n; ++i) {
  10048. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  10049. }
  10050. } // Helper to pick the right setter for a pure (bottom-level) array
  10051. function getPureArraySetter(type) {
  10052. switch (type) {
  10053. case 0x1406:
  10054. return setValueV1fArray;
  10055. // FLOAT
  10056. case 0x8b50:
  10057. return setValueV2fArray;
  10058. // _VEC2
  10059. case 0x8b51:
  10060. return setValueV3fArray;
  10061. // _VEC3
  10062. case 0x8b52:
  10063. return setValueV4fArray;
  10064. // _VEC4
  10065. case 0x8b5a:
  10066. return setValueM2Array;
  10067. // _MAT2
  10068. case 0x8b5b:
  10069. return setValueM3Array;
  10070. // _MAT3
  10071. case 0x8b5c:
  10072. return setValueM4Array;
  10073. // _MAT4
  10074. case 0x1404:
  10075. case 0x8b56:
  10076. return setValueV1iArray;
  10077. // INT, BOOL
  10078. case 0x8b53:
  10079. case 0x8b57:
  10080. return setValueV2iArray;
  10081. // _VEC2
  10082. case 0x8b54:
  10083. case 0x8b58:
  10084. return setValueV3iArray;
  10085. // _VEC3
  10086. case 0x8b55:
  10087. case 0x8b59:
  10088. return setValueV4iArray;
  10089. // _VEC4
  10090. case 0x1405:
  10091. return setValueV1uiArray;
  10092. // UINT
  10093. case 0x8dc6:
  10094. return setValueV2uiArray;
  10095. // _VEC2
  10096. case 0x8dc7:
  10097. return setValueV3uiArray;
  10098. // _VEC3
  10099. case 0x8dc8:
  10100. return setValueV4uiArray;
  10101. // _VEC4
  10102. case 0x8b5e: // SAMPLER_2D
  10103. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10104. case 0x8dca: // INT_SAMPLER_2D
  10105. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10106. case 0x8b62:
  10107. // SAMPLER_2D_SHADOW
  10108. return setValueT1Array;
  10109. case 0x8b60: // SAMPLER_CUBE
  10110. case 0x8dcc: // INT_SAMPLER_CUBE
  10111. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10112. case 0x8dc5:
  10113. // SAMPLER_CUBE_SHADOW
  10114. return setValueT6Array;
  10115. }
  10116. } // --- Uniform Classes ---
  10117. function SingleUniform(id, activeInfo, addr) {
  10118. this.id = id;
  10119. this.addr = addr;
  10120. this.cache = [];
  10121. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10122. }
  10123. function PureArrayUniform(id, activeInfo, addr) {
  10124. this.id = id;
  10125. this.addr = addr;
  10126. this.cache = [];
  10127. this.size = activeInfo.size;
  10128. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10129. }
  10130. PureArrayUniform.prototype.updateCache = function (data) {
  10131. const cache = this.cache;
  10132. if (data instanceof Float32Array && cache.length !== data.length) {
  10133. this.cache = new Float32Array(data.length);
  10134. }
  10135. copyArray(cache, data);
  10136. };
  10137. function StructuredUniform(id) {
  10138. this.id = id;
  10139. this.seq = [];
  10140. this.map = {};
  10141. }
  10142. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  10143. const seq = this.seq;
  10144. for (let i = 0, n = seq.length; i !== n; ++i) {
  10145. const u = seq[i];
  10146. u.setValue(gl, value[u.id], textures);
  10147. }
  10148. }; // --- Top-level ---
  10149. // Parser - builds up the property tree from the path strings
  10150. const RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
  10151. // - the identifier (member name or array index)
  10152. // - followed by an optional right bracket (found when array index)
  10153. // - followed by an optional left bracket or dot (type of subscript)
  10154. //
  10155. // Note: These portions can be read in a non-overlapping fashion and
  10156. // allow straightforward parsing of the hierarchy that WebGL encodes
  10157. // in the uniform names.
  10158. function addUniform(container, uniformObject) {
  10159. container.seq.push(uniformObject);
  10160. container.map[uniformObject.id] = uniformObject;
  10161. }
  10162. function parseUniform(activeInfo, addr, container) {
  10163. const path = activeInfo.name,
  10164. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  10165. RePathPart.lastIndex = 0;
  10166. while (true) {
  10167. const match = RePathPart.exec(path),
  10168. matchEnd = RePathPart.lastIndex;
  10169. let id = match[1];
  10170. const idIsIndex = match[2] === ']',
  10171. subscript = match[3];
  10172. if (idIsIndex) id = id | 0; // convert to integer
  10173. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  10174. // bare name or "pure" bottom-level array "[0]" suffix
  10175. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  10176. break;
  10177. } else {
  10178. // step into inner node / create it in case it doesn't exist
  10179. const map = container.map;
  10180. let next = map[id];
  10181. if (next === undefined) {
  10182. next = new StructuredUniform(id);
  10183. addUniform(container, next);
  10184. }
  10185. container = next;
  10186. }
  10187. }
  10188. } // Root Container
  10189. function WebGLUniforms(gl, program) {
  10190. this.seq = [];
  10191. this.map = {};
  10192. const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  10193. for (let i = 0; i < n; ++i) {
  10194. const info = gl.getActiveUniform(program, i),
  10195. addr = gl.getUniformLocation(program, info.name);
  10196. parseUniform(info, addr, this);
  10197. }
  10198. }
  10199. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  10200. const u = this.map[name];
  10201. if (u !== undefined) u.setValue(gl, value, textures);
  10202. };
  10203. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  10204. const v = object[name];
  10205. if (v !== undefined) this.setValue(gl, name, v);
  10206. }; // Static interface
  10207. WebGLUniforms.upload = function (gl, seq, values, textures) {
  10208. for (let i = 0, n = seq.length; i !== n; ++i) {
  10209. const u = seq[i],
  10210. v = values[u.id];
  10211. if (v.needsUpdate !== false) {
  10212. // note: always updating when .needsUpdate is undefined
  10213. u.setValue(gl, v.value, textures);
  10214. }
  10215. }
  10216. };
  10217. WebGLUniforms.seqWithValue = function (seq, values) {
  10218. const r = [];
  10219. for (let i = 0, n = seq.length; i !== n; ++i) {
  10220. const u = seq[i];
  10221. if (u.id in values) r.push(u);
  10222. }
  10223. return r;
  10224. };
  10225. function WebGLShader(gl, type, string) {
  10226. const shader = gl.createShader(type);
  10227. gl.shaderSource(shader, string);
  10228. gl.compileShader(shader);
  10229. return shader;
  10230. }
  10231. let programIdCount = 0;
  10232. function addLineNumbers(string) {
  10233. const lines = string.split('\n');
  10234. for (let i = 0; i < lines.length; i++) {
  10235. lines[i] = i + 1 + ': ' + lines[i];
  10236. }
  10237. return lines.join('\n');
  10238. }
  10239. function getEncodingComponents(encoding) {
  10240. switch (encoding) {
  10241. case LinearEncoding:
  10242. return ['Linear', '( value )'];
  10243. case sRGBEncoding:
  10244. return ['sRGB', '( value )'];
  10245. case RGBEEncoding:
  10246. return ['RGBE', '( value )'];
  10247. case RGBM7Encoding:
  10248. return ['RGBM', '( value, 7.0 )'];
  10249. case RGBM16Encoding:
  10250. return ['RGBM', '( value, 16.0 )'];
  10251. case RGBDEncoding:
  10252. return ['RGBD', '( value, 256.0 )'];
  10253. case GammaEncoding:
  10254. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  10255. case LogLuvEncoding:
  10256. return ['LogLuv', '( value )'];
  10257. default:
  10258. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  10259. return ['Linear', '( value )'];
  10260. }
  10261. }
  10262. function getShaderErrors(gl, shader, type) {
  10263. const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  10264. const log = gl.getShaderInfoLog(shader).trim();
  10265. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  10266. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10267. const source = gl.getShaderSource(shader);
  10268. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  10269. }
  10270. function getTexelDecodingFunction(functionName, encoding) {
  10271. const components = getEncodingComponents(encoding);
  10272. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  10273. }
  10274. function getTexelEncodingFunction(functionName, encoding) {
  10275. const components = getEncodingComponents(encoding);
  10276. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  10277. }
  10278. function getToneMappingFunction(functionName, toneMapping) {
  10279. let toneMappingName;
  10280. switch (toneMapping) {
  10281. case LinearToneMapping:
  10282. toneMappingName = 'Linear';
  10283. break;
  10284. case ReinhardToneMapping:
  10285. toneMappingName = 'Reinhard';
  10286. break;
  10287. case CineonToneMapping:
  10288. toneMappingName = 'OptimizedCineon';
  10289. break;
  10290. case ACESFilmicToneMapping:
  10291. toneMappingName = 'ACESFilmic';
  10292. break;
  10293. case CustomToneMapping:
  10294. toneMappingName = 'Custom';
  10295. break;
  10296. default:
  10297. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  10298. toneMappingName = 'Linear';
  10299. }
  10300. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  10301. }
  10302. function generateExtensions(parameters) {
  10303. 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' : ''];
  10304. return chunks.filter(filterEmptyLine).join('\n');
  10305. }
  10306. function generateDefines(defines) {
  10307. const chunks = [];
  10308. for (const name in defines) {
  10309. const value = defines[name];
  10310. if (value === false) continue;
  10311. chunks.push('#define ' + name + ' ' + value);
  10312. }
  10313. return chunks.join('\n');
  10314. }
  10315. function fetchAttributeLocations(gl, program) {
  10316. const attributes = {};
  10317. const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  10318. for (let i = 0; i < n; i++) {
  10319. const info = gl.getActiveAttrib(program, i);
  10320. const name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  10321. attributes[name] = gl.getAttribLocation(program, name);
  10322. }
  10323. return attributes;
  10324. }
  10325. function filterEmptyLine(string) {
  10326. return string !== '';
  10327. }
  10328. function replaceLightNums(string, parameters) {
  10329. 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);
  10330. }
  10331. function replaceClippingPlaneNums(string, parameters) {
  10332. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  10333. } // Resolve Includes
  10334. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  10335. function resolveIncludes(string) {
  10336. return string.replace(includePattern, includeReplacer);
  10337. }
  10338. function includeReplacer(match, include) {
  10339. const string = ShaderChunk[include];
  10340. if (string === undefined) {
  10341. throw new Error('Can not resolve #include <' + include + '>');
  10342. }
  10343. return resolveIncludes(string);
  10344. } // Unroll Loops
  10345. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10346. 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;
  10347. function unrollLoops(string) {
  10348. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  10349. }
  10350. function deprecatedLoopReplacer(match, start, end, snippet) {
  10351. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  10352. return loopReplacer(match, start, end, snippet);
  10353. }
  10354. function loopReplacer(match, start, end, snippet) {
  10355. let string = '';
  10356. for (let i = parseInt(start); i < parseInt(end); i++) {
  10357. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  10358. }
  10359. return string;
  10360. } //
  10361. function generatePrecision(parameters) {
  10362. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  10363. if (parameters.precision === 'highp') {
  10364. precisionstring += '\n#define HIGH_PRECISION';
  10365. } else if (parameters.precision === 'mediump') {
  10366. precisionstring += '\n#define MEDIUM_PRECISION';
  10367. } else if (parameters.precision === 'lowp') {
  10368. precisionstring += '\n#define LOW_PRECISION';
  10369. }
  10370. return precisionstring;
  10371. }
  10372. function generateShadowMapTypeDefine(parameters) {
  10373. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10374. if (parameters.shadowMapType === PCFShadowMap) {
  10375. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10376. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  10377. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10378. } else if (parameters.shadowMapType === VSMShadowMap) {
  10379. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  10380. }
  10381. return shadowMapTypeDefine;
  10382. }
  10383. function generateEnvMapTypeDefine(parameters) {
  10384. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10385. if (parameters.envMap) {
  10386. switch (parameters.envMapMode) {
  10387. case CubeReflectionMapping:
  10388. case CubeRefractionMapping:
  10389. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10390. break;
  10391. case CubeUVReflectionMapping:
  10392. case CubeUVRefractionMapping:
  10393. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10394. break;
  10395. }
  10396. }
  10397. return envMapTypeDefine;
  10398. }
  10399. function generateEnvMapModeDefine(parameters) {
  10400. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10401. if (parameters.envMap) {
  10402. switch (parameters.envMapMode) {
  10403. case CubeRefractionMapping:
  10404. case CubeUVRefractionMapping:
  10405. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10406. break;
  10407. }
  10408. }
  10409. return envMapModeDefine;
  10410. }
  10411. function generateEnvMapBlendingDefine(parameters) {
  10412. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  10413. if (parameters.envMap) {
  10414. switch (parameters.combine) {
  10415. case MultiplyOperation:
  10416. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10417. break;
  10418. case MixOperation:
  10419. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  10420. break;
  10421. case AddOperation:
  10422. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  10423. break;
  10424. }
  10425. }
  10426. return envMapBlendingDefine;
  10427. }
  10428. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  10429. const gl = renderer.getContext();
  10430. const defines = parameters.defines;
  10431. let vertexShader = parameters.vertexShader;
  10432. let fragmentShader = parameters.fragmentShader;
  10433. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  10434. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  10435. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  10436. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  10437. const gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  10438. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  10439. const customDefines = generateDefines(defines);
  10440. const program = gl.createProgram();
  10441. let prefixVertex, prefixFragment;
  10442. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  10443. if (parameters.isRawShaderMaterial) {
  10444. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  10445. if (prefixVertex.length > 0) {
  10446. prefixVertex += '\n';
  10447. }
  10448. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  10449. if (prefixFragment.length > 0) {
  10450. prefixFragment += '\n';
  10451. }
  10452. } else {
  10453. 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');
  10454. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  10455. '#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
  10456. 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
  10457. 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');
  10458. }
  10459. vertexShader = resolveIncludes(vertexShader);
  10460. vertexShader = replaceLightNums(vertexShader, parameters);
  10461. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  10462. fragmentShader = resolveIncludes(fragmentShader);
  10463. fragmentShader = replaceLightNums(fragmentShader, parameters);
  10464. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  10465. vertexShader = unrollLoops(vertexShader);
  10466. fragmentShader = unrollLoops(fragmentShader);
  10467. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  10468. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  10469. versionString = '#version 300 es\n';
  10470. prefixVertex = ['#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  10471. 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;
  10472. }
  10473. const vertexGlsl = versionString + prefixVertex + vertexShader;
  10474. const fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  10475. // console.log( '*FRAGMENT*', fragmentGlsl );
  10476. const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl);
  10477. const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl);
  10478. gl.attachShader(program, glVertexShader);
  10479. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  10480. if (parameters.index0AttributeName !== undefined) {
  10481. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  10482. } else if (parameters.morphTargets === true) {
  10483. // programs with morphTargets displace position out of attribute 0
  10484. gl.bindAttribLocation(program, 0, 'position');
  10485. }
  10486. gl.linkProgram(program); // check for link errors
  10487. if (renderer.debug.checkShaderErrors) {
  10488. const programLog = gl.getProgramInfoLog(program).trim();
  10489. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  10490. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  10491. let runnable = true;
  10492. let haveDiagnostics = true;
  10493. if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
  10494. runnable = false;
  10495. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  10496. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  10497. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  10498. } else if (programLog !== '') {
  10499. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  10500. } else if (vertexLog === '' || fragmentLog === '') {
  10501. haveDiagnostics = false;
  10502. }
  10503. if (haveDiagnostics) {
  10504. this.diagnostics = {
  10505. runnable: runnable,
  10506. programLog: programLog,
  10507. vertexShader: {
  10508. log: vertexLog,
  10509. prefix: prefixVertex
  10510. },
  10511. fragmentShader: {
  10512. log: fragmentLog,
  10513. prefix: prefixFragment
  10514. }
  10515. };
  10516. }
  10517. } // Clean up
  10518. // Crashes in iOS9 and iOS10. #18402
  10519. // gl.detachShader( program, glVertexShader );
  10520. // gl.detachShader( program, glFragmentShader );
  10521. gl.deleteShader(glVertexShader);
  10522. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  10523. let cachedUniforms;
  10524. this.getUniforms = function () {
  10525. if (cachedUniforms === undefined) {
  10526. cachedUniforms = new WebGLUniforms(gl, program);
  10527. }
  10528. return cachedUniforms;
  10529. }; // set up caching for attribute locations
  10530. let cachedAttributes;
  10531. this.getAttributes = function () {
  10532. if (cachedAttributes === undefined) {
  10533. cachedAttributes = fetchAttributeLocations(gl, program);
  10534. }
  10535. return cachedAttributes;
  10536. }; // free resource
  10537. this.destroy = function () {
  10538. bindingStates.releaseStatesOfProgram(this);
  10539. gl.deleteProgram(program);
  10540. this.program = undefined;
  10541. }; //
  10542. this.name = parameters.shaderName;
  10543. this.id = programIdCount++;
  10544. this.cacheKey = cacheKey;
  10545. this.usedTimes = 1;
  10546. this.program = program;
  10547. this.vertexShader = glVertexShader;
  10548. this.fragmentShader = glFragmentShader;
  10549. return this;
  10550. }
  10551. function WebGLPrograms(renderer, cubemaps, extensions, capabilities, bindingStates, clipping) {
  10552. const programs = [];
  10553. const isWebGL2 = capabilities.isWebGL2;
  10554. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  10555. const floatVertexTextures = capabilities.floatVertexTextures;
  10556. const maxVertexUniforms = capabilities.maxVertexUniforms;
  10557. const vertexTextures = capabilities.vertexTextures;
  10558. let precision = capabilities.precision;
  10559. const shaderIDs = {
  10560. MeshDepthMaterial: 'depth',
  10561. MeshDistanceMaterial: 'distanceRGBA',
  10562. MeshNormalMaterial: 'normal',
  10563. MeshBasicMaterial: 'basic',
  10564. MeshLambertMaterial: 'lambert',
  10565. MeshPhongMaterial: 'phong',
  10566. MeshToonMaterial: 'toon',
  10567. MeshStandardMaterial: 'physical',
  10568. MeshPhysicalMaterial: 'physical',
  10569. MeshMatcapMaterial: 'matcap',
  10570. LineBasicMaterial: 'basic',
  10571. LineDashedMaterial: 'dashed',
  10572. PointsMaterial: 'points',
  10573. ShadowMaterial: 'shadow',
  10574. SpriteMaterial: 'sprite'
  10575. };
  10576. 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'];
  10577. function getMaxBones(object) {
  10578. const skeleton = object.skeleton;
  10579. const bones = skeleton.bones;
  10580. if (floatVertexTextures) {
  10581. return 1024;
  10582. } else {
  10583. // default for when object is not specified
  10584. // ( for example when prebuilding shader to be used with multiple objects )
  10585. //
  10586. // - leave some extra space for other uniforms
  10587. // - limit here is ANGLE's 254 max uniform vectors
  10588. // (up to 54 should be safe)
  10589. const nVertexUniforms = maxVertexUniforms;
  10590. const nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  10591. const maxBones = Math.min(nVertexMatrices, bones.length);
  10592. if (maxBones < bones.length) {
  10593. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  10594. return 0;
  10595. }
  10596. return maxBones;
  10597. }
  10598. }
  10599. function getTextureEncodingFromMap(map) {
  10600. let encoding;
  10601. if (map && map.isTexture) {
  10602. encoding = map.encoding;
  10603. } else if (map && map.isWebGLRenderTarget) {
  10604. console.warn('THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.');
  10605. encoding = map.texture.encoding;
  10606. } else {
  10607. encoding = LinearEncoding;
  10608. }
  10609. return encoding;
  10610. }
  10611. function getParameters(material, lights, shadows, scene, object) {
  10612. const fog = scene.fog;
  10613. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  10614. const envMap = cubemaps.get(material.envMap || environment);
  10615. const shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  10616. // (not to blow over maxLights budget)
  10617. const maxBones = object.isSkinnedMesh ? getMaxBones(object) : 0;
  10618. if (material.precision !== null) {
  10619. precision = capabilities.getMaxPrecision(material.precision);
  10620. if (precision !== material.precision) {
  10621. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  10622. }
  10623. }
  10624. let vertexShader, fragmentShader;
  10625. if (shaderID) {
  10626. const shader = ShaderLib[shaderID];
  10627. vertexShader = shader.vertexShader;
  10628. fragmentShader = shader.fragmentShader;
  10629. } else {
  10630. vertexShader = material.vertexShader;
  10631. fragmentShader = material.fragmentShader;
  10632. }
  10633. const currentRenderTarget = renderer.getRenderTarget();
  10634. const parameters = {
  10635. isWebGL2: isWebGL2,
  10636. shaderID: shaderID,
  10637. shaderName: material.type,
  10638. vertexShader: vertexShader,
  10639. fragmentShader: fragmentShader,
  10640. defines: material.defines,
  10641. isRawShaderMaterial: material.isRawShaderMaterial === true,
  10642. glslVersion: material.glslVersion,
  10643. precision: precision,
  10644. instancing: object.isInstancedMesh === true,
  10645. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  10646. supportsVertexTextures: vertexTextures,
  10647. outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
  10648. map: !!material.map,
  10649. mapEncoding: getTextureEncodingFromMap(material.map),
  10650. matcap: !!material.matcap,
  10651. matcapEncoding: getTextureEncodingFromMap(material.matcap),
  10652. envMap: !!envMap,
  10653. envMapMode: envMap && envMap.mapping,
  10654. envMapEncoding: getTextureEncodingFromMap(envMap),
  10655. envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
  10656. lightMap: !!material.lightMap,
  10657. lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
  10658. aoMap: !!material.aoMap,
  10659. emissiveMap: !!material.emissiveMap,
  10660. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
  10661. bumpMap: !!material.bumpMap,
  10662. normalMap: !!material.normalMap,
  10663. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  10664. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  10665. clearcoatMap: !!material.clearcoatMap,
  10666. clearcoatRoughnessMap: !!material.clearcoatRoughnessMap,
  10667. clearcoatNormalMap: !!material.clearcoatNormalMap,
  10668. displacementMap: !!material.displacementMap,
  10669. roughnessMap: !!material.roughnessMap,
  10670. metalnessMap: !!material.metalnessMap,
  10671. specularMap: !!material.specularMap,
  10672. alphaMap: !!material.alphaMap,
  10673. gradientMap: !!material.gradientMap,
  10674. sheen: !!material.sheen,
  10675. transmission: !!material.transmission,
  10676. transmissionMap: !!material.transmissionMap,
  10677. thicknessMap: !!material.thicknessMap,
  10678. combine: material.combine,
  10679. vertexTangents: material.normalMap && material.vertexTangents,
  10680. vertexColors: material.vertexColors,
  10681. vertexAlphas: material.vertexColors === true && object.geometry && object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4,
  10682. vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatMap || !!material.clearcoatRoughnessMap || !!material.clearcoatNormalMap || !!material.displacementMap || !!material.transmissionMap || !!material.thicknessMap,
  10683. 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,
  10684. fog: !!fog,
  10685. useFog: material.fog,
  10686. fogExp2: fog && fog.isFogExp2,
  10687. flatShading: !!material.flatShading,
  10688. sizeAttenuation: material.sizeAttenuation,
  10689. logarithmicDepthBuffer: logarithmicDepthBuffer,
  10690. skinning: object.isSkinnedMesh === true && maxBones > 0,
  10691. maxBones: maxBones,
  10692. useVertexTexture: floatVertexTextures,
  10693. morphTargets: object.geometry && object.geometry.morphAttributes.position !== undefined,
  10694. morphNormals: object.geometry && object.geometry.morphAttributes.normal !== undefined,
  10695. numDirLights: lights.directional.length,
  10696. numPointLights: lights.point.length,
  10697. numSpotLights: lights.spot.length,
  10698. numRectAreaLights: lights.rectArea.length,
  10699. numHemiLights: lights.hemi.length,
  10700. numDirLightShadows: lights.directionalShadowMap.length,
  10701. numPointLightShadows: lights.pointShadowMap.length,
  10702. numSpotLightShadows: lights.spotShadowMap.length,
  10703. numClippingPlanes: clipping.numPlanes,
  10704. numClipIntersection: clipping.numIntersection,
  10705. dithering: material.dithering,
  10706. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  10707. shadowMapType: renderer.shadowMap.type,
  10708. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  10709. physicallyCorrectLights: renderer.physicallyCorrectLights,
  10710. premultipliedAlpha: material.premultipliedAlpha,
  10711. alphaTest: material.alphaTest,
  10712. doubleSided: material.side === DoubleSide,
  10713. flipSided: material.side === BackSide,
  10714. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
  10715. index0AttributeName: material.index0AttributeName,
  10716. extensionDerivatives: material.extensions && material.extensions.derivatives,
  10717. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  10718. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  10719. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  10720. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  10721. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  10722. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  10723. customProgramCacheKey: material.customProgramCacheKey()
  10724. };
  10725. return parameters;
  10726. }
  10727. function getProgramCacheKey(parameters) {
  10728. const array = [];
  10729. if (parameters.shaderID) {
  10730. array.push(parameters.shaderID);
  10731. } else {
  10732. array.push(parameters.fragmentShader);
  10733. array.push(parameters.vertexShader);
  10734. }
  10735. if (parameters.defines !== undefined) {
  10736. for (const name in parameters.defines) {
  10737. array.push(name);
  10738. array.push(parameters.defines[name]);
  10739. }
  10740. }
  10741. if (parameters.isRawShaderMaterial === false) {
  10742. for (let i = 0; i < parameterNames.length; i++) {
  10743. array.push(parameters[parameterNames[i]]);
  10744. }
  10745. array.push(renderer.outputEncoding);
  10746. array.push(renderer.gammaFactor);
  10747. }
  10748. array.push(parameters.customProgramCacheKey);
  10749. return array.join();
  10750. }
  10751. function getUniforms(material) {
  10752. const shaderID = shaderIDs[material.type];
  10753. let uniforms;
  10754. if (shaderID) {
  10755. const shader = ShaderLib[shaderID];
  10756. uniforms = UniformsUtils.clone(shader.uniforms);
  10757. } else {
  10758. uniforms = material.uniforms;
  10759. }
  10760. return uniforms;
  10761. }
  10762. function acquireProgram(parameters, cacheKey) {
  10763. let program; // Check if code has been already compiled
  10764. for (let p = 0, pl = programs.length; p < pl; p++) {
  10765. const preexistingProgram = programs[p];
  10766. if (preexistingProgram.cacheKey === cacheKey) {
  10767. program = preexistingProgram;
  10768. ++program.usedTimes;
  10769. break;
  10770. }
  10771. }
  10772. if (program === undefined) {
  10773. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  10774. programs.push(program);
  10775. }
  10776. return program;
  10777. }
  10778. function releaseProgram(program) {
  10779. if (--program.usedTimes === 0) {
  10780. // Remove from unordered set
  10781. const i = programs.indexOf(program);
  10782. programs[i] = programs[programs.length - 1];
  10783. programs.pop(); // Free WebGL resources
  10784. program.destroy();
  10785. }
  10786. }
  10787. return {
  10788. getParameters: getParameters,
  10789. getProgramCacheKey: getProgramCacheKey,
  10790. getUniforms: getUniforms,
  10791. acquireProgram: acquireProgram,
  10792. releaseProgram: releaseProgram,
  10793. // Exposed for resource monitoring & error feedback via renderer.info:
  10794. programs: programs
  10795. };
  10796. }
  10797. function WebGLProperties() {
  10798. let properties = new WeakMap();
  10799. function get(object) {
  10800. let map = properties.get(object);
  10801. if (map === undefined) {
  10802. map = {};
  10803. properties.set(object, map);
  10804. }
  10805. return map;
  10806. }
  10807. function remove(object) {
  10808. properties.delete(object);
  10809. }
  10810. function update(object, key, value) {
  10811. properties.get(object)[key] = value;
  10812. }
  10813. function dispose() {
  10814. properties = new WeakMap();
  10815. }
  10816. return {
  10817. get: get,
  10818. remove: remove,
  10819. update: update,
  10820. dispose: dispose
  10821. };
  10822. }
  10823. function painterSortStable(a, b) {
  10824. if (a.groupOrder !== b.groupOrder) {
  10825. return a.groupOrder - b.groupOrder;
  10826. } else if (a.renderOrder !== b.renderOrder) {
  10827. return a.renderOrder - b.renderOrder;
  10828. } else if (a.program !== b.program) {
  10829. return a.program.id - b.program.id;
  10830. } else if (a.material.id !== b.material.id) {
  10831. return a.material.id - b.material.id;
  10832. } else if (a.z !== b.z) {
  10833. return a.z - b.z;
  10834. } else {
  10835. return a.id - b.id;
  10836. }
  10837. }
  10838. function reversePainterSortStable(a, b) {
  10839. if (a.groupOrder !== b.groupOrder) {
  10840. return a.groupOrder - b.groupOrder;
  10841. } else if (a.renderOrder !== b.renderOrder) {
  10842. return a.renderOrder - b.renderOrder;
  10843. } else if (a.z !== b.z) {
  10844. return b.z - a.z;
  10845. } else {
  10846. return a.id - b.id;
  10847. }
  10848. }
  10849. function WebGLRenderList(properties) {
  10850. const renderItems = [];
  10851. let renderItemsIndex = 0;
  10852. const opaque = [];
  10853. const transmissive = [];
  10854. const transparent = [];
  10855. const defaultProgram = {
  10856. id: -1
  10857. };
  10858. function init() {
  10859. renderItemsIndex = 0;
  10860. opaque.length = 0;
  10861. transmissive.length = 0;
  10862. transparent.length = 0;
  10863. }
  10864. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  10865. let renderItem = renderItems[renderItemsIndex];
  10866. const materialProperties = properties.get(material);
  10867. if (renderItem === undefined) {
  10868. renderItem = {
  10869. id: object.id,
  10870. object: object,
  10871. geometry: geometry,
  10872. material: material,
  10873. program: materialProperties.program || defaultProgram,
  10874. groupOrder: groupOrder,
  10875. renderOrder: object.renderOrder,
  10876. z: z,
  10877. group: group
  10878. };
  10879. renderItems[renderItemsIndex] = renderItem;
  10880. } else {
  10881. renderItem.id = object.id;
  10882. renderItem.object = object;
  10883. renderItem.geometry = geometry;
  10884. renderItem.material = material;
  10885. renderItem.program = materialProperties.program || defaultProgram;
  10886. renderItem.groupOrder = groupOrder;
  10887. renderItem.renderOrder = object.renderOrder;
  10888. renderItem.z = z;
  10889. renderItem.group = group;
  10890. }
  10891. renderItemsIndex++;
  10892. return renderItem;
  10893. }
  10894. function push(object, geometry, material, groupOrder, z, group) {
  10895. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  10896. if (material.transmission > 0.0) {
  10897. transmissive.push(renderItem);
  10898. } else if (material.transparent === true) {
  10899. transparent.push(renderItem);
  10900. } else {
  10901. opaque.push(renderItem);
  10902. }
  10903. }
  10904. function unshift(object, geometry, material, groupOrder, z, group) {
  10905. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  10906. if (material.transmission > 0.0) {
  10907. transmissive.unshift(renderItem);
  10908. } else if (material.transparent === true) {
  10909. transparent.unshift(renderItem);
  10910. } else {
  10911. opaque.unshift(renderItem);
  10912. }
  10913. }
  10914. function sort(customOpaqueSort, customTransparentSort) {
  10915. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  10916. if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable);
  10917. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  10918. }
  10919. function finish() {
  10920. // Clear references from inactive renderItems in the list
  10921. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  10922. const renderItem = renderItems[i];
  10923. if (renderItem.id === null) break;
  10924. renderItem.id = null;
  10925. renderItem.object = null;
  10926. renderItem.geometry = null;
  10927. renderItem.material = null;
  10928. renderItem.program = null;
  10929. renderItem.group = null;
  10930. }
  10931. }
  10932. return {
  10933. opaque: opaque,
  10934. transmissive: transmissive,
  10935. transparent: transparent,
  10936. init: init,
  10937. push: push,
  10938. unshift: unshift,
  10939. finish: finish,
  10940. sort: sort
  10941. };
  10942. }
  10943. function WebGLRenderLists(properties) {
  10944. let lists = new WeakMap();
  10945. function get(scene, renderCallDepth) {
  10946. let list;
  10947. if (lists.has(scene) === false) {
  10948. list = new WebGLRenderList(properties);
  10949. lists.set(scene, [list]);
  10950. } else {
  10951. if (renderCallDepth >= lists.get(scene).length) {
  10952. list = new WebGLRenderList(properties);
  10953. lists.get(scene).push(list);
  10954. } else {
  10955. list = lists.get(scene)[renderCallDepth];
  10956. }
  10957. }
  10958. return list;
  10959. }
  10960. function dispose() {
  10961. lists = new WeakMap();
  10962. }
  10963. return {
  10964. get: get,
  10965. dispose: dispose
  10966. };
  10967. }
  10968. function UniformsCache() {
  10969. const lights = {};
  10970. return {
  10971. get: function (light) {
  10972. if (lights[light.id] !== undefined) {
  10973. return lights[light.id];
  10974. }
  10975. let uniforms;
  10976. switch (light.type) {
  10977. case 'DirectionalLight':
  10978. uniforms = {
  10979. direction: new Vector3(),
  10980. color: new Color()
  10981. };
  10982. break;
  10983. case 'SpotLight':
  10984. uniforms = {
  10985. position: new Vector3(),
  10986. direction: new Vector3(),
  10987. color: new Color(),
  10988. distance: 0,
  10989. coneCos: 0,
  10990. penumbraCos: 0,
  10991. decay: 0
  10992. };
  10993. break;
  10994. case 'PointLight':
  10995. uniforms = {
  10996. position: new Vector3(),
  10997. color: new Color(),
  10998. distance: 0,
  10999. decay: 0
  11000. };
  11001. break;
  11002. case 'HemisphereLight':
  11003. uniforms = {
  11004. direction: new Vector3(),
  11005. skyColor: new Color(),
  11006. groundColor: new Color()
  11007. };
  11008. break;
  11009. case 'RectAreaLight':
  11010. uniforms = {
  11011. color: new Color(),
  11012. position: new Vector3(),
  11013. halfWidth: new Vector3(),
  11014. halfHeight: new Vector3()
  11015. };
  11016. break;
  11017. }
  11018. lights[light.id] = uniforms;
  11019. return uniforms;
  11020. }
  11021. };
  11022. }
  11023. function ShadowUniformsCache() {
  11024. const lights = {};
  11025. return {
  11026. get: function (light) {
  11027. if (lights[light.id] !== undefined) {
  11028. return lights[light.id];
  11029. }
  11030. let uniforms;
  11031. switch (light.type) {
  11032. case 'DirectionalLight':
  11033. uniforms = {
  11034. shadowBias: 0,
  11035. shadowNormalBias: 0,
  11036. shadowRadius: 1,
  11037. shadowMapSize: new Vector2()
  11038. };
  11039. break;
  11040. case 'SpotLight':
  11041. uniforms = {
  11042. shadowBias: 0,
  11043. shadowNormalBias: 0,
  11044. shadowRadius: 1,
  11045. shadowMapSize: new Vector2()
  11046. };
  11047. break;
  11048. case 'PointLight':
  11049. uniforms = {
  11050. shadowBias: 0,
  11051. shadowNormalBias: 0,
  11052. shadowRadius: 1,
  11053. shadowMapSize: new Vector2(),
  11054. shadowCameraNear: 1,
  11055. shadowCameraFar: 1000
  11056. };
  11057. break;
  11058. // TODO (abelnation): set RectAreaLight shadow uniforms
  11059. }
  11060. lights[light.id] = uniforms;
  11061. return uniforms;
  11062. }
  11063. };
  11064. }
  11065. let nextVersion = 0;
  11066. function shadowCastingLightsFirst(lightA, lightB) {
  11067. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  11068. }
  11069. function WebGLLights(extensions, capabilities) {
  11070. const cache = new UniformsCache();
  11071. const shadowCache = ShadowUniformsCache();
  11072. const state = {
  11073. version: 0,
  11074. hash: {
  11075. directionalLength: -1,
  11076. pointLength: -1,
  11077. spotLength: -1,
  11078. rectAreaLength: -1,
  11079. hemiLength: -1,
  11080. numDirectionalShadows: -1,
  11081. numPointShadows: -1,
  11082. numSpotShadows: -1
  11083. },
  11084. ambient: [0, 0, 0],
  11085. probe: [],
  11086. directional: [],
  11087. directionalShadow: [],
  11088. directionalShadowMap: [],
  11089. directionalShadowMatrix: [],
  11090. spot: [],
  11091. spotShadow: [],
  11092. spotShadowMap: [],
  11093. spotShadowMatrix: [],
  11094. rectArea: [],
  11095. rectAreaLTC1: null,
  11096. rectAreaLTC2: null,
  11097. point: [],
  11098. pointShadow: [],
  11099. pointShadowMap: [],
  11100. pointShadowMatrix: [],
  11101. hemi: []
  11102. };
  11103. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  11104. const vector3 = new Vector3();
  11105. const matrix4 = new Matrix4();
  11106. const matrix42 = new Matrix4();
  11107. function setup(lights) {
  11108. let r = 0,
  11109. g = 0,
  11110. b = 0;
  11111. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  11112. let directionalLength = 0;
  11113. let pointLength = 0;
  11114. let spotLength = 0;
  11115. let rectAreaLength = 0;
  11116. let hemiLength = 0;
  11117. let numDirectionalShadows = 0;
  11118. let numPointShadows = 0;
  11119. let numSpotShadows = 0;
  11120. lights.sort(shadowCastingLightsFirst);
  11121. for (let i = 0, l = lights.length; i < l; i++) {
  11122. const light = lights[i];
  11123. const color = light.color;
  11124. const intensity = light.intensity;
  11125. const distance = light.distance;
  11126. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  11127. if (light.isAmbientLight) {
  11128. r += color.r * intensity;
  11129. g += color.g * intensity;
  11130. b += color.b * intensity;
  11131. } else if (light.isLightProbe) {
  11132. for (let j = 0; j < 9; j++) {
  11133. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  11134. }
  11135. } else if (light.isDirectionalLight) {
  11136. const uniforms = cache.get(light);
  11137. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  11138. if (light.castShadow) {
  11139. const shadow = light.shadow;
  11140. const shadowUniforms = shadowCache.get(light);
  11141. shadowUniforms.shadowBias = shadow.bias;
  11142. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11143. shadowUniforms.shadowRadius = shadow.radius;
  11144. shadowUniforms.shadowMapSize = shadow.mapSize;
  11145. state.directionalShadow[directionalLength] = shadowUniforms;
  11146. state.directionalShadowMap[directionalLength] = shadowMap;
  11147. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  11148. numDirectionalShadows++;
  11149. }
  11150. state.directional[directionalLength] = uniforms;
  11151. directionalLength++;
  11152. } else if (light.isSpotLight) {
  11153. const uniforms = cache.get(light);
  11154. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11155. uniforms.color.copy(color).multiplyScalar(intensity);
  11156. uniforms.distance = distance;
  11157. uniforms.coneCos = Math.cos(light.angle);
  11158. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  11159. uniforms.decay = light.decay;
  11160. if (light.castShadow) {
  11161. const shadow = light.shadow;
  11162. const shadowUniforms = shadowCache.get(light);
  11163. shadowUniforms.shadowBias = shadow.bias;
  11164. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11165. shadowUniforms.shadowRadius = shadow.radius;
  11166. shadowUniforms.shadowMapSize = shadow.mapSize;
  11167. state.spotShadow[spotLength] = shadowUniforms;
  11168. state.spotShadowMap[spotLength] = shadowMap;
  11169. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  11170. numSpotShadows++;
  11171. }
  11172. state.spot[spotLength] = uniforms;
  11173. spotLength++;
  11174. } else if (light.isRectAreaLight) {
  11175. const uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  11176. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  11177. // (b) intensity is the brightness of the light
  11178. uniforms.color.copy(color).multiplyScalar(intensity);
  11179. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  11180. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  11181. state.rectArea[rectAreaLength] = uniforms;
  11182. rectAreaLength++;
  11183. } else if (light.isPointLight) {
  11184. const uniforms = cache.get(light);
  11185. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  11186. uniforms.distance = light.distance;
  11187. uniforms.decay = light.decay;
  11188. if (light.castShadow) {
  11189. const shadow = light.shadow;
  11190. const shadowUniforms = shadowCache.get(light);
  11191. shadowUniforms.shadowBias = shadow.bias;
  11192. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11193. shadowUniforms.shadowRadius = shadow.radius;
  11194. shadowUniforms.shadowMapSize = shadow.mapSize;
  11195. shadowUniforms.shadowCameraNear = shadow.camera.near;
  11196. shadowUniforms.shadowCameraFar = shadow.camera.far;
  11197. state.pointShadow[pointLength] = shadowUniforms;
  11198. state.pointShadowMap[pointLength] = shadowMap;
  11199. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  11200. numPointShadows++;
  11201. }
  11202. state.point[pointLength] = uniforms;
  11203. pointLength++;
  11204. } else if (light.isHemisphereLight) {
  11205. const uniforms = cache.get(light);
  11206. uniforms.skyColor.copy(light.color).multiplyScalar(intensity);
  11207. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  11208. state.hemi[hemiLength] = uniforms;
  11209. hemiLength++;
  11210. }
  11211. }
  11212. if (rectAreaLength > 0) {
  11213. if (capabilities.isWebGL2) {
  11214. // WebGL 2
  11215. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11216. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11217. } else {
  11218. // WebGL 1
  11219. if (extensions.has('OES_texture_float_linear') === true) {
  11220. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11221. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11222. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  11223. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  11224. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  11225. } else {
  11226. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  11227. }
  11228. }
  11229. }
  11230. state.ambient[0] = r;
  11231. state.ambient[1] = g;
  11232. state.ambient[2] = b;
  11233. const hash = state.hash;
  11234. 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) {
  11235. state.directional.length = directionalLength;
  11236. state.spot.length = spotLength;
  11237. state.rectArea.length = rectAreaLength;
  11238. state.point.length = pointLength;
  11239. state.hemi.length = hemiLength;
  11240. state.directionalShadow.length = numDirectionalShadows;
  11241. state.directionalShadowMap.length = numDirectionalShadows;
  11242. state.pointShadow.length = numPointShadows;
  11243. state.pointShadowMap.length = numPointShadows;
  11244. state.spotShadow.length = numSpotShadows;
  11245. state.spotShadowMap.length = numSpotShadows;
  11246. state.directionalShadowMatrix.length = numDirectionalShadows;
  11247. state.pointShadowMatrix.length = numPointShadows;
  11248. state.spotShadowMatrix.length = numSpotShadows;
  11249. hash.directionalLength = directionalLength;
  11250. hash.pointLength = pointLength;
  11251. hash.spotLength = spotLength;
  11252. hash.rectAreaLength = rectAreaLength;
  11253. hash.hemiLength = hemiLength;
  11254. hash.numDirectionalShadows = numDirectionalShadows;
  11255. hash.numPointShadows = numPointShadows;
  11256. hash.numSpotShadows = numSpotShadows;
  11257. state.version = nextVersion++;
  11258. }
  11259. }
  11260. function setupView(lights, camera) {
  11261. let directionalLength = 0;
  11262. let pointLength = 0;
  11263. let spotLength = 0;
  11264. let rectAreaLength = 0;
  11265. let hemiLength = 0;
  11266. const viewMatrix = camera.matrixWorldInverse;
  11267. for (let i = 0, l = lights.length; i < l; i++) {
  11268. const light = lights[i];
  11269. if (light.isDirectionalLight) {
  11270. const uniforms = state.directional[directionalLength];
  11271. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11272. vector3.setFromMatrixPosition(light.target.matrixWorld);
  11273. uniforms.direction.sub(vector3);
  11274. uniforms.direction.transformDirection(viewMatrix);
  11275. directionalLength++;
  11276. } else if (light.isSpotLight) {
  11277. const uniforms = state.spot[spotLength];
  11278. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11279. uniforms.position.applyMatrix4(viewMatrix);
  11280. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11281. vector3.setFromMatrixPosition(light.target.matrixWorld);
  11282. uniforms.direction.sub(vector3);
  11283. uniforms.direction.transformDirection(viewMatrix);
  11284. spotLength++;
  11285. } else if (light.isRectAreaLight) {
  11286. const uniforms = state.rectArea[rectAreaLength];
  11287. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11288. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  11289. matrix42.identity();
  11290. matrix4.copy(light.matrixWorld);
  11291. matrix4.premultiply(viewMatrix);
  11292. matrix42.extractRotation(matrix4);
  11293. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  11294. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  11295. uniforms.halfWidth.applyMatrix4(matrix42);
  11296. uniforms.halfHeight.applyMatrix4(matrix42);
  11297. rectAreaLength++;
  11298. } else if (light.isPointLight) {
  11299. const uniforms = state.point[pointLength];
  11300. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11301. uniforms.position.applyMatrix4(viewMatrix);
  11302. pointLength++;
  11303. } else if (light.isHemisphereLight) {
  11304. const uniforms = state.hemi[hemiLength];
  11305. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11306. uniforms.direction.transformDirection(viewMatrix);
  11307. uniforms.direction.normalize();
  11308. hemiLength++;
  11309. }
  11310. }
  11311. }
  11312. return {
  11313. setup: setup,
  11314. setupView: setupView,
  11315. state: state
  11316. };
  11317. }
  11318. function WebGLRenderState(extensions, capabilities) {
  11319. const lights = new WebGLLights(extensions, capabilities);
  11320. const lightsArray = [];
  11321. const shadowsArray = [];
  11322. function init() {
  11323. lightsArray.length = 0;
  11324. shadowsArray.length = 0;
  11325. }
  11326. function pushLight(light) {
  11327. lightsArray.push(light);
  11328. }
  11329. function pushShadow(shadowLight) {
  11330. shadowsArray.push(shadowLight);
  11331. }
  11332. function setupLights() {
  11333. lights.setup(lightsArray);
  11334. }
  11335. function setupLightsView(camera) {
  11336. lights.setupView(lightsArray, camera);
  11337. }
  11338. const state = {
  11339. lightsArray: lightsArray,
  11340. shadowsArray: shadowsArray,
  11341. lights: lights
  11342. };
  11343. return {
  11344. init: init,
  11345. state: state,
  11346. setupLights: setupLights,
  11347. setupLightsView: setupLightsView,
  11348. pushLight: pushLight,
  11349. pushShadow: pushShadow
  11350. };
  11351. }
  11352. function WebGLRenderStates(extensions, capabilities) {
  11353. let renderStates = new WeakMap();
  11354. function get(scene, renderCallDepth = 0) {
  11355. let renderState;
  11356. if (renderStates.has(scene) === false) {
  11357. renderState = new WebGLRenderState(extensions, capabilities);
  11358. renderStates.set(scene, [renderState]);
  11359. } else {
  11360. if (renderCallDepth >= renderStates.get(scene).length) {
  11361. renderState = new WebGLRenderState(extensions, capabilities);
  11362. renderStates.get(scene).push(renderState);
  11363. } else {
  11364. renderState = renderStates.get(scene)[renderCallDepth];
  11365. }
  11366. }
  11367. return renderState;
  11368. }
  11369. function dispose() {
  11370. renderStates = new WeakMap();
  11371. }
  11372. return {
  11373. get: get,
  11374. dispose: dispose
  11375. };
  11376. }
  11377. /**
  11378. * parameters = {
  11379. *
  11380. * opacity: <float>,
  11381. *
  11382. * map: new THREE.Texture( <Image> ),
  11383. *
  11384. * alphaMap: new THREE.Texture( <Image> ),
  11385. *
  11386. * displacementMap: new THREE.Texture( <Image> ),
  11387. * displacementScale: <float>,
  11388. * displacementBias: <float>,
  11389. *
  11390. * wireframe: <boolean>,
  11391. * wireframeLinewidth: <float>
  11392. * }
  11393. */
  11394. class MeshDepthMaterial extends Material {
  11395. constructor(parameters) {
  11396. super();
  11397. this.type = 'MeshDepthMaterial';
  11398. this.depthPacking = BasicDepthPacking;
  11399. this.map = null;
  11400. this.alphaMap = null;
  11401. this.displacementMap = null;
  11402. this.displacementScale = 1;
  11403. this.displacementBias = 0;
  11404. this.wireframe = false;
  11405. this.wireframeLinewidth = 1;
  11406. this.fog = false;
  11407. this.setValues(parameters);
  11408. }
  11409. copy(source) {
  11410. super.copy(source);
  11411. this.depthPacking = source.depthPacking;
  11412. this.map = source.map;
  11413. this.alphaMap = source.alphaMap;
  11414. this.displacementMap = source.displacementMap;
  11415. this.displacementScale = source.displacementScale;
  11416. this.displacementBias = source.displacementBias;
  11417. this.wireframe = source.wireframe;
  11418. this.wireframeLinewidth = source.wireframeLinewidth;
  11419. return this;
  11420. }
  11421. }
  11422. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  11423. /**
  11424. * parameters = {
  11425. *
  11426. * referencePosition: <float>,
  11427. * nearDistance: <float>,
  11428. * farDistance: <float>,
  11429. *
  11430. * map: new THREE.Texture( <Image> ),
  11431. *
  11432. * alphaMap: new THREE.Texture( <Image> ),
  11433. *
  11434. * displacementMap: new THREE.Texture( <Image> ),
  11435. * displacementScale: <float>,
  11436. * displacementBias: <float>
  11437. *
  11438. * }
  11439. */
  11440. class MeshDistanceMaterial extends Material {
  11441. constructor(parameters) {
  11442. super();
  11443. this.type = 'MeshDistanceMaterial';
  11444. this.referencePosition = new Vector3();
  11445. this.nearDistance = 1;
  11446. this.farDistance = 1000;
  11447. this.map = null;
  11448. this.alphaMap = null;
  11449. this.displacementMap = null;
  11450. this.displacementScale = 1;
  11451. this.displacementBias = 0;
  11452. this.fog = false;
  11453. this.setValues(parameters);
  11454. }
  11455. copy(source) {
  11456. super.copy(source);
  11457. this.referencePosition.copy(source.referencePosition);
  11458. this.nearDistance = source.nearDistance;
  11459. this.farDistance = source.farDistance;
  11460. this.map = source.map;
  11461. this.alphaMap = source.alphaMap;
  11462. this.displacementMap = source.displacementMap;
  11463. this.displacementScale = source.displacementScale;
  11464. this.displacementBias = source.displacementBias;
  11465. return this;
  11466. }
  11467. }
  11468. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  11469. 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}";
  11470. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  11471. function WebGLShadowMap(_renderer, _objects, _capabilities) {
  11472. let _frustum = new Frustum();
  11473. const _shadowMapSize = new Vector2(),
  11474. _viewportSize = new Vector2(),
  11475. _viewport = new Vector4(),
  11476. _depthMaterial = new MeshDepthMaterial({
  11477. depthPacking: RGBADepthPacking
  11478. }),
  11479. _distanceMaterial = new MeshDistanceMaterial(),
  11480. _materialCache = {},
  11481. _maxTextureSize = _capabilities.maxTextureSize;
  11482. const shadowSide = {
  11483. 0: BackSide,
  11484. 1: FrontSide,
  11485. 2: DoubleSide
  11486. };
  11487. const shadowMaterialVertical = new ShaderMaterial({
  11488. defines: {
  11489. SAMPLE_RATE: 2.0 / 8.0,
  11490. HALF_SAMPLE_RATE: 1.0 / 8.0
  11491. },
  11492. uniforms: {
  11493. shadow_pass: {
  11494. value: null
  11495. },
  11496. resolution: {
  11497. value: new Vector2()
  11498. },
  11499. radius: {
  11500. value: 4.0
  11501. }
  11502. },
  11503. vertexShader: vsm_vert,
  11504. fragmentShader: vsm_frag
  11505. });
  11506. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  11507. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  11508. const fullScreenTri = new BufferGeometry();
  11509. fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  11510. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  11511. const scope = this;
  11512. this.enabled = false;
  11513. this.autoUpdate = true;
  11514. this.needsUpdate = false;
  11515. this.type = PCFShadowMap;
  11516. this.render = function (lights, scene, camera) {
  11517. if (scope.enabled === false) return;
  11518. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  11519. if (lights.length === 0) return;
  11520. const currentRenderTarget = _renderer.getRenderTarget();
  11521. const activeCubeFace = _renderer.getActiveCubeFace();
  11522. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  11523. const _state = _renderer.state; // Set GL state for depth map.
  11524. _state.setBlending(NoBlending);
  11525. _state.buffers.color.setClear(1, 1, 1, 1);
  11526. _state.buffers.depth.setTest(true);
  11527. _state.setScissorTest(false); // render depth map
  11528. for (let i = 0, il = lights.length; i < il; i++) {
  11529. const light = lights[i];
  11530. const shadow = light.shadow;
  11531. if (shadow === undefined) {
  11532. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  11533. continue;
  11534. }
  11535. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  11536. _shadowMapSize.copy(shadow.mapSize);
  11537. const shadowFrameExtents = shadow.getFrameExtents();
  11538. _shadowMapSize.multiply(shadowFrameExtents);
  11539. _viewportSize.copy(shadow.mapSize);
  11540. if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) {
  11541. if (_shadowMapSize.x > _maxTextureSize) {
  11542. _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x);
  11543. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  11544. shadow.mapSize.x = _viewportSize.x;
  11545. }
  11546. if (_shadowMapSize.y > _maxTextureSize) {
  11547. _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y);
  11548. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  11549. shadow.mapSize.y = _viewportSize.y;
  11550. }
  11551. }
  11552. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  11553. const pars = {
  11554. minFilter: LinearFilter,
  11555. magFilter: LinearFilter,
  11556. format: RGBAFormat
  11557. };
  11558. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  11559. shadow.map.texture.name = light.name + '.shadowMap';
  11560. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  11561. shadow.camera.updateProjectionMatrix();
  11562. }
  11563. if (shadow.map === null) {
  11564. const pars = {
  11565. minFilter: NearestFilter,
  11566. magFilter: NearestFilter,
  11567. format: RGBAFormat
  11568. };
  11569. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  11570. shadow.map.texture.name = light.name + '.shadowMap';
  11571. shadow.camera.updateProjectionMatrix();
  11572. }
  11573. _renderer.setRenderTarget(shadow.map);
  11574. _renderer.clear();
  11575. const viewportCount = shadow.getViewportCount();
  11576. for (let vp = 0; vp < viewportCount; vp++) {
  11577. const viewport = shadow.getViewport(vp);
  11578. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  11579. _state.viewport(_viewport);
  11580. shadow.updateMatrices(light, vp);
  11581. _frustum = shadow.getFrustum();
  11582. renderObject(scene, camera, shadow.camera, light, this.type);
  11583. } // do blur pass for VSM
  11584. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  11585. VSMPass(shadow, camera);
  11586. }
  11587. shadow.needsUpdate = false;
  11588. }
  11589. scope.needsUpdate = false;
  11590. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  11591. };
  11592. function VSMPass(shadow, camera) {
  11593. const geometry = _objects.update(fullScreenMesh); // vertical pass
  11594. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  11595. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  11596. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  11597. _renderer.setRenderTarget(shadow.mapPass);
  11598. _renderer.clear();
  11599. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizontal pass
  11600. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  11601. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  11602. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  11603. _renderer.setRenderTarget(shadow.map);
  11604. _renderer.clear();
  11605. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  11606. }
  11607. function getDepthMaterial(object, geometry, material, light, shadowCameraNear, shadowCameraFar, type) {
  11608. let result = null;
  11609. const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial;
  11610. if (customMaterial !== undefined) {
  11611. result = customMaterial;
  11612. } else {
  11613. result = light.isPointLight === true ? _distanceMaterial : _depthMaterial;
  11614. }
  11615. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  11616. // in this case we need a unique material instance reflecting the
  11617. // appropriate state
  11618. const keyA = result.uuid,
  11619. keyB = material.uuid;
  11620. let materialsForVariant = _materialCache[keyA];
  11621. if (materialsForVariant === undefined) {
  11622. materialsForVariant = {};
  11623. _materialCache[keyA] = materialsForVariant;
  11624. }
  11625. let cachedMaterial = materialsForVariant[keyB];
  11626. if (cachedMaterial === undefined) {
  11627. cachedMaterial = result.clone();
  11628. materialsForVariant[keyB] = cachedMaterial;
  11629. }
  11630. result = cachedMaterial;
  11631. }
  11632. result.visible = material.visible;
  11633. result.wireframe = material.wireframe;
  11634. if (type === VSMShadowMap) {
  11635. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  11636. } else {
  11637. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  11638. }
  11639. result.clipShadows = material.clipShadows;
  11640. result.clippingPlanes = material.clippingPlanes;
  11641. result.clipIntersection = material.clipIntersection;
  11642. result.wireframeLinewidth = material.wireframeLinewidth;
  11643. result.linewidth = material.linewidth;
  11644. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  11645. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  11646. result.nearDistance = shadowCameraNear;
  11647. result.farDistance = shadowCameraFar;
  11648. }
  11649. return result;
  11650. }
  11651. function renderObject(object, camera, shadowCamera, light, type) {
  11652. if (object.visible === false) return;
  11653. const visible = object.layers.test(camera.layers);
  11654. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  11655. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  11656. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  11657. const geometry = _objects.update(object);
  11658. const material = object.material;
  11659. if (Array.isArray(material)) {
  11660. const groups = geometry.groups;
  11661. for (let k = 0, kl = groups.length; k < kl; k++) {
  11662. const group = groups[k];
  11663. const groupMaterial = material[group.materialIndex];
  11664. if (groupMaterial && groupMaterial.visible) {
  11665. const depthMaterial = getDepthMaterial(object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  11666. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  11667. }
  11668. }
  11669. } else if (material.visible) {
  11670. const depthMaterial = getDepthMaterial(object, geometry, material, light, shadowCamera.near, shadowCamera.far, type);
  11671. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  11672. }
  11673. }
  11674. }
  11675. const children = object.children;
  11676. for (let i = 0, l = children.length; i < l; i++) {
  11677. renderObject(children[i], camera, shadowCamera, light, type);
  11678. }
  11679. }
  11680. }
  11681. function WebGLState(gl, extensions, capabilities) {
  11682. const isWebGL2 = capabilities.isWebGL2;
  11683. function ColorBuffer() {
  11684. let locked = false;
  11685. const color = new Vector4();
  11686. let currentColorMask = null;
  11687. const currentColorClear = new Vector4(0, 0, 0, 0);
  11688. return {
  11689. setMask: function (colorMask) {
  11690. if (currentColorMask !== colorMask && !locked) {
  11691. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  11692. currentColorMask = colorMask;
  11693. }
  11694. },
  11695. setLocked: function (lock) {
  11696. locked = lock;
  11697. },
  11698. setClear: function (r, g, b, a, premultipliedAlpha) {
  11699. if (premultipliedAlpha === true) {
  11700. r *= a;
  11701. g *= a;
  11702. b *= a;
  11703. }
  11704. color.set(r, g, b, a);
  11705. if (currentColorClear.equals(color) === false) {
  11706. gl.clearColor(r, g, b, a);
  11707. currentColorClear.copy(color);
  11708. }
  11709. },
  11710. reset: function () {
  11711. locked = false;
  11712. currentColorMask = null;
  11713. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  11714. }
  11715. };
  11716. }
  11717. function DepthBuffer() {
  11718. let locked = false;
  11719. let currentDepthMask = null;
  11720. let currentDepthFunc = null;
  11721. let currentDepthClear = null;
  11722. return {
  11723. setTest: function (depthTest) {
  11724. if (depthTest) {
  11725. enable(gl.DEPTH_TEST);
  11726. } else {
  11727. disable(gl.DEPTH_TEST);
  11728. }
  11729. },
  11730. setMask: function (depthMask) {
  11731. if (currentDepthMask !== depthMask && !locked) {
  11732. gl.depthMask(depthMask);
  11733. currentDepthMask = depthMask;
  11734. }
  11735. },
  11736. setFunc: function (depthFunc) {
  11737. if (currentDepthFunc !== depthFunc) {
  11738. if (depthFunc) {
  11739. switch (depthFunc) {
  11740. case NeverDepth:
  11741. gl.depthFunc(gl.NEVER);
  11742. break;
  11743. case AlwaysDepth:
  11744. gl.depthFunc(gl.ALWAYS);
  11745. break;
  11746. case LessDepth:
  11747. gl.depthFunc(gl.LESS);
  11748. break;
  11749. case LessEqualDepth:
  11750. gl.depthFunc(gl.LEQUAL);
  11751. break;
  11752. case EqualDepth:
  11753. gl.depthFunc(gl.EQUAL);
  11754. break;
  11755. case GreaterEqualDepth:
  11756. gl.depthFunc(gl.GEQUAL);
  11757. break;
  11758. case GreaterDepth:
  11759. gl.depthFunc(gl.GREATER);
  11760. break;
  11761. case NotEqualDepth:
  11762. gl.depthFunc(gl.NOTEQUAL);
  11763. break;
  11764. default:
  11765. gl.depthFunc(gl.LEQUAL);
  11766. }
  11767. } else {
  11768. gl.depthFunc(gl.LEQUAL);
  11769. }
  11770. currentDepthFunc = depthFunc;
  11771. }
  11772. },
  11773. setLocked: function (lock) {
  11774. locked = lock;
  11775. },
  11776. setClear: function (depth) {
  11777. if (currentDepthClear !== depth) {
  11778. gl.clearDepth(depth);
  11779. currentDepthClear = depth;
  11780. }
  11781. },
  11782. reset: function () {
  11783. locked = false;
  11784. currentDepthMask = null;
  11785. currentDepthFunc = null;
  11786. currentDepthClear = null;
  11787. }
  11788. };
  11789. }
  11790. function StencilBuffer() {
  11791. let locked = false;
  11792. let currentStencilMask = null;
  11793. let currentStencilFunc = null;
  11794. let currentStencilRef = null;
  11795. let currentStencilFuncMask = null;
  11796. let currentStencilFail = null;
  11797. let currentStencilZFail = null;
  11798. let currentStencilZPass = null;
  11799. let currentStencilClear = null;
  11800. return {
  11801. setTest: function (stencilTest) {
  11802. if (!locked) {
  11803. if (stencilTest) {
  11804. enable(gl.STENCIL_TEST);
  11805. } else {
  11806. disable(gl.STENCIL_TEST);
  11807. }
  11808. }
  11809. },
  11810. setMask: function (stencilMask) {
  11811. if (currentStencilMask !== stencilMask && !locked) {
  11812. gl.stencilMask(stencilMask);
  11813. currentStencilMask = stencilMask;
  11814. }
  11815. },
  11816. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  11817. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  11818. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  11819. currentStencilFunc = stencilFunc;
  11820. currentStencilRef = stencilRef;
  11821. currentStencilFuncMask = stencilMask;
  11822. }
  11823. },
  11824. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  11825. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  11826. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  11827. currentStencilFail = stencilFail;
  11828. currentStencilZFail = stencilZFail;
  11829. currentStencilZPass = stencilZPass;
  11830. }
  11831. },
  11832. setLocked: function (lock) {
  11833. locked = lock;
  11834. },
  11835. setClear: function (stencil) {
  11836. if (currentStencilClear !== stencil) {
  11837. gl.clearStencil(stencil);
  11838. currentStencilClear = stencil;
  11839. }
  11840. },
  11841. reset: function () {
  11842. locked = false;
  11843. currentStencilMask = null;
  11844. currentStencilFunc = null;
  11845. currentStencilRef = null;
  11846. currentStencilFuncMask = null;
  11847. currentStencilFail = null;
  11848. currentStencilZFail = null;
  11849. currentStencilZPass = null;
  11850. currentStencilClear = null;
  11851. }
  11852. };
  11853. } //
  11854. const colorBuffer = new ColorBuffer();
  11855. const depthBuffer = new DepthBuffer();
  11856. const stencilBuffer = new StencilBuffer();
  11857. let enabledCapabilities = {};
  11858. let xrFramebuffer = null;
  11859. let currentBoundFramebuffers = {};
  11860. let currentProgram = null;
  11861. let currentBlendingEnabled = false;
  11862. let currentBlending = null;
  11863. let currentBlendEquation = null;
  11864. let currentBlendSrc = null;
  11865. let currentBlendDst = null;
  11866. let currentBlendEquationAlpha = null;
  11867. let currentBlendSrcAlpha = null;
  11868. let currentBlendDstAlpha = null;
  11869. let currentPremultipledAlpha = false;
  11870. let currentFlipSided = null;
  11871. let currentCullFace = null;
  11872. let currentLineWidth = null;
  11873. let currentPolygonOffsetFactor = null;
  11874. let currentPolygonOffsetUnits = null;
  11875. const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11876. let lineWidthAvailable = false;
  11877. let version = 0;
  11878. const glVersion = gl.getParameter(gl.VERSION);
  11879. if (glVersion.indexOf('WebGL') !== -1) {
  11880. version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
  11881. lineWidthAvailable = version >= 1.0;
  11882. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  11883. version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
  11884. lineWidthAvailable = version >= 2.0;
  11885. }
  11886. let currentTextureSlot = null;
  11887. let currentBoundTextures = {};
  11888. const scissorParam = gl.getParameter(gl.SCISSOR_BOX);
  11889. const viewportParam = gl.getParameter(gl.VIEWPORT);
  11890. const currentScissor = new Vector4().fromArray(scissorParam);
  11891. const currentViewport = new Vector4().fromArray(viewportParam);
  11892. function createTexture(type, target, count) {
  11893. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  11894. const texture = gl.createTexture();
  11895. gl.bindTexture(type, texture);
  11896. gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11897. gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11898. for (let i = 0; i < count; i++) {
  11899. gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
  11900. }
  11901. return texture;
  11902. }
  11903. const emptyTextures = {};
  11904. emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1);
  11905. emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); // init
  11906. colorBuffer.setClear(0, 0, 0, 1);
  11907. depthBuffer.setClear(1);
  11908. stencilBuffer.setClear(0);
  11909. enable(gl.DEPTH_TEST);
  11910. depthBuffer.setFunc(LessEqualDepth);
  11911. setFlipSided(false);
  11912. setCullFace(CullFaceBack);
  11913. enable(gl.CULL_FACE);
  11914. setBlending(NoBlending); //
  11915. function enable(id) {
  11916. if (enabledCapabilities[id] !== true) {
  11917. gl.enable(id);
  11918. enabledCapabilities[id] = true;
  11919. }
  11920. }
  11921. function disable(id) {
  11922. if (enabledCapabilities[id] !== false) {
  11923. gl.disable(id);
  11924. enabledCapabilities[id] = false;
  11925. }
  11926. }
  11927. function bindXRFramebuffer(framebuffer) {
  11928. if (framebuffer !== xrFramebuffer) {
  11929. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  11930. xrFramebuffer = framebuffer;
  11931. }
  11932. }
  11933. function bindFramebuffer(target, framebuffer) {
  11934. if (framebuffer === null && xrFramebuffer !== null) framebuffer = xrFramebuffer; // use active XR framebuffer if available
  11935. if (currentBoundFramebuffers[target] !== framebuffer) {
  11936. gl.bindFramebuffer(target, framebuffer);
  11937. currentBoundFramebuffers[target] = framebuffer;
  11938. if (isWebGL2) {
  11939. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  11940. if (target === gl.DRAW_FRAMEBUFFER) {
  11941. currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer;
  11942. }
  11943. if (target === gl.FRAMEBUFFER) {
  11944. currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer;
  11945. }
  11946. }
  11947. return true;
  11948. }
  11949. return false;
  11950. }
  11951. function useProgram(program) {
  11952. if (currentProgram !== program) {
  11953. gl.useProgram(program);
  11954. currentProgram = program;
  11955. return true;
  11956. }
  11957. return false;
  11958. }
  11959. const equationToGL = {
  11960. [AddEquation]: gl.FUNC_ADD,
  11961. [SubtractEquation]: gl.FUNC_SUBTRACT,
  11962. [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT
  11963. };
  11964. if (isWebGL2) {
  11965. equationToGL[MinEquation] = gl.MIN;
  11966. equationToGL[MaxEquation] = gl.MAX;
  11967. } else {
  11968. const extension = extensions.get('EXT_blend_minmax');
  11969. if (extension !== null) {
  11970. equationToGL[MinEquation] = extension.MIN_EXT;
  11971. equationToGL[MaxEquation] = extension.MAX_EXT;
  11972. }
  11973. }
  11974. const factorToGL = {
  11975. [ZeroFactor]: gl.ZERO,
  11976. [OneFactor]: gl.ONE,
  11977. [SrcColorFactor]: gl.SRC_COLOR,
  11978. [SrcAlphaFactor]: gl.SRC_ALPHA,
  11979. [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE,
  11980. [DstColorFactor]: gl.DST_COLOR,
  11981. [DstAlphaFactor]: gl.DST_ALPHA,
  11982. [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR,
  11983. [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA,
  11984. [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR,
  11985. [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA
  11986. };
  11987. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  11988. if (blending === NoBlending) {
  11989. if (currentBlendingEnabled === true) {
  11990. disable(gl.BLEND);
  11991. currentBlendingEnabled = false;
  11992. }
  11993. return;
  11994. }
  11995. if (currentBlendingEnabled === false) {
  11996. enable(gl.BLEND);
  11997. currentBlendingEnabled = true;
  11998. }
  11999. if (blending !== CustomBlending) {
  12000. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  12001. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  12002. gl.blendEquation(gl.FUNC_ADD);
  12003. currentBlendEquation = AddEquation;
  12004. currentBlendEquationAlpha = AddEquation;
  12005. }
  12006. if (premultipliedAlpha) {
  12007. switch (blending) {
  12008. case NormalBlending:
  12009. gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  12010. break;
  12011. case AdditiveBlending:
  12012. gl.blendFunc(gl.ONE, gl.ONE);
  12013. break;
  12014. case SubtractiveBlending:
  12015. gl.blendFuncSeparate(gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA);
  12016. break;
  12017. case MultiplyBlending:
  12018. gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA);
  12019. break;
  12020. default:
  12021. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12022. break;
  12023. }
  12024. } else {
  12025. switch (blending) {
  12026. case NormalBlending:
  12027. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  12028. break;
  12029. case AdditiveBlending:
  12030. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  12031. break;
  12032. case SubtractiveBlending:
  12033. gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_COLOR);
  12034. break;
  12035. case MultiplyBlending:
  12036. gl.blendFunc(gl.ZERO, gl.SRC_COLOR);
  12037. break;
  12038. default:
  12039. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12040. break;
  12041. }
  12042. }
  12043. currentBlendSrc = null;
  12044. currentBlendDst = null;
  12045. currentBlendSrcAlpha = null;
  12046. currentBlendDstAlpha = null;
  12047. currentBlending = blending;
  12048. currentPremultipledAlpha = premultipliedAlpha;
  12049. }
  12050. return;
  12051. } // custom blending
  12052. blendEquationAlpha = blendEquationAlpha || blendEquation;
  12053. blendSrcAlpha = blendSrcAlpha || blendSrc;
  12054. blendDstAlpha = blendDstAlpha || blendDst;
  12055. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  12056. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  12057. currentBlendEquation = blendEquation;
  12058. currentBlendEquationAlpha = blendEquationAlpha;
  12059. }
  12060. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  12061. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  12062. currentBlendSrc = blendSrc;
  12063. currentBlendDst = blendDst;
  12064. currentBlendSrcAlpha = blendSrcAlpha;
  12065. currentBlendDstAlpha = blendDstAlpha;
  12066. }
  12067. currentBlending = blending;
  12068. currentPremultipledAlpha = null;
  12069. }
  12070. function setMaterial(material, frontFaceCW) {
  12071. material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE);
  12072. let flipSided = material.side === BackSide;
  12073. if (frontFaceCW) flipSided = !flipSided;
  12074. setFlipSided(flipSided);
  12075. 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);
  12076. depthBuffer.setFunc(material.depthFunc);
  12077. depthBuffer.setTest(material.depthTest);
  12078. depthBuffer.setMask(material.depthWrite);
  12079. colorBuffer.setMask(material.colorWrite);
  12080. const stencilWrite = material.stencilWrite;
  12081. stencilBuffer.setTest(stencilWrite);
  12082. if (stencilWrite) {
  12083. stencilBuffer.setMask(material.stencilWriteMask);
  12084. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  12085. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  12086. }
  12087. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  12088. material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  12089. } //
  12090. function setFlipSided(flipSided) {
  12091. if (currentFlipSided !== flipSided) {
  12092. if (flipSided) {
  12093. gl.frontFace(gl.CW);
  12094. } else {
  12095. gl.frontFace(gl.CCW);
  12096. }
  12097. currentFlipSided = flipSided;
  12098. }
  12099. }
  12100. function setCullFace(cullFace) {
  12101. if (cullFace !== CullFaceNone) {
  12102. enable(gl.CULL_FACE);
  12103. if (cullFace !== currentCullFace) {
  12104. if (cullFace === CullFaceBack) {
  12105. gl.cullFace(gl.BACK);
  12106. } else if (cullFace === CullFaceFront) {
  12107. gl.cullFace(gl.FRONT);
  12108. } else {
  12109. gl.cullFace(gl.FRONT_AND_BACK);
  12110. }
  12111. }
  12112. } else {
  12113. disable(gl.CULL_FACE);
  12114. }
  12115. currentCullFace = cullFace;
  12116. }
  12117. function setLineWidth(width) {
  12118. if (width !== currentLineWidth) {
  12119. if (lineWidthAvailable) gl.lineWidth(width);
  12120. currentLineWidth = width;
  12121. }
  12122. }
  12123. function setPolygonOffset(polygonOffset, factor, units) {
  12124. if (polygonOffset) {
  12125. enable(gl.POLYGON_OFFSET_FILL);
  12126. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  12127. gl.polygonOffset(factor, units);
  12128. currentPolygonOffsetFactor = factor;
  12129. currentPolygonOffsetUnits = units;
  12130. }
  12131. } else {
  12132. disable(gl.POLYGON_OFFSET_FILL);
  12133. }
  12134. }
  12135. function setScissorTest(scissorTest) {
  12136. if (scissorTest) {
  12137. enable(gl.SCISSOR_TEST);
  12138. } else {
  12139. disable(gl.SCISSOR_TEST);
  12140. }
  12141. } // texture
  12142. function activeTexture(webglSlot) {
  12143. if (webglSlot === undefined) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  12144. if (currentTextureSlot !== webglSlot) {
  12145. gl.activeTexture(webglSlot);
  12146. currentTextureSlot = webglSlot;
  12147. }
  12148. }
  12149. function bindTexture(webglType, webglTexture) {
  12150. if (currentTextureSlot === null) {
  12151. activeTexture();
  12152. }
  12153. let boundTexture = currentBoundTextures[currentTextureSlot];
  12154. if (boundTexture === undefined) {
  12155. boundTexture = {
  12156. type: undefined,
  12157. texture: undefined
  12158. };
  12159. currentBoundTextures[currentTextureSlot] = boundTexture;
  12160. }
  12161. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  12162. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  12163. boundTexture.type = webglType;
  12164. boundTexture.texture = webglTexture;
  12165. }
  12166. }
  12167. function unbindTexture() {
  12168. const boundTexture = currentBoundTextures[currentTextureSlot];
  12169. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  12170. gl.bindTexture(boundTexture.type, null);
  12171. boundTexture.type = undefined;
  12172. boundTexture.texture = undefined;
  12173. }
  12174. }
  12175. function compressedTexImage2D() {
  12176. try {
  12177. gl.compressedTexImage2D.apply(gl, arguments);
  12178. } catch (error) {
  12179. console.error('THREE.WebGLState:', error);
  12180. }
  12181. }
  12182. function texImage2D() {
  12183. try {
  12184. gl.texImage2D.apply(gl, arguments);
  12185. } catch (error) {
  12186. console.error('THREE.WebGLState:', error);
  12187. }
  12188. }
  12189. function texImage3D() {
  12190. try {
  12191. gl.texImage3D.apply(gl, arguments);
  12192. } catch (error) {
  12193. console.error('THREE.WebGLState:', error);
  12194. }
  12195. } //
  12196. function scissor(scissor) {
  12197. if (currentScissor.equals(scissor) === false) {
  12198. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  12199. currentScissor.copy(scissor);
  12200. }
  12201. }
  12202. function viewport(viewport) {
  12203. if (currentViewport.equals(viewport) === false) {
  12204. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  12205. currentViewport.copy(viewport);
  12206. }
  12207. } //
  12208. function reset() {
  12209. // reset state
  12210. gl.disable(gl.BLEND);
  12211. gl.disable(gl.CULL_FACE);
  12212. gl.disable(gl.DEPTH_TEST);
  12213. gl.disable(gl.POLYGON_OFFSET_FILL);
  12214. gl.disable(gl.SCISSOR_TEST);
  12215. gl.disable(gl.STENCIL_TEST);
  12216. gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  12217. gl.blendEquation(gl.FUNC_ADD);
  12218. gl.blendFunc(gl.ONE, gl.ZERO);
  12219. gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
  12220. gl.colorMask(true, true, true, true);
  12221. gl.clearColor(0, 0, 0, 0);
  12222. gl.depthMask(true);
  12223. gl.depthFunc(gl.LESS);
  12224. gl.clearDepth(1);
  12225. gl.stencilMask(0xffffffff);
  12226. gl.stencilFunc(gl.ALWAYS, 0, 0xffffffff);
  12227. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  12228. gl.clearStencil(0);
  12229. gl.cullFace(gl.BACK);
  12230. gl.frontFace(gl.CCW);
  12231. gl.polygonOffset(0, 0);
  12232. gl.activeTexture(gl.TEXTURE0);
  12233. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12234. if (isWebGL2 === true) {
  12235. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  12236. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  12237. }
  12238. gl.useProgram(null);
  12239. gl.lineWidth(1);
  12240. gl.scissor(0, 0, gl.canvas.width, gl.canvas.height);
  12241. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); // reset internals
  12242. enabledCapabilities = {};
  12243. currentTextureSlot = null;
  12244. currentBoundTextures = {};
  12245. xrFramebuffer = null;
  12246. currentBoundFramebuffers = {};
  12247. currentProgram = null;
  12248. currentBlendingEnabled = false;
  12249. currentBlending = null;
  12250. currentBlendEquation = null;
  12251. currentBlendSrc = null;
  12252. currentBlendDst = null;
  12253. currentBlendEquationAlpha = null;
  12254. currentBlendSrcAlpha = null;
  12255. currentBlendDstAlpha = null;
  12256. currentPremultipledAlpha = false;
  12257. currentFlipSided = null;
  12258. currentCullFace = null;
  12259. currentLineWidth = null;
  12260. currentPolygonOffsetFactor = null;
  12261. currentPolygonOffsetUnits = null;
  12262. currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height);
  12263. currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height);
  12264. colorBuffer.reset();
  12265. depthBuffer.reset();
  12266. stencilBuffer.reset();
  12267. }
  12268. return {
  12269. buffers: {
  12270. color: colorBuffer,
  12271. depth: depthBuffer,
  12272. stencil: stencilBuffer
  12273. },
  12274. enable: enable,
  12275. disable: disable,
  12276. bindFramebuffer: bindFramebuffer,
  12277. bindXRFramebuffer: bindXRFramebuffer,
  12278. useProgram: useProgram,
  12279. setBlending: setBlending,
  12280. setMaterial: setMaterial,
  12281. setFlipSided: setFlipSided,
  12282. setCullFace: setCullFace,
  12283. setLineWidth: setLineWidth,
  12284. setPolygonOffset: setPolygonOffset,
  12285. setScissorTest: setScissorTest,
  12286. activeTexture: activeTexture,
  12287. bindTexture: bindTexture,
  12288. unbindTexture: unbindTexture,
  12289. compressedTexImage2D: compressedTexImage2D,
  12290. texImage2D: texImage2D,
  12291. texImage3D: texImage3D,
  12292. scissor: scissor,
  12293. viewport: viewport,
  12294. reset: reset
  12295. };
  12296. }
  12297. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  12298. const isWebGL2 = capabilities.isWebGL2;
  12299. const maxTextures = capabilities.maxTextures;
  12300. const maxCubemapSize = capabilities.maxCubemapSize;
  12301. const maxTextureSize = capabilities.maxTextureSize;
  12302. const maxSamples = capabilities.maxSamples;
  12303. const _videoTextures = new WeakMap();
  12304. let _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  12305. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  12306. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  12307. let useOffscreenCanvas = false;
  12308. try {
  12309. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext('2d') !== null;
  12310. } catch (err) {// Ignore any errors
  12311. }
  12312. function createCanvas(width, height) {
  12313. // Use OffscreenCanvas when available. Specially needed in web workers
  12314. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  12315. }
  12316. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  12317. let scale = 1; // handle case if texture exceeds max size
  12318. if (image.width > maxSize || image.height > maxSize) {
  12319. scale = maxSize / Math.max(image.width, image.height);
  12320. } // only perform resize if necessary
  12321. if (scale < 1 || needsPowerOfTwo === true) {
  12322. // only perform resize for certain image types
  12323. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  12324. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  12325. const width = floor(scale * image.width);
  12326. const height = floor(scale * image.height);
  12327. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  12328. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  12329. canvas.width = width;
  12330. canvas.height = height;
  12331. const context = canvas.getContext('2d');
  12332. context.drawImage(image, 0, 0, width, height);
  12333. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  12334. return canvas;
  12335. } else {
  12336. if ('data' in image) {
  12337. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  12338. }
  12339. return image;
  12340. }
  12341. }
  12342. return image;
  12343. }
  12344. function isPowerOfTwo$1(image) {
  12345. return isPowerOfTwo(image.width) && isPowerOfTwo(image.height);
  12346. }
  12347. function textureNeedsPowerOfTwo(texture) {
  12348. if (isWebGL2) return false;
  12349. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  12350. }
  12351. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  12352. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  12353. }
  12354. function generateMipmap(target, texture, width, height, depth = 1) {
  12355. _gl.generateMipmap(target);
  12356. const textureProperties = properties.get(texture);
  12357. textureProperties.__maxMipLevel = Math.log2(Math.max(width, height, depth));
  12358. }
  12359. function getInternalFormat(internalFormatName, glFormat, glType) {
  12360. if (isWebGL2 === false) return glFormat;
  12361. if (internalFormatName !== null) {
  12362. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  12363. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  12364. }
  12365. let internalFormat = glFormat;
  12366. if (glFormat === _gl.RED) {
  12367. if (glType === _gl.FLOAT) internalFormat = _gl.R32F;
  12368. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F;
  12369. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8;
  12370. }
  12371. if (glFormat === _gl.RGB) {
  12372. if (glType === _gl.FLOAT) internalFormat = _gl.RGB32F;
  12373. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGB16F;
  12374. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGB8;
  12375. }
  12376. if (glFormat === _gl.RGBA) {
  12377. if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
  12378. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
  12379. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGBA8;
  12380. }
  12381. if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) {
  12382. extensions.get('EXT_color_buffer_float');
  12383. }
  12384. return internalFormat;
  12385. } // Fallback filters for non-power-of-2 textures
  12386. function filterFallback(f) {
  12387. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  12388. return _gl.NEAREST;
  12389. }
  12390. return _gl.LINEAR;
  12391. } //
  12392. function onTextureDispose(event) {
  12393. const texture = event.target;
  12394. texture.removeEventListener('dispose', onTextureDispose);
  12395. deallocateTexture(texture);
  12396. if (texture.isVideoTexture) {
  12397. _videoTextures.delete(texture);
  12398. }
  12399. info.memory.textures--;
  12400. }
  12401. function onRenderTargetDispose(event) {
  12402. const renderTarget = event.target;
  12403. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  12404. deallocateRenderTarget(renderTarget);
  12405. } //
  12406. function deallocateTexture(texture) {
  12407. const textureProperties = properties.get(texture);
  12408. if (textureProperties.__webglInit === undefined) return;
  12409. _gl.deleteTexture(textureProperties.__webglTexture);
  12410. properties.remove(texture);
  12411. }
  12412. function deallocateRenderTarget(renderTarget) {
  12413. const texture = renderTarget.texture;
  12414. const renderTargetProperties = properties.get(renderTarget);
  12415. const textureProperties = properties.get(texture);
  12416. if (!renderTarget) return;
  12417. if (textureProperties.__webglTexture !== undefined) {
  12418. _gl.deleteTexture(textureProperties.__webglTexture);
  12419. info.memory.textures--;
  12420. }
  12421. if (renderTarget.depthTexture) {
  12422. renderTarget.depthTexture.dispose();
  12423. }
  12424. if (renderTarget.isWebGLCubeRenderTarget) {
  12425. for (let i = 0; i < 6; i++) {
  12426. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  12427. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  12428. }
  12429. } else {
  12430. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  12431. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  12432. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  12433. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  12434. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  12435. }
  12436. if (renderTarget.isWebGLMultipleRenderTargets) {
  12437. for (let i = 0, il = texture.length; i < il; i++) {
  12438. const attachmentProperties = properties.get(texture[i]);
  12439. if (attachmentProperties.__webglTexture) {
  12440. _gl.deleteTexture(attachmentProperties.__webglTexture);
  12441. info.memory.textures--;
  12442. }
  12443. properties.remove(texture[i]);
  12444. }
  12445. }
  12446. properties.remove(texture);
  12447. properties.remove(renderTarget);
  12448. } //
  12449. let textureUnits = 0;
  12450. function resetTextureUnits() {
  12451. textureUnits = 0;
  12452. }
  12453. function allocateTextureUnit() {
  12454. const textureUnit = textureUnits;
  12455. if (textureUnit >= maxTextures) {
  12456. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  12457. }
  12458. textureUnits += 1;
  12459. return textureUnit;
  12460. } //
  12461. function setTexture2D(texture, slot) {
  12462. const textureProperties = properties.get(texture);
  12463. if (texture.isVideoTexture) updateVideoTexture(texture);
  12464. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12465. const image = texture.image;
  12466. if (image === undefined) {
  12467. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  12468. } else if (image.complete === false) {
  12469. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  12470. } else {
  12471. uploadTexture(textureProperties, texture, slot);
  12472. return;
  12473. }
  12474. }
  12475. state.activeTexture(_gl.TEXTURE0 + slot);
  12476. state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture);
  12477. }
  12478. function setTexture2DArray(texture, slot) {
  12479. const textureProperties = properties.get(texture);
  12480. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12481. uploadTexture(textureProperties, texture, slot);
  12482. return;
  12483. }
  12484. state.activeTexture(_gl.TEXTURE0 + slot);
  12485. state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture);
  12486. }
  12487. function setTexture3D(texture, slot) {
  12488. const textureProperties = properties.get(texture);
  12489. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12490. uploadTexture(textureProperties, texture, slot);
  12491. return;
  12492. }
  12493. state.activeTexture(_gl.TEXTURE0 + slot);
  12494. state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture);
  12495. }
  12496. function setTextureCube(texture, slot) {
  12497. const textureProperties = properties.get(texture);
  12498. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12499. uploadCubeTexture(textureProperties, texture, slot);
  12500. return;
  12501. }
  12502. state.activeTexture(_gl.TEXTURE0 + slot);
  12503. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  12504. }
  12505. const wrappingToGL = {
  12506. [RepeatWrapping]: _gl.REPEAT,
  12507. [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE,
  12508. [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT
  12509. };
  12510. const filterToGL = {
  12511. [NearestFilter]: _gl.NEAREST,
  12512. [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST,
  12513. [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR,
  12514. [LinearFilter]: _gl.LINEAR,
  12515. [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST,
  12516. [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR
  12517. };
  12518. function setTextureParameters(textureType, texture, supportsMips) {
  12519. if (supportsMips) {
  12520. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]);
  12521. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]);
  12522. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  12523. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]);
  12524. }
  12525. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]);
  12526. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]);
  12527. } else {
  12528. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE);
  12529. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE);
  12530. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  12531. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE);
  12532. }
  12533. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  12534. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  12535. }
  12536. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter));
  12537. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter));
  12538. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  12539. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  12540. }
  12541. }
  12542. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  12543. const extension = extensions.get('EXT_texture_filter_anisotropic');
  12544. if (texture.type === FloatType && extensions.has('OES_texture_float_linear') === false) return; // verify extension for WebGL 1 and WebGL 2
  12545. if (isWebGL2 === false && texture.type === HalfFloatType && extensions.has('OES_texture_half_float_linear') === false) return; // verify extension for WebGL 1 only
  12546. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  12547. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  12548. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  12549. }
  12550. }
  12551. }
  12552. function initTexture(textureProperties, texture) {
  12553. if (textureProperties.__webglInit === undefined) {
  12554. textureProperties.__webglInit = true;
  12555. texture.addEventListener('dispose', onTextureDispose);
  12556. textureProperties.__webglTexture = _gl.createTexture();
  12557. info.memory.textures++;
  12558. }
  12559. }
  12560. function uploadTexture(textureProperties, texture, slot) {
  12561. let textureType = _gl.TEXTURE_2D;
  12562. if (texture.isDataTexture2DArray) textureType = _gl.TEXTURE_2D_ARRAY;
  12563. if (texture.isDataTexture3D) textureType = _gl.TEXTURE_3D;
  12564. initTexture(textureProperties, texture);
  12565. state.activeTexture(_gl.TEXTURE0 + slot);
  12566. state.bindTexture(textureType, textureProperties.__webglTexture);
  12567. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  12568. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  12569. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  12570. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  12571. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false;
  12572. const image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  12573. const supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  12574. glFormat = utils.convert(texture.format);
  12575. let glType = utils.convert(texture.type),
  12576. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12577. setTextureParameters(textureType, texture, supportsMips);
  12578. let mipmap;
  12579. const mipmaps = texture.mipmaps;
  12580. if (texture.isDepthTexture) {
  12581. // populate depth texture with dummy data
  12582. glInternalFormat = _gl.DEPTH_COMPONENT;
  12583. if (isWebGL2) {
  12584. if (texture.type === FloatType) {
  12585. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  12586. } else if (texture.type === UnsignedIntType) {
  12587. glInternalFormat = _gl.DEPTH_COMPONENT24;
  12588. } else if (texture.type === UnsignedInt248Type) {
  12589. glInternalFormat = _gl.DEPTH24_STENCIL8;
  12590. } else {
  12591. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  12592. }
  12593. } else {
  12594. if (texture.type === FloatType) {
  12595. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  12596. }
  12597. } // validation checks for WebGL 1
  12598. if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  12599. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  12600. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  12601. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12602. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  12603. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  12604. texture.type = UnsignedShortType;
  12605. glType = utils.convert(texture.type);
  12606. }
  12607. }
  12608. if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  12609. // Depth stencil textures need the DEPTH_STENCIL internal format
  12610. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12611. glInternalFormat = _gl.DEPTH_STENCIL; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  12612. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  12613. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12614. if (texture.type !== UnsignedInt248Type) {
  12615. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  12616. texture.type = UnsignedInt248Type;
  12617. glType = utils.convert(texture.type);
  12618. }
  12619. } //
  12620. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  12621. } else if (texture.isDataTexture) {
  12622. // use manually created mipmaps if available
  12623. // if there are no manual mipmaps
  12624. // set 0 level mipmap and then use GL to generate other mipmap levels
  12625. if (mipmaps.length > 0 && supportsMips) {
  12626. for (let i = 0, il = mipmaps.length; i < il; i++) {
  12627. mipmap = mipmaps[i];
  12628. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  12629. }
  12630. texture.generateMipmaps = false;
  12631. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12632. } else {
  12633. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  12634. textureProperties.__maxMipLevel = 0;
  12635. }
  12636. } else if (texture.isCompressedTexture) {
  12637. for (let i = 0, il = mipmaps.length; i < il; i++) {
  12638. mipmap = mipmaps[i];
  12639. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  12640. if (glFormat !== null) {
  12641. state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  12642. } else {
  12643. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  12644. }
  12645. } else {
  12646. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  12647. }
  12648. }
  12649. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12650. } else if (texture.isDataTexture2DArray) {
  12651. state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  12652. textureProperties.__maxMipLevel = 0;
  12653. } else if (texture.isDataTexture3D) {
  12654. state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  12655. textureProperties.__maxMipLevel = 0;
  12656. } else {
  12657. // regular Texture (image, video, canvas)
  12658. // use manually created mipmaps if available
  12659. // if there are no manual mipmaps
  12660. // set 0 level mipmap and then use GL to generate other mipmap levels
  12661. if (mipmaps.length > 0 && supportsMips) {
  12662. for (let i = 0, il = mipmaps.length; i < il; i++) {
  12663. mipmap = mipmaps[i];
  12664. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap);
  12665. }
  12666. texture.generateMipmaps = false;
  12667. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12668. } else {
  12669. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image);
  12670. textureProperties.__maxMipLevel = 0;
  12671. }
  12672. }
  12673. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  12674. generateMipmap(textureType, texture, image.width, image.height);
  12675. }
  12676. textureProperties.__version = texture.version;
  12677. if (texture.onUpdate) texture.onUpdate(texture);
  12678. }
  12679. function uploadCubeTexture(textureProperties, texture, slot) {
  12680. if (texture.image.length !== 6) return;
  12681. initTexture(textureProperties, texture);
  12682. state.activeTexture(_gl.TEXTURE0 + slot);
  12683. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  12684. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  12685. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  12686. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  12687. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  12688. const isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
  12689. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  12690. const cubeImage = [];
  12691. for (let i = 0; i < 6; i++) {
  12692. if (!isCompressed && !isDataTexture) {
  12693. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  12694. } else {
  12695. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  12696. }
  12697. }
  12698. const image = cubeImage[0],
  12699. supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  12700. glFormat = utils.convert(texture.format),
  12701. glType = utils.convert(texture.type),
  12702. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12703. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  12704. let mipmaps;
  12705. if (isCompressed) {
  12706. for (let i = 0; i < 6; i++) {
  12707. mipmaps = cubeImage[i].mipmaps;
  12708. for (let j = 0; j < mipmaps.length; j++) {
  12709. const mipmap = mipmaps[j];
  12710. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  12711. if (glFormat !== null) {
  12712. state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  12713. } else {
  12714. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  12715. }
  12716. } else {
  12717. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  12718. }
  12719. }
  12720. }
  12721. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12722. } else {
  12723. mipmaps = texture.mipmaps;
  12724. for (let i = 0; i < 6; i++) {
  12725. if (isDataTexture) {
  12726. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  12727. for (let j = 0; j < mipmaps.length; j++) {
  12728. const mipmap = mipmaps[j];
  12729. const mipmapImage = mipmap.image[i].image;
  12730. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  12731. }
  12732. } else {
  12733. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  12734. for (let j = 0; j < mipmaps.length; j++) {
  12735. const mipmap = mipmaps[j];
  12736. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  12737. }
  12738. }
  12739. }
  12740. textureProperties.__maxMipLevel = mipmaps.length;
  12741. }
  12742. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  12743. // We assume images for cube map have the same size.
  12744. generateMipmap(_gl.TEXTURE_CUBE_MAP, texture, image.width, image.height);
  12745. }
  12746. textureProperties.__version = texture.version;
  12747. if (texture.onUpdate) texture.onUpdate(texture);
  12748. } // Render targets
  12749. // Setup storage for target texture and bind it to correct framebuffer
  12750. function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) {
  12751. const glFormat = utils.convert(texture.format);
  12752. const glType = utils.convert(texture.type);
  12753. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12754. if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) {
  12755. state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null);
  12756. } else {
  12757. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  12758. }
  12759. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  12760. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0);
  12761. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  12762. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  12763. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  12764. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
  12765. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  12766. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  12767. if (isMultisample) {
  12768. const depthTexture = renderTarget.depthTexture;
  12769. if (depthTexture && depthTexture.isDepthTexture) {
  12770. if (depthTexture.type === FloatType) {
  12771. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  12772. } else if (depthTexture.type === UnsignedIntType) {
  12773. glInternalFormat = _gl.DEPTH_COMPONENT24;
  12774. }
  12775. }
  12776. const samples = getRenderTargetSamples(renderTarget);
  12777. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  12778. } else {
  12779. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  12780. }
  12781. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  12782. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  12783. if (isMultisample) {
  12784. const samples = getRenderTargetSamples(renderTarget);
  12785. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  12786. } else {
  12787. _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height);
  12788. }
  12789. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  12790. } else {
  12791. // Use the first texture for MRT so far
  12792. const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[0] : renderTarget.texture;
  12793. const glFormat = utils.convert(texture.format);
  12794. const glType = utils.convert(texture.type);
  12795. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12796. if (isMultisample) {
  12797. const samples = getRenderTargetSamples(renderTarget);
  12798. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  12799. } else {
  12800. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  12801. }
  12802. }
  12803. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  12804. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  12805. function setupDepthTexture(framebuffer, renderTarget) {
  12806. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  12807. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  12808. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  12809. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  12810. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  12811. } // upload an empty depth texture with framebuffer size
  12812. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  12813. renderTarget.depthTexture.image.width = renderTarget.width;
  12814. renderTarget.depthTexture.image.height = renderTarget.height;
  12815. renderTarget.depthTexture.needsUpdate = true;
  12816. }
  12817. setTexture2D(renderTarget.depthTexture, 0);
  12818. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  12819. if (renderTarget.depthTexture.format === DepthFormat) {
  12820. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  12821. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  12822. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  12823. } else {
  12824. throw new Error('Unknown depthTexture format');
  12825. }
  12826. } // Setup GL resources for a non-texture depth buffer
  12827. function setupDepthRenderbuffer(renderTarget) {
  12828. const renderTargetProperties = properties.get(renderTarget);
  12829. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  12830. if (renderTarget.depthTexture) {
  12831. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  12832. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  12833. } else {
  12834. if (isCube) {
  12835. renderTargetProperties.__webglDepthbuffer = [];
  12836. for (let i = 0; i < 6; i++) {
  12837. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]);
  12838. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  12839. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  12840. }
  12841. } else {
  12842. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  12843. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  12844. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  12845. }
  12846. }
  12847. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  12848. } // Set up GL resources for the render target
  12849. function setupRenderTarget(renderTarget) {
  12850. const texture = renderTarget.texture;
  12851. const renderTargetProperties = properties.get(renderTarget);
  12852. const textureProperties = properties.get(texture);
  12853. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  12854. if (renderTarget.isWebGLMultipleRenderTargets !== true) {
  12855. textureProperties.__webglTexture = _gl.createTexture();
  12856. textureProperties.__version = texture.version;
  12857. info.memory.textures++;
  12858. }
  12859. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  12860. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
  12861. const isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  12862. const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
  12863. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
  12864. if (isWebGL2 && texture.format === RGBFormat && (texture.type === FloatType || texture.type === HalfFloatType)) {
  12865. texture.format = RGBAFormat;
  12866. console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
  12867. } // Setup framebuffer
  12868. if (isCube) {
  12869. renderTargetProperties.__webglFramebuffer = [];
  12870. for (let i = 0; i < 6; i++) {
  12871. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  12872. }
  12873. } else {
  12874. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  12875. if (isMultipleRenderTargets) {
  12876. if (capabilities.drawBuffers) {
  12877. const textures = renderTarget.texture;
  12878. for (let i = 0, il = textures.length; i < il; i++) {
  12879. const attachmentProperties = properties.get(textures[i]);
  12880. if (attachmentProperties.__webglTexture === undefined) {
  12881. attachmentProperties.__webglTexture = _gl.createTexture();
  12882. info.memory.textures++;
  12883. }
  12884. }
  12885. } else {
  12886. console.warn('THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.');
  12887. }
  12888. } else if (isMultisample) {
  12889. if (isWebGL2) {
  12890. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  12891. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  12892. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  12893. const glFormat = utils.convert(texture.format);
  12894. const glType = utils.convert(texture.type);
  12895. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12896. const samples = getRenderTargetSamples(renderTarget);
  12897. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  12898. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  12899. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  12900. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  12901. if (renderTarget.depthBuffer) {
  12902. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  12903. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  12904. }
  12905. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  12906. } else {
  12907. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  12908. }
  12909. }
  12910. } // Setup color buffer
  12911. if (isCube) {
  12912. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  12913. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  12914. for (let i = 0; i < 6; i++) {
  12915. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i);
  12916. }
  12917. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  12918. generateMipmap(_gl.TEXTURE_CUBE_MAP, texture, renderTarget.width, renderTarget.height);
  12919. }
  12920. state.bindTexture(_gl.TEXTURE_CUBE_MAP, null);
  12921. } else if (isMultipleRenderTargets) {
  12922. const textures = renderTarget.texture;
  12923. for (let i = 0, il = textures.length; i < il; i++) {
  12924. const attachment = textures[i];
  12925. const attachmentProperties = properties.get(attachment);
  12926. state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture);
  12927. setTextureParameters(_gl.TEXTURE_2D, attachment, supportsMips);
  12928. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D);
  12929. if (textureNeedsGenerateMipmaps(attachment, supportsMips)) {
  12930. generateMipmap(_gl.TEXTURE_2D, attachment, renderTarget.width, renderTarget.height);
  12931. }
  12932. }
  12933. state.bindTexture(_gl.TEXTURE_2D, null);
  12934. } else {
  12935. let glTextureType = _gl.TEXTURE_2D;
  12936. if (isRenderTarget3D) {
  12937. // Render targets containing layers, i.e: Texture 3D and 2d arrays
  12938. if (isWebGL2) {
  12939. const isTexture3D = texture.isDataTexture3D;
  12940. glTextureType = isTexture3D ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  12941. } else {
  12942. console.warn('THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.');
  12943. }
  12944. }
  12945. state.bindTexture(glTextureType, textureProperties.__webglTexture);
  12946. setTextureParameters(glTextureType, texture, supportsMips);
  12947. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType);
  12948. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  12949. generateMipmap(glTextureType, texture, renderTarget.width, renderTarget.height, renderTarget.depth);
  12950. }
  12951. state.bindTexture(glTextureType, null);
  12952. } // Setup depth and stencil buffers
  12953. if (renderTarget.depthBuffer) {
  12954. setupDepthRenderbuffer(renderTarget);
  12955. }
  12956. }
  12957. function updateRenderTargetMipmap(renderTarget) {
  12958. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
  12959. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  12960. for (let i = 0, il = textures.length; i < il; i++) {
  12961. const texture = textures[i];
  12962. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  12963. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  12964. const webglTexture = properties.get(texture).__webglTexture;
  12965. state.bindTexture(target, webglTexture);
  12966. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  12967. state.bindTexture(target, null);
  12968. }
  12969. }
  12970. }
  12971. function updateMultisampleRenderTarget(renderTarget) {
  12972. if (renderTarget.isWebGLMultisampleRenderTarget) {
  12973. if (isWebGL2) {
  12974. const width = renderTarget.width;
  12975. const height = renderTarget.height;
  12976. let mask = _gl.COLOR_BUFFER_BIT;
  12977. if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT;
  12978. if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT;
  12979. const renderTargetProperties = properties.get(renderTarget);
  12980. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  12981. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  12982. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST);
  12983. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
  12984. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  12985. } else {
  12986. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  12987. }
  12988. }
  12989. }
  12990. function getRenderTargetSamples(renderTarget) {
  12991. return isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(maxSamples, renderTarget.samples) : 0;
  12992. }
  12993. function updateVideoTexture(texture) {
  12994. const frame = info.render.frame; // Check the last frame we updated the VideoTexture
  12995. if (_videoTextures.get(texture) !== frame) {
  12996. _videoTextures.set(texture, frame);
  12997. texture.update();
  12998. }
  12999. } // backwards compatibility
  13000. let warnedTexture2D = false;
  13001. let warnedTextureCube = false;
  13002. function safeSetTexture2D(texture, slot) {
  13003. if (texture && texture.isWebGLRenderTarget) {
  13004. if (warnedTexture2D === false) {
  13005. console.warn('THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.');
  13006. warnedTexture2D = true;
  13007. }
  13008. texture = texture.texture;
  13009. }
  13010. setTexture2D(texture, slot);
  13011. }
  13012. function safeSetTextureCube(texture, slot) {
  13013. if (texture && texture.isWebGLCubeRenderTarget) {
  13014. if (warnedTextureCube === false) {
  13015. console.warn('THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.');
  13016. warnedTextureCube = true;
  13017. }
  13018. texture = texture.texture;
  13019. }
  13020. setTextureCube(texture, slot);
  13021. } //
  13022. this.allocateTextureUnit = allocateTextureUnit;
  13023. this.resetTextureUnits = resetTextureUnits;
  13024. this.setTexture2D = setTexture2D;
  13025. this.setTexture2DArray = setTexture2DArray;
  13026. this.setTexture3D = setTexture3D;
  13027. this.setTextureCube = setTextureCube;
  13028. this.setupRenderTarget = setupRenderTarget;
  13029. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  13030. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  13031. this.safeSetTexture2D = safeSetTexture2D;
  13032. this.safeSetTextureCube = safeSetTextureCube;
  13033. }
  13034. function WebGLUtils(gl, extensions, capabilities) {
  13035. const isWebGL2 = capabilities.isWebGL2;
  13036. function convert(p) {
  13037. let extension;
  13038. if (p === UnsignedByteType) return gl.UNSIGNED_BYTE;
  13039. if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4;
  13040. if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1;
  13041. if (p === UnsignedShort565Type) return gl.UNSIGNED_SHORT_5_6_5;
  13042. if (p === ByteType) return gl.BYTE;
  13043. if (p === ShortType) return gl.SHORT;
  13044. if (p === UnsignedShortType) return gl.UNSIGNED_SHORT;
  13045. if (p === IntType) return gl.INT;
  13046. if (p === UnsignedIntType) return gl.UNSIGNED_INT;
  13047. if (p === FloatType) return gl.FLOAT;
  13048. if (p === HalfFloatType) {
  13049. if (isWebGL2) return gl.HALF_FLOAT;
  13050. extension = extensions.get('OES_texture_half_float');
  13051. if (extension !== null) {
  13052. return extension.HALF_FLOAT_OES;
  13053. } else {
  13054. return null;
  13055. }
  13056. }
  13057. if (p === AlphaFormat) return gl.ALPHA;
  13058. if (p === RGBFormat) return gl.RGB;
  13059. if (p === RGBAFormat) return gl.RGBA;
  13060. if (p === LuminanceFormat) return gl.LUMINANCE;
  13061. if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
  13062. if (p === DepthFormat) return gl.DEPTH_COMPONENT;
  13063. if (p === DepthStencilFormat) return gl.DEPTH_STENCIL;
  13064. if (p === RedFormat) return gl.RED; // WebGL2 formats.
  13065. if (p === RedIntegerFormat) return gl.RED_INTEGER;
  13066. if (p === RGFormat) return gl.RG;
  13067. if (p === RGIntegerFormat) return gl.RG_INTEGER;
  13068. if (p === RGBIntegerFormat) return gl.RGB_INTEGER;
  13069. if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER;
  13070. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  13071. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  13072. if (extension !== null) {
  13073. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13074. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13075. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13076. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13077. } else {
  13078. return null;
  13079. }
  13080. }
  13081. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  13082. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  13083. if (extension !== null) {
  13084. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13085. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13086. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13087. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13088. } else {
  13089. return null;
  13090. }
  13091. }
  13092. if (p === RGB_ETC1_Format) {
  13093. extension = extensions.get('WEBGL_compressed_texture_etc1');
  13094. if (extension !== null) {
  13095. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13096. } else {
  13097. return null;
  13098. }
  13099. }
  13100. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  13101. extension = extensions.get('WEBGL_compressed_texture_etc');
  13102. if (extension !== null) {
  13103. if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
  13104. if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  13105. }
  13106. }
  13107. 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) {
  13108. extension = extensions.get('WEBGL_compressed_texture_astc');
  13109. if (extension !== null) {
  13110. // TODO Complete?
  13111. return p;
  13112. } else {
  13113. return null;
  13114. }
  13115. }
  13116. if (p === RGBA_BPTC_Format) {
  13117. extension = extensions.get('EXT_texture_compression_bptc');
  13118. if (extension !== null) {
  13119. // TODO Complete?
  13120. return p;
  13121. } else {
  13122. return null;
  13123. }
  13124. }
  13125. if (p === UnsignedInt248Type) {
  13126. if (isWebGL2) return gl.UNSIGNED_INT_24_8;
  13127. extension = extensions.get('WEBGL_depth_texture');
  13128. if (extension !== null) {
  13129. return extension.UNSIGNED_INT_24_8_WEBGL;
  13130. } else {
  13131. return null;
  13132. }
  13133. }
  13134. }
  13135. return {
  13136. convert: convert
  13137. };
  13138. }
  13139. class ArrayCamera extends PerspectiveCamera {
  13140. constructor(array = []) {
  13141. super();
  13142. this.cameras = array;
  13143. }
  13144. }
  13145. ArrayCamera.prototype.isArrayCamera = true;
  13146. class Group extends Object3D {
  13147. constructor() {
  13148. super();
  13149. this.type = 'Group';
  13150. }
  13151. }
  13152. Group.prototype.isGroup = true;
  13153. const _moveEvent = {
  13154. type: 'move'
  13155. };
  13156. class WebXRController {
  13157. constructor() {
  13158. this._targetRay = null;
  13159. this._grip = null;
  13160. this._hand = null;
  13161. }
  13162. getHandSpace() {
  13163. if (this._hand === null) {
  13164. this._hand = new Group();
  13165. this._hand.matrixAutoUpdate = false;
  13166. this._hand.visible = false;
  13167. this._hand.joints = {};
  13168. this._hand.inputState = {
  13169. pinching: false
  13170. };
  13171. }
  13172. return this._hand;
  13173. }
  13174. getTargetRaySpace() {
  13175. if (this._targetRay === null) {
  13176. this._targetRay = new Group();
  13177. this._targetRay.matrixAutoUpdate = false;
  13178. this._targetRay.visible = false;
  13179. this._targetRay.hasLinearVelocity = false;
  13180. this._targetRay.linearVelocity = new Vector3();
  13181. this._targetRay.hasAngularVelocity = false;
  13182. this._targetRay.angularVelocity = new Vector3();
  13183. }
  13184. return this._targetRay;
  13185. }
  13186. getGripSpace() {
  13187. if (this._grip === null) {
  13188. this._grip = new Group();
  13189. this._grip.matrixAutoUpdate = false;
  13190. this._grip.visible = false;
  13191. this._grip.hasLinearVelocity = false;
  13192. this._grip.linearVelocity = new Vector3();
  13193. this._grip.hasAngularVelocity = false;
  13194. this._grip.angularVelocity = new Vector3();
  13195. }
  13196. return this._grip;
  13197. }
  13198. dispatchEvent(event) {
  13199. if (this._targetRay !== null) {
  13200. this._targetRay.dispatchEvent(event);
  13201. }
  13202. if (this._grip !== null) {
  13203. this._grip.dispatchEvent(event);
  13204. }
  13205. if (this._hand !== null) {
  13206. this._hand.dispatchEvent(event);
  13207. }
  13208. return this;
  13209. }
  13210. disconnect(inputSource) {
  13211. this.dispatchEvent({
  13212. type: 'disconnected',
  13213. data: inputSource
  13214. });
  13215. if (this._targetRay !== null) {
  13216. this._targetRay.visible = false;
  13217. }
  13218. if (this._grip !== null) {
  13219. this._grip.visible = false;
  13220. }
  13221. if (this._hand !== null) {
  13222. this._hand.visible = false;
  13223. }
  13224. return this;
  13225. }
  13226. update(inputSource, frame, referenceSpace) {
  13227. let inputPose = null;
  13228. let gripPose = null;
  13229. let handPose = null;
  13230. const targetRay = this._targetRay;
  13231. const grip = this._grip;
  13232. const hand = this._hand;
  13233. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  13234. if (targetRay !== null) {
  13235. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  13236. if (inputPose !== null) {
  13237. targetRay.matrix.fromArray(inputPose.transform.matrix);
  13238. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  13239. if (inputPose.linearVelocity) {
  13240. targetRay.hasLinearVelocity = true;
  13241. targetRay.linearVelocity.copy(inputPose.linearVelocity);
  13242. } else {
  13243. targetRay.hasLinearVelocity = false;
  13244. }
  13245. if (inputPose.angularVelocity) {
  13246. targetRay.hasAngularVelocity = true;
  13247. targetRay.angularVelocity.copy(inputPose.angularVelocity);
  13248. } else {
  13249. targetRay.hasAngularVelocity = false;
  13250. }
  13251. this.dispatchEvent(_moveEvent);
  13252. }
  13253. }
  13254. if (hand && inputSource.hand) {
  13255. handPose = true;
  13256. for (const inputjoint of inputSource.hand.values()) {
  13257. // Update the joints groups with the XRJoint poses
  13258. const jointPose = frame.getJointPose(inputjoint, referenceSpace);
  13259. if (hand.joints[inputjoint.jointName] === undefined) {
  13260. // The transform of this joint will be updated with the joint pose on each frame
  13261. const joint = new Group();
  13262. joint.matrixAutoUpdate = false;
  13263. joint.visible = false;
  13264. hand.joints[inputjoint.jointName] = joint; // ??
  13265. hand.add(joint);
  13266. }
  13267. const joint = hand.joints[inputjoint.jointName];
  13268. if (jointPose !== null) {
  13269. joint.matrix.fromArray(jointPose.transform.matrix);
  13270. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  13271. joint.jointRadius = jointPose.radius;
  13272. }
  13273. joint.visible = jointPose !== null;
  13274. } // Custom events
  13275. // Check pinchz
  13276. const indexTip = hand.joints['index-finger-tip'];
  13277. const thumbTip = hand.joints['thumb-tip'];
  13278. const distance = indexTip.position.distanceTo(thumbTip.position);
  13279. const distanceToPinch = 0.02;
  13280. const threshold = 0.005;
  13281. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  13282. hand.inputState.pinching = false;
  13283. this.dispatchEvent({
  13284. type: 'pinchend',
  13285. handedness: inputSource.handedness,
  13286. target: this
  13287. });
  13288. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  13289. hand.inputState.pinching = true;
  13290. this.dispatchEvent({
  13291. type: 'pinchstart',
  13292. handedness: inputSource.handedness,
  13293. target: this
  13294. });
  13295. }
  13296. } else {
  13297. if (grip !== null && inputSource.gripSpace) {
  13298. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  13299. if (gripPose !== null) {
  13300. grip.matrix.fromArray(gripPose.transform.matrix);
  13301. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  13302. if (gripPose.linearVelocity) {
  13303. grip.hasLinearVelocity = true;
  13304. grip.linearVelocity.copy(gripPose.linearVelocity);
  13305. } else {
  13306. grip.hasLinearVelocity = false;
  13307. }
  13308. if (gripPose.angularVelocity) {
  13309. grip.hasAngularVelocity = true;
  13310. grip.angularVelocity.copy(gripPose.angularVelocity);
  13311. } else {
  13312. grip.hasAngularVelocity = false;
  13313. }
  13314. }
  13315. }
  13316. }
  13317. }
  13318. if (targetRay !== null) {
  13319. targetRay.visible = inputPose !== null;
  13320. }
  13321. if (grip !== null) {
  13322. grip.visible = gripPose !== null;
  13323. }
  13324. if (hand !== null) {
  13325. hand.visible = handPose !== null;
  13326. }
  13327. return this;
  13328. }
  13329. }
  13330. class WebXRManager extends EventDispatcher {
  13331. constructor(renderer, gl) {
  13332. super();
  13333. const scope = this;
  13334. const state = renderer.state;
  13335. let session = null;
  13336. let framebufferScaleFactor = 1.0;
  13337. let referenceSpace = null;
  13338. let referenceSpaceType = 'local-floor';
  13339. let pose = null;
  13340. let glBinding = null;
  13341. let glFramebuffer = null;
  13342. let glProjLayer = null;
  13343. let glBaseLayer = null;
  13344. const controllers = [];
  13345. const inputSourcesMap = new Map(); //
  13346. const cameraL = new PerspectiveCamera();
  13347. cameraL.layers.enable(1);
  13348. cameraL.viewport = new Vector4();
  13349. const cameraR = new PerspectiveCamera();
  13350. cameraR.layers.enable(2);
  13351. cameraR.viewport = new Vector4();
  13352. const cameras = [cameraL, cameraR];
  13353. const cameraVR = new ArrayCamera();
  13354. cameraVR.layers.enable(1);
  13355. cameraVR.layers.enable(2);
  13356. let _currentDepthNear = null;
  13357. let _currentDepthFar = null; //
  13358. this.cameraAutoUpdate = true;
  13359. this.enabled = false;
  13360. this.isPresenting = false;
  13361. this.getController = function (index) {
  13362. let controller = controllers[index];
  13363. if (controller === undefined) {
  13364. controller = new WebXRController();
  13365. controllers[index] = controller;
  13366. }
  13367. return controller.getTargetRaySpace();
  13368. };
  13369. this.getControllerGrip = function (index) {
  13370. let controller = controllers[index];
  13371. if (controller === undefined) {
  13372. controller = new WebXRController();
  13373. controllers[index] = controller;
  13374. }
  13375. return controller.getGripSpace();
  13376. };
  13377. this.getHand = function (index) {
  13378. let controller = controllers[index];
  13379. if (controller === undefined) {
  13380. controller = new WebXRController();
  13381. controllers[index] = controller;
  13382. }
  13383. return controller.getHandSpace();
  13384. }; //
  13385. function onSessionEvent(event) {
  13386. const controller = inputSourcesMap.get(event.inputSource);
  13387. if (controller) {
  13388. controller.dispatchEvent({
  13389. type: event.type,
  13390. data: event.inputSource
  13391. });
  13392. }
  13393. }
  13394. function onSessionEnd() {
  13395. inputSourcesMap.forEach(function (controller, inputSource) {
  13396. controller.disconnect(inputSource);
  13397. });
  13398. inputSourcesMap.clear();
  13399. _currentDepthNear = null;
  13400. _currentDepthFar = null; // restore framebuffer/rendering state
  13401. state.bindXRFramebuffer(null);
  13402. renderer.setRenderTarget(renderer.getRenderTarget()); //
  13403. animation.stop();
  13404. scope.isPresenting = false;
  13405. scope.dispatchEvent({
  13406. type: 'sessionend'
  13407. });
  13408. }
  13409. this.setFramebufferScaleFactor = function (value) {
  13410. framebufferScaleFactor = value;
  13411. if (scope.isPresenting === true) {
  13412. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  13413. }
  13414. };
  13415. this.setReferenceSpaceType = function (value) {
  13416. referenceSpaceType = value;
  13417. if (scope.isPresenting === true) {
  13418. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  13419. }
  13420. };
  13421. this.getReferenceSpace = function () {
  13422. return referenceSpace;
  13423. };
  13424. this.getSession = function () {
  13425. return session;
  13426. };
  13427. this.setSession = async function (value) {
  13428. session = value;
  13429. if (session !== null) {
  13430. session.addEventListener('select', onSessionEvent);
  13431. session.addEventListener('selectstart', onSessionEvent);
  13432. session.addEventListener('selectend', onSessionEvent);
  13433. session.addEventListener('squeeze', onSessionEvent);
  13434. session.addEventListener('squeezestart', onSessionEvent);
  13435. session.addEventListener('squeezeend', onSessionEvent);
  13436. session.addEventListener('end', onSessionEnd);
  13437. session.addEventListener('inputsourceschange', onInputSourcesChange);
  13438. const attributes = gl.getContextAttributes();
  13439. if (attributes.xrCompatible !== true) {
  13440. await gl.makeXRCompatible();
  13441. }
  13442. if (session.renderState.layers === undefined) {
  13443. const layerInit = {
  13444. antialias: attributes.antialias,
  13445. alpha: attributes.alpha,
  13446. depth: attributes.depth,
  13447. stencil: attributes.stencil,
  13448. framebufferScaleFactor: framebufferScaleFactor
  13449. };
  13450. glBaseLayer = new XRWebGLLayer(session, gl, layerInit);
  13451. session.updateRenderState({
  13452. baseLayer: glBaseLayer
  13453. });
  13454. } else {
  13455. let depthFormat = 0; // for anti-aliased output, use classic webgllayer for now
  13456. if (attributes.antialias) {
  13457. const layerInit = {
  13458. antialias: true,
  13459. alpha: attributes.alpha,
  13460. depth: attributes.depth,
  13461. stencil: attributes.stencil,
  13462. framebufferScaleFactor: framebufferScaleFactor
  13463. };
  13464. glBaseLayer = new XRWebGLLayer(session, gl, layerInit);
  13465. session.updateRenderState({
  13466. layers: [glBaseLayer]
  13467. });
  13468. } else {
  13469. if (attributes.depth) {
  13470. depthFormat = attributes.stencil ? gl.DEPTH_STENCIL : gl.DEPTH_COMPONENT;
  13471. }
  13472. const projectionlayerInit = {
  13473. colorFormat: attributes.alpha ? gl.RGBA : gl.RGB,
  13474. depthFormat: depthFormat,
  13475. scaleFactor: framebufferScaleFactor
  13476. };
  13477. glBinding = new XRWebGLBinding(session, gl);
  13478. glProjLayer = glBinding.createProjectionLayer(projectionlayerInit);
  13479. glFramebuffer = gl.createFramebuffer();
  13480. session.updateRenderState({
  13481. layers: [glProjLayer]
  13482. });
  13483. }
  13484. }
  13485. referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
  13486. animation.setContext(session);
  13487. animation.start();
  13488. scope.isPresenting = true;
  13489. scope.dispatchEvent({
  13490. type: 'sessionstart'
  13491. });
  13492. }
  13493. };
  13494. function onInputSourcesChange(event) {
  13495. const inputSources = session.inputSources; // Assign inputSources to available controllers
  13496. for (let i = 0; i < controllers.length; i++) {
  13497. inputSourcesMap.set(inputSources[i], controllers[i]);
  13498. } // Notify disconnected
  13499. for (let i = 0; i < event.removed.length; i++) {
  13500. const inputSource = event.removed[i];
  13501. const controller = inputSourcesMap.get(inputSource);
  13502. if (controller) {
  13503. controller.dispatchEvent({
  13504. type: 'disconnected',
  13505. data: inputSource
  13506. });
  13507. inputSourcesMap.delete(inputSource);
  13508. }
  13509. } // Notify connected
  13510. for (let i = 0; i < event.added.length; i++) {
  13511. const inputSource = event.added[i];
  13512. const controller = inputSourcesMap.get(inputSource);
  13513. if (controller) {
  13514. controller.dispatchEvent({
  13515. type: 'connected',
  13516. data: inputSource
  13517. });
  13518. }
  13519. }
  13520. } //
  13521. const cameraLPos = new Vector3();
  13522. const cameraRPos = new Vector3();
  13523. /**
  13524. * Assumes 2 cameras that are parallel and share an X-axis, and that
  13525. * the cameras' projection and world matrices have already been set.
  13526. * And that near and far planes are identical for both cameras.
  13527. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  13528. */
  13529. function setProjectionFromUnion(camera, cameraL, cameraR) {
  13530. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  13531. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  13532. const ipd = cameraLPos.distanceTo(cameraRPos);
  13533. const projL = cameraL.projectionMatrix.elements;
  13534. const projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  13535. // most likely identical top and bottom frustum extents.
  13536. // Use the left camera for these values.
  13537. const near = projL[14] / (projL[10] - 1);
  13538. const far = projL[14] / (projL[10] + 1);
  13539. const topFov = (projL[9] + 1) / projL[5];
  13540. const bottomFov = (projL[9] - 1) / projL[5];
  13541. const leftFov = (projL[8] - 1) / projL[0];
  13542. const rightFov = (projR[8] + 1) / projR[0];
  13543. const left = near * leftFov;
  13544. const right = near * rightFov; // Calculate the new camera's position offset from the
  13545. // left camera. xOffset should be roughly half `ipd`.
  13546. const zOffset = ipd / (-leftFov + rightFov);
  13547. const xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  13548. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  13549. camera.translateX(xOffset);
  13550. camera.translateZ(zOffset);
  13551. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  13552. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  13553. // the values so that the near plane's position does not change in world space,
  13554. // although must now be relative to the new union camera.
  13555. const near2 = near + zOffset;
  13556. const far2 = far + zOffset;
  13557. const left2 = left - xOffset;
  13558. const right2 = right + (ipd - xOffset);
  13559. const top2 = topFov * far / far2 * near2;
  13560. const bottom2 = bottomFov * far / far2 * near2;
  13561. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  13562. }
  13563. function updateCamera(camera, parent) {
  13564. if (parent === null) {
  13565. camera.matrixWorld.copy(camera.matrix);
  13566. } else {
  13567. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  13568. }
  13569. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  13570. }
  13571. this.updateCamera = function (camera) {
  13572. if (session === null) return;
  13573. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  13574. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  13575. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  13576. // Note that the new renderState won't apply until the next frame. See #18320
  13577. session.updateRenderState({
  13578. depthNear: cameraVR.near,
  13579. depthFar: cameraVR.far
  13580. });
  13581. _currentDepthNear = cameraVR.near;
  13582. _currentDepthFar = cameraVR.far;
  13583. }
  13584. const parent = camera.parent;
  13585. const cameras = cameraVR.cameras;
  13586. updateCamera(cameraVR, parent);
  13587. for (let i = 0; i < cameras.length; i++) {
  13588. updateCamera(cameras[i], parent);
  13589. }
  13590. cameraVR.matrixWorld.decompose(cameraVR.position, cameraVR.quaternion, cameraVR.scale); // update user camera and its children
  13591. camera.position.copy(cameraVR.position);
  13592. camera.quaternion.copy(cameraVR.quaternion);
  13593. camera.scale.copy(cameraVR.scale);
  13594. camera.matrix.copy(cameraVR.matrix);
  13595. camera.matrixWorld.copy(cameraVR.matrixWorld);
  13596. const children = camera.children;
  13597. for (let i = 0, l = children.length; i < l; i++) {
  13598. children[i].updateMatrixWorld(true);
  13599. } // update projection matrix for proper view frustum culling
  13600. if (cameras.length === 2) {
  13601. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  13602. } else {
  13603. // assume single camera setup (AR)
  13604. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  13605. }
  13606. };
  13607. this.getCamera = function () {
  13608. return cameraVR;
  13609. }; // Animation Loop
  13610. let onAnimationFrameCallback = null;
  13611. function onAnimationFrame(time, frame) {
  13612. pose = frame.getViewerPose(referenceSpace);
  13613. if (pose !== null) {
  13614. const views = pose.views;
  13615. if (glBaseLayer !== null) {
  13616. state.bindXRFramebuffer(glBaseLayer.framebuffer);
  13617. }
  13618. let cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  13619. if (views.length !== cameraVR.cameras.length) {
  13620. cameraVR.cameras.length = 0;
  13621. cameraVRNeedsUpdate = true;
  13622. }
  13623. for (let i = 0; i < views.length; i++) {
  13624. const view = views[i];
  13625. let viewport = null;
  13626. if (glBaseLayer !== null) {
  13627. viewport = glBaseLayer.getViewport(view);
  13628. } else {
  13629. const glSubImage = glBinding.getViewSubImage(glProjLayer, view);
  13630. state.bindXRFramebuffer(glFramebuffer);
  13631. if (glSubImage.depthStencilTexture !== undefined) {
  13632. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, glSubImage.depthStencilTexture, 0);
  13633. }
  13634. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, glSubImage.colorTexture, 0);
  13635. viewport = glSubImage.viewport;
  13636. }
  13637. const camera = cameras[i];
  13638. camera.matrix.fromArray(view.transform.matrix);
  13639. camera.projectionMatrix.fromArray(view.projectionMatrix);
  13640. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  13641. if (i === 0) {
  13642. cameraVR.matrix.copy(camera.matrix);
  13643. }
  13644. if (cameraVRNeedsUpdate === true) {
  13645. cameraVR.cameras.push(camera);
  13646. }
  13647. }
  13648. } //
  13649. const inputSources = session.inputSources;
  13650. for (let i = 0; i < controllers.length; i++) {
  13651. const controller = controllers[i];
  13652. const inputSource = inputSources[i];
  13653. controller.update(inputSource, frame, referenceSpace);
  13654. }
  13655. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  13656. }
  13657. const animation = new WebGLAnimation();
  13658. animation.setAnimationLoop(onAnimationFrame);
  13659. this.setAnimationLoop = function (callback) {
  13660. onAnimationFrameCallback = callback;
  13661. };
  13662. this.dispose = function () {};
  13663. }
  13664. }
  13665. function WebGLMaterials(properties) {
  13666. function refreshFogUniforms(uniforms, fog) {
  13667. uniforms.fogColor.value.copy(fog.color);
  13668. if (fog.isFog) {
  13669. uniforms.fogNear.value = fog.near;
  13670. uniforms.fogFar.value = fog.far;
  13671. } else if (fog.isFogExp2) {
  13672. uniforms.fogDensity.value = fog.density;
  13673. }
  13674. }
  13675. function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) {
  13676. if (material.isMeshBasicMaterial) {
  13677. refreshUniformsCommon(uniforms, material);
  13678. } else if (material.isMeshLambertMaterial) {
  13679. refreshUniformsCommon(uniforms, material);
  13680. refreshUniformsLambert(uniforms, material);
  13681. } else if (material.isMeshToonMaterial) {
  13682. refreshUniformsCommon(uniforms, material);
  13683. refreshUniformsToon(uniforms, material);
  13684. } else if (material.isMeshPhongMaterial) {
  13685. refreshUniformsCommon(uniforms, material);
  13686. refreshUniformsPhong(uniforms, material);
  13687. } else if (material.isMeshStandardMaterial) {
  13688. refreshUniformsCommon(uniforms, material);
  13689. if (material.isMeshPhysicalMaterial) {
  13690. refreshUniformsPhysical(uniforms, material, transmissionRenderTarget);
  13691. } else {
  13692. refreshUniformsStandard(uniforms, material);
  13693. }
  13694. } else if (material.isMeshMatcapMaterial) {
  13695. refreshUniformsCommon(uniforms, material);
  13696. refreshUniformsMatcap(uniforms, material);
  13697. } else if (material.isMeshDepthMaterial) {
  13698. refreshUniformsCommon(uniforms, material);
  13699. refreshUniformsDepth(uniforms, material);
  13700. } else if (material.isMeshDistanceMaterial) {
  13701. refreshUniformsCommon(uniforms, material);
  13702. refreshUniformsDistance(uniforms, material);
  13703. } else if (material.isMeshNormalMaterial) {
  13704. refreshUniformsCommon(uniforms, material);
  13705. refreshUniformsNormal(uniforms, material);
  13706. } else if (material.isLineBasicMaterial) {
  13707. refreshUniformsLine(uniforms, material);
  13708. if (material.isLineDashedMaterial) {
  13709. refreshUniformsDash(uniforms, material);
  13710. }
  13711. } else if (material.isPointsMaterial) {
  13712. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  13713. } else if (material.isSpriteMaterial) {
  13714. refreshUniformsSprites(uniforms, material);
  13715. } else if (material.isShadowMaterial) {
  13716. uniforms.color.value.copy(material.color);
  13717. uniforms.opacity.value = material.opacity;
  13718. } else if (material.isShaderMaterial) {
  13719. material.uniformsNeedUpdate = false; // #15581
  13720. }
  13721. }
  13722. function refreshUniformsCommon(uniforms, material) {
  13723. uniforms.opacity.value = material.opacity;
  13724. if (material.color) {
  13725. uniforms.diffuse.value.copy(material.color);
  13726. }
  13727. if (material.emissive) {
  13728. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  13729. }
  13730. if (material.map) {
  13731. uniforms.map.value = material.map;
  13732. }
  13733. if (material.alphaMap) {
  13734. uniforms.alphaMap.value = material.alphaMap;
  13735. }
  13736. if (material.specularMap) {
  13737. uniforms.specularMap.value = material.specularMap;
  13738. }
  13739. const envMap = properties.get(material).envMap;
  13740. if (envMap) {
  13741. uniforms.envMap.value = envMap;
  13742. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap._needsFlipEnvMap ? -1 : 1;
  13743. uniforms.reflectivity.value = material.reflectivity;
  13744. uniforms.refractionRatio.value = material.refractionRatio;
  13745. const maxMipLevel = properties.get(envMap).__maxMipLevel;
  13746. if (maxMipLevel !== undefined) {
  13747. uniforms.maxMipLevel.value = maxMipLevel;
  13748. }
  13749. }
  13750. if (material.lightMap) {
  13751. uniforms.lightMap.value = material.lightMap;
  13752. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  13753. }
  13754. if (material.aoMap) {
  13755. uniforms.aoMap.value = material.aoMap;
  13756. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  13757. } // uv repeat and offset setting priorities
  13758. // 1. color map
  13759. // 2. specular map
  13760. // 3. displacementMap map
  13761. // 4. normal map
  13762. // 5. bump map
  13763. // 6. roughnessMap map
  13764. // 7. metalnessMap map
  13765. // 8. alphaMap map
  13766. // 9. emissiveMap map
  13767. // 10. clearcoat map
  13768. // 11. clearcoat normal map
  13769. // 12. clearcoat roughnessMap map
  13770. let uvScaleMap;
  13771. if (material.map) {
  13772. uvScaleMap = material.map;
  13773. } else if (material.specularMap) {
  13774. uvScaleMap = material.specularMap;
  13775. } else if (material.displacementMap) {
  13776. uvScaleMap = material.displacementMap;
  13777. } else if (material.normalMap) {
  13778. uvScaleMap = material.normalMap;
  13779. } else if (material.bumpMap) {
  13780. uvScaleMap = material.bumpMap;
  13781. } else if (material.roughnessMap) {
  13782. uvScaleMap = material.roughnessMap;
  13783. } else if (material.metalnessMap) {
  13784. uvScaleMap = material.metalnessMap;
  13785. } else if (material.alphaMap) {
  13786. uvScaleMap = material.alphaMap;
  13787. } else if (material.emissiveMap) {
  13788. uvScaleMap = material.emissiveMap;
  13789. } else if (material.clearcoatMap) {
  13790. uvScaleMap = material.clearcoatMap;
  13791. } else if (material.clearcoatNormalMap) {
  13792. uvScaleMap = material.clearcoatNormalMap;
  13793. } else if (material.clearcoatRoughnessMap) {
  13794. uvScaleMap = material.clearcoatRoughnessMap;
  13795. }
  13796. if (uvScaleMap !== undefined) {
  13797. // backwards compatibility
  13798. if (uvScaleMap.isWebGLRenderTarget) {
  13799. uvScaleMap = uvScaleMap.texture;
  13800. }
  13801. if (uvScaleMap.matrixAutoUpdate === true) {
  13802. uvScaleMap.updateMatrix();
  13803. }
  13804. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  13805. } // uv repeat and offset setting priorities for uv2
  13806. // 1. ao map
  13807. // 2. light map
  13808. let uv2ScaleMap;
  13809. if (material.aoMap) {
  13810. uv2ScaleMap = material.aoMap;
  13811. } else if (material.lightMap) {
  13812. uv2ScaleMap = material.lightMap;
  13813. }
  13814. if (uv2ScaleMap !== undefined) {
  13815. // backwards compatibility
  13816. if (uv2ScaleMap.isWebGLRenderTarget) {
  13817. uv2ScaleMap = uv2ScaleMap.texture;
  13818. }
  13819. if (uv2ScaleMap.matrixAutoUpdate === true) {
  13820. uv2ScaleMap.updateMatrix();
  13821. }
  13822. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  13823. }
  13824. }
  13825. function refreshUniformsLine(uniforms, material) {
  13826. uniforms.diffuse.value.copy(material.color);
  13827. uniforms.opacity.value = material.opacity;
  13828. }
  13829. function refreshUniformsDash(uniforms, material) {
  13830. uniforms.dashSize.value = material.dashSize;
  13831. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13832. uniforms.scale.value = material.scale;
  13833. }
  13834. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  13835. uniforms.diffuse.value.copy(material.color);
  13836. uniforms.opacity.value = material.opacity;
  13837. uniforms.size.value = material.size * pixelRatio;
  13838. uniforms.scale.value = height * 0.5;
  13839. if (material.map) {
  13840. uniforms.map.value = material.map;
  13841. }
  13842. if (material.alphaMap) {
  13843. uniforms.alphaMap.value = material.alphaMap;
  13844. } // uv repeat and offset setting priorities
  13845. // 1. color map
  13846. // 2. alpha map
  13847. let uvScaleMap;
  13848. if (material.map) {
  13849. uvScaleMap = material.map;
  13850. } else if (material.alphaMap) {
  13851. uvScaleMap = material.alphaMap;
  13852. }
  13853. if (uvScaleMap !== undefined) {
  13854. if (uvScaleMap.matrixAutoUpdate === true) {
  13855. uvScaleMap.updateMatrix();
  13856. }
  13857. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  13858. }
  13859. }
  13860. function refreshUniformsSprites(uniforms, material) {
  13861. uniforms.diffuse.value.copy(material.color);
  13862. uniforms.opacity.value = material.opacity;
  13863. uniforms.rotation.value = material.rotation;
  13864. if (material.map) {
  13865. uniforms.map.value = material.map;
  13866. }
  13867. if (material.alphaMap) {
  13868. uniforms.alphaMap.value = material.alphaMap;
  13869. } // uv repeat and offset setting priorities
  13870. // 1. color map
  13871. // 2. alpha map
  13872. let uvScaleMap;
  13873. if (material.map) {
  13874. uvScaleMap = material.map;
  13875. } else if (material.alphaMap) {
  13876. uvScaleMap = material.alphaMap;
  13877. }
  13878. if (uvScaleMap !== undefined) {
  13879. if (uvScaleMap.matrixAutoUpdate === true) {
  13880. uvScaleMap.updateMatrix();
  13881. }
  13882. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  13883. }
  13884. }
  13885. function refreshUniformsLambert(uniforms, material) {
  13886. if (material.emissiveMap) {
  13887. uniforms.emissiveMap.value = material.emissiveMap;
  13888. }
  13889. }
  13890. function refreshUniformsPhong(uniforms, material) {
  13891. uniforms.specular.value.copy(material.specular);
  13892. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  13893. if (material.emissiveMap) {
  13894. uniforms.emissiveMap.value = material.emissiveMap;
  13895. }
  13896. if (material.bumpMap) {
  13897. uniforms.bumpMap.value = material.bumpMap;
  13898. uniforms.bumpScale.value = material.bumpScale;
  13899. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  13900. }
  13901. if (material.normalMap) {
  13902. uniforms.normalMap.value = material.normalMap;
  13903. uniforms.normalScale.value.copy(material.normalScale);
  13904. if (material.side === BackSide) uniforms.normalScale.value.negate();
  13905. }
  13906. if (material.displacementMap) {
  13907. uniforms.displacementMap.value = material.displacementMap;
  13908. uniforms.displacementScale.value = material.displacementScale;
  13909. uniforms.displacementBias.value = material.displacementBias;
  13910. }
  13911. }
  13912. function refreshUniformsToon(uniforms, material) {
  13913. if (material.gradientMap) {
  13914. uniforms.gradientMap.value = material.gradientMap;
  13915. }
  13916. if (material.emissiveMap) {
  13917. uniforms.emissiveMap.value = material.emissiveMap;
  13918. }
  13919. if (material.bumpMap) {
  13920. uniforms.bumpMap.value = material.bumpMap;
  13921. uniforms.bumpScale.value = material.bumpScale;
  13922. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  13923. }
  13924. if (material.normalMap) {
  13925. uniforms.normalMap.value = material.normalMap;
  13926. uniforms.normalScale.value.copy(material.normalScale);
  13927. if (material.side === BackSide) uniforms.normalScale.value.negate();
  13928. }
  13929. if (material.displacementMap) {
  13930. uniforms.displacementMap.value = material.displacementMap;
  13931. uniforms.displacementScale.value = material.displacementScale;
  13932. uniforms.displacementBias.value = material.displacementBias;
  13933. }
  13934. }
  13935. function refreshUniformsStandard(uniforms, material) {
  13936. uniforms.roughness.value = material.roughness;
  13937. uniforms.metalness.value = material.metalness;
  13938. if (material.roughnessMap) {
  13939. uniforms.roughnessMap.value = material.roughnessMap;
  13940. }
  13941. if (material.metalnessMap) {
  13942. uniforms.metalnessMap.value = material.metalnessMap;
  13943. }
  13944. if (material.emissiveMap) {
  13945. uniforms.emissiveMap.value = material.emissiveMap;
  13946. }
  13947. if (material.bumpMap) {
  13948. uniforms.bumpMap.value = material.bumpMap;
  13949. uniforms.bumpScale.value = material.bumpScale;
  13950. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  13951. }
  13952. if (material.normalMap) {
  13953. uniforms.normalMap.value = material.normalMap;
  13954. uniforms.normalScale.value.copy(material.normalScale);
  13955. if (material.side === BackSide) uniforms.normalScale.value.negate();
  13956. }
  13957. if (material.displacementMap) {
  13958. uniforms.displacementMap.value = material.displacementMap;
  13959. uniforms.displacementScale.value = material.displacementScale;
  13960. uniforms.displacementBias.value = material.displacementBias;
  13961. }
  13962. const envMap = properties.get(material).envMap;
  13963. if (envMap) {
  13964. //uniforms.envMap.value = material.envMap; // part of uniforms common
  13965. uniforms.envMapIntensity.value = material.envMapIntensity;
  13966. }
  13967. }
  13968. function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) {
  13969. refreshUniformsStandard(uniforms, material);
  13970. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  13971. uniforms.clearcoat.value = material.clearcoat;
  13972. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  13973. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  13974. if (material.clearcoatMap) {
  13975. uniforms.clearcoatMap.value = material.clearcoatMap;
  13976. }
  13977. if (material.clearcoatRoughnessMap) {
  13978. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  13979. }
  13980. if (material.clearcoatNormalMap) {
  13981. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  13982. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  13983. if (material.side === BackSide) {
  13984. uniforms.clearcoatNormalScale.value.negate();
  13985. }
  13986. }
  13987. uniforms.transmission.value = material.transmission;
  13988. if (material.transmissionMap) {
  13989. uniforms.transmissionMap.value = material.transmissionMap;
  13990. }
  13991. if (material.transmission > 0.0) {
  13992. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  13993. uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height);
  13994. }
  13995. uniforms.thickness.value = material.thickness;
  13996. if (material.thicknessMap) {
  13997. uniforms.thicknessMap.value = material.thicknessMap;
  13998. }
  13999. uniforms.attenuationDistance.value = material.attenuationDistance;
  14000. uniforms.attenuationColor.value.copy(material.attenuationColor);
  14001. }
  14002. function refreshUniformsMatcap(uniforms, material) {
  14003. if (material.matcap) {
  14004. uniforms.matcap.value = material.matcap;
  14005. }
  14006. if (material.bumpMap) {
  14007. uniforms.bumpMap.value = material.bumpMap;
  14008. uniforms.bumpScale.value = material.bumpScale;
  14009. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14010. }
  14011. if (material.normalMap) {
  14012. uniforms.normalMap.value = material.normalMap;
  14013. uniforms.normalScale.value.copy(material.normalScale);
  14014. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14015. }
  14016. if (material.displacementMap) {
  14017. uniforms.displacementMap.value = material.displacementMap;
  14018. uniforms.displacementScale.value = material.displacementScale;
  14019. uniforms.displacementBias.value = material.displacementBias;
  14020. }
  14021. }
  14022. function refreshUniformsDepth(uniforms, material) {
  14023. if (material.displacementMap) {
  14024. uniforms.displacementMap.value = material.displacementMap;
  14025. uniforms.displacementScale.value = material.displacementScale;
  14026. uniforms.displacementBias.value = material.displacementBias;
  14027. }
  14028. }
  14029. function refreshUniformsDistance(uniforms, material) {
  14030. if (material.displacementMap) {
  14031. uniforms.displacementMap.value = material.displacementMap;
  14032. uniforms.displacementScale.value = material.displacementScale;
  14033. uniforms.displacementBias.value = material.displacementBias;
  14034. }
  14035. uniforms.referencePosition.value.copy(material.referencePosition);
  14036. uniforms.nearDistance.value = material.nearDistance;
  14037. uniforms.farDistance.value = material.farDistance;
  14038. }
  14039. function refreshUniformsNormal(uniforms, material) {
  14040. if (material.bumpMap) {
  14041. uniforms.bumpMap.value = material.bumpMap;
  14042. uniforms.bumpScale.value = material.bumpScale;
  14043. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14044. }
  14045. if (material.normalMap) {
  14046. uniforms.normalMap.value = material.normalMap;
  14047. uniforms.normalScale.value.copy(material.normalScale);
  14048. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14049. }
  14050. if (material.displacementMap) {
  14051. uniforms.displacementMap.value = material.displacementMap;
  14052. uniforms.displacementScale.value = material.displacementScale;
  14053. uniforms.displacementBias.value = material.displacementBias;
  14054. }
  14055. }
  14056. return {
  14057. refreshFogUniforms: refreshFogUniforms,
  14058. refreshMaterialUniforms: refreshMaterialUniforms
  14059. };
  14060. }
  14061. function createCanvasElement() {
  14062. const canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  14063. canvas.style.display = 'block';
  14064. return canvas;
  14065. }
  14066. function WebGLRenderer(parameters = {}) {
  14067. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  14068. _context = parameters.context !== undefined ? parameters.context : null,
  14069. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14070. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14071. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14072. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14073. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14074. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14075. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  14076. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  14077. let currentRenderList = null;
  14078. let currentRenderState = null; // render() can be called from within a callback triggered by another render.
  14079. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  14080. const renderListStack = [];
  14081. const renderStateStack = []; // public properties
  14082. this.domElement = _canvas; // Debug configuration container
  14083. this.debug = {
  14084. /**
  14085. * Enables error checking and reporting when shader programs are being compiled
  14086. * @type {boolean}
  14087. */
  14088. checkShaderErrors: true
  14089. }; // clearing
  14090. this.autoClear = true;
  14091. this.autoClearColor = true;
  14092. this.autoClearDepth = true;
  14093. this.autoClearStencil = true; // scene graph
  14094. this.sortObjects = true; // user-defined clipping
  14095. this.clippingPlanes = [];
  14096. this.localClippingEnabled = false; // physically based shading
  14097. this.gammaFactor = 2.0; // for backwards compatibility
  14098. this.outputEncoding = LinearEncoding; // physical lights
  14099. this.physicallyCorrectLights = false; // tone mapping
  14100. this.toneMapping = NoToneMapping;
  14101. this.toneMappingExposure = 1.0; // internal properties
  14102. const _this = this;
  14103. let _isContextLost = false; // internal state cache
  14104. let _currentActiveCubeFace = 0;
  14105. let _currentActiveMipmapLevel = 0;
  14106. let _currentRenderTarget = null;
  14107. let _currentMaterialId = -1;
  14108. let _currentCamera = null;
  14109. const _currentViewport = new Vector4();
  14110. const _currentScissor = new Vector4();
  14111. let _currentScissorTest = null; //
  14112. let _width = _canvas.width;
  14113. let _height = _canvas.height;
  14114. let _pixelRatio = 1;
  14115. let _opaqueSort = null;
  14116. let _transparentSort = null;
  14117. const _viewport = new Vector4(0, 0, _width, _height);
  14118. const _scissor = new Vector4(0, 0, _width, _height);
  14119. let _scissorTest = false; //
  14120. const _currentDrawBuffers = []; // frustum
  14121. const _frustum = new Frustum(); // clipping
  14122. let _clippingEnabled = false;
  14123. let _localClippingEnabled = false; // transmission
  14124. let _transmissionRenderTarget = null; // camera matrices cache
  14125. const _projScreenMatrix = new Matrix4();
  14126. const _vector3 = new Vector3();
  14127. const _emptyScene = {
  14128. background: null,
  14129. fog: null,
  14130. environment: null,
  14131. overrideMaterial: null,
  14132. isScene: true
  14133. };
  14134. function getTargetPixelRatio() {
  14135. return _currentRenderTarget === null ? _pixelRatio : 1;
  14136. } // initialize
  14137. let _gl = _context;
  14138. function getContext(contextNames, contextAttributes) {
  14139. for (let i = 0; i < contextNames.length; i++) {
  14140. const contextName = contextNames[i];
  14141. const context = _canvas.getContext(contextName, contextAttributes);
  14142. if (context !== null) return context;
  14143. }
  14144. return null;
  14145. }
  14146. try {
  14147. const contextAttributes = {
  14148. alpha: _alpha,
  14149. depth: _depth,
  14150. stencil: _stencil,
  14151. antialias: _antialias,
  14152. premultipliedAlpha: _premultipliedAlpha,
  14153. preserveDrawingBuffer: _preserveDrawingBuffer,
  14154. powerPreference: _powerPreference,
  14155. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  14156. }; // event listeners must be registered before WebGL context is created, see #12753
  14157. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  14158. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  14159. if (_gl === null) {
  14160. const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  14161. if (_this.isWebGL1Renderer === true) {
  14162. contextNames.shift();
  14163. }
  14164. _gl = getContext(contextNames, contextAttributes);
  14165. if (_gl === null) {
  14166. if (getContext(contextNames)) {
  14167. throw new Error('Error creating WebGL context with your selected attributes.');
  14168. } else {
  14169. throw new Error('Error creating WebGL context.');
  14170. }
  14171. }
  14172. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14173. if (_gl.getShaderPrecisionFormat === undefined) {
  14174. _gl.getShaderPrecisionFormat = function () {
  14175. return {
  14176. 'rangeMin': 1,
  14177. 'rangeMax': 1,
  14178. 'precision': 1
  14179. };
  14180. };
  14181. }
  14182. } catch (error) {
  14183. console.error('THREE.WebGLRenderer: ' + error.message);
  14184. throw error;
  14185. }
  14186. let extensions, capabilities, state, info;
  14187. let properties, textures, cubemaps, attributes, geometries, objects;
  14188. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  14189. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  14190. let utils, bindingStates;
  14191. function initGLContext() {
  14192. extensions = new WebGLExtensions(_gl);
  14193. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  14194. extensions.init(capabilities);
  14195. utils = new WebGLUtils(_gl, extensions, capabilities);
  14196. state = new WebGLState(_gl, extensions, capabilities);
  14197. _currentDrawBuffers[0] = _gl.BACK;
  14198. info = new WebGLInfo(_gl);
  14199. properties = new WebGLProperties();
  14200. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  14201. cubemaps = new WebGLCubeMaps(_this);
  14202. attributes = new WebGLAttributes(_gl, capabilities);
  14203. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  14204. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  14205. objects = new WebGLObjects(_gl, geometries, attributes, info);
  14206. morphtargets = new WebGLMorphtargets(_gl);
  14207. clipping = new WebGLClipping(properties);
  14208. programCache = new WebGLPrograms(_this, cubemaps, extensions, capabilities, bindingStates, clipping);
  14209. materials = new WebGLMaterials(properties);
  14210. renderLists = new WebGLRenderLists(properties);
  14211. renderStates = new WebGLRenderStates(extensions, capabilities);
  14212. background = new WebGLBackground(_this, cubemaps, state, objects, _premultipliedAlpha);
  14213. shadowMap = new WebGLShadowMap(_this, objects, capabilities);
  14214. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  14215. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  14216. info.programs = programCache.programs;
  14217. _this.capabilities = capabilities;
  14218. _this.extensions = extensions;
  14219. _this.properties = properties;
  14220. _this.renderLists = renderLists;
  14221. _this.shadowMap = shadowMap;
  14222. _this.state = state;
  14223. _this.info = info;
  14224. }
  14225. initGLContext(); // xr
  14226. const xr = new WebXRManager(_this, _gl);
  14227. this.xr = xr; // API
  14228. this.getContext = function () {
  14229. return _gl;
  14230. };
  14231. this.getContextAttributes = function () {
  14232. return _gl.getContextAttributes();
  14233. };
  14234. this.forceContextLoss = function () {
  14235. const extension = extensions.get('WEBGL_lose_context');
  14236. if (extension) extension.loseContext();
  14237. };
  14238. this.forceContextRestore = function () {
  14239. const extension = extensions.get('WEBGL_lose_context');
  14240. if (extension) extension.restoreContext();
  14241. };
  14242. this.getPixelRatio = function () {
  14243. return _pixelRatio;
  14244. };
  14245. this.setPixelRatio = function (value) {
  14246. if (value === undefined) return;
  14247. _pixelRatio = value;
  14248. this.setSize(_width, _height, false);
  14249. };
  14250. this.getSize = function (target) {
  14251. return target.set(_width, _height);
  14252. };
  14253. this.setSize = function (width, height, updateStyle) {
  14254. if (xr.isPresenting) {
  14255. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  14256. return;
  14257. }
  14258. _width = width;
  14259. _height = height;
  14260. _canvas.width = Math.floor(width * _pixelRatio);
  14261. _canvas.height = Math.floor(height * _pixelRatio);
  14262. if (updateStyle !== false) {
  14263. _canvas.style.width = width + 'px';
  14264. _canvas.style.height = height + 'px';
  14265. }
  14266. this.setViewport(0, 0, width, height);
  14267. };
  14268. this.getDrawingBufferSize = function (target) {
  14269. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  14270. };
  14271. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  14272. _width = width;
  14273. _height = height;
  14274. _pixelRatio = pixelRatio;
  14275. _canvas.width = Math.floor(width * pixelRatio);
  14276. _canvas.height = Math.floor(height * pixelRatio);
  14277. this.setViewport(0, 0, width, height);
  14278. };
  14279. this.getCurrentViewport = function (target) {
  14280. return target.copy(_currentViewport);
  14281. };
  14282. this.getViewport = function (target) {
  14283. return target.copy(_viewport);
  14284. };
  14285. this.setViewport = function (x, y, width, height) {
  14286. if (x.isVector4) {
  14287. _viewport.set(x.x, x.y, x.z, x.w);
  14288. } else {
  14289. _viewport.set(x, y, width, height);
  14290. }
  14291. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  14292. };
  14293. this.getScissor = function (target) {
  14294. return target.copy(_scissor);
  14295. };
  14296. this.setScissor = function (x, y, width, height) {
  14297. if (x.isVector4) {
  14298. _scissor.set(x.x, x.y, x.z, x.w);
  14299. } else {
  14300. _scissor.set(x, y, width, height);
  14301. }
  14302. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  14303. };
  14304. this.getScissorTest = function () {
  14305. return _scissorTest;
  14306. };
  14307. this.setScissorTest = function (boolean) {
  14308. state.setScissorTest(_scissorTest = boolean);
  14309. };
  14310. this.setOpaqueSort = function (method) {
  14311. _opaqueSort = method;
  14312. };
  14313. this.setTransparentSort = function (method) {
  14314. _transparentSort = method;
  14315. }; // Clearing
  14316. this.getClearColor = function (target) {
  14317. return target.copy(background.getClearColor());
  14318. };
  14319. this.setClearColor = function () {
  14320. background.setClearColor.apply(background, arguments);
  14321. };
  14322. this.getClearAlpha = function () {
  14323. return background.getClearAlpha();
  14324. };
  14325. this.setClearAlpha = function () {
  14326. background.setClearAlpha.apply(background, arguments);
  14327. };
  14328. this.clear = function (color, depth, stencil) {
  14329. let bits = 0;
  14330. if (color === undefined || color) bits |= _gl.COLOR_BUFFER_BIT;
  14331. if (depth === undefined || depth) bits |= _gl.DEPTH_BUFFER_BIT;
  14332. if (stencil === undefined || stencil) bits |= _gl.STENCIL_BUFFER_BIT;
  14333. _gl.clear(bits);
  14334. };
  14335. this.clearColor = function () {
  14336. this.clear(true, false, false);
  14337. };
  14338. this.clearDepth = function () {
  14339. this.clear(false, true, false);
  14340. };
  14341. this.clearStencil = function () {
  14342. this.clear(false, false, true);
  14343. }; //
  14344. this.dispose = function () {
  14345. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  14346. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  14347. renderLists.dispose();
  14348. renderStates.dispose();
  14349. properties.dispose();
  14350. cubemaps.dispose();
  14351. objects.dispose();
  14352. bindingStates.dispose();
  14353. xr.dispose();
  14354. xr.removeEventListener('sessionstart', onXRSessionStart);
  14355. xr.removeEventListener('sessionend', onXRSessionEnd);
  14356. if (_transmissionRenderTarget) {
  14357. _transmissionRenderTarget.dispose();
  14358. _transmissionRenderTarget = null;
  14359. }
  14360. animation.stop();
  14361. }; // Events
  14362. function onContextLost(event) {
  14363. event.preventDefault();
  14364. console.log('THREE.WebGLRenderer: Context Lost.');
  14365. _isContextLost = true;
  14366. }
  14367. function onContextRestore()
  14368. /* event */
  14369. {
  14370. console.log('THREE.WebGLRenderer: Context Restored.');
  14371. _isContextLost = false;
  14372. const infoAutoReset = info.autoReset;
  14373. const shadowMapEnabled = shadowMap.enabled;
  14374. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  14375. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  14376. const shadowMapType = shadowMap.type;
  14377. initGLContext();
  14378. info.autoReset = infoAutoReset;
  14379. shadowMap.enabled = shadowMapEnabled;
  14380. shadowMap.autoUpdate = shadowMapAutoUpdate;
  14381. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  14382. shadowMap.type = shadowMapType;
  14383. }
  14384. function onMaterialDispose(event) {
  14385. const material = event.target;
  14386. material.removeEventListener('dispose', onMaterialDispose);
  14387. deallocateMaterial(material);
  14388. } // Buffer deallocation
  14389. function deallocateMaterial(material) {
  14390. releaseMaterialProgramReferences(material);
  14391. properties.remove(material);
  14392. }
  14393. function releaseMaterialProgramReferences(material) {
  14394. const programs = properties.get(material).programs;
  14395. if (programs !== undefined) {
  14396. programs.forEach(function (program) {
  14397. programCache.releaseProgram(program);
  14398. });
  14399. }
  14400. } // Buffer rendering
  14401. function renderObjectImmediate(object, program) {
  14402. object.render(function (object) {
  14403. _this.renderBufferImmediate(object, program);
  14404. });
  14405. }
  14406. this.renderBufferImmediate = function (object, program) {
  14407. bindingStates.initAttributes();
  14408. const buffers = properties.get(object);
  14409. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  14410. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  14411. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  14412. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  14413. const programAttributes = program.getAttributes();
  14414. if (object.hasPositions) {
  14415. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.position);
  14416. _gl.bufferData(_gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW);
  14417. bindingStates.enableAttribute(programAttributes.position);
  14418. _gl.vertexAttribPointer(programAttributes.position, 3, _gl.FLOAT, false, 0, 0);
  14419. }
  14420. if (object.hasNormals) {
  14421. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.normal);
  14422. _gl.bufferData(_gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW);
  14423. bindingStates.enableAttribute(programAttributes.normal);
  14424. _gl.vertexAttribPointer(programAttributes.normal, 3, _gl.FLOAT, false, 0, 0);
  14425. }
  14426. if (object.hasUvs) {
  14427. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.uv);
  14428. _gl.bufferData(_gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW);
  14429. bindingStates.enableAttribute(programAttributes.uv);
  14430. _gl.vertexAttribPointer(programAttributes.uv, 2, _gl.FLOAT, false, 0, 0);
  14431. }
  14432. if (object.hasColors) {
  14433. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.color);
  14434. _gl.bufferData(_gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW);
  14435. bindingStates.enableAttribute(programAttributes.color);
  14436. _gl.vertexAttribPointer(programAttributes.color, 3, _gl.FLOAT, false, 0, 0);
  14437. }
  14438. bindingStates.disableUnusedAttributes();
  14439. _gl.drawArrays(_gl.TRIANGLES, 0, object.count);
  14440. object.count = 0;
  14441. };
  14442. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  14443. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  14444. const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  14445. const program = setProgram(camera, scene, material, object);
  14446. state.setMaterial(material, frontFaceCW); //
  14447. let index = geometry.index;
  14448. const position = geometry.attributes.position; //
  14449. if (index === null) {
  14450. if (position === undefined || position.count === 0) return;
  14451. } else if (index.count === 0) {
  14452. return;
  14453. } //
  14454. let rangeFactor = 1;
  14455. if (material.wireframe === true) {
  14456. index = geometries.getWireframeAttribute(geometry);
  14457. rangeFactor = 2;
  14458. }
  14459. if (geometry.morphAttributes.position !== undefined || geometry.morphAttributes.normal !== undefined) {
  14460. morphtargets.update(object, geometry, material, program);
  14461. }
  14462. bindingStates.setup(object, material, program, geometry, index);
  14463. let attribute;
  14464. let renderer = bufferRenderer;
  14465. if (index !== null) {
  14466. attribute = attributes.get(index);
  14467. renderer = indexedBufferRenderer;
  14468. renderer.setIndex(attribute);
  14469. } //
  14470. const dataCount = index !== null ? index.count : position.count;
  14471. const rangeStart = geometry.drawRange.start * rangeFactor;
  14472. const rangeCount = geometry.drawRange.count * rangeFactor;
  14473. const groupStart = group !== null ? group.start * rangeFactor : 0;
  14474. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  14475. const drawStart = Math.max(rangeStart, groupStart);
  14476. const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  14477. const drawCount = Math.max(0, drawEnd - drawStart + 1);
  14478. if (drawCount === 0) return; //
  14479. if (object.isMesh) {
  14480. if (material.wireframe === true) {
  14481. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  14482. renderer.setMode(_gl.LINES);
  14483. } else {
  14484. renderer.setMode(_gl.TRIANGLES);
  14485. }
  14486. } else if (object.isLine) {
  14487. let lineWidth = material.linewidth;
  14488. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  14489. state.setLineWidth(lineWidth * getTargetPixelRatio());
  14490. if (object.isLineSegments) {
  14491. renderer.setMode(_gl.LINES);
  14492. } else if (object.isLineLoop) {
  14493. renderer.setMode(_gl.LINE_LOOP);
  14494. } else {
  14495. renderer.setMode(_gl.LINE_STRIP);
  14496. }
  14497. } else if (object.isPoints) {
  14498. renderer.setMode(_gl.POINTS);
  14499. } else if (object.isSprite) {
  14500. renderer.setMode(_gl.TRIANGLES);
  14501. }
  14502. if (object.isInstancedMesh) {
  14503. renderer.renderInstances(drawStart, drawCount, object.count);
  14504. } else if (geometry.isInstancedBufferGeometry) {
  14505. const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  14506. renderer.renderInstances(drawStart, drawCount, instanceCount);
  14507. } else {
  14508. renderer.render(drawStart, drawCount);
  14509. }
  14510. }; // Compile
  14511. this.compile = function (scene, camera) {
  14512. currentRenderState = renderStates.get(scene);
  14513. currentRenderState.init();
  14514. scene.traverseVisible(function (object) {
  14515. if (object.isLight && object.layers.test(camera.layers)) {
  14516. currentRenderState.pushLight(object);
  14517. if (object.castShadow) {
  14518. currentRenderState.pushShadow(object);
  14519. }
  14520. }
  14521. });
  14522. currentRenderState.setupLights();
  14523. scene.traverse(function (object) {
  14524. const material = object.material;
  14525. if (material) {
  14526. if (Array.isArray(material)) {
  14527. for (let i = 0; i < material.length; i++) {
  14528. const material2 = material[i];
  14529. getProgram(material2, scene, object);
  14530. }
  14531. } else {
  14532. getProgram(material, scene, object);
  14533. }
  14534. }
  14535. });
  14536. }; // Animation Loop
  14537. let onAnimationFrameCallback = null;
  14538. function onAnimationFrame(time) {
  14539. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  14540. }
  14541. function onXRSessionStart() {
  14542. animation.stop();
  14543. }
  14544. function onXRSessionEnd() {
  14545. animation.start();
  14546. }
  14547. const animation = new WebGLAnimation();
  14548. animation.setAnimationLoop(onAnimationFrame);
  14549. if (typeof window !== 'undefined') animation.setContext(window);
  14550. this.setAnimationLoop = function (callback) {
  14551. onAnimationFrameCallback = callback;
  14552. xr.setAnimationLoop(callback);
  14553. callback === null ? animation.stop() : animation.start();
  14554. };
  14555. xr.addEventListener('sessionstart', onXRSessionStart);
  14556. xr.addEventListener('sessionend', onXRSessionEnd); // Rendering
  14557. this.render = function (scene, camera) {
  14558. if (camera !== undefined && camera.isCamera !== true) {
  14559. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  14560. return;
  14561. }
  14562. if (_isContextLost === true) return; // update scene graph
  14563. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  14564. if (camera.parent === null) camera.updateMatrixWorld();
  14565. if (xr.enabled === true && xr.isPresenting === true) {
  14566. if (xr.cameraAutoUpdate === true) xr.updateCamera(camera);
  14567. camera = xr.getCamera(); // use XR camera for rendering
  14568. } //
  14569. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget);
  14570. currentRenderState = renderStates.get(scene, renderStateStack.length);
  14571. currentRenderState.init();
  14572. renderStateStack.push(currentRenderState);
  14573. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  14574. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  14575. _localClippingEnabled = this.localClippingEnabled;
  14576. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  14577. currentRenderList = renderLists.get(scene, renderListStack.length);
  14578. currentRenderList.init();
  14579. renderListStack.push(currentRenderList);
  14580. projectObject(scene, camera, 0, _this.sortObjects);
  14581. currentRenderList.finish();
  14582. if (_this.sortObjects === true) {
  14583. currentRenderList.sort(_opaqueSort, _transparentSort);
  14584. } //
  14585. if (_clippingEnabled === true) clipping.beginShadows();
  14586. const shadowsArray = currentRenderState.state.shadowsArray;
  14587. shadowMap.render(shadowsArray, scene, camera);
  14588. currentRenderState.setupLights();
  14589. currentRenderState.setupLightsView(camera);
  14590. if (_clippingEnabled === true) clipping.endShadows(); //
  14591. if (this.info.autoReset === true) this.info.reset(); //
  14592. background.render(currentRenderList, scene); // render scene
  14593. const opaqueObjects = currentRenderList.opaque;
  14594. const transmissiveObjects = currentRenderList.transmissive;
  14595. const transparentObjects = currentRenderList.transparent;
  14596. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  14597. if (transmissiveObjects.length > 0) renderTransmissiveObjects(opaqueObjects, transmissiveObjects, scene, camera);
  14598. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera); //
  14599. if (_currentRenderTarget !== null) {
  14600. // resolve multisample renderbuffers to a single-sample texture if necessary
  14601. textures.updateMultisampleRenderTarget(_currentRenderTarget); // Generate mipmap if we're using any kind of mipmap filtering
  14602. textures.updateRenderTargetMipmap(_currentRenderTarget);
  14603. } //
  14604. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); // Ensure depth buffer writing is enabled so it can be cleared on next render
  14605. state.buffers.depth.setTest(true);
  14606. state.buffers.depth.setMask(true);
  14607. state.buffers.color.setMask(true);
  14608. state.setPolygonOffset(false); // _gl.finish();
  14609. bindingStates.resetDefaultState();
  14610. _currentMaterialId = -1;
  14611. _currentCamera = null;
  14612. renderStateStack.pop();
  14613. if (renderStateStack.length > 0) {
  14614. currentRenderState = renderStateStack[renderStateStack.length - 1];
  14615. } else {
  14616. currentRenderState = null;
  14617. }
  14618. renderListStack.pop();
  14619. if (renderListStack.length > 0) {
  14620. currentRenderList = renderListStack[renderListStack.length - 1];
  14621. } else {
  14622. currentRenderList = null;
  14623. }
  14624. };
  14625. function projectObject(object, camera, groupOrder, sortObjects) {
  14626. if (object.visible === false) return;
  14627. const visible = object.layers.test(camera.layers);
  14628. if (visible) {
  14629. if (object.isGroup) {
  14630. groupOrder = object.renderOrder;
  14631. } else if (object.isLOD) {
  14632. if (object.autoUpdate === true) object.update(camera);
  14633. } else if (object.isLight) {
  14634. currentRenderState.pushLight(object);
  14635. if (object.castShadow) {
  14636. currentRenderState.pushShadow(object);
  14637. }
  14638. } else if (object.isSprite) {
  14639. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  14640. if (sortObjects) {
  14641. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  14642. }
  14643. const geometry = objects.update(object);
  14644. const material = object.material;
  14645. if (material.visible) {
  14646. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  14647. }
  14648. }
  14649. } else if (object.isImmediateRenderObject) {
  14650. if (sortObjects) {
  14651. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  14652. }
  14653. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  14654. } else if (object.isMesh || object.isLine || object.isPoints) {
  14655. if (object.isSkinnedMesh) {
  14656. // update skeleton only once in a frame
  14657. if (object.skeleton.frame !== info.render.frame) {
  14658. object.skeleton.update();
  14659. object.skeleton.frame = info.render.frame;
  14660. }
  14661. }
  14662. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  14663. if (sortObjects) {
  14664. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  14665. }
  14666. const geometry = objects.update(object);
  14667. const material = object.material;
  14668. if (Array.isArray(material)) {
  14669. const groups = geometry.groups;
  14670. for (let i = 0, l = groups.length; i < l; i++) {
  14671. const group = groups[i];
  14672. const groupMaterial = material[group.materialIndex];
  14673. if (groupMaterial && groupMaterial.visible) {
  14674. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  14675. }
  14676. }
  14677. } else if (material.visible) {
  14678. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  14679. }
  14680. }
  14681. }
  14682. }
  14683. const children = object.children;
  14684. for (let i = 0, l = children.length; i < l; i++) {
  14685. projectObject(children[i], camera, groupOrder, sortObjects);
  14686. }
  14687. }
  14688. function renderTransmissiveObjects(opaqueObjects, transmissiveObjects, scene, camera) {
  14689. if (_transmissionRenderTarget === null) {
  14690. const needsAntialias = _antialias === true && capabilities.isWebGL2 === true;
  14691. const renderTargetType = needsAntialias ? WebGLMultisampleRenderTarget : WebGLRenderTarget;
  14692. _transmissionRenderTarget = new renderTargetType(1024, 1024, {
  14693. generateMipmaps: true,
  14694. type: utils.convert(HalfFloatType) !== null ? HalfFloatType : UnsignedByteType,
  14695. minFilter: LinearMipmapLinearFilter,
  14696. magFilter: NearestFilter,
  14697. wrapS: ClampToEdgeWrapping,
  14698. wrapT: ClampToEdgeWrapping
  14699. });
  14700. }
  14701. const currentRenderTarget = _this.getRenderTarget();
  14702. _this.setRenderTarget(_transmissionRenderTarget);
  14703. _this.clear(); // Turn off the features which can affect the frag color for opaque objects pass.
  14704. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  14705. const currentToneMapping = _this.toneMapping;
  14706. _this.toneMapping = NoToneMapping;
  14707. renderObjects(opaqueObjects, scene, camera);
  14708. _this.toneMapping = currentToneMapping;
  14709. textures.updateMultisampleRenderTarget(_transmissionRenderTarget);
  14710. textures.updateRenderTargetMipmap(_transmissionRenderTarget);
  14711. _this.setRenderTarget(currentRenderTarget);
  14712. renderObjects(transmissiveObjects, scene, camera);
  14713. }
  14714. function renderObjects(renderList, scene, camera) {
  14715. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  14716. if (camera.isArrayCamera) {
  14717. const cameras = camera.cameras;
  14718. for (let i = 0, l = cameras.length; i < l; i++) {
  14719. const camera2 = cameras[i];
  14720. state.viewport(_currentViewport.copy(camera2.viewport));
  14721. currentRenderState.setupLightsView(camera2);
  14722. for (let j = 0, jl = renderList.length; j < jl; j++) {
  14723. const renderItem = renderList[j];
  14724. const object = renderItem.object;
  14725. const geometry = renderItem.geometry;
  14726. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  14727. const group = renderItem.group;
  14728. if (object.layers.test(camera2.layers)) {
  14729. renderObject(object, scene, camera2, geometry, material, group);
  14730. }
  14731. }
  14732. }
  14733. } else {
  14734. for (let j = 0, jl = renderList.length; j < jl; j++) {
  14735. const renderItem = renderList[j];
  14736. const object = renderItem.object;
  14737. const geometry = renderItem.geometry;
  14738. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  14739. const group = renderItem.group;
  14740. renderObject(object, scene, camera, geometry, material, group);
  14741. }
  14742. }
  14743. }
  14744. function renderObject(object, scene, camera, geometry, material, group) {
  14745. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  14746. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  14747. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  14748. if (object.isImmediateRenderObject) {
  14749. const program = setProgram(camera, scene, material, object);
  14750. state.setMaterial(material);
  14751. bindingStates.reset();
  14752. renderObjectImmediate(object, program);
  14753. } else {
  14754. if (material.transparent === true && material.side === DoubleSide) {
  14755. material.side = BackSide;
  14756. material.needsUpdate = true;
  14757. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  14758. material.side = FrontSide;
  14759. material.needsUpdate = true;
  14760. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  14761. material.side = DoubleSide;
  14762. } else {
  14763. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  14764. }
  14765. }
  14766. object.onAfterRender(_this, scene, camera, geometry, material, group);
  14767. }
  14768. function getProgram(material, scene, object) {
  14769. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  14770. const materialProperties = properties.get(material);
  14771. const lights = currentRenderState.state.lights;
  14772. const shadowsArray = currentRenderState.state.shadowsArray;
  14773. const lightsStateVersion = lights.state.version;
  14774. const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  14775. const programCacheKey = programCache.getProgramCacheKey(parameters);
  14776. 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
  14777. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  14778. materialProperties.fog = scene.fog;
  14779. materialProperties.envMap = cubemaps.get(material.envMap || materialProperties.environment);
  14780. if (programs === undefined) {
  14781. // new material
  14782. material.addEventListener('dispose', onMaterialDispose);
  14783. programs = new Map();
  14784. materialProperties.programs = programs;
  14785. }
  14786. let program = programs.get(programCacheKey);
  14787. if (program !== undefined) {
  14788. // early out if program and light state is identical
  14789. if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) {
  14790. updateCommonMaterialProperties(material, parameters);
  14791. return program;
  14792. }
  14793. } else {
  14794. parameters.uniforms = programCache.getUniforms(material);
  14795. material.onBuild(parameters, _this);
  14796. material.onBeforeCompile(parameters, _this);
  14797. program = programCache.acquireProgram(parameters, programCacheKey);
  14798. programs.set(programCacheKey, program);
  14799. materialProperties.uniforms = parameters.uniforms;
  14800. }
  14801. const uniforms = materialProperties.uniforms;
  14802. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  14803. uniforms.clippingPlanes = clipping.uniform;
  14804. }
  14805. updateCommonMaterialProperties(material, parameters); // store the light setup it was created for
  14806. materialProperties.needsLights = materialNeedsLights(material);
  14807. materialProperties.lightsStateVersion = lightsStateVersion;
  14808. if (materialProperties.needsLights) {
  14809. // wire up the material to this renderer's lighting state
  14810. uniforms.ambientLightColor.value = lights.state.ambient;
  14811. uniforms.lightProbe.value = lights.state.probe;
  14812. uniforms.directionalLights.value = lights.state.directional;
  14813. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  14814. uniforms.spotLights.value = lights.state.spot;
  14815. uniforms.spotLightShadows.value = lights.state.spotShadow;
  14816. uniforms.rectAreaLights.value = lights.state.rectArea;
  14817. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  14818. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  14819. uniforms.pointLights.value = lights.state.point;
  14820. uniforms.pointLightShadows.value = lights.state.pointShadow;
  14821. uniforms.hemisphereLights.value = lights.state.hemi;
  14822. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  14823. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  14824. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  14825. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  14826. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  14827. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  14828. }
  14829. const progUniforms = program.getUniforms();
  14830. const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  14831. materialProperties.currentProgram = program;
  14832. materialProperties.uniformsList = uniformsList;
  14833. return program;
  14834. }
  14835. function updateCommonMaterialProperties(material, parameters) {
  14836. const materialProperties = properties.get(material);
  14837. materialProperties.outputEncoding = parameters.outputEncoding;
  14838. materialProperties.instancing = parameters.instancing;
  14839. materialProperties.skinning = parameters.skinning;
  14840. materialProperties.morphTargets = parameters.morphTargets;
  14841. materialProperties.morphNormals = parameters.morphNormals;
  14842. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  14843. materialProperties.numIntersection = parameters.numClipIntersection;
  14844. materialProperties.vertexAlphas = parameters.vertexAlphas;
  14845. }
  14846. function setProgram(camera, scene, material, object) {
  14847. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  14848. textures.resetTextureUnits();
  14849. const fog = scene.fog;
  14850. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  14851. const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  14852. const envMap = cubemaps.get(material.envMap || environment);
  14853. const vertexAlphas = material.vertexColors === true && object.geometry && object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4;
  14854. const morphTargets = object.geometry && object.geometry.morphAttributes.position;
  14855. const morphNormals = object.geometry && object.geometry.morphAttributes.normal;
  14856. const materialProperties = properties.get(material);
  14857. const lights = currentRenderState.state.lights;
  14858. if (_clippingEnabled === true) {
  14859. if (_localClippingEnabled === true || camera !== _currentCamera) {
  14860. const useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  14861. // object instead of the material, once it becomes feasible
  14862. // (#8465, #8379)
  14863. clipping.setState(material, camera, useCache);
  14864. }
  14865. } //
  14866. let needsProgramChange = false;
  14867. if (material.version === materialProperties.__version) {
  14868. if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  14869. needsProgramChange = true;
  14870. } else if (materialProperties.outputEncoding !== encoding) {
  14871. needsProgramChange = true;
  14872. } else if (object.isInstancedMesh && materialProperties.instancing === false) {
  14873. needsProgramChange = true;
  14874. } else if (!object.isInstancedMesh && materialProperties.instancing === true) {
  14875. needsProgramChange = true;
  14876. } else if (object.isSkinnedMesh && materialProperties.skinning === false) {
  14877. needsProgramChange = true;
  14878. } else if (!object.isSkinnedMesh && materialProperties.skinning === true) {
  14879. needsProgramChange = true;
  14880. } else if (materialProperties.envMap !== envMap) {
  14881. needsProgramChange = true;
  14882. } else if (material.fog && materialProperties.fog !== fog) {
  14883. needsProgramChange = true;
  14884. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  14885. needsProgramChange = true;
  14886. } else if (materialProperties.vertexAlphas !== vertexAlphas) {
  14887. needsProgramChange = true;
  14888. } else if (materialProperties.morphTargets !== morphTargets) {
  14889. needsProgramChange = true;
  14890. } else if (materialProperties.morphNormals !== morphNormals) {
  14891. needsProgramChange = true;
  14892. }
  14893. } else {
  14894. needsProgramChange = true;
  14895. materialProperties.__version = material.version;
  14896. } //
  14897. let program = materialProperties.currentProgram;
  14898. if (needsProgramChange === true) {
  14899. program = getProgram(material, scene, object);
  14900. }
  14901. let refreshProgram = false;
  14902. let refreshMaterial = false;
  14903. let refreshLights = false;
  14904. const p_uniforms = program.getUniforms(),
  14905. m_uniforms = materialProperties.uniforms;
  14906. if (state.useProgram(program.program)) {
  14907. refreshProgram = true;
  14908. refreshMaterial = true;
  14909. refreshLights = true;
  14910. }
  14911. if (material.id !== _currentMaterialId) {
  14912. _currentMaterialId = material.id;
  14913. refreshMaterial = true;
  14914. }
  14915. if (refreshProgram || _currentCamera !== camera) {
  14916. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  14917. if (capabilities.logarithmicDepthBuffer) {
  14918. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  14919. }
  14920. if (_currentCamera !== camera) {
  14921. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  14922. // now, in case this material supports lights - or later, when
  14923. // the next material that does gets activated:
  14924. refreshMaterial = true; // set to true on material change
  14925. refreshLights = true; // remains set until update done
  14926. } // load material specific uniforms
  14927. // (shader material also gets them for the sake of genericity)
  14928. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  14929. const uCamPos = p_uniforms.map.cameraPosition;
  14930. if (uCamPos !== undefined) {
  14931. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  14932. }
  14933. }
  14934. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  14935. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  14936. }
  14937. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || object.isSkinnedMesh) {
  14938. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  14939. }
  14940. } // skinning uniforms must be set even if material didn't change
  14941. // auto-setting of texture unit for bone texture must go before other textures
  14942. // otherwise textures used for skinning can take over texture units reserved for other material textures
  14943. if (object.isSkinnedMesh) {
  14944. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  14945. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  14946. const skeleton = object.skeleton;
  14947. if (skeleton) {
  14948. if (capabilities.floatVertexTextures) {
  14949. if (skeleton.boneTexture === null) skeleton.computeBoneTexture();
  14950. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  14951. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  14952. } else {
  14953. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  14954. }
  14955. }
  14956. }
  14957. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  14958. materialProperties.receiveShadow = object.receiveShadow;
  14959. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  14960. }
  14961. if (refreshMaterial) {
  14962. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  14963. if (materialProperties.needsLights) {
  14964. // the current material requires lighting info
  14965. // note: all lighting uniforms are always set correctly
  14966. // they simply reference the renderer's state for their
  14967. // values
  14968. //
  14969. // use the current material's .needsUpdate flags to set
  14970. // the GL state when required
  14971. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  14972. } // refresh uniforms common to several materials
  14973. if (fog && material.fog) {
  14974. materials.refreshFogUniforms(m_uniforms, fog);
  14975. }
  14976. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget);
  14977. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  14978. }
  14979. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  14980. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  14981. material.uniformsNeedUpdate = false;
  14982. }
  14983. if (material.isSpriteMaterial) {
  14984. p_uniforms.setValue(_gl, 'center', object.center);
  14985. } // common matrices
  14986. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  14987. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  14988. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  14989. return program;
  14990. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  14991. function markUniformsLightsNeedsUpdate(uniforms, value) {
  14992. uniforms.ambientLightColor.needsUpdate = value;
  14993. uniforms.lightProbe.needsUpdate = value;
  14994. uniforms.directionalLights.needsUpdate = value;
  14995. uniforms.directionalLightShadows.needsUpdate = value;
  14996. uniforms.pointLights.needsUpdate = value;
  14997. uniforms.pointLightShadows.needsUpdate = value;
  14998. uniforms.spotLights.needsUpdate = value;
  14999. uniforms.spotLightShadows.needsUpdate = value;
  15000. uniforms.rectAreaLights.needsUpdate = value;
  15001. uniforms.hemisphereLights.needsUpdate = value;
  15002. }
  15003. function materialNeedsLights(material) {
  15004. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  15005. }
  15006. this.getActiveCubeFace = function () {
  15007. return _currentActiveCubeFace;
  15008. };
  15009. this.getActiveMipmapLevel = function () {
  15010. return _currentActiveMipmapLevel;
  15011. };
  15012. this.getRenderTarget = function () {
  15013. return _currentRenderTarget;
  15014. };
  15015. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  15016. _currentRenderTarget = renderTarget;
  15017. _currentActiveCubeFace = activeCubeFace;
  15018. _currentActiveMipmapLevel = activeMipmapLevel;
  15019. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  15020. textures.setupRenderTarget(renderTarget);
  15021. }
  15022. let framebuffer = null;
  15023. let isCube = false;
  15024. let isRenderTarget3D = false;
  15025. if (renderTarget) {
  15026. const texture = renderTarget.texture;
  15027. if (texture.isDataTexture3D || texture.isDataTexture2DArray) {
  15028. isRenderTarget3D = true;
  15029. }
  15030. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  15031. if (renderTarget.isWebGLCubeRenderTarget) {
  15032. framebuffer = __webglFramebuffer[activeCubeFace];
  15033. isCube = true;
  15034. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  15035. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  15036. } else {
  15037. framebuffer = __webglFramebuffer;
  15038. }
  15039. _currentViewport.copy(renderTarget.viewport);
  15040. _currentScissor.copy(renderTarget.scissor);
  15041. _currentScissorTest = renderTarget.scissorTest;
  15042. } else {
  15043. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  15044. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  15045. _currentScissorTest = _scissorTest;
  15046. }
  15047. const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  15048. if (framebufferBound && capabilities.drawBuffers) {
  15049. let needsUpdate = false;
  15050. if (renderTarget) {
  15051. if (renderTarget.isWebGLMultipleRenderTargets) {
  15052. const textures = renderTarget.texture;
  15053. if (_currentDrawBuffers.length !== textures.length || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  15054. for (let i = 0, il = textures.length; i < il; i++) {
  15055. _currentDrawBuffers[i] = _gl.COLOR_ATTACHMENT0 + i;
  15056. }
  15057. _currentDrawBuffers.length = textures.length;
  15058. needsUpdate = true;
  15059. }
  15060. } else {
  15061. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  15062. _currentDrawBuffers[0] = _gl.COLOR_ATTACHMENT0;
  15063. _currentDrawBuffers.length = 1;
  15064. needsUpdate = true;
  15065. }
  15066. }
  15067. } else {
  15068. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.BACK) {
  15069. _currentDrawBuffers[0] = _gl.BACK;
  15070. _currentDrawBuffers.length = 1;
  15071. needsUpdate = true;
  15072. }
  15073. }
  15074. if (needsUpdate) {
  15075. if (capabilities.isWebGL2) {
  15076. _gl.drawBuffers(_currentDrawBuffers);
  15077. } else {
  15078. extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(_currentDrawBuffers);
  15079. }
  15080. }
  15081. }
  15082. state.viewport(_currentViewport);
  15083. state.scissor(_currentScissor);
  15084. state.setScissorTest(_currentScissorTest);
  15085. if (isCube) {
  15086. const textureProperties = properties.get(renderTarget.texture);
  15087. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  15088. } else if (isRenderTarget3D) {
  15089. const textureProperties = properties.get(renderTarget.texture);
  15090. const layer = activeCubeFace || 0;
  15091. _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer);
  15092. }
  15093. };
  15094. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  15095. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  15096. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  15097. return;
  15098. }
  15099. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  15100. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  15101. framebuffer = framebuffer[activeCubeFaceIndex];
  15102. }
  15103. if (framebuffer) {
  15104. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  15105. try {
  15106. const texture = renderTarget.texture;
  15107. const textureFormat = texture.format;
  15108. const textureType = texture.type;
  15109. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) {
  15110. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  15111. return;
  15112. }
  15113. const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
  15114. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513)
  15115. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  15116. !halfFloatSupportedByExt) {
  15117. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  15118. return;
  15119. }
  15120. if (_gl.checkFramebufferStatus(_gl.FRAMEBUFFER) === _gl.FRAMEBUFFER_COMPLETE) {
  15121. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  15122. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  15123. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  15124. }
  15125. } else {
  15126. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  15127. }
  15128. } finally {
  15129. // restore framebuffer of current render target if necessary
  15130. const framebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
  15131. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  15132. }
  15133. }
  15134. };
  15135. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  15136. const levelScale = Math.pow(2, -level);
  15137. const width = Math.floor(texture.image.width * levelScale);
  15138. const height = Math.floor(texture.image.height * levelScale);
  15139. let glFormat = utils.convert(texture.format);
  15140. if (capabilities.isWebGL2) {
  15141. // Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=1120100
  15142. // Not needed in Chrome 93+
  15143. if (glFormat === _gl.RGB) glFormat = _gl.RGB8;
  15144. if (glFormat === _gl.RGBA) glFormat = _gl.RGBA8;
  15145. }
  15146. textures.setTexture2D(texture, 0);
  15147. _gl.copyTexImage2D(_gl.TEXTURE_2D, level, glFormat, position.x, position.y, width, height, 0);
  15148. state.unbindTexture();
  15149. };
  15150. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  15151. const width = srcTexture.image.width;
  15152. const height = srcTexture.image.height;
  15153. const glFormat = utils.convert(dstTexture.format);
  15154. const glType = utils.convert(dstTexture.type);
  15155. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  15156. // parameters, make sure they are correct for the dstTexture
  15157. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  15158. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  15159. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  15160. if (srcTexture.isDataTexture) {
  15161. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  15162. } else {
  15163. if (srcTexture.isCompressedTexture) {
  15164. _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  15165. } else {
  15166. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image);
  15167. }
  15168. } // Generate mipmaps only when copying level 0
  15169. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D);
  15170. state.unbindTexture();
  15171. };
  15172. this.copyTextureToTexture3D = function (sourceBox, position, srcTexture, dstTexture, level = 0) {
  15173. if (_this.isWebGL1Renderer) {
  15174. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.');
  15175. return;
  15176. }
  15177. const width = sourceBox.max.x - sourceBox.min.x + 1;
  15178. const height = sourceBox.max.y - sourceBox.min.y + 1;
  15179. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  15180. const glFormat = utils.convert(dstTexture.format);
  15181. const glType = utils.convert(dstTexture.type);
  15182. let glTarget;
  15183. if (dstTexture.isDataTexture3D) {
  15184. textures.setTexture3D(dstTexture, 0);
  15185. glTarget = _gl.TEXTURE_3D;
  15186. } else if (dstTexture.isDataTexture2DArray) {
  15187. textures.setTexture2DArray(dstTexture, 0);
  15188. glTarget = _gl.TEXTURE_2D_ARRAY;
  15189. } else {
  15190. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.');
  15191. return;
  15192. }
  15193. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  15194. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  15195. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  15196. const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH);
  15197. const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT);
  15198. const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS);
  15199. const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS);
  15200. const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES);
  15201. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[0] : srcTexture.image;
  15202. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width);
  15203. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height);
  15204. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x);
  15205. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y);
  15206. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z);
  15207. if (srcTexture.isDataTexture || srcTexture.isDataTexture3D) {
  15208. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data);
  15209. } else {
  15210. if (srcTexture.isCompressedTexture) {
  15211. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.');
  15212. _gl.compressedTexSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data);
  15213. } else {
  15214. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image);
  15215. }
  15216. }
  15217. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen);
  15218. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight);
  15219. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels);
  15220. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows);
  15221. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages); // Generate mipmaps only when copying level 0
  15222. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget);
  15223. state.unbindTexture();
  15224. };
  15225. this.initTexture = function (texture) {
  15226. textures.setTexture2D(texture, 0);
  15227. state.unbindTexture();
  15228. };
  15229. this.resetState = function () {
  15230. _currentActiveCubeFace = 0;
  15231. _currentActiveMipmapLevel = 0;
  15232. _currentRenderTarget = null;
  15233. state.reset();
  15234. bindingStates.reset();
  15235. };
  15236. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  15237. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  15238. detail: this
  15239. })); // eslint-disable-line no-undef
  15240. }
  15241. }
  15242. class WebGL1Renderer extends WebGLRenderer {}
  15243. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  15244. class FogExp2 {
  15245. constructor(color, density = 0.00025) {
  15246. this.name = '';
  15247. this.color = new Color(color);
  15248. this.density = density;
  15249. }
  15250. clone() {
  15251. return new FogExp2(this.color, this.density);
  15252. }
  15253. toJSON()
  15254. /* meta */
  15255. {
  15256. return {
  15257. type: 'FogExp2',
  15258. color: this.color.getHex(),
  15259. density: this.density
  15260. };
  15261. }
  15262. }
  15263. FogExp2.prototype.isFogExp2 = true;
  15264. class Fog {
  15265. constructor(color, near = 1, far = 1000) {
  15266. this.name = '';
  15267. this.color = new Color(color);
  15268. this.near = near;
  15269. this.far = far;
  15270. }
  15271. clone() {
  15272. return new Fog(this.color, this.near, this.far);
  15273. }
  15274. toJSON()
  15275. /* meta */
  15276. {
  15277. return {
  15278. type: 'Fog',
  15279. color: this.color.getHex(),
  15280. near: this.near,
  15281. far: this.far
  15282. };
  15283. }
  15284. }
  15285. Fog.prototype.isFog = true;
  15286. class Scene extends Object3D {
  15287. constructor() {
  15288. super();
  15289. this.type = 'Scene';
  15290. this.background = null;
  15291. this.environment = null;
  15292. this.fog = null;
  15293. this.overrideMaterial = null;
  15294. this.autoUpdate = true; // checked by the renderer
  15295. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  15296. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  15297. detail: this
  15298. })); // eslint-disable-line no-undef
  15299. }
  15300. }
  15301. copy(source, recursive) {
  15302. super.copy(source, recursive);
  15303. if (source.background !== null) this.background = source.background.clone();
  15304. if (source.environment !== null) this.environment = source.environment.clone();
  15305. if (source.fog !== null) this.fog = source.fog.clone();
  15306. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  15307. this.autoUpdate = source.autoUpdate;
  15308. this.matrixAutoUpdate = source.matrixAutoUpdate;
  15309. return this;
  15310. }
  15311. toJSON(meta) {
  15312. const data = super.toJSON(meta);
  15313. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  15314. return data;
  15315. }
  15316. }
  15317. Scene.prototype.isScene = true;
  15318. class InterleavedBuffer {
  15319. constructor(array, stride) {
  15320. this.array = array;
  15321. this.stride = stride;
  15322. this.count = array !== undefined ? array.length / stride : 0;
  15323. this.usage = StaticDrawUsage;
  15324. this.updateRange = {
  15325. offset: 0,
  15326. count: -1
  15327. };
  15328. this.version = 0;
  15329. this.uuid = generateUUID();
  15330. }
  15331. onUploadCallback() {}
  15332. set needsUpdate(value) {
  15333. if (value === true) this.version++;
  15334. }
  15335. setUsage(value) {
  15336. this.usage = value;
  15337. return this;
  15338. }
  15339. copy(source) {
  15340. this.array = new source.array.constructor(source.array);
  15341. this.count = source.count;
  15342. this.stride = source.stride;
  15343. this.usage = source.usage;
  15344. return this;
  15345. }
  15346. copyAt(index1, attribute, index2) {
  15347. index1 *= this.stride;
  15348. index2 *= attribute.stride;
  15349. for (let i = 0, l = this.stride; i < l; i++) {
  15350. this.array[index1 + i] = attribute.array[index2 + i];
  15351. }
  15352. return this;
  15353. }
  15354. set(value, offset = 0) {
  15355. this.array.set(value, offset);
  15356. return this;
  15357. }
  15358. clone(data) {
  15359. if (data.arrayBuffers === undefined) {
  15360. data.arrayBuffers = {};
  15361. }
  15362. if (this.array.buffer._uuid === undefined) {
  15363. this.array.buffer._uuid = generateUUID();
  15364. }
  15365. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  15366. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  15367. }
  15368. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  15369. const ib = new this.constructor(array, this.stride);
  15370. ib.setUsage(this.usage);
  15371. return ib;
  15372. }
  15373. onUpload(callback) {
  15374. this.onUploadCallback = callback;
  15375. return this;
  15376. }
  15377. toJSON(data) {
  15378. if (data.arrayBuffers === undefined) {
  15379. data.arrayBuffers = {};
  15380. } // generate UUID for array buffer if necessary
  15381. if (this.array.buffer._uuid === undefined) {
  15382. this.array.buffer._uuid = generateUUID();
  15383. }
  15384. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  15385. data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
  15386. } //
  15387. return {
  15388. uuid: this.uuid,
  15389. buffer: this.array.buffer._uuid,
  15390. type: this.array.constructor.name,
  15391. stride: this.stride
  15392. };
  15393. }
  15394. }
  15395. InterleavedBuffer.prototype.isInterleavedBuffer = true;
  15396. const _vector$6 = /*@__PURE__*/new Vector3();
  15397. class InterleavedBufferAttribute {
  15398. constructor(interleavedBuffer, itemSize, offset, normalized = false) {
  15399. this.name = '';
  15400. this.data = interleavedBuffer;
  15401. this.itemSize = itemSize;
  15402. this.offset = offset;
  15403. this.normalized = normalized === true;
  15404. }
  15405. get count() {
  15406. return this.data.count;
  15407. }
  15408. get array() {
  15409. return this.data.array;
  15410. }
  15411. set needsUpdate(value) {
  15412. this.data.needsUpdate = value;
  15413. }
  15414. applyMatrix4(m) {
  15415. for (let i = 0, l = this.data.count; i < l; i++) {
  15416. _vector$6.x = this.getX(i);
  15417. _vector$6.y = this.getY(i);
  15418. _vector$6.z = this.getZ(i);
  15419. _vector$6.applyMatrix4(m);
  15420. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  15421. }
  15422. return this;
  15423. }
  15424. applyNormalMatrix(m) {
  15425. for (let i = 0, l = this.count; i < l; i++) {
  15426. _vector$6.x = this.getX(i);
  15427. _vector$6.y = this.getY(i);
  15428. _vector$6.z = this.getZ(i);
  15429. _vector$6.applyNormalMatrix(m);
  15430. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  15431. }
  15432. return this;
  15433. }
  15434. transformDirection(m) {
  15435. for (let i = 0, l = this.count; i < l; i++) {
  15436. _vector$6.x = this.getX(i);
  15437. _vector$6.y = this.getY(i);
  15438. _vector$6.z = this.getZ(i);
  15439. _vector$6.transformDirection(m);
  15440. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  15441. }
  15442. return this;
  15443. }
  15444. setX(index, x) {
  15445. this.data.array[index * this.data.stride + this.offset] = x;
  15446. return this;
  15447. }
  15448. setY(index, y) {
  15449. this.data.array[index * this.data.stride + this.offset + 1] = y;
  15450. return this;
  15451. }
  15452. setZ(index, z) {
  15453. this.data.array[index * this.data.stride + this.offset + 2] = z;
  15454. return this;
  15455. }
  15456. setW(index, w) {
  15457. this.data.array[index * this.data.stride + this.offset + 3] = w;
  15458. return this;
  15459. }
  15460. getX(index) {
  15461. return this.data.array[index * this.data.stride + this.offset];
  15462. }
  15463. getY(index) {
  15464. return this.data.array[index * this.data.stride + this.offset + 1];
  15465. }
  15466. getZ(index) {
  15467. return this.data.array[index * this.data.stride + this.offset + 2];
  15468. }
  15469. getW(index) {
  15470. return this.data.array[index * this.data.stride + this.offset + 3];
  15471. }
  15472. setXY(index, x, y) {
  15473. index = index * this.data.stride + this.offset;
  15474. this.data.array[index + 0] = x;
  15475. this.data.array[index + 1] = y;
  15476. return this;
  15477. }
  15478. setXYZ(index, x, y, z) {
  15479. index = index * this.data.stride + this.offset;
  15480. this.data.array[index + 0] = x;
  15481. this.data.array[index + 1] = y;
  15482. this.data.array[index + 2] = z;
  15483. return this;
  15484. }
  15485. setXYZW(index, x, y, z, w) {
  15486. index = index * this.data.stride + this.offset;
  15487. this.data.array[index + 0] = x;
  15488. this.data.array[index + 1] = y;
  15489. this.data.array[index + 2] = z;
  15490. this.data.array[index + 3] = w;
  15491. return this;
  15492. }
  15493. clone(data) {
  15494. if (data === undefined) {
  15495. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');
  15496. const array = [];
  15497. for (let i = 0; i < this.count; i++) {
  15498. const index = i * this.data.stride + this.offset;
  15499. for (let j = 0; j < this.itemSize; j++) {
  15500. array.push(this.data.array[index + j]);
  15501. }
  15502. }
  15503. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  15504. } else {
  15505. if (data.interleavedBuffers === undefined) {
  15506. data.interleavedBuffers = {};
  15507. }
  15508. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  15509. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  15510. }
  15511. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  15512. }
  15513. }
  15514. toJSON(data) {
  15515. if (data === undefined) {
  15516. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');
  15517. const array = [];
  15518. for (let i = 0; i < this.count; i++) {
  15519. const index = i * this.data.stride + this.offset;
  15520. for (let j = 0; j < this.itemSize; j++) {
  15521. array.push(this.data.array[index + j]);
  15522. }
  15523. } // deinterleave data and save it as an ordinary buffer attribute for now
  15524. return {
  15525. itemSize: this.itemSize,
  15526. type: this.array.constructor.name,
  15527. array: array,
  15528. normalized: this.normalized
  15529. };
  15530. } else {
  15531. // save as true interlaved attribtue
  15532. if (data.interleavedBuffers === undefined) {
  15533. data.interleavedBuffers = {};
  15534. }
  15535. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  15536. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  15537. }
  15538. return {
  15539. isInterleavedBufferAttribute: true,
  15540. itemSize: this.itemSize,
  15541. data: this.data.uuid,
  15542. offset: this.offset,
  15543. normalized: this.normalized
  15544. };
  15545. }
  15546. }
  15547. }
  15548. InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
  15549. /**
  15550. * parameters = {
  15551. * color: <hex>,
  15552. * map: new THREE.Texture( <Image> ),
  15553. * alphaMap: new THREE.Texture( <Image> ),
  15554. * rotation: <float>,
  15555. * sizeAttenuation: <bool>
  15556. * }
  15557. */
  15558. class SpriteMaterial extends Material {
  15559. constructor(parameters) {
  15560. super();
  15561. this.type = 'SpriteMaterial';
  15562. this.color = new Color(0xffffff);
  15563. this.map = null;
  15564. this.alphaMap = null;
  15565. this.rotation = 0;
  15566. this.sizeAttenuation = true;
  15567. this.transparent = true;
  15568. this.setValues(parameters);
  15569. }
  15570. copy(source) {
  15571. super.copy(source);
  15572. this.color.copy(source.color);
  15573. this.map = source.map;
  15574. this.alphaMap = source.alphaMap;
  15575. this.rotation = source.rotation;
  15576. this.sizeAttenuation = source.sizeAttenuation;
  15577. return this;
  15578. }
  15579. }
  15580. SpriteMaterial.prototype.isSpriteMaterial = true;
  15581. let _geometry;
  15582. const _intersectPoint = /*@__PURE__*/new Vector3();
  15583. const _worldScale = /*@__PURE__*/new Vector3();
  15584. const _mvPosition = /*@__PURE__*/new Vector3();
  15585. const _alignedPosition = /*@__PURE__*/new Vector2();
  15586. const _rotatedPosition = /*@__PURE__*/new Vector2();
  15587. const _viewWorldMatrix = /*@__PURE__*/new Matrix4();
  15588. const _vA = /*@__PURE__*/new Vector3();
  15589. const _vB = /*@__PURE__*/new Vector3();
  15590. const _vC = /*@__PURE__*/new Vector3();
  15591. const _uvA = /*@__PURE__*/new Vector2();
  15592. const _uvB = /*@__PURE__*/new Vector2();
  15593. const _uvC = /*@__PURE__*/new Vector2();
  15594. class Sprite extends Object3D {
  15595. constructor(material) {
  15596. super();
  15597. this.type = 'Sprite';
  15598. if (_geometry === undefined) {
  15599. _geometry = new BufferGeometry();
  15600. 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]);
  15601. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  15602. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  15603. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  15604. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  15605. }
  15606. this.geometry = _geometry;
  15607. this.material = material !== undefined ? material : new SpriteMaterial();
  15608. this.center = new Vector2(0.5, 0.5);
  15609. }
  15610. raycast(raycaster, intersects) {
  15611. if (raycaster.camera === null) {
  15612. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  15613. }
  15614. _worldScale.setFromMatrixScale(this.matrixWorld);
  15615. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  15616. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  15617. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  15618. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  15619. _worldScale.multiplyScalar(-_mvPosition.z);
  15620. }
  15621. const rotation = this.material.rotation;
  15622. let sin, cos;
  15623. if (rotation !== 0) {
  15624. cos = Math.cos(rotation);
  15625. sin = Math.sin(rotation);
  15626. }
  15627. const center = this.center;
  15628. transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15629. transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15630. transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15631. _uvA.set(0, 0);
  15632. _uvB.set(1, 0);
  15633. _uvC.set(1, 1); // check first triangle
  15634. let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
  15635. if (intersect === null) {
  15636. // check second triangle
  15637. transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15638. _uvB.set(0, 1);
  15639. intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
  15640. if (intersect === null) {
  15641. return;
  15642. }
  15643. }
  15644. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  15645. if (distance < raycaster.near || distance > raycaster.far) return;
  15646. intersects.push({
  15647. distance: distance,
  15648. point: _intersectPoint.clone(),
  15649. uv: Triangle.getUV(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()),
  15650. face: null,
  15651. object: this
  15652. });
  15653. }
  15654. copy(source) {
  15655. super.copy(source);
  15656. if (source.center !== undefined) this.center.copy(source.center);
  15657. this.material = source.material;
  15658. return this;
  15659. }
  15660. }
  15661. Sprite.prototype.isSprite = true;
  15662. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  15663. // compute position in camera space
  15664. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  15665. if (sin !== undefined) {
  15666. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  15667. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  15668. } else {
  15669. _rotatedPosition.copy(_alignedPosition);
  15670. }
  15671. vertexPosition.copy(mvPosition);
  15672. vertexPosition.x += _rotatedPosition.x;
  15673. vertexPosition.y += _rotatedPosition.y; // transform to world space
  15674. vertexPosition.applyMatrix4(_viewWorldMatrix);
  15675. }
  15676. const _v1$2 = /*@__PURE__*/new Vector3();
  15677. const _v2$1 = /*@__PURE__*/new Vector3();
  15678. class LOD extends Object3D {
  15679. constructor() {
  15680. super();
  15681. this._currentLevel = 0;
  15682. this.type = 'LOD';
  15683. Object.defineProperties(this, {
  15684. levels: {
  15685. enumerable: true,
  15686. value: []
  15687. },
  15688. isLOD: {
  15689. value: true
  15690. }
  15691. });
  15692. this.autoUpdate = true;
  15693. }
  15694. copy(source) {
  15695. super.copy(source, false);
  15696. const levels = source.levels;
  15697. for (let i = 0, l = levels.length; i < l; i++) {
  15698. const level = levels[i];
  15699. this.addLevel(level.object.clone(), level.distance);
  15700. }
  15701. this.autoUpdate = source.autoUpdate;
  15702. return this;
  15703. }
  15704. addLevel(object, distance = 0) {
  15705. distance = Math.abs(distance);
  15706. const levels = this.levels;
  15707. let l;
  15708. for (l = 0; l < levels.length; l++) {
  15709. if (distance < levels[l].distance) {
  15710. break;
  15711. }
  15712. }
  15713. levels.splice(l, 0, {
  15714. distance: distance,
  15715. object: object
  15716. });
  15717. this.add(object);
  15718. return this;
  15719. }
  15720. getCurrentLevel() {
  15721. return this._currentLevel;
  15722. }
  15723. getObjectForDistance(distance) {
  15724. const levels = this.levels;
  15725. if (levels.length > 0) {
  15726. let i, l;
  15727. for (i = 1, l = levels.length; i < l; i++) {
  15728. if (distance < levels[i].distance) {
  15729. break;
  15730. }
  15731. }
  15732. return levels[i - 1].object;
  15733. }
  15734. return null;
  15735. }
  15736. raycast(raycaster, intersects) {
  15737. const levels = this.levels;
  15738. if (levels.length > 0) {
  15739. _v1$2.setFromMatrixPosition(this.matrixWorld);
  15740. const distance = raycaster.ray.origin.distanceTo(_v1$2);
  15741. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  15742. }
  15743. }
  15744. update(camera) {
  15745. const levels = this.levels;
  15746. if (levels.length > 1) {
  15747. _v1$2.setFromMatrixPosition(camera.matrixWorld);
  15748. _v2$1.setFromMatrixPosition(this.matrixWorld);
  15749. const distance = _v1$2.distanceTo(_v2$1) / camera.zoom;
  15750. levels[0].object.visible = true;
  15751. let i, l;
  15752. for (i = 1, l = levels.length; i < l; i++) {
  15753. if (distance >= levels[i].distance) {
  15754. levels[i - 1].object.visible = false;
  15755. levels[i].object.visible = true;
  15756. } else {
  15757. break;
  15758. }
  15759. }
  15760. this._currentLevel = i - 1;
  15761. for (; i < l; i++) {
  15762. levels[i].object.visible = false;
  15763. }
  15764. }
  15765. }
  15766. toJSON(meta) {
  15767. const data = super.toJSON(meta);
  15768. if (this.autoUpdate === false) data.object.autoUpdate = false;
  15769. data.object.levels = [];
  15770. const levels = this.levels;
  15771. for (let i = 0, l = levels.length; i < l; i++) {
  15772. const level = levels[i];
  15773. data.object.levels.push({
  15774. object: level.object.uuid,
  15775. distance: level.distance
  15776. });
  15777. }
  15778. return data;
  15779. }
  15780. }
  15781. const _basePosition = /*@__PURE__*/new Vector3();
  15782. const _skinIndex = /*@__PURE__*/new Vector4();
  15783. const _skinWeight = /*@__PURE__*/new Vector4();
  15784. const _vector$5 = /*@__PURE__*/new Vector3();
  15785. const _matrix = /*@__PURE__*/new Matrix4();
  15786. class SkinnedMesh extends Mesh {
  15787. constructor(geometry, material) {
  15788. super(geometry, material);
  15789. this.type = 'SkinnedMesh';
  15790. this.bindMode = 'attached';
  15791. this.bindMatrix = new Matrix4();
  15792. this.bindMatrixInverse = new Matrix4();
  15793. }
  15794. copy(source) {
  15795. super.copy(source);
  15796. this.bindMode = source.bindMode;
  15797. this.bindMatrix.copy(source.bindMatrix);
  15798. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  15799. this.skeleton = source.skeleton;
  15800. return this;
  15801. }
  15802. bind(skeleton, bindMatrix) {
  15803. this.skeleton = skeleton;
  15804. if (bindMatrix === undefined) {
  15805. this.updateMatrixWorld(true);
  15806. this.skeleton.calculateInverses();
  15807. bindMatrix = this.matrixWorld;
  15808. }
  15809. this.bindMatrix.copy(bindMatrix);
  15810. this.bindMatrixInverse.copy(bindMatrix).invert();
  15811. }
  15812. pose() {
  15813. this.skeleton.pose();
  15814. }
  15815. normalizeSkinWeights() {
  15816. const vector = new Vector4();
  15817. const skinWeight = this.geometry.attributes.skinWeight;
  15818. for (let i = 0, l = skinWeight.count; i < l; i++) {
  15819. vector.x = skinWeight.getX(i);
  15820. vector.y = skinWeight.getY(i);
  15821. vector.z = skinWeight.getZ(i);
  15822. vector.w = skinWeight.getW(i);
  15823. const scale = 1.0 / vector.manhattanLength();
  15824. if (scale !== Infinity) {
  15825. vector.multiplyScalar(scale);
  15826. } else {
  15827. vector.set(1, 0, 0, 0); // do something reasonable
  15828. }
  15829. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  15830. }
  15831. }
  15832. updateMatrixWorld(force) {
  15833. super.updateMatrixWorld(force);
  15834. if (this.bindMode === 'attached') {
  15835. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  15836. } else if (this.bindMode === 'detached') {
  15837. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  15838. } else {
  15839. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  15840. }
  15841. }
  15842. boneTransform(index, target) {
  15843. const skeleton = this.skeleton;
  15844. const geometry = this.geometry;
  15845. _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  15846. _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  15847. _basePosition.fromBufferAttribute(geometry.attributes.position, index).applyMatrix4(this.bindMatrix);
  15848. target.set(0, 0, 0);
  15849. for (let i = 0; i < 4; i++) {
  15850. const weight = _skinWeight.getComponent(i);
  15851. if (weight !== 0) {
  15852. const boneIndex = _skinIndex.getComponent(i);
  15853. _matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  15854. target.addScaledVector(_vector$5.copy(_basePosition).applyMatrix4(_matrix), weight);
  15855. }
  15856. }
  15857. return target.applyMatrix4(this.bindMatrixInverse);
  15858. }
  15859. }
  15860. SkinnedMesh.prototype.isSkinnedMesh = true;
  15861. class Bone extends Object3D {
  15862. constructor() {
  15863. super();
  15864. this.type = 'Bone';
  15865. }
  15866. }
  15867. Bone.prototype.isBone = true;
  15868. class DataTexture extends Texture {
  15869. constructor(data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding) {
  15870. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  15871. this.image = {
  15872. data: data,
  15873. width: width,
  15874. height: height
  15875. };
  15876. this.magFilter = magFilter;
  15877. this.minFilter = minFilter;
  15878. this.generateMipmaps = false;
  15879. this.flipY = false;
  15880. this.unpackAlignment = 1;
  15881. this.needsUpdate = true;
  15882. }
  15883. }
  15884. DataTexture.prototype.isDataTexture = true;
  15885. const _offsetMatrix = /*@__PURE__*/new Matrix4();
  15886. const _identityMatrix = /*@__PURE__*/new Matrix4();
  15887. class Skeleton {
  15888. constructor(bones = [], boneInverses = []) {
  15889. this.uuid = generateUUID();
  15890. this.bones = bones.slice(0);
  15891. this.boneInverses = boneInverses;
  15892. this.boneMatrices = null;
  15893. this.boneTexture = null;
  15894. this.boneTextureSize = 0;
  15895. this.frame = -1;
  15896. this.init();
  15897. }
  15898. init() {
  15899. const bones = this.bones;
  15900. const boneInverses = this.boneInverses;
  15901. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  15902. if (boneInverses.length === 0) {
  15903. this.calculateInverses();
  15904. } else {
  15905. // handle special case
  15906. if (bones.length !== boneInverses.length) {
  15907. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  15908. this.boneInverses = [];
  15909. for (let i = 0, il = this.bones.length; i < il; i++) {
  15910. this.boneInverses.push(new Matrix4());
  15911. }
  15912. }
  15913. }
  15914. }
  15915. calculateInverses() {
  15916. this.boneInverses.length = 0;
  15917. for (let i = 0, il = this.bones.length; i < il; i++) {
  15918. const inverse = new Matrix4();
  15919. if (this.bones[i]) {
  15920. inverse.copy(this.bones[i].matrixWorld).invert();
  15921. }
  15922. this.boneInverses.push(inverse);
  15923. }
  15924. }
  15925. pose() {
  15926. // recover the bind-time world matrices
  15927. for (let i = 0, il = this.bones.length; i < il; i++) {
  15928. const bone = this.bones[i];
  15929. if (bone) {
  15930. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  15931. }
  15932. } // compute the local matrices, positions, rotations and scales
  15933. for (let i = 0, il = this.bones.length; i < il; i++) {
  15934. const bone = this.bones[i];
  15935. if (bone) {
  15936. if (bone.parent && bone.parent.isBone) {
  15937. bone.matrix.copy(bone.parent.matrixWorld).invert();
  15938. bone.matrix.multiply(bone.matrixWorld);
  15939. } else {
  15940. bone.matrix.copy(bone.matrixWorld);
  15941. }
  15942. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  15943. }
  15944. }
  15945. }
  15946. update() {
  15947. const bones = this.bones;
  15948. const boneInverses = this.boneInverses;
  15949. const boneMatrices = this.boneMatrices;
  15950. const boneTexture = this.boneTexture; // flatten bone matrices to array
  15951. for (let i = 0, il = bones.length; i < il; i++) {
  15952. // compute the offset between the current and the original transform
  15953. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  15954. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  15955. _offsetMatrix.toArray(boneMatrices, i * 16);
  15956. }
  15957. if (boneTexture !== null) {
  15958. boneTexture.needsUpdate = true;
  15959. }
  15960. }
  15961. clone() {
  15962. return new Skeleton(this.bones, this.boneInverses);
  15963. }
  15964. computeBoneTexture() {
  15965. // layout (1 matrix = 4 pixels)
  15966. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  15967. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  15968. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  15969. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  15970. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  15971. let size = Math.sqrt(this.bones.length * 4); // 4 pixels needed for 1 matrix
  15972. size = ceilPowerOfTwo(size);
  15973. size = Math.max(size, 4);
  15974. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  15975. boneMatrices.set(this.boneMatrices); // copy current values
  15976. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  15977. this.boneMatrices = boneMatrices;
  15978. this.boneTexture = boneTexture;
  15979. this.boneTextureSize = size;
  15980. return this;
  15981. }
  15982. getBoneByName(name) {
  15983. for (let i = 0, il = this.bones.length; i < il; i++) {
  15984. const bone = this.bones[i];
  15985. if (bone.name === name) {
  15986. return bone;
  15987. }
  15988. }
  15989. return undefined;
  15990. }
  15991. dispose() {
  15992. if (this.boneTexture !== null) {
  15993. this.boneTexture.dispose();
  15994. this.boneTexture = null;
  15995. }
  15996. }
  15997. fromJSON(json, bones) {
  15998. this.uuid = json.uuid;
  15999. for (let i = 0, l = json.bones.length; i < l; i++) {
  16000. const uuid = json.bones[i];
  16001. let bone = bones[uuid];
  16002. if (bone === undefined) {
  16003. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  16004. bone = new Bone();
  16005. }
  16006. this.bones.push(bone);
  16007. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  16008. }
  16009. this.init();
  16010. return this;
  16011. }
  16012. toJSON() {
  16013. const data = {
  16014. metadata: {
  16015. version: 4.5,
  16016. type: 'Skeleton',
  16017. generator: 'Skeleton.toJSON'
  16018. },
  16019. bones: [],
  16020. boneInverses: []
  16021. };
  16022. data.uuid = this.uuid;
  16023. const bones = this.bones;
  16024. const boneInverses = this.boneInverses;
  16025. for (let i = 0, l = bones.length; i < l; i++) {
  16026. const bone = bones[i];
  16027. data.bones.push(bone.uuid);
  16028. const boneInverse = boneInverses[i];
  16029. data.boneInverses.push(boneInverse.toArray());
  16030. }
  16031. return data;
  16032. }
  16033. }
  16034. const _instanceLocalMatrix = /*@__PURE__*/new Matrix4();
  16035. const _instanceWorldMatrix = /*@__PURE__*/new Matrix4();
  16036. const _instanceIntersects = [];
  16037. const _mesh = /*@__PURE__*/new Mesh();
  16038. class InstancedMesh extends Mesh {
  16039. constructor(geometry, material, count) {
  16040. super(geometry, material);
  16041. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  16042. this.instanceColor = null;
  16043. this.count = count;
  16044. this.frustumCulled = false;
  16045. }
  16046. copy(source) {
  16047. super.copy(source);
  16048. this.instanceMatrix.copy(source.instanceMatrix);
  16049. if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
  16050. this.count = source.count;
  16051. return this;
  16052. }
  16053. getColorAt(index, color) {
  16054. color.fromArray(this.instanceColor.array, index * 3);
  16055. }
  16056. getMatrixAt(index, matrix) {
  16057. matrix.fromArray(this.instanceMatrix.array, index * 16);
  16058. }
  16059. raycast(raycaster, intersects) {
  16060. const matrixWorld = this.matrixWorld;
  16061. const raycastTimes = this.count;
  16062. _mesh.geometry = this.geometry;
  16063. _mesh.material = this.material;
  16064. if (_mesh.material === undefined) return;
  16065. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  16066. // calculate the world matrix for each instance
  16067. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  16068. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  16069. _mesh.matrixWorld = _instanceWorldMatrix;
  16070. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  16071. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  16072. const intersect = _instanceIntersects[i];
  16073. intersect.instanceId = instanceId;
  16074. intersect.object = this;
  16075. intersects.push(intersect);
  16076. }
  16077. _instanceIntersects.length = 0;
  16078. }
  16079. }
  16080. setColorAt(index, color) {
  16081. if (this.instanceColor === null) {
  16082. this.instanceColor = new BufferAttribute(new Float32Array(this.count * 3), 3);
  16083. }
  16084. color.toArray(this.instanceColor.array, index * 3);
  16085. }
  16086. setMatrixAt(index, matrix) {
  16087. matrix.toArray(this.instanceMatrix.array, index * 16);
  16088. }
  16089. updateMorphTargets() {}
  16090. dispose() {
  16091. this.dispatchEvent({
  16092. type: 'dispose'
  16093. });
  16094. }
  16095. }
  16096. InstancedMesh.prototype.isInstancedMesh = true;
  16097. /**
  16098. * parameters = {
  16099. * color: <hex>,
  16100. * opacity: <float>,
  16101. *
  16102. * linewidth: <float>,
  16103. * linecap: "round",
  16104. * linejoin: "round"
  16105. * }
  16106. */
  16107. class LineBasicMaterial extends Material {
  16108. constructor(parameters) {
  16109. super();
  16110. this.type = 'LineBasicMaterial';
  16111. this.color = new Color(0xffffff);
  16112. this.linewidth = 1;
  16113. this.linecap = 'round';
  16114. this.linejoin = 'round';
  16115. this.setValues(parameters);
  16116. }
  16117. copy(source) {
  16118. super.copy(source);
  16119. this.color.copy(source.color);
  16120. this.linewidth = source.linewidth;
  16121. this.linecap = source.linecap;
  16122. this.linejoin = source.linejoin;
  16123. return this;
  16124. }
  16125. }
  16126. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  16127. const _start$1 = /*@__PURE__*/new Vector3();
  16128. const _end$1 = /*@__PURE__*/new Vector3();
  16129. const _inverseMatrix$1 = /*@__PURE__*/new Matrix4();
  16130. const _ray$1 = /*@__PURE__*/new Ray();
  16131. const _sphere$1 = /*@__PURE__*/new Sphere();
  16132. class Line extends Object3D {
  16133. constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) {
  16134. super();
  16135. this.type = 'Line';
  16136. this.geometry = geometry;
  16137. this.material = material;
  16138. this.updateMorphTargets();
  16139. }
  16140. copy(source) {
  16141. super.copy(source);
  16142. this.material = source.material;
  16143. this.geometry = source.geometry;
  16144. return this;
  16145. }
  16146. computeLineDistances() {
  16147. const geometry = this.geometry;
  16148. if (geometry.isBufferGeometry) {
  16149. // we assume non-indexed geometry
  16150. if (geometry.index === null) {
  16151. const positionAttribute = geometry.attributes.position;
  16152. const lineDistances = [0];
  16153. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  16154. _start$1.fromBufferAttribute(positionAttribute, i - 1);
  16155. _end$1.fromBufferAttribute(positionAttribute, i);
  16156. lineDistances[i] = lineDistances[i - 1];
  16157. lineDistances[i] += _start$1.distanceTo(_end$1);
  16158. }
  16159. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16160. } else {
  16161. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16162. }
  16163. } else if (geometry.isGeometry) {
  16164. console.error('THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16165. }
  16166. return this;
  16167. }
  16168. raycast(raycaster, intersects) {
  16169. const geometry = this.geometry;
  16170. const matrixWorld = this.matrixWorld;
  16171. const threshold = raycaster.params.Line.threshold;
  16172. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  16173. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16174. _sphere$1.copy(geometry.boundingSphere);
  16175. _sphere$1.applyMatrix4(matrixWorld);
  16176. _sphere$1.radius += threshold;
  16177. if (raycaster.ray.intersectsSphere(_sphere$1) === false) return; //
  16178. _inverseMatrix$1.copy(matrixWorld).invert();
  16179. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  16180. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16181. const localThresholdSq = localThreshold * localThreshold;
  16182. const vStart = new Vector3();
  16183. const vEnd = new Vector3();
  16184. const interSegment = new Vector3();
  16185. const interRay = new Vector3();
  16186. const step = this.isLineSegments ? 2 : 1;
  16187. if (geometry.isBufferGeometry) {
  16188. const index = geometry.index;
  16189. const attributes = geometry.attributes;
  16190. const positionAttribute = attributes.position;
  16191. if (index !== null) {
  16192. const start = Math.max(0, drawRange.start);
  16193. const end = Math.min(index.count, drawRange.start + drawRange.count);
  16194. for (let i = start, l = end - 1; i < l; i += step) {
  16195. const a = index.getX(i);
  16196. const b = index.getX(i + 1);
  16197. vStart.fromBufferAttribute(positionAttribute, a);
  16198. vEnd.fromBufferAttribute(positionAttribute, b);
  16199. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16200. if (distSq > localThresholdSq) continue;
  16201. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16202. const distance = raycaster.ray.origin.distanceTo(interRay);
  16203. if (distance < raycaster.near || distance > raycaster.far) continue;
  16204. intersects.push({
  16205. distance: distance,
  16206. // What do we want? intersection point on the ray or on the segment??
  16207. // point: raycaster.ray.at( distance ),
  16208. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16209. index: i,
  16210. face: null,
  16211. faceIndex: null,
  16212. object: this
  16213. });
  16214. }
  16215. } else {
  16216. const start = Math.max(0, drawRange.start);
  16217. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  16218. for (let i = start, l = end - 1; i < l; i += step) {
  16219. vStart.fromBufferAttribute(positionAttribute, i);
  16220. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  16221. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16222. if (distSq > localThresholdSq) continue;
  16223. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16224. const distance = raycaster.ray.origin.distanceTo(interRay);
  16225. if (distance < raycaster.near || distance > raycaster.far) continue;
  16226. intersects.push({
  16227. distance: distance,
  16228. // What do we want? intersection point on the ray or on the segment??
  16229. // point: raycaster.ray.at( distance ),
  16230. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16231. index: i,
  16232. face: null,
  16233. faceIndex: null,
  16234. object: this
  16235. });
  16236. }
  16237. }
  16238. } else if (geometry.isGeometry) {
  16239. console.error('THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16240. }
  16241. }
  16242. updateMorphTargets() {
  16243. const geometry = this.geometry;
  16244. if (geometry.isBufferGeometry) {
  16245. const morphAttributes = geometry.morphAttributes;
  16246. const keys = Object.keys(morphAttributes);
  16247. if (keys.length > 0) {
  16248. const morphAttribute = morphAttributes[keys[0]];
  16249. if (morphAttribute !== undefined) {
  16250. this.morphTargetInfluences = [];
  16251. this.morphTargetDictionary = {};
  16252. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  16253. const name = morphAttribute[m].name || String(m);
  16254. this.morphTargetInfluences.push(0);
  16255. this.morphTargetDictionary[name] = m;
  16256. }
  16257. }
  16258. }
  16259. } else {
  16260. const morphTargets = geometry.morphTargets;
  16261. if (morphTargets !== undefined && morphTargets.length > 0) {
  16262. console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  16263. }
  16264. }
  16265. }
  16266. }
  16267. Line.prototype.isLine = true;
  16268. const _start = /*@__PURE__*/new Vector3();
  16269. const _end = /*@__PURE__*/new Vector3();
  16270. class LineSegments extends Line {
  16271. constructor(geometry, material) {
  16272. super(geometry, material);
  16273. this.type = 'LineSegments';
  16274. }
  16275. computeLineDistances() {
  16276. const geometry = this.geometry;
  16277. if (geometry.isBufferGeometry) {
  16278. // we assume non-indexed geometry
  16279. if (geometry.index === null) {
  16280. const positionAttribute = geometry.attributes.position;
  16281. const lineDistances = [];
  16282. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  16283. _start.fromBufferAttribute(positionAttribute, i);
  16284. _end.fromBufferAttribute(positionAttribute, i + 1);
  16285. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  16286. lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end);
  16287. }
  16288. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16289. } else {
  16290. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16291. }
  16292. } else if (geometry.isGeometry) {
  16293. console.error('THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16294. }
  16295. return this;
  16296. }
  16297. }
  16298. LineSegments.prototype.isLineSegments = true;
  16299. class LineLoop extends Line {
  16300. constructor(geometry, material) {
  16301. super(geometry, material);
  16302. this.type = 'LineLoop';
  16303. }
  16304. }
  16305. LineLoop.prototype.isLineLoop = true;
  16306. /**
  16307. * parameters = {
  16308. * color: <hex>,
  16309. * opacity: <float>,
  16310. * map: new THREE.Texture( <Image> ),
  16311. * alphaMap: new THREE.Texture( <Image> ),
  16312. *
  16313. * size: <float>,
  16314. * sizeAttenuation: <bool>
  16315. *
  16316. * }
  16317. */
  16318. class PointsMaterial extends Material {
  16319. constructor(parameters) {
  16320. super();
  16321. this.type = 'PointsMaterial';
  16322. this.color = new Color(0xffffff);
  16323. this.map = null;
  16324. this.alphaMap = null;
  16325. this.size = 1;
  16326. this.sizeAttenuation = true;
  16327. this.setValues(parameters);
  16328. }
  16329. copy(source) {
  16330. super.copy(source);
  16331. this.color.copy(source.color);
  16332. this.map = source.map;
  16333. this.alphaMap = source.alphaMap;
  16334. this.size = source.size;
  16335. this.sizeAttenuation = source.sizeAttenuation;
  16336. return this;
  16337. }
  16338. }
  16339. PointsMaterial.prototype.isPointsMaterial = true;
  16340. const _inverseMatrix = /*@__PURE__*/new Matrix4();
  16341. const _ray = /*@__PURE__*/new Ray();
  16342. const _sphere = /*@__PURE__*/new Sphere();
  16343. const _position$2 = /*@__PURE__*/new Vector3();
  16344. class Points extends Object3D {
  16345. constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) {
  16346. super();
  16347. this.type = 'Points';
  16348. this.geometry = geometry;
  16349. this.material = material;
  16350. this.updateMorphTargets();
  16351. }
  16352. copy(source) {
  16353. super.copy(source);
  16354. this.material = source.material;
  16355. this.geometry = source.geometry;
  16356. return this;
  16357. }
  16358. raycast(raycaster, intersects) {
  16359. const geometry = this.geometry;
  16360. const matrixWorld = this.matrixWorld;
  16361. const threshold = raycaster.params.Points.threshold;
  16362. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  16363. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16364. _sphere.copy(geometry.boundingSphere);
  16365. _sphere.applyMatrix4(matrixWorld);
  16366. _sphere.radius += threshold;
  16367. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  16368. _inverseMatrix.copy(matrixWorld).invert();
  16369. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);
  16370. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16371. const localThresholdSq = localThreshold * localThreshold;
  16372. if (geometry.isBufferGeometry) {
  16373. const index = geometry.index;
  16374. const attributes = geometry.attributes;
  16375. const positionAttribute = attributes.position;
  16376. if (index !== null) {
  16377. const start = Math.max(0, drawRange.start);
  16378. const end = Math.min(index.count, drawRange.start + drawRange.count);
  16379. for (let i = start, il = end; i < il; i++) {
  16380. const a = index.getX(i);
  16381. _position$2.fromBufferAttribute(positionAttribute, a);
  16382. testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16383. }
  16384. } else {
  16385. const start = Math.max(0, drawRange.start);
  16386. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  16387. for (let i = start, l = end; i < l; i++) {
  16388. _position$2.fromBufferAttribute(positionAttribute, i);
  16389. testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16390. }
  16391. }
  16392. } else {
  16393. console.error('THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16394. }
  16395. }
  16396. updateMorphTargets() {
  16397. const geometry = this.geometry;
  16398. if (geometry.isBufferGeometry) {
  16399. const morphAttributes = geometry.morphAttributes;
  16400. const keys = Object.keys(morphAttributes);
  16401. if (keys.length > 0) {
  16402. const morphAttribute = morphAttributes[keys[0]];
  16403. if (morphAttribute !== undefined) {
  16404. this.morphTargetInfluences = [];
  16405. this.morphTargetDictionary = {};
  16406. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  16407. const name = morphAttribute[m].name || String(m);
  16408. this.morphTargetInfluences.push(0);
  16409. this.morphTargetDictionary[name] = m;
  16410. }
  16411. }
  16412. }
  16413. } else {
  16414. const morphTargets = geometry.morphTargets;
  16415. if (morphTargets !== undefined && morphTargets.length > 0) {
  16416. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  16417. }
  16418. }
  16419. }
  16420. }
  16421. Points.prototype.isPoints = true;
  16422. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  16423. const rayPointDistanceSq = _ray.distanceSqToPoint(point);
  16424. if (rayPointDistanceSq < localThresholdSq) {
  16425. const intersectPoint = new Vector3();
  16426. _ray.closestPointToPoint(point, intersectPoint);
  16427. intersectPoint.applyMatrix4(matrixWorld);
  16428. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  16429. if (distance < raycaster.near || distance > raycaster.far) return;
  16430. intersects.push({
  16431. distance: distance,
  16432. distanceToRay: Math.sqrt(rayPointDistanceSq),
  16433. point: intersectPoint,
  16434. index: index,
  16435. face: null,
  16436. object: object
  16437. });
  16438. }
  16439. }
  16440. class VideoTexture extends Texture {
  16441. constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  16442. super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16443. this.format = format !== undefined ? format : RGBFormat;
  16444. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  16445. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  16446. this.generateMipmaps = false;
  16447. const scope = this;
  16448. function updateVideo() {
  16449. scope.needsUpdate = true;
  16450. video.requestVideoFrameCallback(updateVideo);
  16451. }
  16452. if ('requestVideoFrameCallback' in video) {
  16453. video.requestVideoFrameCallback(updateVideo);
  16454. }
  16455. }
  16456. clone() {
  16457. return new this.constructor(this.image).copy(this);
  16458. }
  16459. update() {
  16460. const video = this.image;
  16461. const hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  16462. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  16463. this.needsUpdate = true;
  16464. }
  16465. }
  16466. }
  16467. VideoTexture.prototype.isVideoTexture = true;
  16468. class CompressedTexture extends Texture {
  16469. constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  16470. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  16471. this.image = {
  16472. width: width,
  16473. height: height
  16474. };
  16475. this.mipmaps = mipmaps; // no flipping for cube textures
  16476. // (also flipping doesn't work for compressed textures )
  16477. this.flipY = false; // can't generate mipmaps for compressed textures
  16478. // mips must be embedded in DDS files
  16479. this.generateMipmaps = false;
  16480. }
  16481. }
  16482. CompressedTexture.prototype.isCompressedTexture = true;
  16483. class CanvasTexture extends Texture {
  16484. constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  16485. super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16486. this.needsUpdate = true;
  16487. }
  16488. }
  16489. CanvasTexture.prototype.isCanvasTexture = true;
  16490. class DepthTexture extends Texture {
  16491. constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  16492. format = format !== undefined ? format : DepthFormat;
  16493. if (format !== DepthFormat && format !== DepthStencilFormat) {
  16494. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  16495. }
  16496. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  16497. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  16498. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16499. this.image = {
  16500. width: width,
  16501. height: height
  16502. };
  16503. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  16504. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  16505. this.flipY = false;
  16506. this.generateMipmaps = false;
  16507. }
  16508. }
  16509. DepthTexture.prototype.isDepthTexture = true;
  16510. class CircleGeometry extends BufferGeometry {
  16511. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  16512. super();
  16513. this.type = 'CircleGeometry';
  16514. this.parameters = {
  16515. radius: radius,
  16516. segments: segments,
  16517. thetaStart: thetaStart,
  16518. thetaLength: thetaLength
  16519. };
  16520. segments = Math.max(3, segments); // buffers
  16521. const indices = [];
  16522. const vertices = [];
  16523. const normals = [];
  16524. const uvs = []; // helper variables
  16525. const vertex = new Vector3();
  16526. const uv = new Vector2(); // center point
  16527. vertices.push(0, 0, 0);
  16528. normals.push(0, 0, 1);
  16529. uvs.push(0.5, 0.5);
  16530. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  16531. const segment = thetaStart + s / segments * thetaLength; // vertex
  16532. vertex.x = radius * Math.cos(segment);
  16533. vertex.y = radius * Math.sin(segment);
  16534. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  16535. normals.push(0, 0, 1); // uvs
  16536. uv.x = (vertices[i] / radius + 1) / 2;
  16537. uv.y = (vertices[i + 1] / radius + 1) / 2;
  16538. uvs.push(uv.x, uv.y);
  16539. } // indices
  16540. for (let i = 1; i <= segments; i++) {
  16541. indices.push(i, i + 1, 0);
  16542. } // build geometry
  16543. this.setIndex(indices);
  16544. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  16545. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  16546. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  16547. }
  16548. static fromJSON(data) {
  16549. return new CircleGeometry(data.radius, data.segments, data.thetaStart, data.thetaLength);
  16550. }
  16551. }
  16552. class CylinderGeometry extends BufferGeometry {
  16553. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  16554. super();
  16555. this.type = 'CylinderGeometry';
  16556. this.parameters = {
  16557. radiusTop: radiusTop,
  16558. radiusBottom: radiusBottom,
  16559. height: height,
  16560. radialSegments: radialSegments,
  16561. heightSegments: heightSegments,
  16562. openEnded: openEnded,
  16563. thetaStart: thetaStart,
  16564. thetaLength: thetaLength
  16565. };
  16566. const scope = this;
  16567. radialSegments = Math.floor(radialSegments);
  16568. heightSegments = Math.floor(heightSegments); // buffers
  16569. const indices = [];
  16570. const vertices = [];
  16571. const normals = [];
  16572. const uvs = []; // helper variables
  16573. let index = 0;
  16574. const indexArray = [];
  16575. const halfHeight = height / 2;
  16576. let groupStart = 0; // generate geometry
  16577. generateTorso();
  16578. if (openEnded === false) {
  16579. if (radiusTop > 0) generateCap(true);
  16580. if (radiusBottom > 0) generateCap(false);
  16581. } // build geometry
  16582. this.setIndex(indices);
  16583. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  16584. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  16585. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  16586. function generateTorso() {
  16587. const normal = new Vector3();
  16588. const vertex = new Vector3();
  16589. let groupCount = 0; // this will be used to calculate the normal
  16590. const slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  16591. for (let y = 0; y <= heightSegments; y++) {
  16592. const indexRow = [];
  16593. const v = y / heightSegments; // calculate the radius of the current row
  16594. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  16595. for (let x = 0; x <= radialSegments; x++) {
  16596. const u = x / radialSegments;
  16597. const theta = u * thetaLength + thetaStart;
  16598. const sinTheta = Math.sin(theta);
  16599. const cosTheta = Math.cos(theta); // vertex
  16600. vertex.x = radius * sinTheta;
  16601. vertex.y = -v * height + halfHeight;
  16602. vertex.z = radius * cosTheta;
  16603. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  16604. normal.set(sinTheta, slope, cosTheta).normalize();
  16605. normals.push(normal.x, normal.y, normal.z); // uv
  16606. uvs.push(u, 1 - v); // save index of vertex in respective row
  16607. indexRow.push(index++);
  16608. } // now save vertices of the row in our index array
  16609. indexArray.push(indexRow);
  16610. } // generate indices
  16611. for (let x = 0; x < radialSegments; x++) {
  16612. for (let y = 0; y < heightSegments; y++) {
  16613. // we use the index array to access the correct indices
  16614. const a = indexArray[y][x];
  16615. const b = indexArray[y + 1][x];
  16616. const c = indexArray[y + 1][x + 1];
  16617. const d = indexArray[y][x + 1]; // faces
  16618. indices.push(a, b, d);
  16619. indices.push(b, c, d); // update group counter
  16620. groupCount += 6;
  16621. }
  16622. } // add a group to the geometry. this will ensure multi material support
  16623. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  16624. groupStart += groupCount;
  16625. }
  16626. function generateCap(top) {
  16627. // save the index of the first center vertex
  16628. const centerIndexStart = index;
  16629. const uv = new Vector2();
  16630. const vertex = new Vector3();
  16631. let groupCount = 0;
  16632. const radius = top === true ? radiusTop : radiusBottom;
  16633. const sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  16634. // because the geometry needs one set of uvs per face,
  16635. // we must generate a center vertex per face/segment
  16636. for (let x = 1; x <= radialSegments; x++) {
  16637. // vertex
  16638. vertices.push(0, halfHeight * sign, 0); // normal
  16639. normals.push(0, sign, 0); // uv
  16640. uvs.push(0.5, 0.5); // increase index
  16641. index++;
  16642. } // save the index of the last center vertex
  16643. const centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  16644. for (let x = 0; x <= radialSegments; x++) {
  16645. const u = x / radialSegments;
  16646. const theta = u * thetaLength + thetaStart;
  16647. const cosTheta = Math.cos(theta);
  16648. const sinTheta = Math.sin(theta); // vertex
  16649. vertex.x = radius * sinTheta;
  16650. vertex.y = halfHeight * sign;
  16651. vertex.z = radius * cosTheta;
  16652. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  16653. normals.push(0, sign, 0); // uv
  16654. uv.x = cosTheta * 0.5 + 0.5;
  16655. uv.y = sinTheta * 0.5 * sign + 0.5;
  16656. uvs.push(uv.x, uv.y); // increase index
  16657. index++;
  16658. } // generate indices
  16659. for (let x = 0; x < radialSegments; x++) {
  16660. const c = centerIndexStart + x;
  16661. const i = centerIndexEnd + x;
  16662. if (top === true) {
  16663. // face top
  16664. indices.push(i, i + 1, c);
  16665. } else {
  16666. // face bottom
  16667. indices.push(i + 1, i, c);
  16668. }
  16669. groupCount += 3;
  16670. } // add a group to the geometry. this will ensure multi material support
  16671. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  16672. groupStart += groupCount;
  16673. }
  16674. }
  16675. static fromJSON(data) {
  16676. return new CylinderGeometry(data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  16677. }
  16678. }
  16679. class ConeGeometry extends CylinderGeometry {
  16680. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  16681. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  16682. this.type = 'ConeGeometry';
  16683. this.parameters = {
  16684. radius: radius,
  16685. height: height,
  16686. radialSegments: radialSegments,
  16687. heightSegments: heightSegments,
  16688. openEnded: openEnded,
  16689. thetaStart: thetaStart,
  16690. thetaLength: thetaLength
  16691. };
  16692. }
  16693. static fromJSON(data) {
  16694. return new ConeGeometry(data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  16695. }
  16696. }
  16697. class PolyhedronGeometry extends BufferGeometry {
  16698. constructor(vertices, indices, radius = 1, detail = 0) {
  16699. super();
  16700. this.type = 'PolyhedronGeometry';
  16701. this.parameters = {
  16702. vertices: vertices,
  16703. indices: indices,
  16704. radius: radius,
  16705. detail: detail
  16706. }; // default buffer data
  16707. const vertexBuffer = [];
  16708. const uvBuffer = []; // the subdivision creates the vertex buffer data
  16709. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  16710. applyRadius(radius); // finally, create the uv data
  16711. generateUVs(); // build non-indexed geometry
  16712. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  16713. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  16714. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  16715. if (detail === 0) {
  16716. this.computeVertexNormals(); // flat normals
  16717. } else {
  16718. this.normalizeNormals(); // smooth normals
  16719. } // helper functions
  16720. function subdivide(detail) {
  16721. const a = new Vector3();
  16722. const b = new Vector3();
  16723. const c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  16724. for (let i = 0; i < indices.length; i += 3) {
  16725. // get the vertices of the face
  16726. getVertexByIndex(indices[i + 0], a);
  16727. getVertexByIndex(indices[i + 1], b);
  16728. getVertexByIndex(indices[i + 2], c); // perform subdivision
  16729. subdivideFace(a, b, c, detail);
  16730. }
  16731. }
  16732. function subdivideFace(a, b, c, detail) {
  16733. const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  16734. const v = []; // construct all of the vertices for this subdivision
  16735. for (let i = 0; i <= cols; i++) {
  16736. v[i] = [];
  16737. const aj = a.clone().lerp(c, i / cols);
  16738. const bj = b.clone().lerp(c, i / cols);
  16739. const rows = cols - i;
  16740. for (let j = 0; j <= rows; j++) {
  16741. if (j === 0 && i === cols) {
  16742. v[i][j] = aj;
  16743. } else {
  16744. v[i][j] = aj.clone().lerp(bj, j / rows);
  16745. }
  16746. }
  16747. } // construct all of the faces
  16748. for (let i = 0; i < cols; i++) {
  16749. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  16750. const k = Math.floor(j / 2);
  16751. if (j % 2 === 0) {
  16752. pushVertex(v[i][k + 1]);
  16753. pushVertex(v[i + 1][k]);
  16754. pushVertex(v[i][k]);
  16755. } else {
  16756. pushVertex(v[i][k + 1]);
  16757. pushVertex(v[i + 1][k + 1]);
  16758. pushVertex(v[i + 1][k]);
  16759. }
  16760. }
  16761. }
  16762. }
  16763. function applyRadius(radius) {
  16764. const vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  16765. for (let i = 0; i < vertexBuffer.length; i += 3) {
  16766. vertex.x = vertexBuffer[i + 0];
  16767. vertex.y = vertexBuffer[i + 1];
  16768. vertex.z = vertexBuffer[i + 2];
  16769. vertex.normalize().multiplyScalar(radius);
  16770. vertexBuffer[i + 0] = vertex.x;
  16771. vertexBuffer[i + 1] = vertex.y;
  16772. vertexBuffer[i + 2] = vertex.z;
  16773. }
  16774. }
  16775. function generateUVs() {
  16776. const vertex = new Vector3();
  16777. for (let i = 0; i < vertexBuffer.length; i += 3) {
  16778. vertex.x = vertexBuffer[i + 0];
  16779. vertex.y = vertexBuffer[i + 1];
  16780. vertex.z = vertexBuffer[i + 2];
  16781. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  16782. const v = inclination(vertex) / Math.PI + 0.5;
  16783. uvBuffer.push(u, 1 - v);
  16784. }
  16785. correctUVs();
  16786. correctSeam();
  16787. }
  16788. function correctSeam() {
  16789. // handle case when face straddles the seam, see #3269
  16790. for (let i = 0; i < uvBuffer.length; i += 6) {
  16791. // uv data of a single face
  16792. const x0 = uvBuffer[i + 0];
  16793. const x1 = uvBuffer[i + 2];
  16794. const x2 = uvBuffer[i + 4];
  16795. const max = Math.max(x0, x1, x2);
  16796. const min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  16797. if (max > 0.9 && min < 0.1) {
  16798. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  16799. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  16800. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  16801. }
  16802. }
  16803. }
  16804. function pushVertex(vertex) {
  16805. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  16806. }
  16807. function getVertexByIndex(index, vertex) {
  16808. const stride = index * 3;
  16809. vertex.x = vertices[stride + 0];
  16810. vertex.y = vertices[stride + 1];
  16811. vertex.z = vertices[stride + 2];
  16812. }
  16813. function correctUVs() {
  16814. const a = new Vector3();
  16815. const b = new Vector3();
  16816. const c = new Vector3();
  16817. const centroid = new Vector3();
  16818. const uvA = new Vector2();
  16819. const uvB = new Vector2();
  16820. const uvC = new Vector2();
  16821. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  16822. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  16823. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  16824. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  16825. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  16826. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  16827. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  16828. centroid.copy(a).add(b).add(c).divideScalar(3);
  16829. const azi = azimuth(centroid);
  16830. correctUV(uvA, j + 0, a, azi);
  16831. correctUV(uvB, j + 2, b, azi);
  16832. correctUV(uvC, j + 4, c, azi);
  16833. }
  16834. }
  16835. function correctUV(uv, stride, vector, azimuth) {
  16836. if (azimuth < 0 && uv.x === 1) {
  16837. uvBuffer[stride] = uv.x - 1;
  16838. }
  16839. if (vector.x === 0 && vector.z === 0) {
  16840. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  16841. }
  16842. } // Angle around the Y axis, counter-clockwise when looking from above.
  16843. function azimuth(vector) {
  16844. return Math.atan2(vector.z, -vector.x);
  16845. } // Angle above the XZ plane.
  16846. function inclination(vector) {
  16847. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  16848. }
  16849. }
  16850. static fromJSON(data) {
  16851. return new PolyhedronGeometry(data.vertices, data.indices, data.radius, data.details);
  16852. }
  16853. }
  16854. class DodecahedronGeometry extends PolyhedronGeometry {
  16855. constructor(radius = 1, detail = 0) {
  16856. const t = (1 + Math.sqrt(5)) / 2;
  16857. const r = 1 / t;
  16858. const vertices = [// (±1, ±1, ±1)
  16859. -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/φ, ±φ)
  16860. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  16861. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  16862. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  16863. 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];
  16864. super(vertices, indices, radius, detail);
  16865. this.type = 'DodecahedronGeometry';
  16866. this.parameters = {
  16867. radius: radius,
  16868. detail: detail
  16869. };
  16870. }
  16871. static fromJSON(data) {
  16872. return new DodecahedronGeometry(data.radius, data.detail);
  16873. }
  16874. }
  16875. const _v0 = new Vector3();
  16876. const _v1$1 = new Vector3();
  16877. const _normal = new Vector3();
  16878. const _triangle = new Triangle();
  16879. class EdgesGeometry extends BufferGeometry {
  16880. constructor(geometry, thresholdAngle) {
  16881. super();
  16882. this.type = 'EdgesGeometry';
  16883. this.parameters = {
  16884. thresholdAngle: thresholdAngle
  16885. };
  16886. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1;
  16887. if (geometry.isGeometry === true) {
  16888. console.error('THREE.EdgesGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16889. return;
  16890. }
  16891. const thresholdDot = Math.cos(DEG2RAD * thresholdAngle);
  16892. const indexAttr = geometry.getIndex();
  16893. const positionAttr = geometry.getAttribute('position');
  16894. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  16895. const indexArr = [0, 0, 0];
  16896. const vertKeys = ['a', 'b', 'c'];
  16897. const hashes = new Array(3);
  16898. const edgeData = {};
  16899. const vertices = [];
  16900. for (let i = 0; i < indexCount; i += 3) {
  16901. if (indexAttr) {
  16902. indexArr[0] = indexAttr.getX(i);
  16903. indexArr[1] = indexAttr.getX(i + 1);
  16904. indexArr[2] = indexAttr.getX(i + 2);
  16905. } else {
  16906. indexArr[0] = i;
  16907. indexArr[1] = i + 1;
  16908. indexArr[2] = i + 2;
  16909. }
  16910. const {
  16911. a,
  16912. b,
  16913. c
  16914. } = _triangle;
  16915. a.fromBufferAttribute(positionAttr, indexArr[0]);
  16916. b.fromBufferAttribute(positionAttr, indexArr[1]);
  16917. c.fromBufferAttribute(positionAttr, indexArr[2]);
  16918. _triangle.getNormal(_normal); // create hashes for the edge from the vertices
  16919. hashes[0] = `${a.x},${a.y},${a.z}`;
  16920. hashes[1] = `${b.x},${b.y},${b.z}`;
  16921. hashes[2] = `${c.x},${c.y},${c.z}`; // skip degenerate triangles
  16922. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  16923. continue;
  16924. } // iterate over every edge
  16925. for (let j = 0; j < 3; j++) {
  16926. // get the first and next vertex making up the edge
  16927. const jNext = (j + 1) % 3;
  16928. const vecHash0 = hashes[j];
  16929. const vecHash1 = hashes[jNext];
  16930. const v0 = _triangle[vertKeys[j]];
  16931. const v1 = _triangle[vertKeys[jNext]];
  16932. const hash = `${vecHash0}_${vecHash1}`;
  16933. const reverseHash = `${vecHash1}_${vecHash0}`;
  16934. if (reverseHash in edgeData && edgeData[reverseHash]) {
  16935. // if we found a sibling edge add it into the vertex array if
  16936. // it meets the angle threshold and delete the edge from the map.
  16937. if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  16938. vertices.push(v0.x, v0.y, v0.z);
  16939. vertices.push(v1.x, v1.y, v1.z);
  16940. }
  16941. edgeData[reverseHash] = null;
  16942. } else if (!(hash in edgeData)) {
  16943. // if we've already got an edge here then skip adding a new one
  16944. edgeData[hash] = {
  16945. index0: indexArr[j],
  16946. index1: indexArr[jNext],
  16947. normal: _normal.clone()
  16948. };
  16949. }
  16950. }
  16951. } // iterate over all remaining, unmatched edges and add them to the vertex array
  16952. for (const key in edgeData) {
  16953. if (edgeData[key]) {
  16954. const {
  16955. index0,
  16956. index1
  16957. } = edgeData[key];
  16958. _v0.fromBufferAttribute(positionAttr, index0);
  16959. _v1$1.fromBufferAttribute(positionAttr, index1);
  16960. vertices.push(_v0.x, _v0.y, _v0.z);
  16961. vertices.push(_v1$1.x, _v1$1.y, _v1$1.z);
  16962. }
  16963. }
  16964. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  16965. }
  16966. }
  16967. /**
  16968. * Extensible curve object.
  16969. *
  16970. * Some common of curve methods:
  16971. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  16972. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  16973. * .getPoints(), .getSpacedPoints()
  16974. * .getLength()
  16975. * .updateArcLengths()
  16976. *
  16977. * This following curves inherit from THREE.Curve:
  16978. *
  16979. * -- 2D curves --
  16980. * THREE.ArcCurve
  16981. * THREE.CubicBezierCurve
  16982. * THREE.EllipseCurve
  16983. * THREE.LineCurve
  16984. * THREE.QuadraticBezierCurve
  16985. * THREE.SplineCurve
  16986. *
  16987. * -- 3D curves --
  16988. * THREE.CatmullRomCurve3
  16989. * THREE.CubicBezierCurve3
  16990. * THREE.LineCurve3
  16991. * THREE.QuadraticBezierCurve3
  16992. *
  16993. * A series of curves can be represented as a THREE.CurvePath.
  16994. *
  16995. **/
  16996. class Curve {
  16997. constructor() {
  16998. this.type = 'Curve';
  16999. this.arcLengthDivisions = 200;
  17000. } // Virtual base class method to overwrite and implement in subclasses
  17001. // - t [0 .. 1]
  17002. getPoint()
  17003. /* t, optionalTarget */
  17004. {
  17005. console.warn('THREE.Curve: .getPoint() not implemented.');
  17006. return null;
  17007. } // Get point at relative position in curve according to arc length
  17008. // - u [0 .. 1]
  17009. getPointAt(u, optionalTarget) {
  17010. const t = this.getUtoTmapping(u);
  17011. return this.getPoint(t, optionalTarget);
  17012. } // Get sequence of points using getPoint( t )
  17013. getPoints(divisions = 5) {
  17014. const points = [];
  17015. for (let d = 0; d <= divisions; d++) {
  17016. points.push(this.getPoint(d / divisions));
  17017. }
  17018. return points;
  17019. } // Get sequence of points using getPointAt( u )
  17020. getSpacedPoints(divisions = 5) {
  17021. const points = [];
  17022. for (let d = 0; d <= divisions; d++) {
  17023. points.push(this.getPointAt(d / divisions));
  17024. }
  17025. return points;
  17026. } // Get total curve arc length
  17027. getLength() {
  17028. const lengths = this.getLengths();
  17029. return lengths[lengths.length - 1];
  17030. } // Get list of cumulative segment lengths
  17031. getLengths(divisions = this.arcLengthDivisions) {
  17032. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  17033. return this.cacheArcLengths;
  17034. }
  17035. this.needsUpdate = false;
  17036. const cache = [];
  17037. let current,
  17038. last = this.getPoint(0);
  17039. let sum = 0;
  17040. cache.push(0);
  17041. for (let p = 1; p <= divisions; p++) {
  17042. current = this.getPoint(p / divisions);
  17043. sum += current.distanceTo(last);
  17044. cache.push(sum);
  17045. last = current;
  17046. }
  17047. this.cacheArcLengths = cache;
  17048. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  17049. }
  17050. updateArcLengths() {
  17051. this.needsUpdate = true;
  17052. this.getLengths();
  17053. } // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  17054. getUtoTmapping(u, distance) {
  17055. const arcLengths = this.getLengths();
  17056. let i = 0;
  17057. const il = arcLengths.length;
  17058. let targetArcLength; // The targeted u distance value to get
  17059. if (distance) {
  17060. targetArcLength = distance;
  17061. } else {
  17062. targetArcLength = u * arcLengths[il - 1];
  17063. } // binary search for the index with largest value smaller than target u distance
  17064. let low = 0,
  17065. high = il - 1,
  17066. comparison;
  17067. while (low <= high) {
  17068. 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
  17069. comparison = arcLengths[i] - targetArcLength;
  17070. if (comparison < 0) {
  17071. low = i + 1;
  17072. } else if (comparison > 0) {
  17073. high = i - 1;
  17074. } else {
  17075. high = i;
  17076. break; // DONE
  17077. }
  17078. }
  17079. i = high;
  17080. if (arcLengths[i] === targetArcLength) {
  17081. return i / (il - 1);
  17082. } // we could get finer grain at lengths, or use simple interpolation between two points
  17083. const lengthBefore = arcLengths[i];
  17084. const lengthAfter = arcLengths[i + 1];
  17085. const segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  17086. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  17087. const t = (i + segmentFraction) / (il - 1);
  17088. return t;
  17089. } // Returns a unit vector tangent at t
  17090. // In case any sub curve does not implement its tangent derivation,
  17091. // 2 points a small delta apart will be used to find its gradient
  17092. // which seems to give a reasonable approximation
  17093. getTangent(t, optionalTarget) {
  17094. const delta = 0.0001;
  17095. let t1 = t - delta;
  17096. let t2 = t + delta; // Capping in case of danger
  17097. if (t1 < 0) t1 = 0;
  17098. if (t2 > 1) t2 = 1;
  17099. const pt1 = this.getPoint(t1);
  17100. const pt2 = this.getPoint(t2);
  17101. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  17102. tangent.copy(pt2).sub(pt1).normalize();
  17103. return tangent;
  17104. }
  17105. getTangentAt(u, optionalTarget) {
  17106. const t = this.getUtoTmapping(u);
  17107. return this.getTangent(t, optionalTarget);
  17108. }
  17109. computeFrenetFrames(segments, closed) {
  17110. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  17111. const normal = new Vector3();
  17112. const tangents = [];
  17113. const normals = [];
  17114. const binormals = [];
  17115. const vec = new Vector3();
  17116. const mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  17117. for (let i = 0; i <= segments; i++) {
  17118. const u = i / segments;
  17119. tangents[i] = this.getTangentAt(u, new Vector3());
  17120. tangents[i].normalize();
  17121. } // select an initial normal vector perpendicular to the first tangent vector,
  17122. // and in the direction of the minimum tangent xyz component
  17123. normals[0] = new Vector3();
  17124. binormals[0] = new Vector3();
  17125. let min = Number.MAX_VALUE;
  17126. const tx = Math.abs(tangents[0].x);
  17127. const ty = Math.abs(tangents[0].y);
  17128. const tz = Math.abs(tangents[0].z);
  17129. if (tx <= min) {
  17130. min = tx;
  17131. normal.set(1, 0, 0);
  17132. }
  17133. if (ty <= min) {
  17134. min = ty;
  17135. normal.set(0, 1, 0);
  17136. }
  17137. if (tz <= min) {
  17138. normal.set(0, 0, 1);
  17139. }
  17140. vec.crossVectors(tangents[0], normal).normalize();
  17141. normals[0].crossVectors(tangents[0], vec);
  17142. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  17143. for (let i = 1; i <= segments; i++) {
  17144. normals[i] = normals[i - 1].clone();
  17145. binormals[i] = binormals[i - 1].clone();
  17146. vec.crossVectors(tangents[i - 1], tangents[i]);
  17147. if (vec.length() > Number.EPSILON) {
  17148. vec.normalize();
  17149. const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  17150. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  17151. }
  17152. binormals[i].crossVectors(tangents[i], normals[i]);
  17153. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  17154. if (closed === true) {
  17155. let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1));
  17156. theta /= segments;
  17157. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  17158. theta = -theta;
  17159. }
  17160. for (let i = 1; i <= segments; i++) {
  17161. // twist a little...
  17162. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  17163. binormals[i].crossVectors(tangents[i], normals[i]);
  17164. }
  17165. }
  17166. return {
  17167. tangents: tangents,
  17168. normals: normals,
  17169. binormals: binormals
  17170. };
  17171. }
  17172. clone() {
  17173. return new this.constructor().copy(this);
  17174. }
  17175. copy(source) {
  17176. this.arcLengthDivisions = source.arcLengthDivisions;
  17177. return this;
  17178. }
  17179. toJSON() {
  17180. const data = {
  17181. metadata: {
  17182. version: 4.5,
  17183. type: 'Curve',
  17184. generator: 'Curve.toJSON'
  17185. }
  17186. };
  17187. data.arcLengthDivisions = this.arcLengthDivisions;
  17188. data.type = this.type;
  17189. return data;
  17190. }
  17191. fromJSON(json) {
  17192. this.arcLengthDivisions = json.arcLengthDivisions;
  17193. return this;
  17194. }
  17195. }
  17196. class EllipseCurve extends Curve {
  17197. constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) {
  17198. super();
  17199. this.type = 'EllipseCurve';
  17200. this.aX = aX;
  17201. this.aY = aY;
  17202. this.xRadius = xRadius;
  17203. this.yRadius = yRadius;
  17204. this.aStartAngle = aStartAngle;
  17205. this.aEndAngle = aEndAngle;
  17206. this.aClockwise = aClockwise;
  17207. this.aRotation = aRotation;
  17208. }
  17209. getPoint(t, optionalTarget) {
  17210. const point = optionalTarget || new Vector2();
  17211. const twoPi = Math.PI * 2;
  17212. let deltaAngle = this.aEndAngle - this.aStartAngle;
  17213. const samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  17214. while (deltaAngle < 0) deltaAngle += twoPi;
  17215. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  17216. if (deltaAngle < Number.EPSILON) {
  17217. if (samePoints) {
  17218. deltaAngle = 0;
  17219. } else {
  17220. deltaAngle = twoPi;
  17221. }
  17222. }
  17223. if (this.aClockwise === true && !samePoints) {
  17224. if (deltaAngle === twoPi) {
  17225. deltaAngle = -twoPi;
  17226. } else {
  17227. deltaAngle = deltaAngle - twoPi;
  17228. }
  17229. }
  17230. const angle = this.aStartAngle + t * deltaAngle;
  17231. let x = this.aX + this.xRadius * Math.cos(angle);
  17232. let y = this.aY + this.yRadius * Math.sin(angle);
  17233. if (this.aRotation !== 0) {
  17234. const cos = Math.cos(this.aRotation);
  17235. const sin = Math.sin(this.aRotation);
  17236. const tx = x - this.aX;
  17237. const ty = y - this.aY; // Rotate the point about the center of the ellipse.
  17238. x = tx * cos - ty * sin + this.aX;
  17239. y = tx * sin + ty * cos + this.aY;
  17240. }
  17241. return point.set(x, y);
  17242. }
  17243. copy(source) {
  17244. super.copy(source);
  17245. this.aX = source.aX;
  17246. this.aY = source.aY;
  17247. this.xRadius = source.xRadius;
  17248. this.yRadius = source.yRadius;
  17249. this.aStartAngle = source.aStartAngle;
  17250. this.aEndAngle = source.aEndAngle;
  17251. this.aClockwise = source.aClockwise;
  17252. this.aRotation = source.aRotation;
  17253. return this;
  17254. }
  17255. toJSON() {
  17256. const data = super.toJSON();
  17257. data.aX = this.aX;
  17258. data.aY = this.aY;
  17259. data.xRadius = this.xRadius;
  17260. data.yRadius = this.yRadius;
  17261. data.aStartAngle = this.aStartAngle;
  17262. data.aEndAngle = this.aEndAngle;
  17263. data.aClockwise = this.aClockwise;
  17264. data.aRotation = this.aRotation;
  17265. return data;
  17266. }
  17267. fromJSON(json) {
  17268. super.fromJSON(json);
  17269. this.aX = json.aX;
  17270. this.aY = json.aY;
  17271. this.xRadius = json.xRadius;
  17272. this.yRadius = json.yRadius;
  17273. this.aStartAngle = json.aStartAngle;
  17274. this.aEndAngle = json.aEndAngle;
  17275. this.aClockwise = json.aClockwise;
  17276. this.aRotation = json.aRotation;
  17277. return this;
  17278. }
  17279. }
  17280. EllipseCurve.prototype.isEllipseCurve = true;
  17281. class ArcCurve extends EllipseCurve {
  17282. constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  17283. super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17284. this.type = 'ArcCurve';
  17285. }
  17286. }
  17287. ArcCurve.prototype.isArcCurve = true;
  17288. /**
  17289. * Centripetal CatmullRom Curve - which is useful for avoiding
  17290. * cusps and self-intersections in non-uniform catmull rom curves.
  17291. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  17292. *
  17293. * curve.type accepts centripetal(default), chordal and catmullrom
  17294. * curve.tension is used for catmullrom which defaults to 0.5
  17295. */
  17296. /*
  17297. Based on an optimized c++ solution in
  17298. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  17299. - http://ideone.com/NoEbVM
  17300. This CubicPoly class could be used for reusing some variables and calculations,
  17301. but for three.js curve use, it could be possible inlined and flatten into a single function call
  17302. which can be placed in CurveUtils.
  17303. */
  17304. function CubicPoly() {
  17305. let c0 = 0,
  17306. c1 = 0,
  17307. c2 = 0,
  17308. c3 = 0;
  17309. /*
  17310. * Compute coefficients for a cubic polynomial
  17311. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  17312. * such that
  17313. * p(0) = x0, p(1) = x1
  17314. * and
  17315. * p'(0) = t0, p'(1) = t1.
  17316. */
  17317. function init(x0, x1, t0, t1) {
  17318. c0 = x0;
  17319. c1 = t0;
  17320. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  17321. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  17322. }
  17323. return {
  17324. initCatmullRom: function (x0, x1, x2, x3, tension) {
  17325. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  17326. },
  17327. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  17328. // compute tangents when parameterized in [t1,t2]
  17329. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  17330. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  17331. t1 *= dt1;
  17332. t2 *= dt1;
  17333. init(x1, x2, t1, t2);
  17334. },
  17335. calc: function (t) {
  17336. const t2 = t * t;
  17337. const t3 = t2 * t;
  17338. return c0 + c1 * t + c2 * t2 + c3 * t3;
  17339. }
  17340. };
  17341. } //
  17342. const tmp = new Vector3();
  17343. const px = new CubicPoly(),
  17344. py = new CubicPoly(),
  17345. pz = new CubicPoly();
  17346. class CatmullRomCurve3 extends Curve {
  17347. constructor(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  17348. super();
  17349. this.type = 'CatmullRomCurve3';
  17350. this.points = points;
  17351. this.closed = closed;
  17352. this.curveType = curveType;
  17353. this.tension = tension;
  17354. }
  17355. getPoint(t, optionalTarget = new Vector3()) {
  17356. const point = optionalTarget;
  17357. const points = this.points;
  17358. const l = points.length;
  17359. const p = (l - (this.closed ? 0 : 1)) * t;
  17360. let intPoint = Math.floor(p);
  17361. let weight = p - intPoint;
  17362. if (this.closed) {
  17363. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  17364. } else if (weight === 0 && intPoint === l - 1) {
  17365. intPoint = l - 2;
  17366. weight = 1;
  17367. }
  17368. let p0, p3; // 4 points (p1 & p2 defined below)
  17369. if (this.closed || intPoint > 0) {
  17370. p0 = points[(intPoint - 1) % l];
  17371. } else {
  17372. // extrapolate first point
  17373. tmp.subVectors(points[0], points[1]).add(points[0]);
  17374. p0 = tmp;
  17375. }
  17376. const p1 = points[intPoint % l];
  17377. const p2 = points[(intPoint + 1) % l];
  17378. if (this.closed || intPoint + 2 < l) {
  17379. p3 = points[(intPoint + 2) % l];
  17380. } else {
  17381. // extrapolate last point
  17382. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  17383. p3 = tmp;
  17384. }
  17385. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  17386. // init Centripetal / Chordal Catmull-Rom
  17387. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  17388. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  17389. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  17390. let dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  17391. if (dt1 < 1e-4) dt1 = 1.0;
  17392. if (dt0 < 1e-4) dt0 = dt1;
  17393. if (dt2 < 1e-4) dt2 = dt1;
  17394. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  17395. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  17396. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  17397. } else if (this.curveType === 'catmullrom') {
  17398. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  17399. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  17400. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  17401. }
  17402. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  17403. return point;
  17404. }
  17405. copy(source) {
  17406. super.copy(source);
  17407. this.points = [];
  17408. for (let i = 0, l = source.points.length; i < l; i++) {
  17409. const point = source.points[i];
  17410. this.points.push(point.clone());
  17411. }
  17412. this.closed = source.closed;
  17413. this.curveType = source.curveType;
  17414. this.tension = source.tension;
  17415. return this;
  17416. }
  17417. toJSON() {
  17418. const data = super.toJSON();
  17419. data.points = [];
  17420. for (let i = 0, l = this.points.length; i < l; i++) {
  17421. const point = this.points[i];
  17422. data.points.push(point.toArray());
  17423. }
  17424. data.closed = this.closed;
  17425. data.curveType = this.curveType;
  17426. data.tension = this.tension;
  17427. return data;
  17428. }
  17429. fromJSON(json) {
  17430. super.fromJSON(json);
  17431. this.points = [];
  17432. for (let i = 0, l = json.points.length; i < l; i++) {
  17433. const point = json.points[i];
  17434. this.points.push(new Vector3().fromArray(point));
  17435. }
  17436. this.closed = json.closed;
  17437. this.curveType = json.curveType;
  17438. this.tension = json.tension;
  17439. return this;
  17440. }
  17441. }
  17442. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  17443. /**
  17444. * Bezier Curves formulas obtained from
  17445. * http://en.wikipedia.org/wiki/Bézier_curve
  17446. */
  17447. function CatmullRom(t, p0, p1, p2, p3) {
  17448. const v0 = (p2 - p0) * 0.5;
  17449. const v1 = (p3 - p1) * 0.5;
  17450. const t2 = t * t;
  17451. const t3 = t * t2;
  17452. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  17453. } //
  17454. function QuadraticBezierP0(t, p) {
  17455. const k = 1 - t;
  17456. return k * k * p;
  17457. }
  17458. function QuadraticBezierP1(t, p) {
  17459. return 2 * (1 - t) * t * p;
  17460. }
  17461. function QuadraticBezierP2(t, p) {
  17462. return t * t * p;
  17463. }
  17464. function QuadraticBezier(t, p0, p1, p2) {
  17465. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  17466. } //
  17467. function CubicBezierP0(t, p) {
  17468. const k = 1 - t;
  17469. return k * k * k * p;
  17470. }
  17471. function CubicBezierP1(t, p) {
  17472. const k = 1 - t;
  17473. return 3 * k * k * t * p;
  17474. }
  17475. function CubicBezierP2(t, p) {
  17476. return 3 * (1 - t) * t * t * p;
  17477. }
  17478. function CubicBezierP3(t, p) {
  17479. return t * t * t * p;
  17480. }
  17481. function CubicBezier(t, p0, p1, p2, p3) {
  17482. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  17483. }
  17484. class CubicBezierCurve extends Curve {
  17485. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  17486. super();
  17487. this.type = 'CubicBezierCurve';
  17488. this.v0 = v0;
  17489. this.v1 = v1;
  17490. this.v2 = v2;
  17491. this.v3 = v3;
  17492. }
  17493. getPoint(t, optionalTarget = new Vector2()) {
  17494. const point = optionalTarget;
  17495. const v0 = this.v0,
  17496. v1 = this.v1,
  17497. v2 = this.v2,
  17498. v3 = this.v3;
  17499. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  17500. return point;
  17501. }
  17502. copy(source) {
  17503. super.copy(source);
  17504. this.v0.copy(source.v0);
  17505. this.v1.copy(source.v1);
  17506. this.v2.copy(source.v2);
  17507. this.v3.copy(source.v3);
  17508. return this;
  17509. }
  17510. toJSON() {
  17511. const data = super.toJSON();
  17512. data.v0 = this.v0.toArray();
  17513. data.v1 = this.v1.toArray();
  17514. data.v2 = this.v2.toArray();
  17515. data.v3 = this.v3.toArray();
  17516. return data;
  17517. }
  17518. fromJSON(json) {
  17519. super.fromJSON(json);
  17520. this.v0.fromArray(json.v0);
  17521. this.v1.fromArray(json.v1);
  17522. this.v2.fromArray(json.v2);
  17523. this.v3.fromArray(json.v3);
  17524. return this;
  17525. }
  17526. }
  17527. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  17528. class CubicBezierCurve3 extends Curve {
  17529. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  17530. super();
  17531. this.type = 'CubicBezierCurve3';
  17532. this.v0 = v0;
  17533. this.v1 = v1;
  17534. this.v2 = v2;
  17535. this.v3 = v3;
  17536. }
  17537. getPoint(t, optionalTarget = new Vector3()) {
  17538. const point = optionalTarget;
  17539. const v0 = this.v0,
  17540. v1 = this.v1,
  17541. v2 = this.v2,
  17542. v3 = this.v3;
  17543. 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));
  17544. return point;
  17545. }
  17546. copy(source) {
  17547. super.copy(source);
  17548. this.v0.copy(source.v0);
  17549. this.v1.copy(source.v1);
  17550. this.v2.copy(source.v2);
  17551. this.v3.copy(source.v3);
  17552. return this;
  17553. }
  17554. toJSON() {
  17555. const data = super.toJSON();
  17556. data.v0 = this.v0.toArray();
  17557. data.v1 = this.v1.toArray();
  17558. data.v2 = this.v2.toArray();
  17559. data.v3 = this.v3.toArray();
  17560. return data;
  17561. }
  17562. fromJSON(json) {
  17563. super.fromJSON(json);
  17564. this.v0.fromArray(json.v0);
  17565. this.v1.fromArray(json.v1);
  17566. this.v2.fromArray(json.v2);
  17567. this.v3.fromArray(json.v3);
  17568. return this;
  17569. }
  17570. }
  17571. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  17572. class LineCurve extends Curve {
  17573. constructor(v1 = new Vector2(), v2 = new Vector2()) {
  17574. super();
  17575. this.type = 'LineCurve';
  17576. this.v1 = v1;
  17577. this.v2 = v2;
  17578. }
  17579. getPoint(t, optionalTarget = new Vector2()) {
  17580. const point = optionalTarget;
  17581. if (t === 1) {
  17582. point.copy(this.v2);
  17583. } else {
  17584. point.copy(this.v2).sub(this.v1);
  17585. point.multiplyScalar(t).add(this.v1);
  17586. }
  17587. return point;
  17588. } // Line curve is linear, so we can overwrite default getPointAt
  17589. getPointAt(u, optionalTarget) {
  17590. return this.getPoint(u, optionalTarget);
  17591. }
  17592. getTangent(t, optionalTarget) {
  17593. const tangent = optionalTarget || new Vector2();
  17594. tangent.copy(this.v2).sub(this.v1).normalize();
  17595. return tangent;
  17596. }
  17597. copy(source) {
  17598. super.copy(source);
  17599. this.v1.copy(source.v1);
  17600. this.v2.copy(source.v2);
  17601. return this;
  17602. }
  17603. toJSON() {
  17604. const data = super.toJSON();
  17605. data.v1 = this.v1.toArray();
  17606. data.v2 = this.v2.toArray();
  17607. return data;
  17608. }
  17609. fromJSON(json) {
  17610. super.fromJSON(json);
  17611. this.v1.fromArray(json.v1);
  17612. this.v2.fromArray(json.v2);
  17613. return this;
  17614. }
  17615. }
  17616. LineCurve.prototype.isLineCurve = true;
  17617. class LineCurve3 extends Curve {
  17618. constructor(v1 = new Vector3(), v2 = new Vector3()) {
  17619. super();
  17620. this.type = 'LineCurve3';
  17621. this.isLineCurve3 = true;
  17622. this.v1 = v1;
  17623. this.v2 = v2;
  17624. }
  17625. getPoint(t, optionalTarget = new Vector3()) {
  17626. const point = optionalTarget;
  17627. if (t === 1) {
  17628. point.copy(this.v2);
  17629. } else {
  17630. point.copy(this.v2).sub(this.v1);
  17631. point.multiplyScalar(t).add(this.v1);
  17632. }
  17633. return point;
  17634. } // Line curve is linear, so we can overwrite default getPointAt
  17635. getPointAt(u, optionalTarget) {
  17636. return this.getPoint(u, optionalTarget);
  17637. }
  17638. copy(source) {
  17639. super.copy(source);
  17640. this.v1.copy(source.v1);
  17641. this.v2.copy(source.v2);
  17642. return this;
  17643. }
  17644. toJSON() {
  17645. const data = super.toJSON();
  17646. data.v1 = this.v1.toArray();
  17647. data.v2 = this.v2.toArray();
  17648. return data;
  17649. }
  17650. fromJSON(json) {
  17651. super.fromJSON(json);
  17652. this.v1.fromArray(json.v1);
  17653. this.v2.fromArray(json.v2);
  17654. return this;
  17655. }
  17656. }
  17657. class QuadraticBezierCurve extends Curve {
  17658. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  17659. super();
  17660. this.type = 'QuadraticBezierCurve';
  17661. this.v0 = v0;
  17662. this.v1 = v1;
  17663. this.v2 = v2;
  17664. }
  17665. getPoint(t, optionalTarget = new Vector2()) {
  17666. const point = optionalTarget;
  17667. const v0 = this.v0,
  17668. v1 = this.v1,
  17669. v2 = this.v2;
  17670. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  17671. return point;
  17672. }
  17673. copy(source) {
  17674. super.copy(source);
  17675. this.v0.copy(source.v0);
  17676. this.v1.copy(source.v1);
  17677. this.v2.copy(source.v2);
  17678. return this;
  17679. }
  17680. toJSON() {
  17681. const data = super.toJSON();
  17682. data.v0 = this.v0.toArray();
  17683. data.v1 = this.v1.toArray();
  17684. data.v2 = this.v2.toArray();
  17685. return data;
  17686. }
  17687. fromJSON(json) {
  17688. super.fromJSON(json);
  17689. this.v0.fromArray(json.v0);
  17690. this.v1.fromArray(json.v1);
  17691. this.v2.fromArray(json.v2);
  17692. return this;
  17693. }
  17694. }
  17695. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  17696. class QuadraticBezierCurve3 extends Curve {
  17697. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  17698. super();
  17699. this.type = 'QuadraticBezierCurve3';
  17700. this.v0 = v0;
  17701. this.v1 = v1;
  17702. this.v2 = v2;
  17703. }
  17704. getPoint(t, optionalTarget = new Vector3()) {
  17705. const point = optionalTarget;
  17706. const v0 = this.v0,
  17707. v1 = this.v1,
  17708. v2 = this.v2;
  17709. 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));
  17710. return point;
  17711. }
  17712. copy(source) {
  17713. super.copy(source);
  17714. this.v0.copy(source.v0);
  17715. this.v1.copy(source.v1);
  17716. this.v2.copy(source.v2);
  17717. return this;
  17718. }
  17719. toJSON() {
  17720. const data = super.toJSON();
  17721. data.v0 = this.v0.toArray();
  17722. data.v1 = this.v1.toArray();
  17723. data.v2 = this.v2.toArray();
  17724. return data;
  17725. }
  17726. fromJSON(json) {
  17727. super.fromJSON(json);
  17728. this.v0.fromArray(json.v0);
  17729. this.v1.fromArray(json.v1);
  17730. this.v2.fromArray(json.v2);
  17731. return this;
  17732. }
  17733. }
  17734. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  17735. class SplineCurve extends Curve {
  17736. constructor(points = []) {
  17737. super();
  17738. this.type = 'SplineCurve';
  17739. this.points = points;
  17740. }
  17741. getPoint(t, optionalTarget = new Vector2()) {
  17742. const point = optionalTarget;
  17743. const points = this.points;
  17744. const p = (points.length - 1) * t;
  17745. const intPoint = Math.floor(p);
  17746. const weight = p - intPoint;
  17747. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  17748. const p1 = points[intPoint];
  17749. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  17750. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  17751. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  17752. return point;
  17753. }
  17754. copy(source) {
  17755. super.copy(source);
  17756. this.points = [];
  17757. for (let i = 0, l = source.points.length; i < l; i++) {
  17758. const point = source.points[i];
  17759. this.points.push(point.clone());
  17760. }
  17761. return this;
  17762. }
  17763. toJSON() {
  17764. const data = super.toJSON();
  17765. data.points = [];
  17766. for (let i = 0, l = this.points.length; i < l; i++) {
  17767. const point = this.points[i];
  17768. data.points.push(point.toArray());
  17769. }
  17770. return data;
  17771. }
  17772. fromJSON(json) {
  17773. super.fromJSON(json);
  17774. this.points = [];
  17775. for (let i = 0, l = json.points.length; i < l; i++) {
  17776. const point = json.points[i];
  17777. this.points.push(new Vector2().fromArray(point));
  17778. }
  17779. return this;
  17780. }
  17781. }
  17782. SplineCurve.prototype.isSplineCurve = true;
  17783. var Curves = /*#__PURE__*/Object.freeze({
  17784. __proto__: null,
  17785. ArcCurve: ArcCurve,
  17786. CatmullRomCurve3: CatmullRomCurve3,
  17787. CubicBezierCurve: CubicBezierCurve,
  17788. CubicBezierCurve3: CubicBezierCurve3,
  17789. EllipseCurve: EllipseCurve,
  17790. LineCurve: LineCurve,
  17791. LineCurve3: LineCurve3,
  17792. QuadraticBezierCurve: QuadraticBezierCurve,
  17793. QuadraticBezierCurve3: QuadraticBezierCurve3,
  17794. SplineCurve: SplineCurve
  17795. });
  17796. /**
  17797. * Port from https://github.com/mapbox/earcut (v2.2.2)
  17798. */
  17799. const Earcut = {
  17800. triangulate: function (data, holeIndices, dim = 2) {
  17801. const hasHoles = holeIndices && holeIndices.length;
  17802. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  17803. let outerNode = linkedList(data, 0, outerLen, dim, true);
  17804. const triangles = [];
  17805. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  17806. let minX, minY, maxX, maxY, x, y, invSize;
  17807. 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
  17808. if (data.length > 80 * dim) {
  17809. minX = maxX = data[0];
  17810. minY = maxY = data[1];
  17811. for (let i = dim; i < outerLen; i += dim) {
  17812. x = data[i];
  17813. y = data[i + 1];
  17814. if (x < minX) minX = x;
  17815. if (y < minY) minY = y;
  17816. if (x > maxX) maxX = x;
  17817. if (y > maxY) maxY = y;
  17818. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  17819. invSize = Math.max(maxX - minX, maxY - minY);
  17820. invSize = invSize !== 0 ? 1 / invSize : 0;
  17821. }
  17822. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  17823. return triangles;
  17824. }
  17825. }; // create a circular doubly linked list from polygon points in the specified winding order
  17826. function linkedList(data, start, end, dim, clockwise) {
  17827. let i, last;
  17828. if (clockwise === signedArea(data, start, end, dim) > 0) {
  17829. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  17830. } else {
  17831. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  17832. }
  17833. if (last && equals(last, last.next)) {
  17834. removeNode(last);
  17835. last = last.next;
  17836. }
  17837. return last;
  17838. } // eliminate colinear or duplicate points
  17839. function filterPoints(start, end) {
  17840. if (!start) return start;
  17841. if (!end) end = start;
  17842. let p = start,
  17843. again;
  17844. do {
  17845. again = false;
  17846. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  17847. removeNode(p);
  17848. p = end = p.prev;
  17849. if (p === p.next) break;
  17850. again = true;
  17851. } else {
  17852. p = p.next;
  17853. }
  17854. } while (again || p !== end);
  17855. return end;
  17856. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  17857. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  17858. if (!ear) return; // interlink polygon nodes in z-order
  17859. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  17860. let stop = ear,
  17861. prev,
  17862. next; // iterate through ears, slicing them one by one
  17863. while (ear.prev !== ear.next) {
  17864. prev = ear.prev;
  17865. next = ear.next;
  17866. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  17867. // cut off the triangle
  17868. triangles.push(prev.i / dim);
  17869. triangles.push(ear.i / dim);
  17870. triangles.push(next.i / dim);
  17871. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  17872. ear = next.next;
  17873. stop = next.next;
  17874. continue;
  17875. }
  17876. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  17877. if (ear === stop) {
  17878. // try filtering points and slicing again
  17879. if (!pass) {
  17880. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  17881. } else if (pass === 1) {
  17882. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  17883. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  17884. } else if (pass === 2) {
  17885. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  17886. }
  17887. break;
  17888. }
  17889. }
  17890. } // check whether a polygon node forms a valid ear with adjacent nodes
  17891. function isEar(ear) {
  17892. const a = ear.prev,
  17893. b = ear,
  17894. c = ear.next;
  17895. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  17896. // now make sure we don't have other points inside the potential ear
  17897. let p = ear.next.next;
  17898. while (p !== ear.prev) {
  17899. 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;
  17900. p = p.next;
  17901. }
  17902. return true;
  17903. }
  17904. function isEarHashed(ear, minX, minY, invSize) {
  17905. const a = ear.prev,
  17906. b = ear,
  17907. c = ear.next;
  17908. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  17909. // triangle bbox; min & max are calculated like this for speed
  17910. const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  17911. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  17912. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  17913. 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;
  17914. const minZ = zOrder(minTX, minTY, minX, minY, invSize),
  17915. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  17916. let p = ear.prevZ,
  17917. n = ear.nextZ; // look for points inside the triangle in both directions
  17918. while (p && p.z >= minZ && n && n.z <= maxZ) {
  17919. 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;
  17920. p = p.prevZ;
  17921. 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;
  17922. n = n.nextZ;
  17923. } // look for remaining points in decreasing z-order
  17924. while (p && p.z >= minZ) {
  17925. 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;
  17926. p = p.prevZ;
  17927. } // look for remaining points in increasing z-order
  17928. while (n && n.z <= maxZ) {
  17929. 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;
  17930. n = n.nextZ;
  17931. }
  17932. return true;
  17933. } // go through all polygon nodes and cure small local self-intersections
  17934. function cureLocalIntersections(start, triangles, dim) {
  17935. let p = start;
  17936. do {
  17937. const a = p.prev,
  17938. b = p.next.next;
  17939. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  17940. triangles.push(a.i / dim);
  17941. triangles.push(p.i / dim);
  17942. triangles.push(b.i / dim); // remove two nodes involved
  17943. removeNode(p);
  17944. removeNode(p.next);
  17945. p = start = b;
  17946. }
  17947. p = p.next;
  17948. } while (p !== start);
  17949. return filterPoints(p);
  17950. } // try splitting polygon into two and triangulate them independently
  17951. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  17952. // look for a valid diagonal that divides the polygon into two
  17953. let a = start;
  17954. do {
  17955. let b = a.next.next;
  17956. while (b !== a.prev) {
  17957. if (a.i !== b.i && isValidDiagonal(a, b)) {
  17958. // split the polygon in two by the diagonal
  17959. let c = splitPolygon(a, b); // filter colinear points around the cuts
  17960. a = filterPoints(a, a.next);
  17961. c = filterPoints(c, c.next); // run earcut on each half
  17962. earcutLinked(a, triangles, dim, minX, minY, invSize);
  17963. earcutLinked(c, triangles, dim, minX, minY, invSize);
  17964. return;
  17965. }
  17966. b = b.next;
  17967. }
  17968. a = a.next;
  17969. } while (a !== start);
  17970. } // link every hole into the outer loop, producing a single-ring polygon without holes
  17971. function eliminateHoles(data, holeIndices, outerNode, dim) {
  17972. const queue = [];
  17973. let i, len, start, end, list;
  17974. for (i = 0, len = holeIndices.length; i < len; i++) {
  17975. start = holeIndices[i] * dim;
  17976. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  17977. list = linkedList(data, start, end, dim, false);
  17978. if (list === list.next) list.steiner = true;
  17979. queue.push(getLeftmost(list));
  17980. }
  17981. queue.sort(compareX); // process holes from left to right
  17982. for (i = 0; i < queue.length; i++) {
  17983. eliminateHole(queue[i], outerNode);
  17984. outerNode = filterPoints(outerNode, outerNode.next);
  17985. }
  17986. return outerNode;
  17987. }
  17988. function compareX(a, b) {
  17989. return a.x - b.x;
  17990. } // find a bridge between vertices that connects hole with an outer ring and and link it
  17991. function eliminateHole(hole, outerNode) {
  17992. outerNode = findHoleBridge(hole, outerNode);
  17993. if (outerNode) {
  17994. const b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  17995. filterPoints(outerNode, outerNode.next);
  17996. filterPoints(b, b.next);
  17997. }
  17998. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  17999. function findHoleBridge(hole, outerNode) {
  18000. let p = outerNode;
  18001. const hx = hole.x;
  18002. const hy = hole.y;
  18003. let qx = -Infinity,
  18004. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  18005. // segment's endpoint with lesser x will be potential connection point
  18006. do {
  18007. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  18008. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  18009. if (x <= hx && x > qx) {
  18010. qx = x;
  18011. if (x === hx) {
  18012. if (hy === p.y) return p;
  18013. if (hy === p.next.y) return p.next;
  18014. }
  18015. m = p.x < p.next.x ? p : p.next;
  18016. }
  18017. }
  18018. p = p.next;
  18019. } while (p !== outerNode);
  18020. if (!m) return null;
  18021. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  18022. // look for points inside the triangle of hole point, segment intersection and endpoint;
  18023. // if there are no points found, we have a valid connection;
  18024. // otherwise choose the point of the minimum angle with the ray as connection point
  18025. const stop = m,
  18026. mx = m.x,
  18027. my = m.y;
  18028. let tanMin = Infinity,
  18029. tan;
  18030. p = m;
  18031. do {
  18032. 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)) {
  18033. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  18034. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  18035. m = p;
  18036. tanMin = tan;
  18037. }
  18038. }
  18039. p = p.next;
  18040. } while (p !== stop);
  18041. return m;
  18042. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  18043. function sectorContainsSector(m, p) {
  18044. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  18045. } // interlink polygon nodes in z-order
  18046. function indexCurve(start, minX, minY, invSize) {
  18047. let p = start;
  18048. do {
  18049. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  18050. p.prevZ = p.prev;
  18051. p.nextZ = p.next;
  18052. p = p.next;
  18053. } while (p !== start);
  18054. p.prevZ.nextZ = null;
  18055. p.prevZ = null;
  18056. sortLinked(p);
  18057. } // Simon Tatham's linked list merge sort algorithm
  18058. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  18059. function sortLinked(list) {
  18060. let i,
  18061. p,
  18062. q,
  18063. e,
  18064. tail,
  18065. numMerges,
  18066. pSize,
  18067. qSize,
  18068. inSize = 1;
  18069. do {
  18070. p = list;
  18071. list = null;
  18072. tail = null;
  18073. numMerges = 0;
  18074. while (p) {
  18075. numMerges++;
  18076. q = p;
  18077. pSize = 0;
  18078. for (i = 0; i < inSize; i++) {
  18079. pSize++;
  18080. q = q.nextZ;
  18081. if (!q) break;
  18082. }
  18083. qSize = inSize;
  18084. while (pSize > 0 || qSize > 0 && q) {
  18085. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  18086. e = p;
  18087. p = p.nextZ;
  18088. pSize--;
  18089. } else {
  18090. e = q;
  18091. q = q.nextZ;
  18092. qSize--;
  18093. }
  18094. if (tail) tail.nextZ = e;else list = e;
  18095. e.prevZ = tail;
  18096. tail = e;
  18097. }
  18098. p = q;
  18099. }
  18100. tail.nextZ = null;
  18101. inSize *= 2;
  18102. } while (numMerges > 1);
  18103. return list;
  18104. } // z-order of a point given coords and inverse of the longer side of data bbox
  18105. function zOrder(x, y, minX, minY, invSize) {
  18106. // coords are transformed into non-negative 15-bit integer range
  18107. x = 32767 * (x - minX) * invSize;
  18108. y = 32767 * (y - minY) * invSize;
  18109. x = (x | x << 8) & 0x00FF00FF;
  18110. x = (x | x << 4) & 0x0F0F0F0F;
  18111. x = (x | x << 2) & 0x33333333;
  18112. x = (x | x << 1) & 0x55555555;
  18113. y = (y | y << 8) & 0x00FF00FF;
  18114. y = (y | y << 4) & 0x0F0F0F0F;
  18115. y = (y | y << 2) & 0x33333333;
  18116. y = (y | y << 1) & 0x55555555;
  18117. return x | y << 1;
  18118. } // find the leftmost node of a polygon ring
  18119. function getLeftmost(start) {
  18120. let p = start,
  18121. leftmost = start;
  18122. do {
  18123. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  18124. p = p.next;
  18125. } while (p !== start);
  18126. return leftmost;
  18127. } // check if a point lies within a convex triangle
  18128. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  18129. 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;
  18130. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  18131. function isValidDiagonal(a, b) {
  18132. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( // dones't intersect other edges
  18133. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && ( // locally visible
  18134. area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  18135. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  18136. } // signed area of a triangle
  18137. function area(p, q, r) {
  18138. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  18139. } // check if two points are equal
  18140. function equals(p1, p2) {
  18141. return p1.x === p2.x && p1.y === p2.y;
  18142. } // check if two segments intersect
  18143. function intersects(p1, q1, p2, q2) {
  18144. const o1 = sign(area(p1, q1, p2));
  18145. const o2 = sign(area(p1, q1, q2));
  18146. const o3 = sign(area(p2, q2, p1));
  18147. const o4 = sign(area(p2, q2, q1));
  18148. if (o1 !== o2 && o3 !== o4) return true; // general case
  18149. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  18150. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  18151. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  18152. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  18153. return false;
  18154. } // for collinear points p, q, r, check if point q lies on segment pr
  18155. function onSegment(p, q, r) {
  18156. 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);
  18157. }
  18158. function sign(num) {
  18159. return num > 0 ? 1 : num < 0 ? -1 : 0;
  18160. } // check if a polygon diagonal intersects any polygon segments
  18161. function intersectsPolygon(a, b) {
  18162. let p = a;
  18163. do {
  18164. 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;
  18165. p = p.next;
  18166. } while (p !== a);
  18167. return false;
  18168. } // check if a polygon diagonal is locally inside the polygon
  18169. function locallyInside(a, b) {
  18170. 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;
  18171. } // check if the middle point of a polygon diagonal is inside the polygon
  18172. function middleInside(a, b) {
  18173. let p = a,
  18174. inside = false;
  18175. const px = (a.x + b.x) / 2,
  18176. py = (a.y + b.y) / 2;
  18177. do {
  18178. 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;
  18179. p = p.next;
  18180. } while (p !== a);
  18181. return inside;
  18182. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  18183. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  18184. function splitPolygon(a, b) {
  18185. const a2 = new Node(a.i, a.x, a.y),
  18186. b2 = new Node(b.i, b.x, b.y),
  18187. an = a.next,
  18188. bp = b.prev;
  18189. a.next = b;
  18190. b.prev = a;
  18191. a2.next = an;
  18192. an.prev = a2;
  18193. b2.next = a2;
  18194. a2.prev = b2;
  18195. bp.next = b2;
  18196. b2.prev = bp;
  18197. return b2;
  18198. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  18199. function insertNode(i, x, y, last) {
  18200. const p = new Node(i, x, y);
  18201. if (!last) {
  18202. p.prev = p;
  18203. p.next = p;
  18204. } else {
  18205. p.next = last.next;
  18206. p.prev = last;
  18207. last.next.prev = p;
  18208. last.next = p;
  18209. }
  18210. return p;
  18211. }
  18212. function removeNode(p) {
  18213. p.next.prev = p.prev;
  18214. p.prev.next = p.next;
  18215. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  18216. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  18217. }
  18218. function Node(i, x, y) {
  18219. // vertex index in coordinates array
  18220. this.i = i; // vertex coordinates
  18221. this.x = x;
  18222. this.y = y; // previous and next vertex nodes in a polygon ring
  18223. this.prev = null;
  18224. this.next = null; // z-order curve value
  18225. this.z = null; // previous and next nodes in z-order
  18226. this.prevZ = null;
  18227. this.nextZ = null; // indicates whether this is a steiner point
  18228. this.steiner = false;
  18229. }
  18230. function signedArea(data, start, end, dim) {
  18231. let sum = 0;
  18232. for (let i = start, j = end - dim; i < end; i += dim) {
  18233. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  18234. j = i;
  18235. }
  18236. return sum;
  18237. }
  18238. class ShapeUtils {
  18239. // calculate area of the contour polygon
  18240. static area(contour) {
  18241. const n = contour.length;
  18242. let a = 0.0;
  18243. for (let p = n - 1, q = 0; q < n; p = q++) {
  18244. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  18245. }
  18246. return a * 0.5;
  18247. }
  18248. static isClockWise(pts) {
  18249. return ShapeUtils.area(pts) < 0;
  18250. }
  18251. static triangulateShape(contour, holes) {
  18252. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  18253. const holeIndices = []; // array of hole indices
  18254. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  18255. removeDupEndPts(contour);
  18256. addContour(vertices, contour); //
  18257. let holeIndex = contour.length;
  18258. holes.forEach(removeDupEndPts);
  18259. for (let i = 0; i < holes.length; i++) {
  18260. holeIndices.push(holeIndex);
  18261. holeIndex += holes[i].length;
  18262. addContour(vertices, holes[i]);
  18263. } //
  18264. const triangles = Earcut.triangulate(vertices, holeIndices); //
  18265. for (let i = 0; i < triangles.length; i += 3) {
  18266. faces.push(triangles.slice(i, i + 3));
  18267. }
  18268. return faces;
  18269. }
  18270. }
  18271. function removeDupEndPts(points) {
  18272. const l = points.length;
  18273. if (l > 2 && points[l - 1].equals(points[0])) {
  18274. points.pop();
  18275. }
  18276. }
  18277. function addContour(vertices, contour) {
  18278. for (let i = 0; i < contour.length; i++) {
  18279. vertices.push(contour[i].x);
  18280. vertices.push(contour[i].y);
  18281. }
  18282. }
  18283. /**
  18284. * Creates extruded geometry from a path shape.
  18285. *
  18286. * parameters = {
  18287. *
  18288. * curveSegments: <int>, // number of points on the curves
  18289. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  18290. * depth: <float>, // Depth to extrude the shape
  18291. *
  18292. * bevelEnabled: <bool>, // turn on bevel
  18293. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18294. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  18295. * bevelOffset: <float>, // how far from shape outline does bevel start
  18296. * bevelSegments: <int>, // number of bevel layers
  18297. *
  18298. * extrudePath: <THREE.Curve> // curve to extrude shape along
  18299. *
  18300. * UVGenerator: <Object> // object that provides UV generator functions
  18301. *
  18302. * }
  18303. */
  18304. class ExtrudeGeometry extends BufferGeometry {
  18305. constructor(shapes, options) {
  18306. super();
  18307. this.type = 'ExtrudeGeometry';
  18308. this.parameters = {
  18309. shapes: shapes,
  18310. options: options
  18311. };
  18312. shapes = Array.isArray(shapes) ? shapes : [shapes];
  18313. const scope = this;
  18314. const verticesArray = [];
  18315. const uvArray = [];
  18316. for (let i = 0, l = shapes.length; i < l; i++) {
  18317. const shape = shapes[i];
  18318. addShape(shape);
  18319. } // build geometry
  18320. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  18321. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  18322. this.computeVertexNormals(); // functions
  18323. function addShape(shape) {
  18324. const placeholder = []; // options
  18325. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18326. const steps = options.steps !== undefined ? options.steps : 1;
  18327. let depth = options.depth !== undefined ? options.depth : 100;
  18328. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  18329. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  18330. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  18331. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  18332. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18333. const extrudePath = options.extrudePath;
  18334. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  18335. if (options.amount !== undefined) {
  18336. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  18337. depth = options.amount;
  18338. } //
  18339. let extrudePts,
  18340. extrudeByPath = false;
  18341. let splineTube, binormal, normal, position2;
  18342. if (extrudePath) {
  18343. extrudePts = extrudePath.getSpacedPoints(steps);
  18344. extrudeByPath = true;
  18345. bevelEnabled = false; // bevels not supported for path extrusion
  18346. // SETUP TNB variables
  18347. // TODO1 - have a .isClosed in spline?
  18348. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18349. binormal = new Vector3();
  18350. normal = new Vector3();
  18351. position2 = new Vector3();
  18352. } // Safeguards if bevels are not enabled
  18353. if (!bevelEnabled) {
  18354. bevelSegments = 0;
  18355. bevelThickness = 0;
  18356. bevelSize = 0;
  18357. bevelOffset = 0;
  18358. } // Variables initialization
  18359. const shapePoints = shape.extractPoints(curveSegments);
  18360. let vertices = shapePoints.shape;
  18361. const holes = shapePoints.holes;
  18362. const reverse = !ShapeUtils.isClockWise(vertices);
  18363. if (reverse) {
  18364. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18365. for (let h = 0, hl = holes.length; h < hl; h++) {
  18366. const ahole = holes[h];
  18367. if (ShapeUtils.isClockWise(ahole)) {
  18368. holes[h] = ahole.reverse();
  18369. }
  18370. }
  18371. }
  18372. const faces = ShapeUtils.triangulateShape(vertices, holes);
  18373. /* Vertices */
  18374. const contour = vertices; // vertices has all points but contour has only points of circumference
  18375. for (let h = 0, hl = holes.length; h < hl; h++) {
  18376. const ahole = holes[h];
  18377. vertices = vertices.concat(ahole);
  18378. }
  18379. function scalePt2(pt, vec, size) {
  18380. if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
  18381. return vec.clone().multiplyScalar(size).add(pt);
  18382. }
  18383. const vlen = vertices.length,
  18384. flen = faces.length; // Find directions for point movement
  18385. function getBevelVec(inPt, inPrev, inNext) {
  18386. // computes for inPt the corresponding point inPt' on a new contour
  18387. // shifted by 1 unit (length of normalized vector) to the left
  18388. // if we walk along contour clockwise, this new contour is outside the old one
  18389. //
  18390. // inPt' is the intersection of the two lines parallel to the two
  18391. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18392. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  18393. // good reading for geometry algorithms (here: line-line intersection)
  18394. // http://geomalgorithms.com/a05-_intersect-1.html
  18395. const v_prev_x = inPt.x - inPrev.x,
  18396. v_prev_y = inPt.y - inPrev.y;
  18397. const v_next_x = inNext.x - inPt.x,
  18398. v_next_y = inNext.y - inPt.y;
  18399. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  18400. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  18401. if (Math.abs(collinear0) > Number.EPSILON) {
  18402. // not collinear
  18403. // length of vectors for normalizing
  18404. const v_prev_len = Math.sqrt(v_prev_lensq);
  18405. 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
  18406. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  18407. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  18408. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  18409. const ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  18410. 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
  18411. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  18412. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  18413. // but prevent crazy spikes
  18414. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  18415. if (v_trans_lensq <= 2) {
  18416. return new Vector2(v_trans_x, v_trans_y);
  18417. } else {
  18418. shrink_by = Math.sqrt(v_trans_lensq / 2);
  18419. }
  18420. } else {
  18421. // handle special case of collinear edges
  18422. let direction_eq = false; // assumes: opposite
  18423. if (v_prev_x > Number.EPSILON) {
  18424. if (v_next_x > Number.EPSILON) {
  18425. direction_eq = true;
  18426. }
  18427. } else {
  18428. if (v_prev_x < -Number.EPSILON) {
  18429. if (v_next_x < -Number.EPSILON) {
  18430. direction_eq = true;
  18431. }
  18432. } else {
  18433. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  18434. direction_eq = true;
  18435. }
  18436. }
  18437. }
  18438. if (direction_eq) {
  18439. // console.log("Warning: lines are a straight sequence");
  18440. v_trans_x = -v_prev_y;
  18441. v_trans_y = v_prev_x;
  18442. shrink_by = Math.sqrt(v_prev_lensq);
  18443. } else {
  18444. // console.log("Warning: lines are a straight spike");
  18445. v_trans_x = v_prev_x;
  18446. v_trans_y = v_prev_y;
  18447. shrink_by = Math.sqrt(v_prev_lensq / 2);
  18448. }
  18449. }
  18450. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  18451. }
  18452. const contourMovements = [];
  18453. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  18454. if (j === il) j = 0;
  18455. if (k === il) k = 0; // (j)---(i)---(k)
  18456. // console.log('i,j,k', i, j , k)
  18457. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  18458. }
  18459. const holesMovements = [];
  18460. let oneHoleMovements,
  18461. verticesMovements = contourMovements.concat();
  18462. for (let h = 0, hl = holes.length; h < hl; h++) {
  18463. const ahole = holes[h];
  18464. oneHoleMovements = [];
  18465. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  18466. if (j === il) j = 0;
  18467. if (k === il) k = 0; // (j)---(i)---(k)
  18468. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  18469. }
  18470. holesMovements.push(oneHoleMovements);
  18471. verticesMovements = verticesMovements.concat(oneHoleMovements);
  18472. } // Loop bevelSegments, 1 for the front, 1 for the back
  18473. for (let b = 0; b < bevelSegments; b++) {
  18474. //for ( b = bevelSegments; b > 0; b -- ) {
  18475. const t = b / bevelSegments;
  18476. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  18477. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  18478. for (let i = 0, il = contour.length; i < il; i++) {
  18479. const vert = scalePt2(contour[i], contourMovements[i], bs);
  18480. v(vert.x, vert.y, -z);
  18481. } // expand holes
  18482. for (let h = 0, hl = holes.length; h < hl; h++) {
  18483. const ahole = holes[h];
  18484. oneHoleMovements = holesMovements[h];
  18485. for (let i = 0, il = ahole.length; i < il; i++) {
  18486. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  18487. v(vert.x, vert.y, -z);
  18488. }
  18489. }
  18490. }
  18491. const bs = bevelSize + bevelOffset; // Back facing vertices
  18492. for (let i = 0; i < vlen; i++) {
  18493. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  18494. if (!extrudeByPath) {
  18495. v(vert.x, vert.y, 0);
  18496. } else {
  18497. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18498. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  18499. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  18500. position2.copy(extrudePts[0]).add(normal).add(binormal);
  18501. v(position2.x, position2.y, position2.z);
  18502. }
  18503. } // Add stepped vertices...
  18504. // Including front facing vertices
  18505. for (let s = 1; s <= steps; s++) {
  18506. for (let i = 0; i < vlen; i++) {
  18507. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  18508. if (!extrudeByPath) {
  18509. v(vert.x, vert.y, depth / steps * s);
  18510. } else {
  18511. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18512. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  18513. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  18514. position2.copy(extrudePts[s]).add(normal).add(binormal);
  18515. v(position2.x, position2.y, position2.z);
  18516. }
  18517. }
  18518. } // Add bevel segments planes
  18519. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18520. for (let b = bevelSegments - 1; b >= 0; b--) {
  18521. const t = b / bevelSegments;
  18522. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  18523. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  18524. for (let i = 0, il = contour.length; i < il; i++) {
  18525. const vert = scalePt2(contour[i], contourMovements[i], bs);
  18526. v(vert.x, vert.y, depth + z);
  18527. } // expand holes
  18528. for (let h = 0, hl = holes.length; h < hl; h++) {
  18529. const ahole = holes[h];
  18530. oneHoleMovements = holesMovements[h];
  18531. for (let i = 0, il = ahole.length; i < il; i++) {
  18532. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  18533. if (!extrudeByPath) {
  18534. v(vert.x, vert.y, depth + z);
  18535. } else {
  18536. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  18537. }
  18538. }
  18539. }
  18540. }
  18541. /* Faces */
  18542. // Top and bottom faces
  18543. buildLidFaces(); // Sides faces
  18544. buildSideFaces(); ///// Internal functions
  18545. function buildLidFaces() {
  18546. const start = verticesArray.length / 3;
  18547. if (bevelEnabled) {
  18548. let layer = 0; // steps + 1
  18549. let offset = vlen * layer; // Bottom faces
  18550. for (let i = 0; i < flen; i++) {
  18551. const face = faces[i];
  18552. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  18553. }
  18554. layer = steps + bevelSegments * 2;
  18555. offset = vlen * layer; // Top faces
  18556. for (let i = 0; i < flen; i++) {
  18557. const face = faces[i];
  18558. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  18559. }
  18560. } else {
  18561. // Bottom faces
  18562. for (let i = 0; i < flen; i++) {
  18563. const face = faces[i];
  18564. f3(face[2], face[1], face[0]);
  18565. } // Top faces
  18566. for (let i = 0; i < flen; i++) {
  18567. const face = faces[i];
  18568. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  18569. }
  18570. }
  18571. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  18572. } // Create faces for the z-sides of the shape
  18573. function buildSideFaces() {
  18574. const start = verticesArray.length / 3;
  18575. let layeroffset = 0;
  18576. sidewalls(contour, layeroffset);
  18577. layeroffset += contour.length;
  18578. for (let h = 0, hl = holes.length; h < hl; h++) {
  18579. const ahole = holes[h];
  18580. sidewalls(ahole, layeroffset); //, true
  18581. layeroffset += ahole.length;
  18582. }
  18583. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  18584. }
  18585. function sidewalls(contour, layeroffset) {
  18586. let i = contour.length;
  18587. while (--i >= 0) {
  18588. const j = i;
  18589. let k = i - 1;
  18590. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  18591. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  18592. const slen1 = vlen * s;
  18593. const slen2 = vlen * (s + 1);
  18594. const a = layeroffset + j + slen1,
  18595. b = layeroffset + k + slen1,
  18596. c = layeroffset + k + slen2,
  18597. d = layeroffset + j + slen2;
  18598. f4(a, b, c, d);
  18599. }
  18600. }
  18601. }
  18602. function v(x, y, z) {
  18603. placeholder.push(x);
  18604. placeholder.push(y);
  18605. placeholder.push(z);
  18606. }
  18607. function f3(a, b, c) {
  18608. addVertex(a);
  18609. addVertex(b);
  18610. addVertex(c);
  18611. const nextIndex = verticesArray.length / 3;
  18612. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  18613. addUV(uvs[0]);
  18614. addUV(uvs[1]);
  18615. addUV(uvs[2]);
  18616. }
  18617. function f4(a, b, c, d) {
  18618. addVertex(a);
  18619. addVertex(b);
  18620. addVertex(d);
  18621. addVertex(b);
  18622. addVertex(c);
  18623. addVertex(d);
  18624. const nextIndex = verticesArray.length / 3;
  18625. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  18626. addUV(uvs[0]);
  18627. addUV(uvs[1]);
  18628. addUV(uvs[3]);
  18629. addUV(uvs[1]);
  18630. addUV(uvs[2]);
  18631. addUV(uvs[3]);
  18632. }
  18633. function addVertex(index) {
  18634. verticesArray.push(placeholder[index * 3 + 0]);
  18635. verticesArray.push(placeholder[index * 3 + 1]);
  18636. verticesArray.push(placeholder[index * 3 + 2]);
  18637. }
  18638. function addUV(vector2) {
  18639. uvArray.push(vector2.x);
  18640. uvArray.push(vector2.y);
  18641. }
  18642. }
  18643. }
  18644. toJSON() {
  18645. const data = super.toJSON();
  18646. const shapes = this.parameters.shapes;
  18647. const options = this.parameters.options;
  18648. return toJSON$1(shapes, options, data);
  18649. }
  18650. static fromJSON(data, shapes) {
  18651. const geometryShapes = [];
  18652. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  18653. const shape = shapes[data.shapes[j]];
  18654. geometryShapes.push(shape);
  18655. }
  18656. const extrudePath = data.options.extrudePath;
  18657. if (extrudePath !== undefined) {
  18658. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  18659. }
  18660. return new ExtrudeGeometry(geometryShapes, data.options);
  18661. }
  18662. }
  18663. const WorldUVGenerator = {
  18664. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  18665. const a_x = vertices[indexA * 3];
  18666. const a_y = vertices[indexA * 3 + 1];
  18667. const b_x = vertices[indexB * 3];
  18668. const b_y = vertices[indexB * 3 + 1];
  18669. const c_x = vertices[indexC * 3];
  18670. const c_y = vertices[indexC * 3 + 1];
  18671. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  18672. },
  18673. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  18674. const a_x = vertices[indexA * 3];
  18675. const a_y = vertices[indexA * 3 + 1];
  18676. const a_z = vertices[indexA * 3 + 2];
  18677. const b_x = vertices[indexB * 3];
  18678. const b_y = vertices[indexB * 3 + 1];
  18679. const b_z = vertices[indexB * 3 + 2];
  18680. const c_x = vertices[indexC * 3];
  18681. const c_y = vertices[indexC * 3 + 1];
  18682. const c_z = vertices[indexC * 3 + 2];
  18683. const d_x = vertices[indexD * 3];
  18684. const d_y = vertices[indexD * 3 + 1];
  18685. const d_z = vertices[indexD * 3 + 2];
  18686. if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) {
  18687. 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)];
  18688. } else {
  18689. 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)];
  18690. }
  18691. }
  18692. };
  18693. function toJSON$1(shapes, options, data) {
  18694. data.shapes = [];
  18695. if (Array.isArray(shapes)) {
  18696. for (let i = 0, l = shapes.length; i < l; i++) {
  18697. const shape = shapes[i];
  18698. data.shapes.push(shape.uuid);
  18699. }
  18700. } else {
  18701. data.shapes.push(shapes.uuid);
  18702. }
  18703. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  18704. return data;
  18705. }
  18706. class IcosahedronGeometry extends PolyhedronGeometry {
  18707. constructor(radius = 1, detail = 0) {
  18708. const t = (1 + Math.sqrt(5)) / 2;
  18709. 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];
  18710. 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];
  18711. super(vertices, indices, radius, detail);
  18712. this.type = 'IcosahedronGeometry';
  18713. this.parameters = {
  18714. radius: radius,
  18715. detail: detail
  18716. };
  18717. }
  18718. static fromJSON(data) {
  18719. return new IcosahedronGeometry(data.radius, data.detail);
  18720. }
  18721. }
  18722. class LatheGeometry extends BufferGeometry {
  18723. constructor(points, segments = 12, phiStart = 0, phiLength = Math.PI * 2) {
  18724. super();
  18725. this.type = 'LatheGeometry';
  18726. this.parameters = {
  18727. points: points,
  18728. segments: segments,
  18729. phiStart: phiStart,
  18730. phiLength: phiLength
  18731. };
  18732. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  18733. phiLength = clamp(phiLength, 0, Math.PI * 2); // buffers
  18734. const indices = [];
  18735. const vertices = [];
  18736. const uvs = []; // helper variables
  18737. const inverseSegments = 1.0 / segments;
  18738. const vertex = new Vector3();
  18739. const uv = new Vector2(); // generate vertices and uvs
  18740. for (let i = 0; i <= segments; i++) {
  18741. const phi = phiStart + i * inverseSegments * phiLength;
  18742. const sin = Math.sin(phi);
  18743. const cos = Math.cos(phi);
  18744. for (let j = 0; j <= points.length - 1; j++) {
  18745. // vertex
  18746. vertex.x = points[j].x * sin;
  18747. vertex.y = points[j].y;
  18748. vertex.z = points[j].x * cos;
  18749. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  18750. uv.x = i / segments;
  18751. uv.y = j / (points.length - 1);
  18752. uvs.push(uv.x, uv.y);
  18753. }
  18754. } // indices
  18755. for (let i = 0; i < segments; i++) {
  18756. for (let j = 0; j < points.length - 1; j++) {
  18757. const base = j + i * points.length;
  18758. const a = base;
  18759. const b = base + points.length;
  18760. const c = base + points.length + 1;
  18761. const d = base + 1; // faces
  18762. indices.push(a, b, d);
  18763. indices.push(b, c, d);
  18764. }
  18765. } // build geometry
  18766. this.setIndex(indices);
  18767. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18768. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  18769. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  18770. // because the corresponding vertices are identical (but still have different UVs).
  18771. if (phiLength === Math.PI * 2) {
  18772. const normals = this.attributes.normal.array;
  18773. const n1 = new Vector3();
  18774. const n2 = new Vector3();
  18775. const n = new Vector3(); // this is the buffer offset for the last line of vertices
  18776. const base = segments * points.length * 3;
  18777. for (let i = 0, j = 0; i < points.length; i++, j += 3) {
  18778. // select the normal of the vertex in the first line
  18779. n1.x = normals[j + 0];
  18780. n1.y = normals[j + 1];
  18781. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  18782. n2.x = normals[base + j + 0];
  18783. n2.y = normals[base + j + 1];
  18784. n2.z = normals[base + j + 2]; // average normals
  18785. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  18786. normals[j + 0] = normals[base + j + 0] = n.x;
  18787. normals[j + 1] = normals[base + j + 1] = n.y;
  18788. normals[j + 2] = normals[base + j + 2] = n.z;
  18789. }
  18790. }
  18791. }
  18792. static fromJSON(data) {
  18793. return new LatheGeometry(data.points, data.segments, data.phiStart, data.phiLength);
  18794. }
  18795. }
  18796. class OctahedronGeometry extends PolyhedronGeometry {
  18797. constructor(radius = 1, detail = 0) {
  18798. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  18799. 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];
  18800. super(vertices, indices, radius, detail);
  18801. this.type = 'OctahedronGeometry';
  18802. this.parameters = {
  18803. radius: radius,
  18804. detail: detail
  18805. };
  18806. }
  18807. static fromJSON(data) {
  18808. return new OctahedronGeometry(data.radius, data.detail);
  18809. }
  18810. }
  18811. /**
  18812. * Parametric Surfaces Geometry
  18813. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  18814. */
  18815. class ParametricGeometry extends BufferGeometry {
  18816. constructor(func, slices, stacks) {
  18817. super();
  18818. this.type = 'ParametricGeometry';
  18819. this.parameters = {
  18820. func: func,
  18821. slices: slices,
  18822. stacks: stacks
  18823. }; // buffers
  18824. const indices = [];
  18825. const vertices = [];
  18826. const normals = [];
  18827. const uvs = [];
  18828. const EPS = 0.00001;
  18829. const normal = new Vector3();
  18830. const p0 = new Vector3(),
  18831. p1 = new Vector3();
  18832. const pu = new Vector3(),
  18833. pv = new Vector3();
  18834. if (func.length < 3) {
  18835. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  18836. } // generate vertices, normals and uvs
  18837. const sliceCount = slices + 1;
  18838. for (let i = 0; i <= stacks; i++) {
  18839. const v = i / stacks;
  18840. for (let j = 0; j <= slices; j++) {
  18841. const u = j / slices; // vertex
  18842. func(u, v, p0);
  18843. vertices.push(p0.x, p0.y, p0.z); // normal
  18844. // approximate tangent vectors via finite differences
  18845. if (u - EPS >= 0) {
  18846. func(u - EPS, v, p1);
  18847. pu.subVectors(p0, p1);
  18848. } else {
  18849. func(u + EPS, v, p1);
  18850. pu.subVectors(p1, p0);
  18851. }
  18852. if (v - EPS >= 0) {
  18853. func(u, v - EPS, p1);
  18854. pv.subVectors(p0, p1);
  18855. } else {
  18856. func(u, v + EPS, p1);
  18857. pv.subVectors(p1, p0);
  18858. } // cross product of tangent vectors returns surface normal
  18859. normal.crossVectors(pu, pv).normalize();
  18860. normals.push(normal.x, normal.y, normal.z); // uv
  18861. uvs.push(u, v);
  18862. }
  18863. } // generate indices
  18864. for (let i = 0; i < stacks; i++) {
  18865. for (let j = 0; j < slices; j++) {
  18866. const a = i * sliceCount + j;
  18867. const b = i * sliceCount + j + 1;
  18868. const c = (i + 1) * sliceCount + j + 1;
  18869. const d = (i + 1) * sliceCount + j; // faces one and two
  18870. indices.push(a, b, d);
  18871. indices.push(b, c, d);
  18872. }
  18873. } // build geometry
  18874. this.setIndex(indices);
  18875. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18876. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18877. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18878. }
  18879. }
  18880. class RingGeometry extends BufferGeometry {
  18881. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  18882. super();
  18883. this.type = 'RingGeometry';
  18884. this.parameters = {
  18885. innerRadius: innerRadius,
  18886. outerRadius: outerRadius,
  18887. thetaSegments: thetaSegments,
  18888. phiSegments: phiSegments,
  18889. thetaStart: thetaStart,
  18890. thetaLength: thetaLength
  18891. };
  18892. thetaSegments = Math.max(3, thetaSegments);
  18893. phiSegments = Math.max(1, phiSegments); // buffers
  18894. const indices = [];
  18895. const vertices = [];
  18896. const normals = [];
  18897. const uvs = []; // some helper variables
  18898. let radius = innerRadius;
  18899. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  18900. const vertex = new Vector3();
  18901. const uv = new Vector2(); // generate vertices, normals and uvs
  18902. for (let j = 0; j <= phiSegments; j++) {
  18903. for (let i = 0; i <= thetaSegments; i++) {
  18904. // values are generate from the inside of the ring to the outside
  18905. const segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  18906. vertex.x = radius * Math.cos(segment);
  18907. vertex.y = radius * Math.sin(segment);
  18908. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18909. normals.push(0, 0, 1); // uv
  18910. uv.x = (vertex.x / outerRadius + 1) / 2;
  18911. uv.y = (vertex.y / outerRadius + 1) / 2;
  18912. uvs.push(uv.x, uv.y);
  18913. } // increase the radius for next row of vertices
  18914. radius += radiusStep;
  18915. } // indices
  18916. for (let j = 0; j < phiSegments; j++) {
  18917. const thetaSegmentLevel = j * (thetaSegments + 1);
  18918. for (let i = 0; i < thetaSegments; i++) {
  18919. const segment = i + thetaSegmentLevel;
  18920. const a = segment;
  18921. const b = segment + thetaSegments + 1;
  18922. const c = segment + thetaSegments + 2;
  18923. const d = segment + 1; // faces
  18924. indices.push(a, b, d);
  18925. indices.push(b, c, d);
  18926. }
  18927. } // build geometry
  18928. this.setIndex(indices);
  18929. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18930. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18931. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18932. }
  18933. static fromJSON(data) {
  18934. return new RingGeometry(data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  18935. }
  18936. }
  18937. class ShapeGeometry extends BufferGeometry {
  18938. constructor(shapes, curveSegments = 12) {
  18939. super();
  18940. this.type = 'ShapeGeometry';
  18941. this.parameters = {
  18942. shapes: shapes,
  18943. curveSegments: curveSegments
  18944. }; // buffers
  18945. const indices = [];
  18946. const vertices = [];
  18947. const normals = [];
  18948. const uvs = []; // helper variables
  18949. let groupStart = 0;
  18950. let groupCount = 0; // allow single and array values for "shapes" parameter
  18951. if (Array.isArray(shapes) === false) {
  18952. addShape(shapes);
  18953. } else {
  18954. for (let i = 0; i < shapes.length; i++) {
  18955. addShape(shapes[i]);
  18956. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  18957. groupStart += groupCount;
  18958. groupCount = 0;
  18959. }
  18960. } // build geometry
  18961. this.setIndex(indices);
  18962. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18963. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18964. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  18965. function addShape(shape) {
  18966. const indexOffset = vertices.length / 3;
  18967. const points = shape.extractPoints(curveSegments);
  18968. let shapeVertices = points.shape;
  18969. const shapeHoles = points.holes; // check direction of vertices
  18970. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  18971. shapeVertices = shapeVertices.reverse();
  18972. }
  18973. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  18974. const shapeHole = shapeHoles[i];
  18975. if (ShapeUtils.isClockWise(shapeHole) === true) {
  18976. shapeHoles[i] = shapeHole.reverse();
  18977. }
  18978. }
  18979. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  18980. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  18981. const shapeHole = shapeHoles[i];
  18982. shapeVertices = shapeVertices.concat(shapeHole);
  18983. } // vertices, normals, uvs
  18984. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  18985. const vertex = shapeVertices[i];
  18986. vertices.push(vertex.x, vertex.y, 0);
  18987. normals.push(0, 0, 1);
  18988. uvs.push(vertex.x, vertex.y); // world uvs
  18989. } // incides
  18990. for (let i = 0, l = faces.length; i < l; i++) {
  18991. const face = faces[i];
  18992. const a = face[0] + indexOffset;
  18993. const b = face[1] + indexOffset;
  18994. const c = face[2] + indexOffset;
  18995. indices.push(a, b, c);
  18996. groupCount += 3;
  18997. }
  18998. }
  18999. }
  19000. toJSON() {
  19001. const data = super.toJSON();
  19002. const shapes = this.parameters.shapes;
  19003. return toJSON(shapes, data);
  19004. }
  19005. static fromJSON(data, shapes) {
  19006. const geometryShapes = [];
  19007. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  19008. const shape = shapes[data.shapes[j]];
  19009. geometryShapes.push(shape);
  19010. }
  19011. return new ShapeGeometry(geometryShapes, data.curveSegments);
  19012. }
  19013. }
  19014. function toJSON(shapes, data) {
  19015. data.shapes = [];
  19016. if (Array.isArray(shapes)) {
  19017. for (let i = 0, l = shapes.length; i < l; i++) {
  19018. const shape = shapes[i];
  19019. data.shapes.push(shape.uuid);
  19020. }
  19021. } else {
  19022. data.shapes.push(shapes.uuid);
  19023. }
  19024. return data;
  19025. }
  19026. class SphereGeometry extends BufferGeometry {
  19027. constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  19028. super();
  19029. this.type = 'SphereGeometry';
  19030. this.parameters = {
  19031. radius: radius,
  19032. widthSegments: widthSegments,
  19033. heightSegments: heightSegments,
  19034. phiStart: phiStart,
  19035. phiLength: phiLength,
  19036. thetaStart: thetaStart,
  19037. thetaLength: thetaLength
  19038. };
  19039. widthSegments = Math.max(3, Math.floor(widthSegments));
  19040. heightSegments = Math.max(2, Math.floor(heightSegments));
  19041. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  19042. let index = 0;
  19043. const grid = [];
  19044. const vertex = new Vector3();
  19045. const normal = new Vector3(); // buffers
  19046. const indices = [];
  19047. const vertices = [];
  19048. const normals = [];
  19049. const uvs = []; // generate vertices, normals and uvs
  19050. for (let iy = 0; iy <= heightSegments; iy++) {
  19051. const verticesRow = [];
  19052. const v = iy / heightSegments; // special case for the poles
  19053. let uOffset = 0;
  19054. if (iy == 0 && thetaStart == 0) {
  19055. uOffset = 0.5 / widthSegments;
  19056. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  19057. uOffset = -0.5 / widthSegments;
  19058. }
  19059. for (let ix = 0; ix <= widthSegments; ix++) {
  19060. const u = ix / widthSegments; // vertex
  19061. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  19062. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  19063. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  19064. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19065. normal.copy(vertex).normalize();
  19066. normals.push(normal.x, normal.y, normal.z); // uv
  19067. uvs.push(u + uOffset, 1 - v);
  19068. verticesRow.push(index++);
  19069. }
  19070. grid.push(verticesRow);
  19071. } // indices
  19072. for (let iy = 0; iy < heightSegments; iy++) {
  19073. for (let ix = 0; ix < widthSegments; ix++) {
  19074. const a = grid[iy][ix + 1];
  19075. const b = grid[iy][ix];
  19076. const c = grid[iy + 1][ix];
  19077. const d = grid[iy + 1][ix + 1];
  19078. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  19079. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  19080. }
  19081. } // build geometry
  19082. this.setIndex(indices);
  19083. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19084. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19085. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19086. }
  19087. static fromJSON(data) {
  19088. return new SphereGeometry(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  19089. }
  19090. }
  19091. class TetrahedronGeometry extends PolyhedronGeometry {
  19092. constructor(radius = 1, detail = 0) {
  19093. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  19094. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  19095. super(vertices, indices, radius, detail);
  19096. this.type = 'TetrahedronGeometry';
  19097. this.parameters = {
  19098. radius: radius,
  19099. detail: detail
  19100. };
  19101. }
  19102. static fromJSON(data) {
  19103. return new TetrahedronGeometry(data.radius, data.detail);
  19104. }
  19105. }
  19106. /**
  19107. * Text = 3D Text
  19108. *
  19109. * parameters = {
  19110. * font: <THREE.Font>, // font
  19111. *
  19112. * size: <float>, // size of the text
  19113. * height: <float>, // thickness to extrude text
  19114. * curveSegments: <int>, // number of points on the curves
  19115. *
  19116. * bevelEnabled: <bool>, // turn on bevel
  19117. * bevelThickness: <float>, // how deep into text bevel goes
  19118. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  19119. * bevelOffset: <float> // how far from text outline does bevel start
  19120. * }
  19121. */
  19122. class TextGeometry extends ExtrudeGeometry {
  19123. constructor(text, parameters = {}) {
  19124. const font = parameters.font;
  19125. if (!(font && font.isFont)) {
  19126. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  19127. return new BufferGeometry();
  19128. }
  19129. const shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  19130. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  19131. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  19132. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  19133. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  19134. super(shapes, parameters);
  19135. this.type = 'TextGeometry';
  19136. }
  19137. }
  19138. class TorusGeometry extends BufferGeometry {
  19139. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  19140. super();
  19141. this.type = 'TorusGeometry';
  19142. this.parameters = {
  19143. radius: radius,
  19144. tube: tube,
  19145. radialSegments: radialSegments,
  19146. tubularSegments: tubularSegments,
  19147. arc: arc
  19148. };
  19149. radialSegments = Math.floor(radialSegments);
  19150. tubularSegments = Math.floor(tubularSegments); // buffers
  19151. const indices = [];
  19152. const vertices = [];
  19153. const normals = [];
  19154. const uvs = []; // helper variables
  19155. const center = new Vector3();
  19156. const vertex = new Vector3();
  19157. const normal = new Vector3(); // generate vertices, normals and uvs
  19158. for (let j = 0; j <= radialSegments; j++) {
  19159. for (let i = 0; i <= tubularSegments; i++) {
  19160. const u = i / tubularSegments * arc;
  19161. const v = j / radialSegments * Math.PI * 2; // vertex
  19162. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  19163. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  19164. vertex.z = tube * Math.sin(v);
  19165. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19166. center.x = radius * Math.cos(u);
  19167. center.y = radius * Math.sin(u);
  19168. normal.subVectors(vertex, center).normalize();
  19169. normals.push(normal.x, normal.y, normal.z); // uv
  19170. uvs.push(i / tubularSegments);
  19171. uvs.push(j / radialSegments);
  19172. }
  19173. } // generate indices
  19174. for (let j = 1; j <= radialSegments; j++) {
  19175. for (let i = 1; i <= tubularSegments; i++) {
  19176. // indices
  19177. const a = (tubularSegments + 1) * j + i - 1;
  19178. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  19179. const c = (tubularSegments + 1) * (j - 1) + i;
  19180. const d = (tubularSegments + 1) * j + i; // faces
  19181. indices.push(a, b, d);
  19182. indices.push(b, c, d);
  19183. }
  19184. } // build geometry
  19185. this.setIndex(indices);
  19186. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19187. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19188. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19189. }
  19190. static fromJSON(data) {
  19191. return new TorusGeometry(data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  19192. }
  19193. }
  19194. class TorusKnotGeometry extends BufferGeometry {
  19195. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  19196. super();
  19197. this.type = 'TorusKnotGeometry';
  19198. this.parameters = {
  19199. radius: radius,
  19200. tube: tube,
  19201. tubularSegments: tubularSegments,
  19202. radialSegments: radialSegments,
  19203. p: p,
  19204. q: q
  19205. };
  19206. tubularSegments = Math.floor(tubularSegments);
  19207. radialSegments = Math.floor(radialSegments); // buffers
  19208. const indices = [];
  19209. const vertices = [];
  19210. const normals = [];
  19211. const uvs = []; // helper variables
  19212. const vertex = new Vector3();
  19213. const normal = new Vector3();
  19214. const P1 = new Vector3();
  19215. const P2 = new Vector3();
  19216. const B = new Vector3();
  19217. const T = new Vector3();
  19218. const N = new Vector3(); // generate vertices, normals and uvs
  19219. for (let i = 0; i <= tubularSegments; ++i) {
  19220. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  19221. 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.
  19222. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  19223. calculatePositionOnCurve(u, p, q, radius, P1);
  19224. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  19225. T.subVectors(P2, P1);
  19226. N.addVectors(P2, P1);
  19227. B.crossVectors(T, N);
  19228. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  19229. B.normalize();
  19230. N.normalize();
  19231. for (let j = 0; j <= radialSegments; ++j) {
  19232. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  19233. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  19234. const v = j / radialSegments * Math.PI * 2;
  19235. const cx = -tube * Math.cos(v);
  19236. const cy = tube * Math.sin(v); // now calculate the final vertex position.
  19237. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  19238. vertex.x = P1.x + (cx * N.x + cy * B.x);
  19239. vertex.y = P1.y + (cx * N.y + cy * B.y);
  19240. vertex.z = P1.z + (cx * N.z + cy * B.z);
  19241. 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)
  19242. normal.subVectors(vertex, P1).normalize();
  19243. normals.push(normal.x, normal.y, normal.z); // uv
  19244. uvs.push(i / tubularSegments);
  19245. uvs.push(j / radialSegments);
  19246. }
  19247. } // generate indices
  19248. for (let j = 1; j <= tubularSegments; j++) {
  19249. for (let i = 1; i <= radialSegments; i++) {
  19250. // indices
  19251. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  19252. const b = (radialSegments + 1) * j + (i - 1);
  19253. const c = (radialSegments + 1) * j + i;
  19254. const d = (radialSegments + 1) * (j - 1) + i; // faces
  19255. indices.push(a, b, d);
  19256. indices.push(b, c, d);
  19257. }
  19258. } // build geometry
  19259. this.setIndex(indices);
  19260. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19261. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19262. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  19263. function calculatePositionOnCurve(u, p, q, radius, position) {
  19264. const cu = Math.cos(u);
  19265. const su = Math.sin(u);
  19266. const quOverP = q / p * u;
  19267. const cs = Math.cos(quOverP);
  19268. position.x = radius * (2 + cs) * 0.5 * cu;
  19269. position.y = radius * (2 + cs) * su * 0.5;
  19270. position.z = radius * Math.sin(quOverP) * 0.5;
  19271. }
  19272. }
  19273. static fromJSON(data) {
  19274. return new TorusKnotGeometry(data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  19275. }
  19276. }
  19277. class TubeGeometry extends BufferGeometry {
  19278. constructor(path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) {
  19279. super();
  19280. this.type = 'TubeGeometry';
  19281. this.parameters = {
  19282. path: path,
  19283. tubularSegments: tubularSegments,
  19284. radius: radius,
  19285. radialSegments: radialSegments,
  19286. closed: closed
  19287. };
  19288. const frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  19289. this.tangents = frames.tangents;
  19290. this.normals = frames.normals;
  19291. this.binormals = frames.binormals; // helper variables
  19292. const vertex = new Vector3();
  19293. const normal = new Vector3();
  19294. const uv = new Vector2();
  19295. let P = new Vector3(); // buffer
  19296. const vertices = [];
  19297. const normals = [];
  19298. const uvs = [];
  19299. const indices = []; // create buffer data
  19300. generateBufferData(); // build geometry
  19301. this.setIndex(indices);
  19302. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19303. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19304. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  19305. function generateBufferData() {
  19306. for (let i = 0; i < tubularSegments; i++) {
  19307. generateSegment(i);
  19308. } // if the geometry is not closed, generate the last row of vertices and normals
  19309. // at the regular position on the given path
  19310. //
  19311. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  19312. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  19313. // this makes it easy compute correct values for closed geometries
  19314. generateUVs(); // finally create faces
  19315. generateIndices();
  19316. }
  19317. function generateSegment(i) {
  19318. // we use getPointAt to sample evenly distributed points from the given path
  19319. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  19320. const N = frames.normals[i];
  19321. const B = frames.binormals[i]; // generate normals and vertices for the current segment
  19322. for (let j = 0; j <= radialSegments; j++) {
  19323. const v = j / radialSegments * Math.PI * 2;
  19324. const sin = Math.sin(v);
  19325. const cos = -Math.cos(v); // normal
  19326. normal.x = cos * N.x + sin * B.x;
  19327. normal.y = cos * N.y + sin * B.y;
  19328. normal.z = cos * N.z + sin * B.z;
  19329. normal.normalize();
  19330. normals.push(normal.x, normal.y, normal.z); // vertex
  19331. vertex.x = P.x + radius * normal.x;
  19332. vertex.y = P.y + radius * normal.y;
  19333. vertex.z = P.z + radius * normal.z;
  19334. vertices.push(vertex.x, vertex.y, vertex.z);
  19335. }
  19336. }
  19337. function generateIndices() {
  19338. for (let j = 1; j <= tubularSegments; j++) {
  19339. for (let i = 1; i <= radialSegments; i++) {
  19340. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  19341. const b = (radialSegments + 1) * j + (i - 1);
  19342. const c = (radialSegments + 1) * j + i;
  19343. const d = (radialSegments + 1) * (j - 1) + i; // faces
  19344. indices.push(a, b, d);
  19345. indices.push(b, c, d);
  19346. }
  19347. }
  19348. }
  19349. function generateUVs() {
  19350. for (let i = 0; i <= tubularSegments; i++) {
  19351. for (let j = 0; j <= radialSegments; j++) {
  19352. uv.x = i / tubularSegments;
  19353. uv.y = j / radialSegments;
  19354. uvs.push(uv.x, uv.y);
  19355. }
  19356. }
  19357. }
  19358. }
  19359. toJSON() {
  19360. const data = super.toJSON();
  19361. data.path = this.parameters.path.toJSON();
  19362. return data;
  19363. }
  19364. static fromJSON(data) {
  19365. // This only works for built-in curves (e.g. CatmullRomCurve3).
  19366. // User defined curves or instances of CurvePath will not be deserialized.
  19367. return new TubeGeometry(new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  19368. }
  19369. }
  19370. class WireframeGeometry extends BufferGeometry {
  19371. constructor(geometry) {
  19372. super();
  19373. this.type = 'WireframeGeometry';
  19374. if (geometry.isGeometry === true) {
  19375. console.error('THREE.WireframeGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  19376. return;
  19377. } // buffer
  19378. const vertices = [];
  19379. const edges = new Set(); // helper variables
  19380. const start = new Vector3();
  19381. const end = new Vector3();
  19382. if (geometry.index !== null) {
  19383. // indexed BufferGeometry
  19384. const position = geometry.attributes.position;
  19385. const indices = geometry.index;
  19386. let groups = geometry.groups;
  19387. if (groups.length === 0) {
  19388. groups = [{
  19389. start: 0,
  19390. count: indices.count,
  19391. materialIndex: 0
  19392. }];
  19393. } // create a data structure that contains all eges without duplicates
  19394. for (let o = 0, ol = groups.length; o < ol; ++o) {
  19395. const group = groups[o];
  19396. const groupStart = group.start;
  19397. const groupCount = group.count;
  19398. for (let i = groupStart, l = groupStart + groupCount; i < l; i += 3) {
  19399. for (let j = 0; j < 3; j++) {
  19400. const index1 = indices.getX(i + j);
  19401. const index2 = indices.getX(i + (j + 1) % 3);
  19402. start.fromBufferAttribute(position, index1);
  19403. end.fromBufferAttribute(position, index2);
  19404. if (isUniqueEdge(start, end, edges) === true) {
  19405. vertices.push(start.x, start.y, start.z);
  19406. vertices.push(end.x, end.y, end.z);
  19407. }
  19408. }
  19409. }
  19410. }
  19411. } else {
  19412. // non-indexed BufferGeometry
  19413. const position = geometry.attributes.position;
  19414. for (let i = 0, l = position.count / 3; i < l; i++) {
  19415. for (let j = 0; j < 3; j++) {
  19416. // three edges per triangle, an edge is represented as (index1, index2)
  19417. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  19418. const index1 = 3 * i + j;
  19419. const index2 = 3 * i + (j + 1) % 3;
  19420. start.fromBufferAttribute(position, index1);
  19421. end.fromBufferAttribute(position, index2);
  19422. if (isUniqueEdge(start, end, edges) === true) {
  19423. vertices.push(start.x, start.y, start.z);
  19424. vertices.push(end.x, end.y, end.z);
  19425. }
  19426. }
  19427. }
  19428. } // build geometry
  19429. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19430. }
  19431. }
  19432. function isUniqueEdge(start, end, edges) {
  19433. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  19434. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  19435. if (edges.has(hash1) === true || edges.has(hash2) === true) {
  19436. return false;
  19437. } else {
  19438. edges.add(hash1, hash2);
  19439. return true;
  19440. }
  19441. }
  19442. var Geometries = /*#__PURE__*/Object.freeze({
  19443. __proto__: null,
  19444. BoxGeometry: BoxGeometry,
  19445. BoxBufferGeometry: BoxGeometry,
  19446. CircleGeometry: CircleGeometry,
  19447. CircleBufferGeometry: CircleGeometry,
  19448. ConeGeometry: ConeGeometry,
  19449. ConeBufferGeometry: ConeGeometry,
  19450. CylinderGeometry: CylinderGeometry,
  19451. CylinderBufferGeometry: CylinderGeometry,
  19452. DodecahedronGeometry: DodecahedronGeometry,
  19453. DodecahedronBufferGeometry: DodecahedronGeometry,
  19454. EdgesGeometry: EdgesGeometry,
  19455. ExtrudeGeometry: ExtrudeGeometry,
  19456. ExtrudeBufferGeometry: ExtrudeGeometry,
  19457. IcosahedronGeometry: IcosahedronGeometry,
  19458. IcosahedronBufferGeometry: IcosahedronGeometry,
  19459. LatheGeometry: LatheGeometry,
  19460. LatheBufferGeometry: LatheGeometry,
  19461. OctahedronGeometry: OctahedronGeometry,
  19462. OctahedronBufferGeometry: OctahedronGeometry,
  19463. ParametricGeometry: ParametricGeometry,
  19464. ParametricBufferGeometry: ParametricGeometry,
  19465. PlaneGeometry: PlaneGeometry,
  19466. PlaneBufferGeometry: PlaneGeometry,
  19467. PolyhedronGeometry: PolyhedronGeometry,
  19468. PolyhedronBufferGeometry: PolyhedronGeometry,
  19469. RingGeometry: RingGeometry,
  19470. RingBufferGeometry: RingGeometry,
  19471. ShapeGeometry: ShapeGeometry,
  19472. ShapeBufferGeometry: ShapeGeometry,
  19473. SphereGeometry: SphereGeometry,
  19474. SphereBufferGeometry: SphereGeometry,
  19475. TetrahedronGeometry: TetrahedronGeometry,
  19476. TetrahedronBufferGeometry: TetrahedronGeometry,
  19477. TextGeometry: TextGeometry,
  19478. TextBufferGeometry: TextGeometry,
  19479. TorusGeometry: TorusGeometry,
  19480. TorusBufferGeometry: TorusGeometry,
  19481. TorusKnotGeometry: TorusKnotGeometry,
  19482. TorusKnotBufferGeometry: TorusKnotGeometry,
  19483. TubeGeometry: TubeGeometry,
  19484. TubeBufferGeometry: TubeGeometry,
  19485. WireframeGeometry: WireframeGeometry
  19486. });
  19487. /**
  19488. * parameters = {
  19489. * color: <THREE.Color>
  19490. * }
  19491. */
  19492. class ShadowMaterial extends Material {
  19493. constructor(parameters) {
  19494. super();
  19495. this.type = 'ShadowMaterial';
  19496. this.color = new Color(0x000000);
  19497. this.transparent = true;
  19498. this.setValues(parameters);
  19499. }
  19500. copy(source) {
  19501. super.copy(source);
  19502. this.color.copy(source.color);
  19503. return this;
  19504. }
  19505. }
  19506. ShadowMaterial.prototype.isShadowMaterial = true;
  19507. class RawShaderMaterial extends ShaderMaterial {
  19508. constructor(parameters) {
  19509. super(parameters);
  19510. this.type = 'RawShaderMaterial';
  19511. }
  19512. }
  19513. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  19514. /**
  19515. * parameters = {
  19516. * color: <hex>,
  19517. * roughness: <float>,
  19518. * metalness: <float>,
  19519. * opacity: <float>,
  19520. *
  19521. * map: new THREE.Texture( <Image> ),
  19522. *
  19523. * lightMap: new THREE.Texture( <Image> ),
  19524. * lightMapIntensity: <float>
  19525. *
  19526. * aoMap: new THREE.Texture( <Image> ),
  19527. * aoMapIntensity: <float>
  19528. *
  19529. * emissive: <hex>,
  19530. * emissiveIntensity: <float>
  19531. * emissiveMap: new THREE.Texture( <Image> ),
  19532. *
  19533. * bumpMap: new THREE.Texture( <Image> ),
  19534. * bumpScale: <float>,
  19535. *
  19536. * normalMap: new THREE.Texture( <Image> ),
  19537. * normalMapType: THREE.TangentSpaceNormalMap,
  19538. * normalScale: <Vector2>,
  19539. *
  19540. * displacementMap: new THREE.Texture( <Image> ),
  19541. * displacementScale: <float>,
  19542. * displacementBias: <float>,
  19543. *
  19544. * roughnessMap: new THREE.Texture( <Image> ),
  19545. *
  19546. * metalnessMap: new THREE.Texture( <Image> ),
  19547. *
  19548. * alphaMap: new THREE.Texture( <Image> ),
  19549. *
  19550. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19551. * envMapIntensity: <float>
  19552. *
  19553. * refractionRatio: <float>,
  19554. *
  19555. * wireframe: <boolean>,
  19556. * wireframeLinewidth: <float>,
  19557. *
  19558. * flatShading: <bool>
  19559. * }
  19560. */
  19561. class MeshStandardMaterial extends Material {
  19562. constructor(parameters) {
  19563. super();
  19564. this.defines = {
  19565. 'STANDARD': ''
  19566. };
  19567. this.type = 'MeshStandardMaterial';
  19568. this.color = new Color(0xffffff); // diffuse
  19569. this.roughness = 1.0;
  19570. this.metalness = 0.0;
  19571. this.map = null;
  19572. this.lightMap = null;
  19573. this.lightMapIntensity = 1.0;
  19574. this.aoMap = null;
  19575. this.aoMapIntensity = 1.0;
  19576. this.emissive = new Color(0x000000);
  19577. this.emissiveIntensity = 1.0;
  19578. this.emissiveMap = null;
  19579. this.bumpMap = null;
  19580. this.bumpScale = 1;
  19581. this.normalMap = null;
  19582. this.normalMapType = TangentSpaceNormalMap;
  19583. this.normalScale = new Vector2(1, 1);
  19584. this.displacementMap = null;
  19585. this.displacementScale = 1;
  19586. this.displacementBias = 0;
  19587. this.roughnessMap = null;
  19588. this.metalnessMap = null;
  19589. this.alphaMap = null;
  19590. this.envMap = null;
  19591. this.envMapIntensity = 1.0;
  19592. this.refractionRatio = 0.98;
  19593. this.wireframe = false;
  19594. this.wireframeLinewidth = 1;
  19595. this.wireframeLinecap = 'round';
  19596. this.wireframeLinejoin = 'round';
  19597. this.flatShading = false;
  19598. this.vertexTangents = false;
  19599. this.setValues(parameters);
  19600. }
  19601. copy(source) {
  19602. super.copy(source);
  19603. this.defines = {
  19604. 'STANDARD': ''
  19605. };
  19606. this.color.copy(source.color);
  19607. this.roughness = source.roughness;
  19608. this.metalness = source.metalness;
  19609. this.map = source.map;
  19610. this.lightMap = source.lightMap;
  19611. this.lightMapIntensity = source.lightMapIntensity;
  19612. this.aoMap = source.aoMap;
  19613. this.aoMapIntensity = source.aoMapIntensity;
  19614. this.emissive.copy(source.emissive);
  19615. this.emissiveMap = source.emissiveMap;
  19616. this.emissiveIntensity = source.emissiveIntensity;
  19617. this.bumpMap = source.bumpMap;
  19618. this.bumpScale = source.bumpScale;
  19619. this.normalMap = source.normalMap;
  19620. this.normalMapType = source.normalMapType;
  19621. this.normalScale.copy(source.normalScale);
  19622. this.displacementMap = source.displacementMap;
  19623. this.displacementScale = source.displacementScale;
  19624. this.displacementBias = source.displacementBias;
  19625. this.roughnessMap = source.roughnessMap;
  19626. this.metalnessMap = source.metalnessMap;
  19627. this.alphaMap = source.alphaMap;
  19628. this.envMap = source.envMap;
  19629. this.envMapIntensity = source.envMapIntensity;
  19630. this.refractionRatio = source.refractionRatio;
  19631. this.wireframe = source.wireframe;
  19632. this.wireframeLinewidth = source.wireframeLinewidth;
  19633. this.wireframeLinecap = source.wireframeLinecap;
  19634. this.wireframeLinejoin = source.wireframeLinejoin;
  19635. this.flatShading = source.flatShading;
  19636. this.vertexTangents = source.vertexTangents;
  19637. return this;
  19638. }
  19639. }
  19640. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  19641. /**
  19642. * parameters = {
  19643. * clearcoat: <float>,
  19644. * clearcoatMap: new THREE.Texture( <Image> ),
  19645. * clearcoatRoughness: <float>,
  19646. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  19647. * clearcoatNormalScale: <Vector2>,
  19648. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  19649. *
  19650. * reflectivity: <float>,
  19651. * ior: <float>,
  19652. *
  19653. * sheen: <Color>,
  19654. *
  19655. * transmission: <float>,
  19656. * transmissionMap: new THREE.Texture( <Image> ),
  19657. *
  19658. * thickness: <float>,
  19659. * thicknessMap: new THREE.Texture( <Image> ),
  19660. * attenuationDistance: <float>,
  19661. * attenuationColor: <Color>
  19662. * }
  19663. */
  19664. class MeshPhysicalMaterial extends MeshStandardMaterial {
  19665. constructor(parameters) {
  19666. super();
  19667. this.defines = {
  19668. 'STANDARD': '',
  19669. 'PHYSICAL': ''
  19670. };
  19671. this.type = 'MeshPhysicalMaterial';
  19672. this.clearcoat = 0.0;
  19673. this.clearcoatMap = null;
  19674. this.clearcoatRoughness = 0.0;
  19675. this.clearcoatRoughnessMap = null;
  19676. this.clearcoatNormalScale = new Vector2(1, 1);
  19677. this.clearcoatNormalMap = null;
  19678. this.reflectivity = 0.5; // maps to F0 = 0.04
  19679. Object.defineProperty(this, 'ior', {
  19680. get: function () {
  19681. return (1 + 0.4 * this.reflectivity) / (1 - 0.4 * this.reflectivity);
  19682. },
  19683. set: function (ior) {
  19684. this.reflectivity = clamp(2.5 * (ior - 1) / (ior + 1), 0, 1);
  19685. }
  19686. });
  19687. this.sheen = null; // null will disable sheen bsdf
  19688. this.transmission = 0.0;
  19689. this.transmissionMap = null;
  19690. this.thickness = 0.01;
  19691. this.thicknessMap = null;
  19692. this.attenuationDistance = 0.0;
  19693. this.attenuationColor = new Color(1, 1, 1);
  19694. this.setValues(parameters);
  19695. }
  19696. copy(source) {
  19697. super.copy(source);
  19698. this.defines = {
  19699. 'STANDARD': '',
  19700. 'PHYSICAL': ''
  19701. };
  19702. this.clearcoat = source.clearcoat;
  19703. this.clearcoatMap = source.clearcoatMap;
  19704. this.clearcoatRoughness = source.clearcoatRoughness;
  19705. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  19706. this.clearcoatNormalMap = source.clearcoatNormalMap;
  19707. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  19708. this.reflectivity = source.reflectivity;
  19709. if (source.sheen) {
  19710. this.sheen = (this.sheen || new Color()).copy(source.sheen);
  19711. } else {
  19712. this.sheen = null;
  19713. }
  19714. this.transmission = source.transmission;
  19715. this.transmissionMap = source.transmissionMap;
  19716. this.thickness = source.thickness;
  19717. this.thicknessMap = source.thicknessMap;
  19718. this.attenuationDistance = source.attenuationDistance;
  19719. this.attenuationColor.copy(source.attenuationColor);
  19720. return this;
  19721. }
  19722. }
  19723. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  19724. /**
  19725. * parameters = {
  19726. * color: <hex>,
  19727. * specular: <hex>,
  19728. * shininess: <float>,
  19729. * opacity: <float>,
  19730. *
  19731. * map: new THREE.Texture( <Image> ),
  19732. *
  19733. * lightMap: new THREE.Texture( <Image> ),
  19734. * lightMapIntensity: <float>
  19735. *
  19736. * aoMap: new THREE.Texture( <Image> ),
  19737. * aoMapIntensity: <float>
  19738. *
  19739. * emissive: <hex>,
  19740. * emissiveIntensity: <float>
  19741. * emissiveMap: new THREE.Texture( <Image> ),
  19742. *
  19743. * bumpMap: new THREE.Texture( <Image> ),
  19744. * bumpScale: <float>,
  19745. *
  19746. * normalMap: new THREE.Texture( <Image> ),
  19747. * normalMapType: THREE.TangentSpaceNormalMap,
  19748. * normalScale: <Vector2>,
  19749. *
  19750. * displacementMap: new THREE.Texture( <Image> ),
  19751. * displacementScale: <float>,
  19752. * displacementBias: <float>,
  19753. *
  19754. * specularMap: new THREE.Texture( <Image> ),
  19755. *
  19756. * alphaMap: new THREE.Texture( <Image> ),
  19757. *
  19758. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19759. * combine: THREE.MultiplyOperation,
  19760. * reflectivity: <float>,
  19761. * refractionRatio: <float>,
  19762. *
  19763. * wireframe: <boolean>,
  19764. * wireframeLinewidth: <float>,
  19765. *
  19766. * flatShading: <bool>
  19767. * }
  19768. */
  19769. class MeshPhongMaterial extends Material {
  19770. constructor(parameters) {
  19771. super();
  19772. this.type = 'MeshPhongMaterial';
  19773. this.color = new Color(0xffffff); // diffuse
  19774. this.specular = new Color(0x111111);
  19775. this.shininess = 30;
  19776. this.map = null;
  19777. this.lightMap = null;
  19778. this.lightMapIntensity = 1.0;
  19779. this.aoMap = null;
  19780. this.aoMapIntensity = 1.0;
  19781. this.emissive = new Color(0x000000);
  19782. this.emissiveIntensity = 1.0;
  19783. this.emissiveMap = null;
  19784. this.bumpMap = null;
  19785. this.bumpScale = 1;
  19786. this.normalMap = null;
  19787. this.normalMapType = TangentSpaceNormalMap;
  19788. this.normalScale = new Vector2(1, 1);
  19789. this.displacementMap = null;
  19790. this.displacementScale = 1;
  19791. this.displacementBias = 0;
  19792. this.specularMap = null;
  19793. this.alphaMap = null;
  19794. this.envMap = null;
  19795. this.combine = MultiplyOperation;
  19796. this.reflectivity = 1;
  19797. this.refractionRatio = 0.98;
  19798. this.wireframe = false;
  19799. this.wireframeLinewidth = 1;
  19800. this.wireframeLinecap = 'round';
  19801. this.wireframeLinejoin = 'round';
  19802. this.flatShading = false;
  19803. this.setValues(parameters);
  19804. }
  19805. copy(source) {
  19806. super.copy(source);
  19807. this.color.copy(source.color);
  19808. this.specular.copy(source.specular);
  19809. this.shininess = source.shininess;
  19810. this.map = source.map;
  19811. this.lightMap = source.lightMap;
  19812. this.lightMapIntensity = source.lightMapIntensity;
  19813. this.aoMap = source.aoMap;
  19814. this.aoMapIntensity = source.aoMapIntensity;
  19815. this.emissive.copy(source.emissive);
  19816. this.emissiveMap = source.emissiveMap;
  19817. this.emissiveIntensity = source.emissiveIntensity;
  19818. this.bumpMap = source.bumpMap;
  19819. this.bumpScale = source.bumpScale;
  19820. this.normalMap = source.normalMap;
  19821. this.normalMapType = source.normalMapType;
  19822. this.normalScale.copy(source.normalScale);
  19823. this.displacementMap = source.displacementMap;
  19824. this.displacementScale = source.displacementScale;
  19825. this.displacementBias = source.displacementBias;
  19826. this.specularMap = source.specularMap;
  19827. this.alphaMap = source.alphaMap;
  19828. this.envMap = source.envMap;
  19829. this.combine = source.combine;
  19830. this.reflectivity = source.reflectivity;
  19831. this.refractionRatio = source.refractionRatio;
  19832. this.wireframe = source.wireframe;
  19833. this.wireframeLinewidth = source.wireframeLinewidth;
  19834. this.wireframeLinecap = source.wireframeLinecap;
  19835. this.wireframeLinejoin = source.wireframeLinejoin;
  19836. this.flatShading = source.flatShading;
  19837. return this;
  19838. }
  19839. }
  19840. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  19841. /**
  19842. * parameters = {
  19843. * color: <hex>,
  19844. *
  19845. * map: new THREE.Texture( <Image> ),
  19846. * gradientMap: new THREE.Texture( <Image> ),
  19847. *
  19848. * lightMap: new THREE.Texture( <Image> ),
  19849. * lightMapIntensity: <float>
  19850. *
  19851. * aoMap: new THREE.Texture( <Image> ),
  19852. * aoMapIntensity: <float>
  19853. *
  19854. * emissive: <hex>,
  19855. * emissiveIntensity: <float>
  19856. * emissiveMap: new THREE.Texture( <Image> ),
  19857. *
  19858. * bumpMap: new THREE.Texture( <Image> ),
  19859. * bumpScale: <float>,
  19860. *
  19861. * normalMap: new THREE.Texture( <Image> ),
  19862. * normalMapType: THREE.TangentSpaceNormalMap,
  19863. * normalScale: <Vector2>,
  19864. *
  19865. * displacementMap: new THREE.Texture( <Image> ),
  19866. * displacementScale: <float>,
  19867. * displacementBias: <float>,
  19868. *
  19869. * alphaMap: new THREE.Texture( <Image> ),
  19870. *
  19871. * wireframe: <boolean>,
  19872. * wireframeLinewidth: <float>,
  19873. *
  19874. * }
  19875. */
  19876. class MeshToonMaterial extends Material {
  19877. constructor(parameters) {
  19878. super();
  19879. this.defines = {
  19880. 'TOON': ''
  19881. };
  19882. this.type = 'MeshToonMaterial';
  19883. this.color = new Color(0xffffff);
  19884. this.map = null;
  19885. this.gradientMap = null;
  19886. this.lightMap = null;
  19887. this.lightMapIntensity = 1.0;
  19888. this.aoMap = null;
  19889. this.aoMapIntensity = 1.0;
  19890. this.emissive = new Color(0x000000);
  19891. this.emissiveIntensity = 1.0;
  19892. this.emissiveMap = null;
  19893. this.bumpMap = null;
  19894. this.bumpScale = 1;
  19895. this.normalMap = null;
  19896. this.normalMapType = TangentSpaceNormalMap;
  19897. this.normalScale = new Vector2(1, 1);
  19898. this.displacementMap = null;
  19899. this.displacementScale = 1;
  19900. this.displacementBias = 0;
  19901. this.alphaMap = null;
  19902. this.wireframe = false;
  19903. this.wireframeLinewidth = 1;
  19904. this.wireframeLinecap = 'round';
  19905. this.wireframeLinejoin = 'round';
  19906. this.setValues(parameters);
  19907. }
  19908. copy(source) {
  19909. super.copy(source);
  19910. this.color.copy(source.color);
  19911. this.map = source.map;
  19912. this.gradientMap = source.gradientMap;
  19913. this.lightMap = source.lightMap;
  19914. this.lightMapIntensity = source.lightMapIntensity;
  19915. this.aoMap = source.aoMap;
  19916. this.aoMapIntensity = source.aoMapIntensity;
  19917. this.emissive.copy(source.emissive);
  19918. this.emissiveMap = source.emissiveMap;
  19919. this.emissiveIntensity = source.emissiveIntensity;
  19920. this.bumpMap = source.bumpMap;
  19921. this.bumpScale = source.bumpScale;
  19922. this.normalMap = source.normalMap;
  19923. this.normalMapType = source.normalMapType;
  19924. this.normalScale.copy(source.normalScale);
  19925. this.displacementMap = source.displacementMap;
  19926. this.displacementScale = source.displacementScale;
  19927. this.displacementBias = source.displacementBias;
  19928. this.alphaMap = source.alphaMap;
  19929. this.wireframe = source.wireframe;
  19930. this.wireframeLinewidth = source.wireframeLinewidth;
  19931. this.wireframeLinecap = source.wireframeLinecap;
  19932. this.wireframeLinejoin = source.wireframeLinejoin;
  19933. return this;
  19934. }
  19935. }
  19936. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  19937. /**
  19938. * parameters = {
  19939. * opacity: <float>,
  19940. *
  19941. * bumpMap: new THREE.Texture( <Image> ),
  19942. * bumpScale: <float>,
  19943. *
  19944. * normalMap: new THREE.Texture( <Image> ),
  19945. * normalMapType: THREE.TangentSpaceNormalMap,
  19946. * normalScale: <Vector2>,
  19947. *
  19948. * displacementMap: new THREE.Texture( <Image> ),
  19949. * displacementScale: <float>,
  19950. * displacementBias: <float>,
  19951. *
  19952. * wireframe: <boolean>,
  19953. * wireframeLinewidth: <float>
  19954. *
  19955. * flatShading: <bool>
  19956. * }
  19957. */
  19958. class MeshNormalMaterial extends Material {
  19959. constructor(parameters) {
  19960. super();
  19961. this.type = 'MeshNormalMaterial';
  19962. this.bumpMap = null;
  19963. this.bumpScale = 1;
  19964. this.normalMap = null;
  19965. this.normalMapType = TangentSpaceNormalMap;
  19966. this.normalScale = new Vector2(1, 1);
  19967. this.displacementMap = null;
  19968. this.displacementScale = 1;
  19969. this.displacementBias = 0;
  19970. this.wireframe = false;
  19971. this.wireframeLinewidth = 1;
  19972. this.fog = false;
  19973. this.flatShading = false;
  19974. this.setValues(parameters);
  19975. }
  19976. copy(source) {
  19977. super.copy(source);
  19978. this.bumpMap = source.bumpMap;
  19979. this.bumpScale = source.bumpScale;
  19980. this.normalMap = source.normalMap;
  19981. this.normalMapType = source.normalMapType;
  19982. this.normalScale.copy(source.normalScale);
  19983. this.displacementMap = source.displacementMap;
  19984. this.displacementScale = source.displacementScale;
  19985. this.displacementBias = source.displacementBias;
  19986. this.wireframe = source.wireframe;
  19987. this.wireframeLinewidth = source.wireframeLinewidth;
  19988. this.flatShading = source.flatShading;
  19989. return this;
  19990. }
  19991. }
  19992. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  19993. /**
  19994. * parameters = {
  19995. * color: <hex>,
  19996. * opacity: <float>,
  19997. *
  19998. * map: new THREE.Texture( <Image> ),
  19999. *
  20000. * lightMap: new THREE.Texture( <Image> ),
  20001. * lightMapIntensity: <float>
  20002. *
  20003. * aoMap: new THREE.Texture( <Image> ),
  20004. * aoMapIntensity: <float>
  20005. *
  20006. * emissive: <hex>,
  20007. * emissiveIntensity: <float>
  20008. * emissiveMap: new THREE.Texture( <Image> ),
  20009. *
  20010. * specularMap: new THREE.Texture( <Image> ),
  20011. *
  20012. * alphaMap: new THREE.Texture( <Image> ),
  20013. *
  20014. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20015. * combine: THREE.Multiply,
  20016. * reflectivity: <float>,
  20017. * refractionRatio: <float>,
  20018. *
  20019. * wireframe: <boolean>,
  20020. * wireframeLinewidth: <float>,
  20021. *
  20022. * }
  20023. */
  20024. class MeshLambertMaterial extends Material {
  20025. constructor(parameters) {
  20026. super();
  20027. this.type = 'MeshLambertMaterial';
  20028. this.color = new Color(0xffffff); // diffuse
  20029. this.map = null;
  20030. this.lightMap = null;
  20031. this.lightMapIntensity = 1.0;
  20032. this.aoMap = null;
  20033. this.aoMapIntensity = 1.0;
  20034. this.emissive = new Color(0x000000);
  20035. this.emissiveIntensity = 1.0;
  20036. this.emissiveMap = null;
  20037. this.specularMap = null;
  20038. this.alphaMap = null;
  20039. this.envMap = null;
  20040. this.combine = MultiplyOperation;
  20041. this.reflectivity = 1;
  20042. this.refractionRatio = 0.98;
  20043. this.wireframe = false;
  20044. this.wireframeLinewidth = 1;
  20045. this.wireframeLinecap = 'round';
  20046. this.wireframeLinejoin = 'round';
  20047. this.setValues(parameters);
  20048. }
  20049. copy(source) {
  20050. super.copy(source);
  20051. this.color.copy(source.color);
  20052. this.map = source.map;
  20053. this.lightMap = source.lightMap;
  20054. this.lightMapIntensity = source.lightMapIntensity;
  20055. this.aoMap = source.aoMap;
  20056. this.aoMapIntensity = source.aoMapIntensity;
  20057. this.emissive.copy(source.emissive);
  20058. this.emissiveMap = source.emissiveMap;
  20059. this.emissiveIntensity = source.emissiveIntensity;
  20060. this.specularMap = source.specularMap;
  20061. this.alphaMap = source.alphaMap;
  20062. this.envMap = source.envMap;
  20063. this.combine = source.combine;
  20064. this.reflectivity = source.reflectivity;
  20065. this.refractionRatio = source.refractionRatio;
  20066. this.wireframe = source.wireframe;
  20067. this.wireframeLinewidth = source.wireframeLinewidth;
  20068. this.wireframeLinecap = source.wireframeLinecap;
  20069. this.wireframeLinejoin = source.wireframeLinejoin;
  20070. return this;
  20071. }
  20072. }
  20073. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  20074. /**
  20075. * parameters = {
  20076. * color: <hex>,
  20077. * opacity: <float>,
  20078. *
  20079. * matcap: new THREE.Texture( <Image> ),
  20080. *
  20081. * map: new THREE.Texture( <Image> ),
  20082. *
  20083. * bumpMap: new THREE.Texture( <Image> ),
  20084. * bumpScale: <float>,
  20085. *
  20086. * normalMap: new THREE.Texture( <Image> ),
  20087. * normalMapType: THREE.TangentSpaceNormalMap,
  20088. * normalScale: <Vector2>,
  20089. *
  20090. * displacementMap: new THREE.Texture( <Image> ),
  20091. * displacementScale: <float>,
  20092. * displacementBias: <float>,
  20093. *
  20094. * alphaMap: new THREE.Texture( <Image> ),
  20095. *
  20096. * flatShading: <bool>
  20097. * }
  20098. */
  20099. class MeshMatcapMaterial extends Material {
  20100. constructor(parameters) {
  20101. super();
  20102. this.defines = {
  20103. 'MATCAP': ''
  20104. };
  20105. this.type = 'MeshMatcapMaterial';
  20106. this.color = new Color(0xffffff); // diffuse
  20107. this.matcap = null;
  20108. this.map = null;
  20109. this.bumpMap = null;
  20110. this.bumpScale = 1;
  20111. this.normalMap = null;
  20112. this.normalMapType = TangentSpaceNormalMap;
  20113. this.normalScale = new Vector2(1, 1);
  20114. this.displacementMap = null;
  20115. this.displacementScale = 1;
  20116. this.displacementBias = 0;
  20117. this.alphaMap = null;
  20118. this.flatShading = false;
  20119. this.setValues(parameters);
  20120. }
  20121. copy(source) {
  20122. super.copy(source);
  20123. this.defines = {
  20124. 'MATCAP': ''
  20125. };
  20126. this.color.copy(source.color);
  20127. this.matcap = source.matcap;
  20128. this.map = source.map;
  20129. this.bumpMap = source.bumpMap;
  20130. this.bumpScale = source.bumpScale;
  20131. this.normalMap = source.normalMap;
  20132. this.normalMapType = source.normalMapType;
  20133. this.normalScale.copy(source.normalScale);
  20134. this.displacementMap = source.displacementMap;
  20135. this.displacementScale = source.displacementScale;
  20136. this.displacementBias = source.displacementBias;
  20137. this.alphaMap = source.alphaMap;
  20138. this.flatShading = source.flatShading;
  20139. return this;
  20140. }
  20141. }
  20142. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  20143. /**
  20144. * parameters = {
  20145. * color: <hex>,
  20146. * opacity: <float>,
  20147. *
  20148. * linewidth: <float>,
  20149. *
  20150. * scale: <float>,
  20151. * dashSize: <float>,
  20152. * gapSize: <float>
  20153. * }
  20154. */
  20155. class LineDashedMaterial extends LineBasicMaterial {
  20156. constructor(parameters) {
  20157. super();
  20158. this.type = 'LineDashedMaterial';
  20159. this.scale = 1;
  20160. this.dashSize = 3;
  20161. this.gapSize = 1;
  20162. this.setValues(parameters);
  20163. }
  20164. copy(source) {
  20165. super.copy(source);
  20166. this.scale = source.scale;
  20167. this.dashSize = source.dashSize;
  20168. this.gapSize = source.gapSize;
  20169. return this;
  20170. }
  20171. }
  20172. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  20173. var Materials = /*#__PURE__*/Object.freeze({
  20174. __proto__: null,
  20175. ShadowMaterial: ShadowMaterial,
  20176. SpriteMaterial: SpriteMaterial,
  20177. RawShaderMaterial: RawShaderMaterial,
  20178. ShaderMaterial: ShaderMaterial,
  20179. PointsMaterial: PointsMaterial,
  20180. MeshPhysicalMaterial: MeshPhysicalMaterial,
  20181. MeshStandardMaterial: MeshStandardMaterial,
  20182. MeshPhongMaterial: MeshPhongMaterial,
  20183. MeshToonMaterial: MeshToonMaterial,
  20184. MeshNormalMaterial: MeshNormalMaterial,
  20185. MeshLambertMaterial: MeshLambertMaterial,
  20186. MeshDepthMaterial: MeshDepthMaterial,
  20187. MeshDistanceMaterial: MeshDistanceMaterial,
  20188. MeshBasicMaterial: MeshBasicMaterial,
  20189. MeshMatcapMaterial: MeshMatcapMaterial,
  20190. LineDashedMaterial: LineDashedMaterial,
  20191. LineBasicMaterial: LineBasicMaterial,
  20192. Material: Material
  20193. });
  20194. const AnimationUtils = {
  20195. // same as Array.prototype.slice, but also works on typed arrays
  20196. arraySlice: function (array, from, to) {
  20197. if (AnimationUtils.isTypedArray(array)) {
  20198. // in ios9 array.subarray(from, undefined) will return empty array
  20199. // but array.subarray(from) or array.subarray(from, len) is correct
  20200. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  20201. }
  20202. return array.slice(from, to);
  20203. },
  20204. // converts an array to a specific type
  20205. convertArray: function (array, type, forceClone) {
  20206. if (!array || // let 'undefined' and 'null' pass
  20207. !forceClone && array.constructor === type) return array;
  20208. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  20209. return new type(array); // create typed array
  20210. }
  20211. return Array.prototype.slice.call(array); // create Array
  20212. },
  20213. isTypedArray: function (object) {
  20214. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  20215. },
  20216. // returns an array by which times and values can be sorted
  20217. getKeyframeOrder: function (times) {
  20218. function compareTime(i, j) {
  20219. return times[i] - times[j];
  20220. }
  20221. const n = times.length;
  20222. const result = new Array(n);
  20223. for (let i = 0; i !== n; ++i) result[i] = i;
  20224. result.sort(compareTime);
  20225. return result;
  20226. },
  20227. // uses the array previously returned by 'getKeyframeOrder' to sort data
  20228. sortedArray: function (values, stride, order) {
  20229. const nValues = values.length;
  20230. const result = new values.constructor(nValues);
  20231. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  20232. const srcOffset = order[i] * stride;
  20233. for (let j = 0; j !== stride; ++j) {
  20234. result[dstOffset++] = values[srcOffset + j];
  20235. }
  20236. }
  20237. return result;
  20238. },
  20239. // function for parsing AOS keyframe formats
  20240. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  20241. let i = 1,
  20242. key = jsonKeys[0];
  20243. while (key !== undefined && key[valuePropertyName] === undefined) {
  20244. key = jsonKeys[i++];
  20245. }
  20246. if (key === undefined) return; // no data
  20247. let value = key[valuePropertyName];
  20248. if (value === undefined) return; // no data
  20249. if (Array.isArray(value)) {
  20250. do {
  20251. value = key[valuePropertyName];
  20252. if (value !== undefined) {
  20253. times.push(key.time);
  20254. values.push.apply(values, value); // push all elements
  20255. }
  20256. key = jsonKeys[i++];
  20257. } while (key !== undefined);
  20258. } else if (value.toArray !== undefined) {
  20259. // ...assume THREE.Math-ish
  20260. do {
  20261. value = key[valuePropertyName];
  20262. if (value !== undefined) {
  20263. times.push(key.time);
  20264. value.toArray(values, values.length);
  20265. }
  20266. key = jsonKeys[i++];
  20267. } while (key !== undefined);
  20268. } else {
  20269. // otherwise push as-is
  20270. do {
  20271. value = key[valuePropertyName];
  20272. if (value !== undefined) {
  20273. times.push(key.time);
  20274. values.push(value);
  20275. }
  20276. key = jsonKeys[i++];
  20277. } while (key !== undefined);
  20278. }
  20279. },
  20280. subclip: function (sourceClip, name, startFrame, endFrame, fps = 30) {
  20281. const clip = sourceClip.clone();
  20282. clip.name = name;
  20283. const tracks = [];
  20284. for (let i = 0; i < clip.tracks.length; ++i) {
  20285. const track = clip.tracks[i];
  20286. const valueSize = track.getValueSize();
  20287. const times = [];
  20288. const values = [];
  20289. for (let j = 0; j < track.times.length; ++j) {
  20290. const frame = track.times[j] * fps;
  20291. if (frame < startFrame || frame >= endFrame) continue;
  20292. times.push(track.times[j]);
  20293. for (let k = 0; k < valueSize; ++k) {
  20294. values.push(track.values[j * valueSize + k]);
  20295. }
  20296. }
  20297. if (times.length === 0) continue;
  20298. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  20299. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  20300. tracks.push(track);
  20301. }
  20302. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  20303. let minStartTime = Infinity;
  20304. for (let i = 0; i < clip.tracks.length; ++i) {
  20305. if (minStartTime > clip.tracks[i].times[0]) {
  20306. minStartTime = clip.tracks[i].times[0];
  20307. }
  20308. } // shift all tracks such that clip begins at t=0
  20309. for (let i = 0; i < clip.tracks.length; ++i) {
  20310. clip.tracks[i].shift(-1 * minStartTime);
  20311. }
  20312. clip.resetDuration();
  20313. return clip;
  20314. },
  20315. makeClipAdditive: function (targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  20316. if (fps <= 0) fps = 30;
  20317. const numTracks = referenceClip.tracks.length;
  20318. const referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  20319. for (let i = 0; i < numTracks; ++i) {
  20320. const referenceTrack = referenceClip.tracks[i];
  20321. const referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  20322. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue; // Find the track in the target clip whose name and type matches the reference track
  20323. const targetTrack = targetClip.tracks.find(function (track) {
  20324. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  20325. });
  20326. if (targetTrack === undefined) continue;
  20327. let referenceOffset = 0;
  20328. const referenceValueSize = referenceTrack.getValueSize();
  20329. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  20330. referenceOffset = referenceValueSize / 3;
  20331. }
  20332. let targetOffset = 0;
  20333. const targetValueSize = targetTrack.getValueSize();
  20334. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  20335. targetOffset = targetValueSize / 3;
  20336. }
  20337. const lastIndex = referenceTrack.times.length - 1;
  20338. let referenceValue; // Find the value to subtract out of the track
  20339. if (referenceTime <= referenceTrack.times[0]) {
  20340. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  20341. const startIndex = referenceOffset;
  20342. const endIndex = referenceValueSize - referenceOffset;
  20343. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  20344. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  20345. // Reference frame is after the last keyframe, so just use the last keyframe
  20346. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  20347. const endIndex = startIndex + referenceValueSize - referenceOffset;
  20348. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  20349. } else {
  20350. // Interpolate to the reference value
  20351. const interpolant = referenceTrack.createInterpolant();
  20352. const startIndex = referenceOffset;
  20353. const endIndex = referenceValueSize - referenceOffset;
  20354. interpolant.evaluate(referenceTime);
  20355. referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  20356. } // Conjugate the quaternion
  20357. if (referenceTrackType === 'quaternion') {
  20358. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  20359. referenceQuat.toArray(referenceValue);
  20360. } // Subtract the reference value from all of the track values
  20361. const numTimes = targetTrack.times.length;
  20362. for (let j = 0; j < numTimes; ++j) {
  20363. const valueStart = j * targetValueSize + targetOffset;
  20364. if (referenceTrackType === 'quaternion') {
  20365. // Multiply the conjugate for quaternion track types
  20366. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  20367. } else {
  20368. const valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  20369. for (let k = 0; k < valueEnd; ++k) {
  20370. targetTrack.values[valueStart + k] -= referenceValue[k];
  20371. }
  20372. }
  20373. }
  20374. }
  20375. targetClip.blendMode = AdditiveAnimationBlendMode;
  20376. return targetClip;
  20377. }
  20378. };
  20379. /**
  20380. * Abstract base class of interpolants over parametric samples.
  20381. *
  20382. * The parameter domain is one dimensional, typically the time or a path
  20383. * along a curve defined by the data.
  20384. *
  20385. * The sample values can have any dimensionality and derived classes may
  20386. * apply special interpretations to the data.
  20387. *
  20388. * This class provides the interval seek in a Template Method, deferring
  20389. * the actual interpolation to derived classes.
  20390. *
  20391. * Time complexity is O(1) for linear access crossing at most two points
  20392. * and O(log N) for random access, where N is the number of positions.
  20393. *
  20394. * References:
  20395. *
  20396. * http://www.oodesign.com/template-method-pattern.html
  20397. *
  20398. */
  20399. class Interpolant {
  20400. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20401. this.parameterPositions = parameterPositions;
  20402. this._cachedIndex = 0;
  20403. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  20404. this.sampleValues = sampleValues;
  20405. this.valueSize = sampleSize;
  20406. this.settings = null;
  20407. this.DefaultSettings_ = {};
  20408. }
  20409. evaluate(t) {
  20410. const pp = this.parameterPositions;
  20411. let i1 = this._cachedIndex,
  20412. t1 = pp[i1],
  20413. t0 = pp[i1 - 1];
  20414. validate_interval: {
  20415. seek: {
  20416. let right;
  20417. linear_scan: {
  20418. //- See http://jsperf.com/comparison-to-undefined/3
  20419. //- slower code:
  20420. //-
  20421. //- if ( t >= t1 || t1 === undefined ) {
  20422. forward_scan: if (!(t < t1)) {
  20423. for (let giveUpAt = i1 + 2;;) {
  20424. if (t1 === undefined) {
  20425. if (t < t0) break forward_scan; // after end
  20426. i1 = pp.length;
  20427. this._cachedIndex = i1;
  20428. return this.afterEnd_(i1 - 1, t, t0);
  20429. }
  20430. if (i1 === giveUpAt) break; // this loop
  20431. t0 = t1;
  20432. t1 = pp[++i1];
  20433. if (t < t1) {
  20434. // we have arrived at the sought interval
  20435. break seek;
  20436. }
  20437. } // prepare binary search on the right side of the index
  20438. right = pp.length;
  20439. break linear_scan;
  20440. } //- slower code:
  20441. //- if ( t < t0 || t0 === undefined ) {
  20442. if (!(t >= t0)) {
  20443. // looping?
  20444. const t1global = pp[1];
  20445. if (t < t1global) {
  20446. i1 = 2; // + 1, using the scan for the details
  20447. t0 = t1global;
  20448. } // linear reverse scan
  20449. for (let giveUpAt = i1 - 2;;) {
  20450. if (t0 === undefined) {
  20451. // before start
  20452. this._cachedIndex = 0;
  20453. return this.beforeStart_(0, t, t1);
  20454. }
  20455. if (i1 === giveUpAt) break; // this loop
  20456. t1 = t0;
  20457. t0 = pp[--i1 - 1];
  20458. if (t >= t0) {
  20459. // we have arrived at the sought interval
  20460. break seek;
  20461. }
  20462. } // prepare binary search on the left side of the index
  20463. right = i1;
  20464. i1 = 0;
  20465. break linear_scan;
  20466. } // the interval is valid
  20467. break validate_interval;
  20468. } // linear scan
  20469. // binary search
  20470. while (i1 < right) {
  20471. const mid = i1 + right >>> 1;
  20472. if (t < pp[mid]) {
  20473. right = mid;
  20474. } else {
  20475. i1 = mid + 1;
  20476. }
  20477. }
  20478. t1 = pp[i1];
  20479. t0 = pp[i1 - 1]; // check boundary cases, again
  20480. if (t0 === undefined) {
  20481. this._cachedIndex = 0;
  20482. return this.beforeStart_(0, t, t1);
  20483. }
  20484. if (t1 === undefined) {
  20485. i1 = pp.length;
  20486. this._cachedIndex = i1;
  20487. return this.afterEnd_(i1 - 1, t0, t);
  20488. }
  20489. } // seek
  20490. this._cachedIndex = i1;
  20491. this.intervalChanged_(i1, t0, t1);
  20492. } // validate_interval
  20493. return this.interpolate_(i1, t0, t, t1);
  20494. }
  20495. getSettings_() {
  20496. return this.settings || this.DefaultSettings_;
  20497. }
  20498. copySampleValue_(index) {
  20499. // copies a sample value to the result buffer
  20500. const result = this.resultBuffer,
  20501. values = this.sampleValues,
  20502. stride = this.valueSize,
  20503. offset = index * stride;
  20504. for (let i = 0; i !== stride; ++i) {
  20505. result[i] = values[offset + i];
  20506. }
  20507. return result;
  20508. } // Template methods for derived classes:
  20509. interpolate_()
  20510. /* i1, t0, t, t1 */
  20511. {
  20512. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  20513. }
  20514. intervalChanged_()
  20515. /* i1, t0, t1 */
  20516. {// empty
  20517. }
  20518. } // ALIAS DEFINITIONS
  20519. Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
  20520. Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
  20521. /**
  20522. * Fast and simple cubic spline interpolant.
  20523. *
  20524. * It was derived from a Hermitian construction setting the first derivative
  20525. * at each sample position to the linear slope between neighboring positions
  20526. * over their parameter interval.
  20527. */
  20528. class CubicInterpolant extends Interpolant {
  20529. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20530. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  20531. this._weightPrev = -0;
  20532. this._offsetPrev = -0;
  20533. this._weightNext = -0;
  20534. this._offsetNext = -0;
  20535. this.DefaultSettings_ = {
  20536. endingStart: ZeroCurvatureEnding,
  20537. endingEnd: ZeroCurvatureEnding
  20538. };
  20539. }
  20540. intervalChanged_(i1, t0, t1) {
  20541. const pp = this.parameterPositions;
  20542. let iPrev = i1 - 2,
  20543. iNext = i1 + 1,
  20544. tPrev = pp[iPrev],
  20545. tNext = pp[iNext];
  20546. if (tPrev === undefined) {
  20547. switch (this.getSettings_().endingStart) {
  20548. case ZeroSlopeEnding:
  20549. // f'(t0) = 0
  20550. iPrev = i1;
  20551. tPrev = 2 * t0 - t1;
  20552. break;
  20553. case WrapAroundEnding:
  20554. // use the other end of the curve
  20555. iPrev = pp.length - 2;
  20556. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  20557. break;
  20558. default:
  20559. // ZeroCurvatureEnding
  20560. // f''(t0) = 0 a.k.a. Natural Spline
  20561. iPrev = i1;
  20562. tPrev = t1;
  20563. }
  20564. }
  20565. if (tNext === undefined) {
  20566. switch (this.getSettings_().endingEnd) {
  20567. case ZeroSlopeEnding:
  20568. // f'(tN) = 0
  20569. iNext = i1;
  20570. tNext = 2 * t1 - t0;
  20571. break;
  20572. case WrapAroundEnding:
  20573. // use the other end of the curve
  20574. iNext = 1;
  20575. tNext = t1 + pp[1] - pp[0];
  20576. break;
  20577. default:
  20578. // ZeroCurvatureEnding
  20579. // f''(tN) = 0, a.k.a. Natural Spline
  20580. iNext = i1 - 1;
  20581. tNext = t0;
  20582. }
  20583. }
  20584. const halfDt = (t1 - t0) * 0.5,
  20585. stride = this.valueSize;
  20586. this._weightPrev = halfDt / (t0 - tPrev);
  20587. this._weightNext = halfDt / (tNext - t1);
  20588. this._offsetPrev = iPrev * stride;
  20589. this._offsetNext = iNext * stride;
  20590. }
  20591. interpolate_(i1, t0, t, t1) {
  20592. const result = this.resultBuffer,
  20593. values = this.sampleValues,
  20594. stride = this.valueSize,
  20595. o1 = i1 * stride,
  20596. o0 = o1 - stride,
  20597. oP = this._offsetPrev,
  20598. oN = this._offsetNext,
  20599. wP = this._weightPrev,
  20600. wN = this._weightNext,
  20601. p = (t - t0) / (t1 - t0),
  20602. pp = p * p,
  20603. ppp = pp * p; // evaluate polynomials
  20604. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  20605. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  20606. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  20607. const sN = wN * ppp - wN * pp; // combine data linearly
  20608. for (let i = 0; i !== stride; ++i) {
  20609. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  20610. }
  20611. return result;
  20612. }
  20613. }
  20614. class LinearInterpolant extends Interpolant {
  20615. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20616. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  20617. }
  20618. interpolate_(i1, t0, t, t1) {
  20619. const result = this.resultBuffer,
  20620. values = this.sampleValues,
  20621. stride = this.valueSize,
  20622. offset1 = i1 * stride,
  20623. offset0 = offset1 - stride,
  20624. weight1 = (t - t0) / (t1 - t0),
  20625. weight0 = 1 - weight1;
  20626. for (let i = 0; i !== stride; ++i) {
  20627. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  20628. }
  20629. return result;
  20630. }
  20631. }
  20632. /**
  20633. *
  20634. * Interpolant that evaluates to the sample value at the position preceeding
  20635. * the parameter.
  20636. */
  20637. class DiscreteInterpolant extends Interpolant {
  20638. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20639. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  20640. }
  20641. interpolate_(i1
  20642. /*, t0, t, t1 */
  20643. ) {
  20644. return this.copySampleValue_(i1 - 1);
  20645. }
  20646. }
  20647. class KeyframeTrack {
  20648. constructor(name, times, values, interpolation) {
  20649. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  20650. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  20651. this.name = name;
  20652. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  20653. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  20654. this.setInterpolation(interpolation || this.DefaultInterpolation);
  20655. } // Serialization (in static context, because of constructor invocation
  20656. // and automatic invocation of .toJSON):
  20657. static toJSON(track) {
  20658. const trackType = track.constructor;
  20659. let json; // derived classes can define a static toJSON method
  20660. if (trackType.toJSON !== this.toJSON) {
  20661. json = trackType.toJSON(track);
  20662. } else {
  20663. // by default, we assume the data can be serialized as-is
  20664. json = {
  20665. 'name': track.name,
  20666. 'times': AnimationUtils.convertArray(track.times, Array),
  20667. 'values': AnimationUtils.convertArray(track.values, Array)
  20668. };
  20669. const interpolation = track.getInterpolation();
  20670. if (interpolation !== track.DefaultInterpolation) {
  20671. json.interpolation = interpolation;
  20672. }
  20673. }
  20674. json.type = track.ValueTypeName; // mandatory
  20675. return json;
  20676. }
  20677. InterpolantFactoryMethodDiscrete(result) {
  20678. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  20679. }
  20680. InterpolantFactoryMethodLinear(result) {
  20681. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  20682. }
  20683. InterpolantFactoryMethodSmooth(result) {
  20684. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  20685. }
  20686. setInterpolation(interpolation) {
  20687. let factoryMethod;
  20688. switch (interpolation) {
  20689. case InterpolateDiscrete:
  20690. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  20691. break;
  20692. case InterpolateLinear:
  20693. factoryMethod = this.InterpolantFactoryMethodLinear;
  20694. break;
  20695. case InterpolateSmooth:
  20696. factoryMethod = this.InterpolantFactoryMethodSmooth;
  20697. break;
  20698. }
  20699. if (factoryMethod === undefined) {
  20700. const message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
  20701. if (this.createInterpolant === undefined) {
  20702. // fall back to default, unless the default itself is messed up
  20703. if (interpolation !== this.DefaultInterpolation) {
  20704. this.setInterpolation(this.DefaultInterpolation);
  20705. } else {
  20706. throw new Error(message); // fatal, in this case
  20707. }
  20708. }
  20709. console.warn('THREE.KeyframeTrack:', message);
  20710. return this;
  20711. }
  20712. this.createInterpolant = factoryMethod;
  20713. return this;
  20714. }
  20715. getInterpolation() {
  20716. switch (this.createInterpolant) {
  20717. case this.InterpolantFactoryMethodDiscrete:
  20718. return InterpolateDiscrete;
  20719. case this.InterpolantFactoryMethodLinear:
  20720. return InterpolateLinear;
  20721. case this.InterpolantFactoryMethodSmooth:
  20722. return InterpolateSmooth;
  20723. }
  20724. }
  20725. getValueSize() {
  20726. return this.values.length / this.times.length;
  20727. } // move all keyframes either forwards or backwards in time
  20728. shift(timeOffset) {
  20729. if (timeOffset !== 0.0) {
  20730. const times = this.times;
  20731. for (let i = 0, n = times.length; i !== n; ++i) {
  20732. times[i] += timeOffset;
  20733. }
  20734. }
  20735. return this;
  20736. } // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  20737. scale(timeScale) {
  20738. if (timeScale !== 1.0) {
  20739. const times = this.times;
  20740. for (let i = 0, n = times.length; i !== n; ++i) {
  20741. times[i] *= timeScale;
  20742. }
  20743. }
  20744. return this;
  20745. } // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  20746. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  20747. trim(startTime, endTime) {
  20748. const times = this.times,
  20749. nKeys = times.length;
  20750. let from = 0,
  20751. to = nKeys - 1;
  20752. while (from !== nKeys && times[from] < startTime) {
  20753. ++from;
  20754. }
  20755. while (to !== -1 && times[to] > endTime) {
  20756. --to;
  20757. }
  20758. ++to; // inclusive -> exclusive bound
  20759. if (from !== 0 || to !== nKeys) {
  20760. // empty tracks are forbidden, so keep at least one keyframe
  20761. if (from >= to) {
  20762. to = Math.max(to, 1);
  20763. from = to - 1;
  20764. }
  20765. const stride = this.getValueSize();
  20766. this.times = AnimationUtils.arraySlice(times, from, to);
  20767. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  20768. }
  20769. return this;
  20770. } // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  20771. validate() {
  20772. let valid = true;
  20773. const valueSize = this.getValueSize();
  20774. if (valueSize - Math.floor(valueSize) !== 0) {
  20775. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  20776. valid = false;
  20777. }
  20778. const times = this.times,
  20779. values = this.values,
  20780. nKeys = times.length;
  20781. if (nKeys === 0) {
  20782. console.error('THREE.KeyframeTrack: Track is empty.', this);
  20783. valid = false;
  20784. }
  20785. let prevTime = null;
  20786. for (let i = 0; i !== nKeys; i++) {
  20787. const currTime = times[i];
  20788. if (typeof currTime === 'number' && isNaN(currTime)) {
  20789. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  20790. valid = false;
  20791. break;
  20792. }
  20793. if (prevTime !== null && prevTime > currTime) {
  20794. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  20795. valid = false;
  20796. break;
  20797. }
  20798. prevTime = currTime;
  20799. }
  20800. if (values !== undefined) {
  20801. if (AnimationUtils.isTypedArray(values)) {
  20802. for (let i = 0, n = values.length; i !== n; ++i) {
  20803. const value = values[i];
  20804. if (isNaN(value)) {
  20805. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  20806. valid = false;
  20807. break;
  20808. }
  20809. }
  20810. }
  20811. }
  20812. return valid;
  20813. } // removes equivalent sequential keys as common in morph target sequences
  20814. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  20815. optimize() {
  20816. // times or values may be shared with other tracks, so overwriting is unsafe
  20817. const times = AnimationUtils.arraySlice(this.times),
  20818. values = AnimationUtils.arraySlice(this.values),
  20819. stride = this.getValueSize(),
  20820. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  20821. lastIndex = times.length - 1;
  20822. let writeIndex = 1;
  20823. for (let i = 1; i < lastIndex; ++i) {
  20824. let keep = false;
  20825. const time = times[i];
  20826. const timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  20827. if (time !== timeNext && (i !== 1 || time !== times[0])) {
  20828. if (!smoothInterpolation) {
  20829. // remove unnecessary keyframes same as their neighbors
  20830. const offset = i * stride,
  20831. offsetP = offset - stride,
  20832. offsetN = offset + stride;
  20833. for (let j = 0; j !== stride; ++j) {
  20834. const value = values[offset + j];
  20835. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  20836. keep = true;
  20837. break;
  20838. }
  20839. }
  20840. } else {
  20841. keep = true;
  20842. }
  20843. } // in-place compaction
  20844. if (keep) {
  20845. if (i !== writeIndex) {
  20846. times[writeIndex] = times[i];
  20847. const readOffset = i * stride,
  20848. writeOffset = writeIndex * stride;
  20849. for (let j = 0; j !== stride; ++j) {
  20850. values[writeOffset + j] = values[readOffset + j];
  20851. }
  20852. }
  20853. ++writeIndex;
  20854. }
  20855. } // flush last keyframe (compaction looks ahead)
  20856. if (lastIndex > 0) {
  20857. times[writeIndex] = times[lastIndex];
  20858. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  20859. values[writeOffset + j] = values[readOffset + j];
  20860. }
  20861. ++writeIndex;
  20862. }
  20863. if (writeIndex !== times.length) {
  20864. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  20865. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  20866. } else {
  20867. this.times = times;
  20868. this.values = values;
  20869. }
  20870. return this;
  20871. }
  20872. clone() {
  20873. const times = AnimationUtils.arraySlice(this.times, 0);
  20874. const values = AnimationUtils.arraySlice(this.values, 0);
  20875. const TypedKeyframeTrack = this.constructor;
  20876. const track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  20877. track.createInterpolant = this.createInterpolant;
  20878. return track;
  20879. }
  20880. }
  20881. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  20882. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  20883. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  20884. /**
  20885. * A Track of Boolean keyframe values.
  20886. */
  20887. class BooleanKeyframeTrack extends KeyframeTrack {}
  20888. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  20889. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  20890. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  20891. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  20892. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; // Note: Actually this track could have a optimized / compressed
  20893. /**
  20894. * A Track of keyframe values that represent color.
  20895. */
  20896. class ColorKeyframeTrack extends KeyframeTrack {}
  20897. ColorKeyframeTrack.prototype.ValueTypeName = 'color'; // ValueBufferType is inherited
  20898. /**
  20899. * A Track of numeric keyframe values.
  20900. */
  20901. class NumberKeyframeTrack extends KeyframeTrack {}
  20902. NumberKeyframeTrack.prototype.ValueTypeName = 'number'; // ValueBufferType is inherited
  20903. /**
  20904. * Spherical linear unit quaternion interpolant.
  20905. */
  20906. class QuaternionLinearInterpolant extends Interpolant {
  20907. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20908. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  20909. }
  20910. interpolate_(i1, t0, t, t1) {
  20911. const result = this.resultBuffer,
  20912. values = this.sampleValues,
  20913. stride = this.valueSize,
  20914. alpha = (t - t0) / (t1 - t0);
  20915. let offset = i1 * stride;
  20916. for (let end = offset + stride; offset !== end; offset += 4) {
  20917. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  20918. }
  20919. return result;
  20920. }
  20921. }
  20922. /**
  20923. * A Track of quaternion keyframe values.
  20924. */
  20925. class QuaternionKeyframeTrack extends KeyframeTrack {
  20926. InterpolantFactoryMethodLinear(result) {
  20927. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  20928. }
  20929. }
  20930. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; // ValueBufferType is inherited
  20931. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  20932. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  20933. /**
  20934. * A Track that interpolates Strings
  20935. */
  20936. class StringKeyframeTrack extends KeyframeTrack {}
  20937. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  20938. StringKeyframeTrack.prototype.ValueBufferType = Array;
  20939. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  20940. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  20941. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  20942. /**
  20943. * A Track of vectored keyframe values.
  20944. */
  20945. class VectorKeyframeTrack extends KeyframeTrack {}
  20946. VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; // ValueBufferType is inherited
  20947. class AnimationClip {
  20948. constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) {
  20949. this.name = name;
  20950. this.tracks = tracks;
  20951. this.duration = duration;
  20952. this.blendMode = blendMode;
  20953. this.uuid = generateUUID(); // this means it should figure out its duration by scanning the tracks
  20954. if (this.duration < 0) {
  20955. this.resetDuration();
  20956. }
  20957. }
  20958. static parse(json) {
  20959. const tracks = [],
  20960. jsonTracks = json.tracks,
  20961. frameTime = 1.0 / (json.fps || 1.0);
  20962. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  20963. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  20964. }
  20965. const clip = new this(json.name, json.duration, tracks, json.blendMode);
  20966. clip.uuid = json.uuid;
  20967. return clip;
  20968. }
  20969. static toJSON(clip) {
  20970. const tracks = [],
  20971. clipTracks = clip.tracks;
  20972. const json = {
  20973. 'name': clip.name,
  20974. 'duration': clip.duration,
  20975. 'tracks': tracks,
  20976. 'uuid': clip.uuid,
  20977. 'blendMode': clip.blendMode
  20978. };
  20979. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  20980. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  20981. }
  20982. return json;
  20983. }
  20984. static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  20985. const numMorphTargets = morphTargetSequence.length;
  20986. const tracks = [];
  20987. for (let i = 0; i < numMorphTargets; i++) {
  20988. let times = [];
  20989. let values = [];
  20990. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  20991. values.push(0, 1, 0);
  20992. const order = AnimationUtils.getKeyframeOrder(times);
  20993. times = AnimationUtils.sortedArray(times, 1, order);
  20994. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  20995. // last frame as well for perfect loop.
  20996. if (!noLoop && times[0] === 0) {
  20997. times.push(numMorphTargets);
  20998. values.push(values[0]);
  20999. }
  21000. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  21001. }
  21002. return new this(name, -1, tracks);
  21003. }
  21004. static findByName(objectOrClipArray, name) {
  21005. let clipArray = objectOrClipArray;
  21006. if (!Array.isArray(objectOrClipArray)) {
  21007. const o = objectOrClipArray;
  21008. clipArray = o.geometry && o.geometry.animations || o.animations;
  21009. }
  21010. for (let i = 0; i < clipArray.length; i++) {
  21011. if (clipArray[i].name === name) {
  21012. return clipArray[i];
  21013. }
  21014. }
  21015. return null;
  21016. }
  21017. static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  21018. const animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  21019. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  21020. const pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  21021. // patterns like Walk_001, Walk_002, Run_001, Run_002
  21022. for (let i = 0, il = morphTargets.length; i < il; i++) {
  21023. const morphTarget = morphTargets[i];
  21024. const parts = morphTarget.name.match(pattern);
  21025. if (parts && parts.length > 1) {
  21026. const name = parts[1];
  21027. let animationMorphTargets = animationToMorphTargets[name];
  21028. if (!animationMorphTargets) {
  21029. animationToMorphTargets[name] = animationMorphTargets = [];
  21030. }
  21031. animationMorphTargets.push(morphTarget);
  21032. }
  21033. }
  21034. const clips = [];
  21035. for (const name in animationToMorphTargets) {
  21036. clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  21037. }
  21038. return clips;
  21039. } // parse the animation.hierarchy format
  21040. static parseAnimation(animation, bones) {
  21041. if (!animation) {
  21042. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  21043. return null;
  21044. }
  21045. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  21046. // only return track if there are actually keys.
  21047. if (animationKeys.length !== 0) {
  21048. const times = [];
  21049. const values = [];
  21050. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  21051. if (times.length !== 0) {
  21052. destTracks.push(new trackType(trackName, times, values));
  21053. }
  21054. }
  21055. };
  21056. const tracks = [];
  21057. const clipName = animation.name || 'default';
  21058. const fps = animation.fps || 30;
  21059. const blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  21060. let duration = animation.length || -1;
  21061. const hierarchyTracks = animation.hierarchy || [];
  21062. for (let h = 0; h < hierarchyTracks.length; h++) {
  21063. const animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  21064. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  21065. if (animationKeys[0].morphTargets) {
  21066. // figure out all morph targets used in this track
  21067. const morphTargetNames = {};
  21068. let k;
  21069. for (k = 0; k < animationKeys.length; k++) {
  21070. if (animationKeys[k].morphTargets) {
  21071. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  21072. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  21073. }
  21074. }
  21075. } // create a track for each morph target with all zero
  21076. // morphTargetInfluences except for the keys in which
  21077. // the morphTarget is named.
  21078. for (const morphTargetName in morphTargetNames) {
  21079. const times = [];
  21080. const values = [];
  21081. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  21082. const animationKey = animationKeys[k];
  21083. times.push(animationKey.time);
  21084. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  21085. }
  21086. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  21087. }
  21088. duration = morphTargetNames.length * (fps || 1.0);
  21089. } else {
  21090. // ...assume skeletal animation
  21091. const boneName = '.bones[' + bones[h].name + ']';
  21092. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  21093. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  21094. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  21095. }
  21096. }
  21097. if (tracks.length === 0) {
  21098. return null;
  21099. }
  21100. const clip = new this(clipName, duration, tracks, blendMode);
  21101. return clip;
  21102. }
  21103. resetDuration() {
  21104. const tracks = this.tracks;
  21105. let duration = 0;
  21106. for (let i = 0, n = tracks.length; i !== n; ++i) {
  21107. const track = this.tracks[i];
  21108. duration = Math.max(duration, track.times[track.times.length - 1]);
  21109. }
  21110. this.duration = duration;
  21111. return this;
  21112. }
  21113. trim() {
  21114. for (let i = 0; i < this.tracks.length; i++) {
  21115. this.tracks[i].trim(0, this.duration);
  21116. }
  21117. return this;
  21118. }
  21119. validate() {
  21120. let valid = true;
  21121. for (let i = 0; i < this.tracks.length; i++) {
  21122. valid = valid && this.tracks[i].validate();
  21123. }
  21124. return valid;
  21125. }
  21126. optimize() {
  21127. for (let i = 0; i < this.tracks.length; i++) {
  21128. this.tracks[i].optimize();
  21129. }
  21130. return this;
  21131. }
  21132. clone() {
  21133. const tracks = [];
  21134. for (let i = 0; i < this.tracks.length; i++) {
  21135. tracks.push(this.tracks[i].clone());
  21136. }
  21137. return new this.constructor(this.name, this.duration, tracks, this.blendMode);
  21138. }
  21139. toJSON() {
  21140. return this.constructor.toJSON(this);
  21141. }
  21142. }
  21143. function getTrackTypeForValueTypeName(typeName) {
  21144. switch (typeName.toLowerCase()) {
  21145. case 'scalar':
  21146. case 'double':
  21147. case 'float':
  21148. case 'number':
  21149. case 'integer':
  21150. return NumberKeyframeTrack;
  21151. case 'vector':
  21152. case 'vector2':
  21153. case 'vector3':
  21154. case 'vector4':
  21155. return VectorKeyframeTrack;
  21156. case 'color':
  21157. return ColorKeyframeTrack;
  21158. case 'quaternion':
  21159. return QuaternionKeyframeTrack;
  21160. case 'bool':
  21161. case 'boolean':
  21162. return BooleanKeyframeTrack;
  21163. case 'string':
  21164. return StringKeyframeTrack;
  21165. }
  21166. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  21167. }
  21168. function parseKeyframeTrack(json) {
  21169. if (json.type === undefined) {
  21170. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  21171. }
  21172. const trackType = getTrackTypeForValueTypeName(json.type);
  21173. if (json.times === undefined) {
  21174. const times = [],
  21175. values = [];
  21176. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  21177. json.times = times;
  21178. json.values = values;
  21179. } // derived classes can define a static parse method
  21180. if (trackType.parse !== undefined) {
  21181. return trackType.parse(json);
  21182. } else {
  21183. // by default, we assume a constructor compatible with the base
  21184. return new trackType(json.name, json.times, json.values, json.interpolation);
  21185. }
  21186. }
  21187. const Cache = {
  21188. enabled: false,
  21189. files: {},
  21190. add: function (key, file) {
  21191. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  21192. this.files[key] = file;
  21193. },
  21194. get: function (key) {
  21195. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  21196. return this.files[key];
  21197. },
  21198. remove: function (key) {
  21199. delete this.files[key];
  21200. },
  21201. clear: function () {
  21202. this.files = {};
  21203. }
  21204. };
  21205. class LoadingManager {
  21206. constructor(onLoad, onProgress, onError) {
  21207. const scope = this;
  21208. let isLoading = false;
  21209. let itemsLoaded = 0;
  21210. let itemsTotal = 0;
  21211. let urlModifier = undefined;
  21212. const handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  21213. // in the constructor
  21214. this.onStart = undefined;
  21215. this.onLoad = onLoad;
  21216. this.onProgress = onProgress;
  21217. this.onError = onError;
  21218. this.itemStart = function (url) {
  21219. itemsTotal++;
  21220. if (isLoading === false) {
  21221. if (scope.onStart !== undefined) {
  21222. scope.onStart(url, itemsLoaded, itemsTotal);
  21223. }
  21224. }
  21225. isLoading = true;
  21226. };
  21227. this.itemEnd = function (url) {
  21228. itemsLoaded++;
  21229. if (scope.onProgress !== undefined) {
  21230. scope.onProgress(url, itemsLoaded, itemsTotal);
  21231. }
  21232. if (itemsLoaded === itemsTotal) {
  21233. isLoading = false;
  21234. if (scope.onLoad !== undefined) {
  21235. scope.onLoad();
  21236. }
  21237. }
  21238. };
  21239. this.itemError = function (url) {
  21240. if (scope.onError !== undefined) {
  21241. scope.onError(url);
  21242. }
  21243. };
  21244. this.resolveURL = function (url) {
  21245. if (urlModifier) {
  21246. return urlModifier(url);
  21247. }
  21248. return url;
  21249. };
  21250. this.setURLModifier = function (transform) {
  21251. urlModifier = transform;
  21252. return this;
  21253. };
  21254. this.addHandler = function (regex, loader) {
  21255. handlers.push(regex, loader);
  21256. return this;
  21257. };
  21258. this.removeHandler = function (regex) {
  21259. const index = handlers.indexOf(regex);
  21260. if (index !== -1) {
  21261. handlers.splice(index, 2);
  21262. }
  21263. return this;
  21264. };
  21265. this.getHandler = function (file) {
  21266. for (let i = 0, l = handlers.length; i < l; i += 2) {
  21267. const regex = handlers[i];
  21268. const loader = handlers[i + 1];
  21269. if (regex.global) regex.lastIndex = 0; // see #17920
  21270. if (regex.test(file)) {
  21271. return loader;
  21272. }
  21273. }
  21274. return null;
  21275. };
  21276. }
  21277. }
  21278. const DefaultLoadingManager = new LoadingManager();
  21279. class Loader {
  21280. constructor(manager) {
  21281. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  21282. this.crossOrigin = 'anonymous';
  21283. this.withCredentials = false;
  21284. this.path = '';
  21285. this.resourcePath = '';
  21286. this.requestHeader = {};
  21287. }
  21288. load()
  21289. /* url, onLoad, onProgress, onError */
  21290. {}
  21291. loadAsync(url, onProgress) {
  21292. const scope = this;
  21293. return new Promise(function (resolve, reject) {
  21294. scope.load(url, resolve, onProgress, reject);
  21295. });
  21296. }
  21297. parse()
  21298. /* data */
  21299. {}
  21300. setCrossOrigin(crossOrigin) {
  21301. this.crossOrigin = crossOrigin;
  21302. return this;
  21303. }
  21304. setWithCredentials(value) {
  21305. this.withCredentials = value;
  21306. return this;
  21307. }
  21308. setPath(path) {
  21309. this.path = path;
  21310. return this;
  21311. }
  21312. setResourcePath(resourcePath) {
  21313. this.resourcePath = resourcePath;
  21314. return this;
  21315. }
  21316. setRequestHeader(requestHeader) {
  21317. this.requestHeader = requestHeader;
  21318. return this;
  21319. }
  21320. }
  21321. const loading = {};
  21322. class FileLoader extends Loader {
  21323. constructor(manager) {
  21324. super(manager);
  21325. }
  21326. load(url, onLoad, onProgress, onError) {
  21327. if (url === undefined) url = '';
  21328. if (this.path !== undefined) url = this.path + url;
  21329. url = this.manager.resolveURL(url);
  21330. const scope = this;
  21331. const cached = Cache.get(url);
  21332. if (cached !== undefined) {
  21333. scope.manager.itemStart(url);
  21334. setTimeout(function () {
  21335. if (onLoad) onLoad(cached);
  21336. scope.manager.itemEnd(url);
  21337. }, 0);
  21338. return cached;
  21339. } // Check if request is duplicate
  21340. if (loading[url] !== undefined) {
  21341. loading[url].push({
  21342. onLoad: onLoad,
  21343. onProgress: onProgress,
  21344. onError: onError
  21345. });
  21346. return;
  21347. } // Check for data: URI
  21348. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  21349. const dataUriRegexResult = url.match(dataUriRegex);
  21350. let request; // Safari can not handle Data URIs through XMLHttpRequest so process manually
  21351. if (dataUriRegexResult) {
  21352. const mimeType = dataUriRegexResult[1];
  21353. const isBase64 = !!dataUriRegexResult[2];
  21354. let data = dataUriRegexResult[3];
  21355. data = decodeURIComponent(data);
  21356. if (isBase64) data = atob(data);
  21357. try {
  21358. let response;
  21359. const responseType = (this.responseType || '').toLowerCase();
  21360. switch (responseType) {
  21361. case 'arraybuffer':
  21362. case 'blob':
  21363. const view = new Uint8Array(data.length);
  21364. for (let i = 0; i < data.length; i++) {
  21365. view[i] = data.charCodeAt(i);
  21366. }
  21367. if (responseType === 'blob') {
  21368. response = new Blob([view.buffer], {
  21369. type: mimeType
  21370. });
  21371. } else {
  21372. response = view.buffer;
  21373. }
  21374. break;
  21375. case 'document':
  21376. const parser = new DOMParser();
  21377. response = parser.parseFromString(data, mimeType);
  21378. break;
  21379. case 'json':
  21380. response = JSON.parse(data);
  21381. break;
  21382. default:
  21383. // 'text' or other
  21384. response = data;
  21385. break;
  21386. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  21387. setTimeout(function () {
  21388. if (onLoad) onLoad(response);
  21389. scope.manager.itemEnd(url);
  21390. }, 0);
  21391. } catch (error) {
  21392. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  21393. setTimeout(function () {
  21394. if (onError) onError(error);
  21395. scope.manager.itemError(url);
  21396. scope.manager.itemEnd(url);
  21397. }, 0);
  21398. }
  21399. } else {
  21400. // Initialise array for duplicate requests
  21401. loading[url] = [];
  21402. loading[url].push({
  21403. onLoad: onLoad,
  21404. onProgress: onProgress,
  21405. onError: onError
  21406. });
  21407. request = new XMLHttpRequest();
  21408. request.open('GET', url, true);
  21409. request.addEventListener('load', function (event) {
  21410. const response = this.response;
  21411. const callbacks = loading[url];
  21412. delete loading[url];
  21413. if (this.status === 200 || this.status === 0) {
  21414. // Some browsers return HTTP Status 0 when using non-http protocol
  21415. // e.g. 'file://' or 'data://'. Handle as success.
  21416. 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
  21417. // error response bodies as proper responses to requests.
  21418. Cache.add(url, response);
  21419. for (let i = 0, il = callbacks.length; i < il; i++) {
  21420. const callback = callbacks[i];
  21421. if (callback.onLoad) callback.onLoad(response);
  21422. }
  21423. scope.manager.itemEnd(url);
  21424. } else {
  21425. for (let i = 0, il = callbacks.length; i < il; i++) {
  21426. const callback = callbacks[i];
  21427. if (callback.onError) callback.onError(event);
  21428. }
  21429. scope.manager.itemError(url);
  21430. scope.manager.itemEnd(url);
  21431. }
  21432. }, false);
  21433. request.addEventListener('progress', function (event) {
  21434. const callbacks = loading[url];
  21435. for (let i = 0, il = callbacks.length; i < il; i++) {
  21436. const callback = callbacks[i];
  21437. if (callback.onProgress) callback.onProgress(event);
  21438. }
  21439. }, false);
  21440. request.addEventListener('error', function (event) {
  21441. const callbacks = loading[url];
  21442. delete loading[url];
  21443. for (let i = 0, il = callbacks.length; i < il; i++) {
  21444. const callback = callbacks[i];
  21445. if (callback.onError) callback.onError(event);
  21446. }
  21447. scope.manager.itemError(url);
  21448. scope.manager.itemEnd(url);
  21449. }, false);
  21450. request.addEventListener('abort', function (event) {
  21451. const callbacks = loading[url];
  21452. delete loading[url];
  21453. for (let i = 0, il = callbacks.length; i < il; i++) {
  21454. const callback = callbacks[i];
  21455. if (callback.onError) callback.onError(event);
  21456. }
  21457. scope.manager.itemError(url);
  21458. scope.manager.itemEnd(url);
  21459. }, false);
  21460. if (this.responseType !== undefined) request.responseType = this.responseType;
  21461. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  21462. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  21463. for (const header in this.requestHeader) {
  21464. request.setRequestHeader(header, this.requestHeader[header]);
  21465. }
  21466. request.send(null);
  21467. }
  21468. scope.manager.itemStart(url);
  21469. return request;
  21470. }
  21471. setResponseType(value) {
  21472. this.responseType = value;
  21473. return this;
  21474. }
  21475. setMimeType(value) {
  21476. this.mimeType = value;
  21477. return this;
  21478. }
  21479. }
  21480. class AnimationLoader extends Loader {
  21481. constructor(manager) {
  21482. super(manager);
  21483. }
  21484. load(url, onLoad, onProgress, onError) {
  21485. const scope = this;
  21486. const loader = new FileLoader(this.manager);
  21487. loader.setPath(this.path);
  21488. loader.setRequestHeader(this.requestHeader);
  21489. loader.setWithCredentials(this.withCredentials);
  21490. loader.load(url, function (text) {
  21491. try {
  21492. onLoad(scope.parse(JSON.parse(text)));
  21493. } catch (e) {
  21494. if (onError) {
  21495. onError(e);
  21496. } else {
  21497. console.error(e);
  21498. }
  21499. scope.manager.itemError(url);
  21500. }
  21501. }, onProgress, onError);
  21502. }
  21503. parse(json) {
  21504. const animations = [];
  21505. for (let i = 0; i < json.length; i++) {
  21506. const clip = AnimationClip.parse(json[i]);
  21507. animations.push(clip);
  21508. }
  21509. return animations;
  21510. }
  21511. }
  21512. /**
  21513. * Abstract Base class to block based textures loader (dds, pvr, ...)
  21514. *
  21515. * Sub classes have to implement the parse() method which will be used in load().
  21516. */
  21517. class CompressedTextureLoader extends Loader {
  21518. constructor(manager) {
  21519. super(manager);
  21520. }
  21521. load(url, onLoad, onProgress, onError) {
  21522. const scope = this;
  21523. const images = [];
  21524. const texture = new CompressedTexture();
  21525. const loader = new FileLoader(this.manager);
  21526. loader.setPath(this.path);
  21527. loader.setResponseType('arraybuffer');
  21528. loader.setRequestHeader(this.requestHeader);
  21529. loader.setWithCredentials(scope.withCredentials);
  21530. let loaded = 0;
  21531. function loadTexture(i) {
  21532. loader.load(url[i], function (buffer) {
  21533. const texDatas = scope.parse(buffer, true);
  21534. images[i] = {
  21535. width: texDatas.width,
  21536. height: texDatas.height,
  21537. format: texDatas.format,
  21538. mipmaps: texDatas.mipmaps
  21539. };
  21540. loaded += 1;
  21541. if (loaded === 6) {
  21542. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  21543. texture.image = images;
  21544. texture.format = texDatas.format;
  21545. texture.needsUpdate = true;
  21546. if (onLoad) onLoad(texture);
  21547. }
  21548. }, onProgress, onError);
  21549. }
  21550. if (Array.isArray(url)) {
  21551. for (let i = 0, il = url.length; i < il; ++i) {
  21552. loadTexture(i);
  21553. }
  21554. } else {
  21555. // compressed cubemap texture stored in a single DDS file
  21556. loader.load(url, function (buffer) {
  21557. const texDatas = scope.parse(buffer, true);
  21558. if (texDatas.isCubemap) {
  21559. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  21560. for (let f = 0; f < faces; f++) {
  21561. images[f] = {
  21562. mipmaps: []
  21563. };
  21564. for (let i = 0; i < texDatas.mipmapCount; i++) {
  21565. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  21566. images[f].format = texDatas.format;
  21567. images[f].width = texDatas.width;
  21568. images[f].height = texDatas.height;
  21569. }
  21570. }
  21571. texture.image = images;
  21572. } else {
  21573. texture.image.width = texDatas.width;
  21574. texture.image.height = texDatas.height;
  21575. texture.mipmaps = texDatas.mipmaps;
  21576. }
  21577. if (texDatas.mipmapCount === 1) {
  21578. texture.minFilter = LinearFilter;
  21579. }
  21580. texture.format = texDatas.format;
  21581. texture.needsUpdate = true;
  21582. if (onLoad) onLoad(texture);
  21583. }, onProgress, onError);
  21584. }
  21585. return texture;
  21586. }
  21587. }
  21588. class ImageLoader extends Loader {
  21589. constructor(manager) {
  21590. super(manager);
  21591. }
  21592. load(url, onLoad, onProgress, onError) {
  21593. if (this.path !== undefined) url = this.path + url;
  21594. url = this.manager.resolveURL(url);
  21595. const scope = this;
  21596. const cached = Cache.get(url);
  21597. if (cached !== undefined) {
  21598. scope.manager.itemStart(url);
  21599. setTimeout(function () {
  21600. if (onLoad) onLoad(cached);
  21601. scope.manager.itemEnd(url);
  21602. }, 0);
  21603. return cached;
  21604. }
  21605. const image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  21606. function onImageLoad() {
  21607. image.removeEventListener('load', onImageLoad, false);
  21608. image.removeEventListener('error', onImageError, false);
  21609. Cache.add(url, this);
  21610. if (onLoad) onLoad(this);
  21611. scope.manager.itemEnd(url);
  21612. }
  21613. function onImageError(event) {
  21614. image.removeEventListener('load', onImageLoad, false);
  21615. image.removeEventListener('error', onImageError, false);
  21616. if (onError) onError(event);
  21617. scope.manager.itemError(url);
  21618. scope.manager.itemEnd(url);
  21619. }
  21620. image.addEventListener('load', onImageLoad, false);
  21621. image.addEventListener('error', onImageError, false);
  21622. if (url.substr(0, 5) !== 'data:') {
  21623. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  21624. }
  21625. scope.manager.itemStart(url);
  21626. image.src = url;
  21627. return image;
  21628. }
  21629. }
  21630. class CubeTextureLoader extends Loader {
  21631. constructor(manager) {
  21632. super(manager);
  21633. }
  21634. load(urls, onLoad, onProgress, onError) {
  21635. const texture = new CubeTexture();
  21636. const loader = new ImageLoader(this.manager);
  21637. loader.setCrossOrigin(this.crossOrigin);
  21638. loader.setPath(this.path);
  21639. let loaded = 0;
  21640. function loadTexture(i) {
  21641. loader.load(urls[i], function (image) {
  21642. texture.images[i] = image;
  21643. loaded++;
  21644. if (loaded === 6) {
  21645. texture.needsUpdate = true;
  21646. if (onLoad) onLoad(texture);
  21647. }
  21648. }, undefined, onError);
  21649. }
  21650. for (let i = 0; i < urls.length; ++i) {
  21651. loadTexture(i);
  21652. }
  21653. return texture;
  21654. }
  21655. }
  21656. /**
  21657. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  21658. *
  21659. * Sub classes have to implement the parse() method which will be used in load().
  21660. */
  21661. class DataTextureLoader extends Loader {
  21662. constructor(manager) {
  21663. super(manager);
  21664. }
  21665. load(url, onLoad, onProgress, onError) {
  21666. const scope = this;
  21667. const texture = new DataTexture();
  21668. const loader = new FileLoader(this.manager);
  21669. loader.setResponseType('arraybuffer');
  21670. loader.setRequestHeader(this.requestHeader);
  21671. loader.setPath(this.path);
  21672. loader.setWithCredentials(scope.withCredentials);
  21673. loader.load(url, function (buffer) {
  21674. const texData = scope.parse(buffer);
  21675. if (!texData) return;
  21676. if (texData.image !== undefined) {
  21677. texture.image = texData.image;
  21678. } else if (texData.data !== undefined) {
  21679. texture.image.width = texData.width;
  21680. texture.image.height = texData.height;
  21681. texture.image.data = texData.data;
  21682. }
  21683. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  21684. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  21685. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  21686. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  21687. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  21688. if (texData.encoding !== undefined) {
  21689. texture.encoding = texData.encoding;
  21690. }
  21691. if (texData.flipY !== undefined) {
  21692. texture.flipY = texData.flipY;
  21693. }
  21694. if (texData.format !== undefined) {
  21695. texture.format = texData.format;
  21696. }
  21697. if (texData.type !== undefined) {
  21698. texture.type = texData.type;
  21699. }
  21700. if (texData.mipmaps !== undefined) {
  21701. texture.mipmaps = texData.mipmaps;
  21702. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  21703. }
  21704. if (texData.mipmapCount === 1) {
  21705. texture.minFilter = LinearFilter;
  21706. }
  21707. if (texData.generateMipmaps !== undefined) {
  21708. texture.generateMipmaps = texData.generateMipmaps;
  21709. }
  21710. texture.needsUpdate = true;
  21711. if (onLoad) onLoad(texture, texData);
  21712. }, onProgress, onError);
  21713. return texture;
  21714. }
  21715. }
  21716. class TextureLoader extends Loader {
  21717. constructor(manager) {
  21718. super(manager);
  21719. }
  21720. load(url, onLoad, onProgress, onError) {
  21721. const texture = new Texture();
  21722. const loader = new ImageLoader(this.manager);
  21723. loader.setCrossOrigin(this.crossOrigin);
  21724. loader.setPath(this.path);
  21725. loader.load(url, function (image) {
  21726. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  21727. const isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  21728. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  21729. texture.needsUpdate = true;
  21730. if (onLoad !== undefined) {
  21731. onLoad(texture);
  21732. }
  21733. }, onProgress, onError);
  21734. return texture;
  21735. }
  21736. }
  21737. /**************************************************************
  21738. * Curved Path - a curve path is simply a array of connected
  21739. * curves, but retains the api of a curve
  21740. **************************************************************/
  21741. class CurvePath extends Curve {
  21742. constructor() {
  21743. super();
  21744. this.type = 'CurvePath';
  21745. this.curves = [];
  21746. this.autoClose = false; // Automatically closes the path
  21747. }
  21748. add(curve) {
  21749. this.curves.push(curve);
  21750. }
  21751. closePath() {
  21752. // Add a line curve if start and end of lines are not connected
  21753. const startPoint = this.curves[0].getPoint(0);
  21754. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  21755. if (!startPoint.equals(endPoint)) {
  21756. this.curves.push(new LineCurve(endPoint, startPoint));
  21757. }
  21758. } // To get accurate point with reference to
  21759. // entire path distance at time t,
  21760. // following has to be done:
  21761. // 1. Length of each sub path have to be known
  21762. // 2. Locate and identify type of curve
  21763. // 3. Get t for the curve
  21764. // 4. Return curve.getPointAt(t')
  21765. getPoint(t) {
  21766. const d = t * this.getLength();
  21767. const curveLengths = this.getCurveLengths();
  21768. let i = 0; // To think about boundaries points.
  21769. while (i < curveLengths.length) {
  21770. if (curveLengths[i] >= d) {
  21771. const diff = curveLengths[i] - d;
  21772. const curve = this.curves[i];
  21773. const segmentLength = curve.getLength();
  21774. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  21775. return curve.getPointAt(u);
  21776. }
  21777. i++;
  21778. }
  21779. return null; // loop where sum != 0, sum > d , sum+1 <d
  21780. } // We cannot use the default THREE.Curve getPoint() with getLength() because in
  21781. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  21782. // getPoint() depends on getLength
  21783. getLength() {
  21784. const lens = this.getCurveLengths();
  21785. return lens[lens.length - 1];
  21786. } // cacheLengths must be recalculated.
  21787. updateArcLengths() {
  21788. this.needsUpdate = true;
  21789. this.cacheLengths = null;
  21790. this.getCurveLengths();
  21791. } // Compute lengths and cache them
  21792. // We cannot overwrite getLengths() because UtoT mapping uses it.
  21793. getCurveLengths() {
  21794. // We use cache values if curves and cache array are same length
  21795. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  21796. return this.cacheLengths;
  21797. } // Get length of sub-curve
  21798. // Push sums into cached array
  21799. const lengths = [];
  21800. let sums = 0;
  21801. for (let i = 0, l = this.curves.length; i < l; i++) {
  21802. sums += this.curves[i].getLength();
  21803. lengths.push(sums);
  21804. }
  21805. this.cacheLengths = lengths;
  21806. return lengths;
  21807. }
  21808. getSpacedPoints(divisions = 40) {
  21809. const points = [];
  21810. for (let i = 0; i <= divisions; i++) {
  21811. points.push(this.getPoint(i / divisions));
  21812. }
  21813. if (this.autoClose) {
  21814. points.push(points[0]);
  21815. }
  21816. return points;
  21817. }
  21818. getPoints(divisions = 12) {
  21819. const points = [];
  21820. let last;
  21821. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  21822. const curve = curves[i];
  21823. const resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  21824. const pts = curve.getPoints(resolution);
  21825. for (let j = 0; j < pts.length; j++) {
  21826. const point = pts[j];
  21827. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  21828. points.push(point);
  21829. last = point;
  21830. }
  21831. }
  21832. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  21833. points.push(points[0]);
  21834. }
  21835. return points;
  21836. }
  21837. copy(source) {
  21838. super.copy(source);
  21839. this.curves = [];
  21840. for (let i = 0, l = source.curves.length; i < l; i++) {
  21841. const curve = source.curves[i];
  21842. this.curves.push(curve.clone());
  21843. }
  21844. this.autoClose = source.autoClose;
  21845. return this;
  21846. }
  21847. toJSON() {
  21848. const data = super.toJSON();
  21849. data.autoClose = this.autoClose;
  21850. data.curves = [];
  21851. for (let i = 0, l = this.curves.length; i < l; i++) {
  21852. const curve = this.curves[i];
  21853. data.curves.push(curve.toJSON());
  21854. }
  21855. return data;
  21856. }
  21857. fromJSON(json) {
  21858. super.fromJSON(json);
  21859. this.autoClose = json.autoClose;
  21860. this.curves = [];
  21861. for (let i = 0, l = json.curves.length; i < l; i++) {
  21862. const curve = json.curves[i];
  21863. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  21864. }
  21865. return this;
  21866. }
  21867. }
  21868. class Path extends CurvePath {
  21869. constructor(points) {
  21870. super();
  21871. this.type = 'Path';
  21872. this.currentPoint = new Vector2();
  21873. if (points) {
  21874. this.setFromPoints(points);
  21875. }
  21876. }
  21877. setFromPoints(points) {
  21878. this.moveTo(points[0].x, points[0].y);
  21879. for (let i = 1, l = points.length; i < l; i++) {
  21880. this.lineTo(points[i].x, points[i].y);
  21881. }
  21882. return this;
  21883. }
  21884. moveTo(x, y) {
  21885. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  21886. return this;
  21887. }
  21888. lineTo(x, y) {
  21889. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  21890. this.curves.push(curve);
  21891. this.currentPoint.set(x, y);
  21892. return this;
  21893. }
  21894. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  21895. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  21896. this.curves.push(curve);
  21897. this.currentPoint.set(aX, aY);
  21898. return this;
  21899. }
  21900. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  21901. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  21902. this.curves.push(curve);
  21903. this.currentPoint.set(aX, aY);
  21904. return this;
  21905. }
  21906. splineThru(pts
  21907. /*Array of Vector*/
  21908. ) {
  21909. const npts = [this.currentPoint.clone()].concat(pts);
  21910. const curve = new SplineCurve(npts);
  21911. this.curves.push(curve);
  21912. this.currentPoint.copy(pts[pts.length - 1]);
  21913. return this;
  21914. }
  21915. arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  21916. const x0 = this.currentPoint.x;
  21917. const y0 = this.currentPoint.y;
  21918. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  21919. return this;
  21920. }
  21921. absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  21922. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  21923. return this;
  21924. }
  21925. ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  21926. const x0 = this.currentPoint.x;
  21927. const y0 = this.currentPoint.y;
  21928. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  21929. return this;
  21930. }
  21931. absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  21932. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  21933. if (this.curves.length > 0) {
  21934. // if a previous curve is present, attempt to join
  21935. const firstPoint = curve.getPoint(0);
  21936. if (!firstPoint.equals(this.currentPoint)) {
  21937. this.lineTo(firstPoint.x, firstPoint.y);
  21938. }
  21939. }
  21940. this.curves.push(curve);
  21941. const lastPoint = curve.getPoint(1);
  21942. this.currentPoint.copy(lastPoint);
  21943. return this;
  21944. }
  21945. copy(source) {
  21946. super.copy(source);
  21947. this.currentPoint.copy(source.currentPoint);
  21948. return this;
  21949. }
  21950. toJSON() {
  21951. const data = super.toJSON();
  21952. data.currentPoint = this.currentPoint.toArray();
  21953. return data;
  21954. }
  21955. fromJSON(json) {
  21956. super.fromJSON(json);
  21957. this.currentPoint.fromArray(json.currentPoint);
  21958. return this;
  21959. }
  21960. }
  21961. class Shape extends Path {
  21962. constructor(points) {
  21963. super(points);
  21964. this.uuid = generateUUID();
  21965. this.type = 'Shape';
  21966. this.holes = [];
  21967. }
  21968. getPointsHoles(divisions) {
  21969. const holesPts = [];
  21970. for (let i = 0, l = this.holes.length; i < l; i++) {
  21971. holesPts[i] = this.holes[i].getPoints(divisions);
  21972. }
  21973. return holesPts;
  21974. } // get points of shape and holes (keypoints based on segments parameter)
  21975. extractPoints(divisions) {
  21976. return {
  21977. shape: this.getPoints(divisions),
  21978. holes: this.getPointsHoles(divisions)
  21979. };
  21980. }
  21981. copy(source) {
  21982. super.copy(source);
  21983. this.holes = [];
  21984. for (let i = 0, l = source.holes.length; i < l; i++) {
  21985. const hole = source.holes[i];
  21986. this.holes.push(hole.clone());
  21987. }
  21988. return this;
  21989. }
  21990. toJSON() {
  21991. const data = super.toJSON();
  21992. data.uuid = this.uuid;
  21993. data.holes = [];
  21994. for (let i = 0, l = this.holes.length; i < l; i++) {
  21995. const hole = this.holes[i];
  21996. data.holes.push(hole.toJSON());
  21997. }
  21998. return data;
  21999. }
  22000. fromJSON(json) {
  22001. super.fromJSON(json);
  22002. this.uuid = json.uuid;
  22003. this.holes = [];
  22004. for (let i = 0, l = json.holes.length; i < l; i++) {
  22005. const hole = json.holes[i];
  22006. this.holes.push(new Path().fromJSON(hole));
  22007. }
  22008. return this;
  22009. }
  22010. }
  22011. class Light extends Object3D {
  22012. constructor(color, intensity = 1) {
  22013. super();
  22014. this.type = 'Light';
  22015. this.color = new Color(color);
  22016. this.intensity = intensity;
  22017. }
  22018. dispose() {// Empty here in base class; some subclasses override.
  22019. }
  22020. copy(source) {
  22021. super.copy(source);
  22022. this.color.copy(source.color);
  22023. this.intensity = source.intensity;
  22024. return this;
  22025. }
  22026. toJSON(meta) {
  22027. const data = super.toJSON(meta);
  22028. data.object.color = this.color.getHex();
  22029. data.object.intensity = this.intensity;
  22030. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  22031. if (this.distance !== undefined) data.object.distance = this.distance;
  22032. if (this.angle !== undefined) data.object.angle = this.angle;
  22033. if (this.decay !== undefined) data.object.decay = this.decay;
  22034. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  22035. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  22036. return data;
  22037. }
  22038. }
  22039. Light.prototype.isLight = true;
  22040. class HemisphereLight extends Light {
  22041. constructor(skyColor, groundColor, intensity) {
  22042. super(skyColor, intensity);
  22043. this.type = 'HemisphereLight';
  22044. this.position.copy(Object3D.DefaultUp);
  22045. this.updateMatrix();
  22046. this.groundColor = new Color(groundColor);
  22047. }
  22048. copy(source) {
  22049. Light.prototype.copy.call(this, source);
  22050. this.groundColor.copy(source.groundColor);
  22051. return this;
  22052. }
  22053. }
  22054. HemisphereLight.prototype.isHemisphereLight = true;
  22055. const _projScreenMatrix$1 = /*@__PURE__*/new Matrix4();
  22056. const _lightPositionWorld$1 = /*@__PURE__*/new Vector3();
  22057. const _lookTarget$1 = /*@__PURE__*/new Vector3();
  22058. class LightShadow {
  22059. constructor(camera) {
  22060. this.camera = camera;
  22061. this.bias = 0;
  22062. this.normalBias = 0;
  22063. this.radius = 1;
  22064. this.mapSize = new Vector2(512, 512);
  22065. this.map = null;
  22066. this.mapPass = null;
  22067. this.matrix = new Matrix4();
  22068. this.autoUpdate = true;
  22069. this.needsUpdate = false;
  22070. this._frustum = new Frustum();
  22071. this._frameExtents = new Vector2(1, 1);
  22072. this._viewportCount = 1;
  22073. this._viewports = [new Vector4(0, 0, 1, 1)];
  22074. }
  22075. getViewportCount() {
  22076. return this._viewportCount;
  22077. }
  22078. getFrustum() {
  22079. return this._frustum;
  22080. }
  22081. updateMatrices(light) {
  22082. const shadowCamera = this.camera;
  22083. const shadowMatrix = this.matrix;
  22084. _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld);
  22085. shadowCamera.position.copy(_lightPositionWorld$1);
  22086. _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld);
  22087. shadowCamera.lookAt(_lookTarget$1);
  22088. shadowCamera.updateMatrixWorld();
  22089. _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  22090. this._frustum.setFromProjectionMatrix(_projScreenMatrix$1);
  22091. 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);
  22092. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  22093. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  22094. }
  22095. getViewport(viewportIndex) {
  22096. return this._viewports[viewportIndex];
  22097. }
  22098. getFrameExtents() {
  22099. return this._frameExtents;
  22100. }
  22101. dispose() {
  22102. if (this.map) {
  22103. this.map.dispose();
  22104. }
  22105. if (this.mapPass) {
  22106. this.mapPass.dispose();
  22107. }
  22108. }
  22109. copy(source) {
  22110. this.camera = source.camera.clone();
  22111. this.bias = source.bias;
  22112. this.radius = source.radius;
  22113. this.mapSize.copy(source.mapSize);
  22114. return this;
  22115. }
  22116. clone() {
  22117. return new this.constructor().copy(this);
  22118. }
  22119. toJSON() {
  22120. const object = {};
  22121. if (this.bias !== 0) object.bias = this.bias;
  22122. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  22123. if (this.radius !== 1) object.radius = this.radius;
  22124. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  22125. object.camera = this.camera.toJSON(false).object;
  22126. delete object.camera.matrix;
  22127. return object;
  22128. }
  22129. }
  22130. class SpotLightShadow extends LightShadow {
  22131. constructor() {
  22132. super(new PerspectiveCamera(50, 1, 0.5, 500));
  22133. this.focus = 1;
  22134. }
  22135. updateMatrices(light) {
  22136. const camera = this.camera;
  22137. const fov = RAD2DEG * 2 * light.angle * this.focus;
  22138. const aspect = this.mapSize.width / this.mapSize.height;
  22139. const far = light.distance || camera.far;
  22140. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  22141. camera.fov = fov;
  22142. camera.aspect = aspect;
  22143. camera.far = far;
  22144. camera.updateProjectionMatrix();
  22145. }
  22146. super.updateMatrices(light);
  22147. }
  22148. copy(source) {
  22149. super.copy(source);
  22150. this.focus = source.focus;
  22151. return this;
  22152. }
  22153. }
  22154. SpotLightShadow.prototype.isSpotLightShadow = true;
  22155. class SpotLight extends Light {
  22156. constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1) {
  22157. super(color, intensity);
  22158. this.type = 'SpotLight';
  22159. this.position.copy(Object3D.DefaultUp);
  22160. this.updateMatrix();
  22161. this.target = new Object3D();
  22162. this.distance = distance;
  22163. this.angle = angle;
  22164. this.penumbra = penumbra;
  22165. this.decay = decay; // for physically correct lights, should be 2.
  22166. this.shadow = new SpotLightShadow();
  22167. }
  22168. get power() {
  22169. // intensity = power per solid angle.
  22170. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22171. return this.intensity * Math.PI;
  22172. }
  22173. set power(power) {
  22174. // intensity = power per solid angle.
  22175. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22176. this.intensity = power / Math.PI;
  22177. }
  22178. dispose() {
  22179. this.shadow.dispose();
  22180. }
  22181. copy(source) {
  22182. super.copy(source);
  22183. this.distance = source.distance;
  22184. this.angle = source.angle;
  22185. this.penumbra = source.penumbra;
  22186. this.decay = source.decay;
  22187. this.target = source.target.clone();
  22188. this.shadow = source.shadow.clone();
  22189. return this;
  22190. }
  22191. }
  22192. SpotLight.prototype.isSpotLight = true;
  22193. const _projScreenMatrix = /*@__PURE__*/new Matrix4();
  22194. const _lightPositionWorld = /*@__PURE__*/new Vector3();
  22195. const _lookTarget = /*@__PURE__*/new Vector3();
  22196. class PointLightShadow extends LightShadow {
  22197. constructor() {
  22198. super(new PerspectiveCamera(90, 1, 0.5, 500));
  22199. this._frameExtents = new Vector2(4, 2);
  22200. this._viewportCount = 6;
  22201. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  22202. // following orientation:
  22203. //
  22204. // xzXZ
  22205. // y Y
  22206. //
  22207. // X - Positive x direction
  22208. // x - Negative x direction
  22209. // Y - Positive y direction
  22210. // y - Negative y direction
  22211. // Z - Positive z direction
  22212. // z - Negative z direction
  22213. // positive X
  22214. new Vector4(2, 1, 1, 1), // negative X
  22215. new Vector4(0, 1, 1, 1), // positive Z
  22216. new Vector4(3, 1, 1, 1), // negative Z
  22217. new Vector4(1, 1, 1, 1), // positive Y
  22218. new Vector4(3, 0, 1, 1), // negative Y
  22219. new Vector4(1, 0, 1, 1)];
  22220. 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)];
  22221. 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)];
  22222. }
  22223. updateMatrices(light, viewportIndex = 0) {
  22224. const camera = this.camera;
  22225. const shadowMatrix = this.matrix;
  22226. const far = light.distance || camera.far;
  22227. if (far !== camera.far) {
  22228. camera.far = far;
  22229. camera.updateProjectionMatrix();
  22230. }
  22231. _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  22232. camera.position.copy(_lightPositionWorld);
  22233. _lookTarget.copy(camera.position);
  22234. _lookTarget.add(this._cubeDirections[viewportIndex]);
  22235. camera.up.copy(this._cubeUps[viewportIndex]);
  22236. camera.lookAt(_lookTarget);
  22237. camera.updateMatrixWorld();
  22238. shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
  22239. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  22240. this._frustum.setFromProjectionMatrix(_projScreenMatrix);
  22241. }
  22242. }
  22243. PointLightShadow.prototype.isPointLightShadow = true;
  22244. class PointLight extends Light {
  22245. constructor(color, intensity, distance = 0, decay = 1) {
  22246. super(color, intensity);
  22247. this.type = 'PointLight';
  22248. this.distance = distance;
  22249. this.decay = decay; // for physically correct lights, should be 2.
  22250. this.shadow = new PointLightShadow();
  22251. }
  22252. get power() {
  22253. // intensity = power per solid angle.
  22254. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22255. return this.intensity * 4 * Math.PI;
  22256. }
  22257. set power(power) {
  22258. // intensity = power per solid angle.
  22259. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22260. this.intensity = power / (4 * Math.PI);
  22261. }
  22262. dispose() {
  22263. this.shadow.dispose();
  22264. }
  22265. copy(source) {
  22266. super.copy(source);
  22267. this.distance = source.distance;
  22268. this.decay = source.decay;
  22269. this.shadow = source.shadow.clone();
  22270. return this;
  22271. }
  22272. }
  22273. PointLight.prototype.isPointLight = true;
  22274. class OrthographicCamera extends Camera {
  22275. constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) {
  22276. super();
  22277. this.type = 'OrthographicCamera';
  22278. this.zoom = 1;
  22279. this.view = null;
  22280. this.left = left;
  22281. this.right = right;
  22282. this.top = top;
  22283. this.bottom = bottom;
  22284. this.near = near;
  22285. this.far = far;
  22286. this.updateProjectionMatrix();
  22287. }
  22288. copy(source, recursive) {
  22289. super.copy(source, recursive);
  22290. this.left = source.left;
  22291. this.right = source.right;
  22292. this.top = source.top;
  22293. this.bottom = source.bottom;
  22294. this.near = source.near;
  22295. this.far = source.far;
  22296. this.zoom = source.zoom;
  22297. this.view = source.view === null ? null : Object.assign({}, source.view);
  22298. return this;
  22299. }
  22300. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  22301. if (this.view === null) {
  22302. this.view = {
  22303. enabled: true,
  22304. fullWidth: 1,
  22305. fullHeight: 1,
  22306. offsetX: 0,
  22307. offsetY: 0,
  22308. width: 1,
  22309. height: 1
  22310. };
  22311. }
  22312. this.view.enabled = true;
  22313. this.view.fullWidth = fullWidth;
  22314. this.view.fullHeight = fullHeight;
  22315. this.view.offsetX = x;
  22316. this.view.offsetY = y;
  22317. this.view.width = width;
  22318. this.view.height = height;
  22319. this.updateProjectionMatrix();
  22320. }
  22321. clearViewOffset() {
  22322. if (this.view !== null) {
  22323. this.view.enabled = false;
  22324. }
  22325. this.updateProjectionMatrix();
  22326. }
  22327. updateProjectionMatrix() {
  22328. const dx = (this.right - this.left) / (2 * this.zoom);
  22329. const dy = (this.top - this.bottom) / (2 * this.zoom);
  22330. const cx = (this.right + this.left) / 2;
  22331. const cy = (this.top + this.bottom) / 2;
  22332. let left = cx - dx;
  22333. let right = cx + dx;
  22334. let top = cy + dy;
  22335. let bottom = cy - dy;
  22336. if (this.view !== null && this.view.enabled) {
  22337. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  22338. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  22339. left += scaleW * this.view.offsetX;
  22340. right = left + scaleW * this.view.width;
  22341. top -= scaleH * this.view.offsetY;
  22342. bottom = top - scaleH * this.view.height;
  22343. }
  22344. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  22345. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  22346. }
  22347. toJSON(meta) {
  22348. const data = super.toJSON(meta);
  22349. data.object.zoom = this.zoom;
  22350. data.object.left = this.left;
  22351. data.object.right = this.right;
  22352. data.object.top = this.top;
  22353. data.object.bottom = this.bottom;
  22354. data.object.near = this.near;
  22355. data.object.far = this.far;
  22356. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  22357. return data;
  22358. }
  22359. }
  22360. OrthographicCamera.prototype.isOrthographicCamera = true;
  22361. class DirectionalLightShadow extends LightShadow {
  22362. constructor() {
  22363. super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  22364. }
  22365. }
  22366. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  22367. class DirectionalLight extends Light {
  22368. constructor(color, intensity) {
  22369. super(color, intensity);
  22370. this.type = 'DirectionalLight';
  22371. this.position.copy(Object3D.DefaultUp);
  22372. this.updateMatrix();
  22373. this.target = new Object3D();
  22374. this.shadow = new DirectionalLightShadow();
  22375. }
  22376. dispose() {
  22377. this.shadow.dispose();
  22378. }
  22379. copy(source) {
  22380. super.copy(source);
  22381. this.target = source.target.clone();
  22382. this.shadow = source.shadow.clone();
  22383. return this;
  22384. }
  22385. }
  22386. DirectionalLight.prototype.isDirectionalLight = true;
  22387. class AmbientLight extends Light {
  22388. constructor(color, intensity) {
  22389. super(color, intensity);
  22390. this.type = 'AmbientLight';
  22391. }
  22392. }
  22393. AmbientLight.prototype.isAmbientLight = true;
  22394. class RectAreaLight extends Light {
  22395. constructor(color, intensity, width = 10, height = 10) {
  22396. super(color, intensity);
  22397. this.type = 'RectAreaLight';
  22398. this.width = width;
  22399. this.height = height;
  22400. }
  22401. copy(source) {
  22402. super.copy(source);
  22403. this.width = source.width;
  22404. this.height = source.height;
  22405. return this;
  22406. }
  22407. toJSON(meta) {
  22408. const data = super.toJSON(meta);
  22409. data.object.width = this.width;
  22410. data.object.height = this.height;
  22411. return data;
  22412. }
  22413. }
  22414. RectAreaLight.prototype.isRectAreaLight = true;
  22415. /**
  22416. * Primary reference:
  22417. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  22418. *
  22419. * Secondary reference:
  22420. * https://www.ppsloan.org/publications/StupidSH36.pdf
  22421. */
  22422. // 3-band SH defined by 9 coefficients
  22423. class SphericalHarmonics3 {
  22424. constructor() {
  22425. this.coefficients = [];
  22426. for (let i = 0; i < 9; i++) {
  22427. this.coefficients.push(new Vector3());
  22428. }
  22429. }
  22430. set(coefficients) {
  22431. for (let i = 0; i < 9; i++) {
  22432. this.coefficients[i].copy(coefficients[i]);
  22433. }
  22434. return this;
  22435. }
  22436. zero() {
  22437. for (let i = 0; i < 9; i++) {
  22438. this.coefficients[i].set(0, 0, 0);
  22439. }
  22440. return this;
  22441. } // get the radiance in the direction of the normal
  22442. // target is a Vector3
  22443. getAt(normal, target) {
  22444. // normal is assumed to be unit length
  22445. const x = normal.x,
  22446. y = normal.y,
  22447. z = normal.z;
  22448. const coeff = this.coefficients; // band 0
  22449. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  22450. target.addScaledVector(coeff[1], 0.488603 * y);
  22451. target.addScaledVector(coeff[2], 0.488603 * z);
  22452. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  22453. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  22454. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  22455. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  22456. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  22457. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  22458. return target;
  22459. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  22460. // target is a Vector3
  22461. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  22462. getIrradianceAt(normal, target) {
  22463. // normal is assumed to be unit length
  22464. const x = normal.x,
  22465. y = normal.y,
  22466. z = normal.z;
  22467. const coeff = this.coefficients; // band 0
  22468. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  22469. // band 1
  22470. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  22471. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  22472. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  22473. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  22474. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  22475. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  22476. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  22477. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  22478. return target;
  22479. }
  22480. add(sh) {
  22481. for (let i = 0; i < 9; i++) {
  22482. this.coefficients[i].add(sh.coefficients[i]);
  22483. }
  22484. return this;
  22485. }
  22486. addScaledSH(sh, s) {
  22487. for (let i = 0; i < 9; i++) {
  22488. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  22489. }
  22490. return this;
  22491. }
  22492. scale(s) {
  22493. for (let i = 0; i < 9; i++) {
  22494. this.coefficients[i].multiplyScalar(s);
  22495. }
  22496. return this;
  22497. }
  22498. lerp(sh, alpha) {
  22499. for (let i = 0; i < 9; i++) {
  22500. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  22501. }
  22502. return this;
  22503. }
  22504. equals(sh) {
  22505. for (let i = 0; i < 9; i++) {
  22506. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  22507. return false;
  22508. }
  22509. }
  22510. return true;
  22511. }
  22512. copy(sh) {
  22513. return this.set(sh.coefficients);
  22514. }
  22515. clone() {
  22516. return new this.constructor().copy(this);
  22517. }
  22518. fromArray(array, offset = 0) {
  22519. const coefficients = this.coefficients;
  22520. for (let i = 0; i < 9; i++) {
  22521. coefficients[i].fromArray(array, offset + i * 3);
  22522. }
  22523. return this;
  22524. }
  22525. toArray(array = [], offset = 0) {
  22526. const coefficients = this.coefficients;
  22527. for (let i = 0; i < 9; i++) {
  22528. coefficients[i].toArray(array, offset + i * 3);
  22529. }
  22530. return array;
  22531. } // evaluate the basis functions
  22532. // shBasis is an Array[ 9 ]
  22533. static getBasisAt(normal, shBasis) {
  22534. // normal is assumed to be unit length
  22535. const x = normal.x,
  22536. y = normal.y,
  22537. z = normal.z; // band 0
  22538. shBasis[0] = 0.282095; // band 1
  22539. shBasis[1] = 0.488603 * y;
  22540. shBasis[2] = 0.488603 * z;
  22541. shBasis[3] = 0.488603 * x; // band 2
  22542. shBasis[4] = 1.092548 * x * y;
  22543. shBasis[5] = 1.092548 * y * z;
  22544. shBasis[6] = 0.315392 * (3 * z * z - 1);
  22545. shBasis[7] = 1.092548 * x * z;
  22546. shBasis[8] = 0.546274 * (x * x - y * y);
  22547. }
  22548. }
  22549. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  22550. class LightProbe extends Light {
  22551. constructor(sh = new SphericalHarmonics3(), intensity = 1) {
  22552. super(undefined, intensity);
  22553. this.sh = sh;
  22554. }
  22555. copy(source) {
  22556. super.copy(source);
  22557. this.sh.copy(source.sh);
  22558. return this;
  22559. }
  22560. fromJSON(json) {
  22561. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  22562. this.sh.fromArray(json.sh);
  22563. return this;
  22564. }
  22565. toJSON(meta) {
  22566. const data = super.toJSON(meta);
  22567. data.object.sh = this.sh.toArray();
  22568. return data;
  22569. }
  22570. }
  22571. LightProbe.prototype.isLightProbe = true;
  22572. class MaterialLoader extends Loader {
  22573. constructor(manager) {
  22574. super(manager);
  22575. this.textures = {};
  22576. }
  22577. load(url, onLoad, onProgress, onError) {
  22578. const scope = this;
  22579. const loader = new FileLoader(scope.manager);
  22580. loader.setPath(scope.path);
  22581. loader.setRequestHeader(scope.requestHeader);
  22582. loader.setWithCredentials(scope.withCredentials);
  22583. loader.load(url, function (text) {
  22584. try {
  22585. onLoad(scope.parse(JSON.parse(text)));
  22586. } catch (e) {
  22587. if (onError) {
  22588. onError(e);
  22589. } else {
  22590. console.error(e);
  22591. }
  22592. scope.manager.itemError(url);
  22593. }
  22594. }, onProgress, onError);
  22595. }
  22596. parse(json) {
  22597. const textures = this.textures;
  22598. function getTexture(name) {
  22599. if (textures[name] === undefined) {
  22600. console.warn('THREE.MaterialLoader: Undefined texture', name);
  22601. }
  22602. return textures[name];
  22603. }
  22604. const material = new Materials[json.type]();
  22605. if (json.uuid !== undefined) material.uuid = json.uuid;
  22606. if (json.name !== undefined) material.name = json.name;
  22607. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  22608. if (json.roughness !== undefined) material.roughness = json.roughness;
  22609. if (json.metalness !== undefined) material.metalness = json.metalness;
  22610. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  22611. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  22612. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  22613. if (json.shininess !== undefined) material.shininess = json.shininess;
  22614. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  22615. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  22616. if (json.transmission !== undefined) material.transmission = json.transmission;
  22617. if (json.thickness !== undefined) material.thickness = json.thickness;
  22618. if (json.attenuationDistance !== undefined) material.attenuationDistance = json.attenuationDistance;
  22619. if (json.attenuationColor !== undefined && material.attenuationColor !== undefined) material.attenuationColor.setHex(json.attenuationColor);
  22620. if (json.fog !== undefined) material.fog = json.fog;
  22621. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  22622. if (json.blending !== undefined) material.blending = json.blending;
  22623. if (json.combine !== undefined) material.combine = json.combine;
  22624. if (json.side !== undefined) material.side = json.side;
  22625. if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
  22626. if (json.opacity !== undefined) material.opacity = json.opacity;
  22627. if (json.transparent !== undefined) material.transparent = json.transparent;
  22628. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  22629. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  22630. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  22631. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  22632. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  22633. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  22634. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  22635. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  22636. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  22637. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  22638. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  22639. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  22640. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  22641. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  22642. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  22643. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  22644. if (json.rotation !== undefined) material.rotation = json.rotation;
  22645. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  22646. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  22647. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  22648. if (json.scale !== undefined) material.scale = json.scale;
  22649. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  22650. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  22651. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  22652. if (json.dithering !== undefined) material.dithering = json.dithering;
  22653. if (json.alphaToCoverage !== undefined) material.alphaToCoverage = json.alphaToCoverage;
  22654. if (json.premultipliedAlpha !== undefined) material.premultipliedAlpha = json.premultipliedAlpha;
  22655. if (json.vertexTangents !== undefined) material.vertexTangents = json.vertexTangents;
  22656. if (json.visible !== undefined) material.visible = json.visible;
  22657. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  22658. if (json.userData !== undefined) material.userData = json.userData;
  22659. if (json.vertexColors !== undefined) {
  22660. if (typeof json.vertexColors === 'number') {
  22661. material.vertexColors = json.vertexColors > 0 ? true : false;
  22662. } else {
  22663. material.vertexColors = json.vertexColors;
  22664. }
  22665. } // Shader Material
  22666. if (json.uniforms !== undefined) {
  22667. for (const name in json.uniforms) {
  22668. const uniform = json.uniforms[name];
  22669. material.uniforms[name] = {};
  22670. switch (uniform.type) {
  22671. case 't':
  22672. material.uniforms[name].value = getTexture(uniform.value);
  22673. break;
  22674. case 'c':
  22675. material.uniforms[name].value = new Color().setHex(uniform.value);
  22676. break;
  22677. case 'v2':
  22678. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  22679. break;
  22680. case 'v3':
  22681. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  22682. break;
  22683. case 'v4':
  22684. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  22685. break;
  22686. case 'm3':
  22687. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  22688. break;
  22689. case 'm4':
  22690. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  22691. break;
  22692. default:
  22693. material.uniforms[name].value = uniform.value;
  22694. }
  22695. }
  22696. }
  22697. if (json.defines !== undefined) material.defines = json.defines;
  22698. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  22699. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  22700. if (json.extensions !== undefined) {
  22701. for (const key in json.extensions) {
  22702. material.extensions[key] = json.extensions[key];
  22703. }
  22704. } // Deprecated
  22705. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  22706. // for PointsMaterial
  22707. if (json.size !== undefined) material.size = json.size;
  22708. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  22709. if (json.map !== undefined) material.map = getTexture(json.map);
  22710. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  22711. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  22712. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  22713. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  22714. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  22715. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  22716. if (json.normalScale !== undefined) {
  22717. let normalScale = json.normalScale;
  22718. if (Array.isArray(normalScale) === false) {
  22719. // Blender exporter used to export a scalar. See #7459
  22720. normalScale = [normalScale, normalScale];
  22721. }
  22722. material.normalScale = new Vector2().fromArray(normalScale);
  22723. }
  22724. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  22725. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  22726. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  22727. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  22728. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  22729. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  22730. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  22731. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  22732. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  22733. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  22734. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  22735. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  22736. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  22737. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  22738. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  22739. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  22740. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  22741. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  22742. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  22743. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  22744. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  22745. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  22746. if (json.thicknessMap !== undefined) material.thicknessMap = getTexture(json.thicknessMap);
  22747. return material;
  22748. }
  22749. setTextures(value) {
  22750. this.textures = value;
  22751. return this;
  22752. }
  22753. }
  22754. class LoaderUtils {
  22755. static decodeText(array) {
  22756. if (typeof TextDecoder !== 'undefined') {
  22757. return new TextDecoder().decode(array);
  22758. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  22759. // throws a "maximum call stack size exceeded" error for large arrays.
  22760. let s = '';
  22761. for (let i = 0, il = array.length; i < il; i++) {
  22762. // Implicitly assumes little-endian.
  22763. s += String.fromCharCode(array[i]);
  22764. }
  22765. try {
  22766. // merges multi-byte utf-8 characters.
  22767. return decodeURIComponent(escape(s));
  22768. } catch (e) {
  22769. // see #16358
  22770. return s;
  22771. }
  22772. }
  22773. static extractUrlBase(url) {
  22774. const index = url.lastIndexOf('/');
  22775. if (index === -1) return './';
  22776. return url.substr(0, index + 1);
  22777. }
  22778. }
  22779. class InstancedBufferGeometry extends BufferGeometry {
  22780. constructor() {
  22781. super();
  22782. this.type = 'InstancedBufferGeometry';
  22783. this.instanceCount = Infinity;
  22784. }
  22785. copy(source) {
  22786. super.copy(source);
  22787. this.instanceCount = source.instanceCount;
  22788. return this;
  22789. }
  22790. clone() {
  22791. return new this.constructor().copy(this);
  22792. }
  22793. toJSON() {
  22794. const data = super.toJSON(this);
  22795. data.instanceCount = this.instanceCount;
  22796. data.isInstancedBufferGeometry = true;
  22797. return data;
  22798. }
  22799. }
  22800. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  22801. class InstancedBufferAttribute extends BufferAttribute {
  22802. constructor(array, itemSize, normalized, meshPerAttribute = 1) {
  22803. if (typeof normalized === 'number') {
  22804. meshPerAttribute = normalized;
  22805. normalized = false;
  22806. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  22807. }
  22808. super(array, itemSize, normalized);
  22809. this.meshPerAttribute = meshPerAttribute;
  22810. }
  22811. copy(source) {
  22812. super.copy(source);
  22813. this.meshPerAttribute = source.meshPerAttribute;
  22814. return this;
  22815. }
  22816. toJSON() {
  22817. const data = super.toJSON();
  22818. data.meshPerAttribute = this.meshPerAttribute;
  22819. data.isInstancedBufferAttribute = true;
  22820. return data;
  22821. }
  22822. }
  22823. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  22824. class BufferGeometryLoader extends Loader {
  22825. constructor(manager) {
  22826. super(manager);
  22827. }
  22828. load(url, onLoad, onProgress, onError) {
  22829. const scope = this;
  22830. const loader = new FileLoader(scope.manager);
  22831. loader.setPath(scope.path);
  22832. loader.setRequestHeader(scope.requestHeader);
  22833. loader.setWithCredentials(scope.withCredentials);
  22834. loader.load(url, function (text) {
  22835. try {
  22836. onLoad(scope.parse(JSON.parse(text)));
  22837. } catch (e) {
  22838. if (onError) {
  22839. onError(e);
  22840. } else {
  22841. console.error(e);
  22842. }
  22843. scope.manager.itemError(url);
  22844. }
  22845. }, onProgress, onError);
  22846. }
  22847. parse(json) {
  22848. const interleavedBufferMap = {};
  22849. const arrayBufferMap = {};
  22850. function getInterleavedBuffer(json, uuid) {
  22851. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  22852. const interleavedBuffers = json.interleavedBuffers;
  22853. const interleavedBuffer = interleavedBuffers[uuid];
  22854. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  22855. const array = getTypedArray(interleavedBuffer.type, buffer);
  22856. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  22857. ib.uuid = interleavedBuffer.uuid;
  22858. interleavedBufferMap[uuid] = ib;
  22859. return ib;
  22860. }
  22861. function getArrayBuffer(json, uuid) {
  22862. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  22863. const arrayBuffers = json.arrayBuffers;
  22864. const arrayBuffer = arrayBuffers[uuid];
  22865. const ab = new Uint32Array(arrayBuffer).buffer;
  22866. arrayBufferMap[uuid] = ab;
  22867. return ab;
  22868. }
  22869. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  22870. const index = json.data.index;
  22871. if (index !== undefined) {
  22872. const typedArray = getTypedArray(index.type, index.array);
  22873. geometry.setIndex(new BufferAttribute(typedArray, 1));
  22874. }
  22875. const attributes = json.data.attributes;
  22876. for (const key in attributes) {
  22877. const attribute = attributes[key];
  22878. let bufferAttribute;
  22879. if (attribute.isInterleavedBufferAttribute) {
  22880. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  22881. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  22882. } else {
  22883. const typedArray = getTypedArray(attribute.type, attribute.array);
  22884. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  22885. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  22886. }
  22887. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  22888. if (attribute.usage !== undefined) bufferAttribute.setUsage(attribute.usage);
  22889. if (attribute.updateRange !== undefined) {
  22890. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  22891. bufferAttribute.updateRange.count = attribute.updateRange.count;
  22892. }
  22893. geometry.setAttribute(key, bufferAttribute);
  22894. }
  22895. const morphAttributes = json.data.morphAttributes;
  22896. if (morphAttributes) {
  22897. for (const key in morphAttributes) {
  22898. const attributeArray = morphAttributes[key];
  22899. const array = [];
  22900. for (let i = 0, il = attributeArray.length; i < il; i++) {
  22901. const attribute = attributeArray[i];
  22902. let bufferAttribute;
  22903. if (attribute.isInterleavedBufferAttribute) {
  22904. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  22905. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  22906. } else {
  22907. const typedArray = getTypedArray(attribute.type, attribute.array);
  22908. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  22909. }
  22910. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  22911. array.push(bufferAttribute);
  22912. }
  22913. geometry.morphAttributes[key] = array;
  22914. }
  22915. }
  22916. const morphTargetsRelative = json.data.morphTargetsRelative;
  22917. if (morphTargetsRelative) {
  22918. geometry.morphTargetsRelative = true;
  22919. }
  22920. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  22921. if (groups !== undefined) {
  22922. for (let i = 0, n = groups.length; i !== n; ++i) {
  22923. const group = groups[i];
  22924. geometry.addGroup(group.start, group.count, group.materialIndex);
  22925. }
  22926. }
  22927. const boundingSphere = json.data.boundingSphere;
  22928. if (boundingSphere !== undefined) {
  22929. const center = new Vector3();
  22930. if (boundingSphere.center !== undefined) {
  22931. center.fromArray(boundingSphere.center);
  22932. }
  22933. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  22934. }
  22935. if (json.name) geometry.name = json.name;
  22936. if (json.userData) geometry.userData = json.userData;
  22937. return geometry;
  22938. }
  22939. }
  22940. class ObjectLoader extends Loader {
  22941. constructor(manager) {
  22942. super(manager);
  22943. }
  22944. load(url, onLoad, onProgress, onError) {
  22945. const scope = this;
  22946. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  22947. this.resourcePath = this.resourcePath || path;
  22948. const loader = new FileLoader(this.manager);
  22949. loader.setPath(this.path);
  22950. loader.setRequestHeader(this.requestHeader);
  22951. loader.setWithCredentials(this.withCredentials);
  22952. loader.load(url, function (text) {
  22953. let json = null;
  22954. try {
  22955. json = JSON.parse(text);
  22956. } catch (error) {
  22957. if (onError !== undefined) onError(error);
  22958. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  22959. return;
  22960. }
  22961. const metadata = json.metadata;
  22962. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  22963. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  22964. return;
  22965. }
  22966. scope.parse(json, onLoad);
  22967. }, onProgress, onError);
  22968. }
  22969. async loadAsync(url, onProgress) {
  22970. const scope = this;
  22971. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  22972. this.resourcePath = this.resourcePath || path;
  22973. const loader = new FileLoader(this.manager);
  22974. loader.setPath(this.path);
  22975. loader.setRequestHeader(this.requestHeader);
  22976. loader.setWithCredentials(this.withCredentials);
  22977. const text = await loader.loadAsync(url, onProgress);
  22978. const json = JSON.parse(text);
  22979. const metadata = json.metadata;
  22980. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  22981. throw new Error('THREE.ObjectLoader: Can\'t load ' + url);
  22982. }
  22983. return await scope.parseAsync(json);
  22984. }
  22985. parse(json, onLoad) {
  22986. const animations = this.parseAnimations(json.animations);
  22987. const shapes = this.parseShapes(json.shapes);
  22988. const geometries = this.parseGeometries(json.geometries, shapes);
  22989. const images = this.parseImages(json.images, function () {
  22990. if (onLoad !== undefined) onLoad(object);
  22991. });
  22992. const textures = this.parseTextures(json.textures, images);
  22993. const materials = this.parseMaterials(json.materials, textures);
  22994. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  22995. const skeletons = this.parseSkeletons(json.skeletons, object);
  22996. this.bindSkeletons(object, skeletons); //
  22997. if (onLoad !== undefined) {
  22998. let hasImages = false;
  22999. for (const uuid in images) {
  23000. if (images[uuid] instanceof HTMLImageElement) {
  23001. hasImages = true;
  23002. break;
  23003. }
  23004. }
  23005. if (hasImages === false) onLoad(object);
  23006. }
  23007. return object;
  23008. }
  23009. async parseAsync(json) {
  23010. const animations = this.parseAnimations(json.animations);
  23011. const shapes = this.parseShapes(json.shapes);
  23012. const geometries = this.parseGeometries(json.geometries, shapes);
  23013. const images = await this.parseImagesAsync(json.images);
  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, textures, animations);
  23017. const skeletons = this.parseSkeletons(json.skeletons, object);
  23018. this.bindSkeletons(object, skeletons);
  23019. return object;
  23020. }
  23021. parseShapes(json) {
  23022. const shapes = {};
  23023. if (json !== undefined) {
  23024. for (let i = 0, l = json.length; i < l; i++) {
  23025. const shape = new Shape().fromJSON(json[i]);
  23026. shapes[shape.uuid] = shape;
  23027. }
  23028. }
  23029. return shapes;
  23030. }
  23031. parseSkeletons(json, object) {
  23032. const skeletons = {};
  23033. const bones = {}; // generate bone lookup table
  23034. object.traverse(function (child) {
  23035. if (child.isBone) bones[child.uuid] = child;
  23036. }); // create skeletons
  23037. if (json !== undefined) {
  23038. for (let i = 0, l = json.length; i < l; i++) {
  23039. const skeleton = new Skeleton().fromJSON(json[i], bones);
  23040. skeletons[skeleton.uuid] = skeleton;
  23041. }
  23042. }
  23043. return skeletons;
  23044. }
  23045. parseGeometries(json, shapes) {
  23046. const geometries = {};
  23047. if (json !== undefined) {
  23048. const bufferGeometryLoader = new BufferGeometryLoader();
  23049. for (let i = 0, l = json.length; i < l; i++) {
  23050. let geometry;
  23051. const data = json[i];
  23052. switch (data.type) {
  23053. case 'BufferGeometry':
  23054. case 'InstancedBufferGeometry':
  23055. geometry = bufferGeometryLoader.parse(data);
  23056. break;
  23057. case 'Geometry':
  23058. console.error('THREE.ObjectLoader: The legacy Geometry type is no longer supported.');
  23059. break;
  23060. default:
  23061. if (data.type in Geometries) {
  23062. geometry = Geometries[data.type].fromJSON(data, shapes);
  23063. } else {
  23064. console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data.type}"`);
  23065. }
  23066. }
  23067. geometry.uuid = data.uuid;
  23068. if (data.name !== undefined) geometry.name = data.name;
  23069. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  23070. geometries[data.uuid] = geometry;
  23071. }
  23072. }
  23073. return geometries;
  23074. }
  23075. parseMaterials(json, textures) {
  23076. const cache = {}; // MultiMaterial
  23077. const materials = {};
  23078. if (json !== undefined) {
  23079. const loader = new MaterialLoader();
  23080. loader.setTextures(textures);
  23081. for (let i = 0, l = json.length; i < l; i++) {
  23082. const data = json[i];
  23083. if (data.type === 'MultiMaterial') {
  23084. // Deprecated
  23085. const array = [];
  23086. for (let j = 0; j < data.materials.length; j++) {
  23087. const material = data.materials[j];
  23088. if (cache[material.uuid] === undefined) {
  23089. cache[material.uuid] = loader.parse(material);
  23090. }
  23091. array.push(cache[material.uuid]);
  23092. }
  23093. materials[data.uuid] = array;
  23094. } else {
  23095. if (cache[data.uuid] === undefined) {
  23096. cache[data.uuid] = loader.parse(data);
  23097. }
  23098. materials[data.uuid] = cache[data.uuid];
  23099. }
  23100. }
  23101. }
  23102. return materials;
  23103. }
  23104. parseAnimations(json) {
  23105. const animations = {};
  23106. if (json !== undefined) {
  23107. for (let i = 0; i < json.length; i++) {
  23108. const data = json[i];
  23109. const clip = AnimationClip.parse(data);
  23110. animations[clip.uuid] = clip;
  23111. }
  23112. }
  23113. return animations;
  23114. }
  23115. parseImages(json, onLoad) {
  23116. const scope = this;
  23117. const images = {};
  23118. let loader;
  23119. function loadImage(url) {
  23120. scope.manager.itemStart(url);
  23121. return loader.load(url, function () {
  23122. scope.manager.itemEnd(url);
  23123. }, undefined, function () {
  23124. scope.manager.itemError(url);
  23125. scope.manager.itemEnd(url);
  23126. });
  23127. }
  23128. function deserializeImage(image) {
  23129. if (typeof image === 'string') {
  23130. const url = image;
  23131. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  23132. return loadImage(path);
  23133. } else {
  23134. if (image.data) {
  23135. return {
  23136. data: getTypedArray(image.type, image.data),
  23137. width: image.width,
  23138. height: image.height
  23139. };
  23140. } else {
  23141. return null;
  23142. }
  23143. }
  23144. }
  23145. if (json !== undefined && json.length > 0) {
  23146. const manager = new LoadingManager(onLoad);
  23147. loader = new ImageLoader(manager);
  23148. loader.setCrossOrigin(this.crossOrigin);
  23149. for (let i = 0, il = json.length; i < il; i++) {
  23150. const image = json[i];
  23151. const url = image.url;
  23152. if (Array.isArray(url)) {
  23153. // load array of images e.g CubeTexture
  23154. images[image.uuid] = [];
  23155. for (let j = 0, jl = url.length; j < jl; j++) {
  23156. const currentUrl = url[j];
  23157. const deserializedImage = deserializeImage(currentUrl);
  23158. if (deserializedImage !== null) {
  23159. if (deserializedImage instanceof HTMLImageElement) {
  23160. images[image.uuid].push(deserializedImage);
  23161. } else {
  23162. // special case: handle array of data textures for cube textures
  23163. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  23164. }
  23165. }
  23166. }
  23167. } else {
  23168. // load single image
  23169. const deserializedImage = deserializeImage(image.url);
  23170. if (deserializedImage !== null) {
  23171. images[image.uuid] = deserializedImage;
  23172. }
  23173. }
  23174. }
  23175. }
  23176. return images;
  23177. }
  23178. async parseImagesAsync(json) {
  23179. const scope = this;
  23180. const images = {};
  23181. let loader;
  23182. async function deserializeImage(image) {
  23183. if (typeof image === 'string') {
  23184. const url = image;
  23185. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  23186. return await loader.loadAsync(path);
  23187. } else {
  23188. if (image.data) {
  23189. return {
  23190. data: getTypedArray(image.type, image.data),
  23191. width: image.width,
  23192. height: image.height
  23193. };
  23194. } else {
  23195. return null;
  23196. }
  23197. }
  23198. }
  23199. if (json !== undefined && json.length > 0) {
  23200. loader = new ImageLoader(this.manager);
  23201. loader.setCrossOrigin(this.crossOrigin);
  23202. for (let i = 0, il = json.length; i < il; i++) {
  23203. const image = json[i];
  23204. const url = image.url;
  23205. if (Array.isArray(url)) {
  23206. // load array of images e.g CubeTexture
  23207. images[image.uuid] = [];
  23208. for (let j = 0, jl = url.length; j < jl; j++) {
  23209. const currentUrl = url[j];
  23210. const deserializedImage = await deserializeImage(currentUrl);
  23211. if (deserializedImage !== null) {
  23212. if (deserializedImage instanceof HTMLImageElement) {
  23213. images[image.uuid].push(deserializedImage);
  23214. } else {
  23215. // special case: handle array of data textures for cube textures
  23216. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  23217. }
  23218. }
  23219. }
  23220. } else {
  23221. // load single image
  23222. const deserializedImage = await deserializeImage(image.url);
  23223. if (deserializedImage !== null) {
  23224. images[image.uuid] = deserializedImage;
  23225. }
  23226. }
  23227. }
  23228. }
  23229. return images;
  23230. }
  23231. parseTextures(json, images) {
  23232. function parseConstant(value, type) {
  23233. if (typeof value === 'number') return value;
  23234. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  23235. return type[value];
  23236. }
  23237. const textures = {};
  23238. if (json !== undefined) {
  23239. for (let i = 0, l = json.length; i < l; i++) {
  23240. const data = json[i];
  23241. if (data.image === undefined) {
  23242. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  23243. }
  23244. if (images[data.image] === undefined) {
  23245. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  23246. }
  23247. let texture;
  23248. const image = images[data.image];
  23249. if (Array.isArray(image)) {
  23250. texture = new CubeTexture(image);
  23251. if (image.length === 6) texture.needsUpdate = true;
  23252. } else {
  23253. if (image && image.data) {
  23254. texture = new DataTexture(image.data, image.width, image.height);
  23255. } else {
  23256. texture = new Texture(image);
  23257. }
  23258. if (image) texture.needsUpdate = true; // textures can have undefined image data
  23259. }
  23260. texture.uuid = data.uuid;
  23261. if (data.name !== undefined) texture.name = data.name;
  23262. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  23263. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  23264. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  23265. if (data.center !== undefined) texture.center.fromArray(data.center);
  23266. if (data.rotation !== undefined) texture.rotation = data.rotation;
  23267. if (data.wrap !== undefined) {
  23268. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  23269. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  23270. }
  23271. if (data.format !== undefined) texture.format = data.format;
  23272. if (data.type !== undefined) texture.type = data.type;
  23273. if (data.encoding !== undefined) texture.encoding = data.encoding;
  23274. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  23275. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  23276. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  23277. if (data.flipY !== undefined) texture.flipY = data.flipY;
  23278. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  23279. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  23280. textures[data.uuid] = texture;
  23281. }
  23282. }
  23283. return textures;
  23284. }
  23285. parseObject(data, geometries, materials, textures, animations) {
  23286. let object;
  23287. function getGeometry(name) {
  23288. if (geometries[name] === undefined) {
  23289. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  23290. }
  23291. return geometries[name];
  23292. }
  23293. function getMaterial(name) {
  23294. if (name === undefined) return undefined;
  23295. if (Array.isArray(name)) {
  23296. const array = [];
  23297. for (let i = 0, l = name.length; i < l; i++) {
  23298. const uuid = name[i];
  23299. if (materials[uuid] === undefined) {
  23300. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  23301. }
  23302. array.push(materials[uuid]);
  23303. }
  23304. return array;
  23305. }
  23306. if (materials[name] === undefined) {
  23307. console.warn('THREE.ObjectLoader: Undefined material', name);
  23308. }
  23309. return materials[name];
  23310. }
  23311. function getTexture(uuid) {
  23312. if (textures[uuid] === undefined) {
  23313. console.warn('THREE.ObjectLoader: Undefined texture', uuid);
  23314. }
  23315. return textures[uuid];
  23316. }
  23317. let geometry, material;
  23318. switch (data.type) {
  23319. case 'Scene':
  23320. object = new Scene();
  23321. if (data.background !== undefined) {
  23322. if (Number.isInteger(data.background)) {
  23323. object.background = new Color(data.background);
  23324. } else {
  23325. object.background = getTexture(data.background);
  23326. }
  23327. }
  23328. if (data.environment !== undefined) object.environment = getTexture(data.environment);
  23329. if (data.fog !== undefined) {
  23330. if (data.fog.type === 'Fog') {
  23331. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  23332. } else if (data.fog.type === 'FogExp2') {
  23333. object.fog = new FogExp2(data.fog.color, data.fog.density);
  23334. }
  23335. }
  23336. break;
  23337. case 'PerspectiveCamera':
  23338. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  23339. if (data.focus !== undefined) object.focus = data.focus;
  23340. if (data.zoom !== undefined) object.zoom = data.zoom;
  23341. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  23342. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  23343. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  23344. break;
  23345. case 'OrthographicCamera':
  23346. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  23347. if (data.zoom !== undefined) object.zoom = data.zoom;
  23348. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  23349. break;
  23350. case 'AmbientLight':
  23351. object = new AmbientLight(data.color, data.intensity);
  23352. break;
  23353. case 'DirectionalLight':
  23354. object = new DirectionalLight(data.color, data.intensity);
  23355. break;
  23356. case 'PointLight':
  23357. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  23358. break;
  23359. case 'RectAreaLight':
  23360. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  23361. break;
  23362. case 'SpotLight':
  23363. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  23364. break;
  23365. case 'HemisphereLight':
  23366. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  23367. break;
  23368. case 'LightProbe':
  23369. object = new LightProbe().fromJSON(data);
  23370. break;
  23371. case 'SkinnedMesh':
  23372. geometry = getGeometry(data.geometry);
  23373. material = getMaterial(data.material);
  23374. object = new SkinnedMesh(geometry, material);
  23375. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  23376. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  23377. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  23378. break;
  23379. case 'Mesh':
  23380. geometry = getGeometry(data.geometry);
  23381. material = getMaterial(data.material);
  23382. object = new Mesh(geometry, material);
  23383. break;
  23384. case 'InstancedMesh':
  23385. geometry = getGeometry(data.geometry);
  23386. material = getMaterial(data.material);
  23387. const count = data.count;
  23388. const instanceMatrix = data.instanceMatrix;
  23389. const instanceColor = data.instanceColor;
  23390. object = new InstancedMesh(geometry, material, count);
  23391. object.instanceMatrix = new BufferAttribute(new Float32Array(instanceMatrix.array), 16);
  23392. if (instanceColor !== undefined) object.instanceColor = new BufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
  23393. break;
  23394. case 'LOD':
  23395. object = new LOD();
  23396. break;
  23397. case 'Line':
  23398. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  23399. break;
  23400. case 'LineLoop':
  23401. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  23402. break;
  23403. case 'LineSegments':
  23404. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  23405. break;
  23406. case 'PointCloud':
  23407. case 'Points':
  23408. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  23409. break;
  23410. case 'Sprite':
  23411. object = new Sprite(getMaterial(data.material));
  23412. break;
  23413. case 'Group':
  23414. object = new Group();
  23415. break;
  23416. case 'Bone':
  23417. object = new Bone();
  23418. break;
  23419. default:
  23420. object = new Object3D();
  23421. }
  23422. object.uuid = data.uuid;
  23423. if (data.name !== undefined) object.name = data.name;
  23424. if (data.matrix !== undefined) {
  23425. object.matrix.fromArray(data.matrix);
  23426. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  23427. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  23428. } else {
  23429. if (data.position !== undefined) object.position.fromArray(data.position);
  23430. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  23431. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  23432. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  23433. }
  23434. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  23435. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  23436. if (data.shadow) {
  23437. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  23438. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  23439. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  23440. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  23441. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  23442. }
  23443. if (data.visible !== undefined) object.visible = data.visible;
  23444. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  23445. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  23446. if (data.userData !== undefined) object.userData = data.userData;
  23447. if (data.layers !== undefined) object.layers.mask = data.layers;
  23448. if (data.children !== undefined) {
  23449. const children = data.children;
  23450. for (let i = 0; i < children.length; i++) {
  23451. object.add(this.parseObject(children[i], geometries, materials, textures, animations));
  23452. }
  23453. }
  23454. if (data.animations !== undefined) {
  23455. const objectAnimations = data.animations;
  23456. for (let i = 0; i < objectAnimations.length; i++) {
  23457. const uuid = objectAnimations[i];
  23458. object.animations.push(animations[uuid]);
  23459. }
  23460. }
  23461. if (data.type === 'LOD') {
  23462. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  23463. const levels = data.levels;
  23464. for (let l = 0; l < levels.length; l++) {
  23465. const level = levels[l];
  23466. const child = object.getObjectByProperty('uuid', level.object);
  23467. if (child !== undefined) {
  23468. object.addLevel(child, level.distance);
  23469. }
  23470. }
  23471. }
  23472. return object;
  23473. }
  23474. bindSkeletons(object, skeletons) {
  23475. if (Object.keys(skeletons).length === 0) return;
  23476. object.traverse(function (child) {
  23477. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  23478. const skeleton = skeletons[child.skeleton];
  23479. if (skeleton === undefined) {
  23480. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  23481. } else {
  23482. child.bind(skeleton, child.bindMatrix);
  23483. }
  23484. }
  23485. });
  23486. }
  23487. /* DEPRECATED */
  23488. setTexturePath(value) {
  23489. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  23490. return this.setResourcePath(value);
  23491. }
  23492. }
  23493. const TEXTURE_MAPPING = {
  23494. UVMapping: UVMapping,
  23495. CubeReflectionMapping: CubeReflectionMapping,
  23496. CubeRefractionMapping: CubeRefractionMapping,
  23497. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  23498. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  23499. CubeUVReflectionMapping: CubeUVReflectionMapping,
  23500. CubeUVRefractionMapping: CubeUVRefractionMapping
  23501. };
  23502. const TEXTURE_WRAPPING = {
  23503. RepeatWrapping: RepeatWrapping,
  23504. ClampToEdgeWrapping: ClampToEdgeWrapping,
  23505. MirroredRepeatWrapping: MirroredRepeatWrapping
  23506. };
  23507. const TEXTURE_FILTER = {
  23508. NearestFilter: NearestFilter,
  23509. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  23510. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  23511. LinearFilter: LinearFilter,
  23512. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  23513. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  23514. };
  23515. class ImageBitmapLoader extends Loader {
  23516. constructor(manager) {
  23517. super(manager);
  23518. if (typeof createImageBitmap === 'undefined') {
  23519. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  23520. }
  23521. if (typeof fetch === 'undefined') {
  23522. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  23523. }
  23524. this.options = {
  23525. premultiplyAlpha: 'none'
  23526. };
  23527. }
  23528. setOptions(options) {
  23529. this.options = options;
  23530. return this;
  23531. }
  23532. load(url, onLoad, onProgress, onError) {
  23533. if (url === undefined) url = '';
  23534. if (this.path !== undefined) url = this.path + url;
  23535. url = this.manager.resolveURL(url);
  23536. const scope = this;
  23537. const cached = Cache.get(url);
  23538. if (cached !== undefined) {
  23539. scope.manager.itemStart(url);
  23540. setTimeout(function () {
  23541. if (onLoad) onLoad(cached);
  23542. scope.manager.itemEnd(url);
  23543. }, 0);
  23544. return cached;
  23545. }
  23546. const fetchOptions = {};
  23547. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  23548. fetchOptions.headers = this.requestHeader;
  23549. fetch(url, fetchOptions).then(function (res) {
  23550. return res.blob();
  23551. }).then(function (blob) {
  23552. return createImageBitmap(blob, Object.assign(scope.options, {
  23553. colorSpaceConversion: 'none'
  23554. }));
  23555. }).then(function (imageBitmap) {
  23556. Cache.add(url, imageBitmap);
  23557. if (onLoad) onLoad(imageBitmap);
  23558. scope.manager.itemEnd(url);
  23559. }).catch(function (e) {
  23560. if (onError) onError(e);
  23561. scope.manager.itemError(url);
  23562. scope.manager.itemEnd(url);
  23563. });
  23564. scope.manager.itemStart(url);
  23565. }
  23566. }
  23567. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  23568. class ShapePath {
  23569. constructor() {
  23570. this.type = 'ShapePath';
  23571. this.color = new Color();
  23572. this.subPaths = [];
  23573. this.currentPath = null;
  23574. }
  23575. moveTo(x, y) {
  23576. this.currentPath = new Path();
  23577. this.subPaths.push(this.currentPath);
  23578. this.currentPath.moveTo(x, y);
  23579. return this;
  23580. }
  23581. lineTo(x, y) {
  23582. this.currentPath.lineTo(x, y);
  23583. return this;
  23584. }
  23585. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  23586. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  23587. return this;
  23588. }
  23589. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  23590. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  23591. return this;
  23592. }
  23593. splineThru(pts) {
  23594. this.currentPath.splineThru(pts);
  23595. return this;
  23596. }
  23597. toShapes(isCCW, noHoles) {
  23598. function toShapesNoHoles(inSubpaths) {
  23599. const shapes = [];
  23600. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  23601. const tmpPath = inSubpaths[i];
  23602. const tmpShape = new Shape();
  23603. tmpShape.curves = tmpPath.curves;
  23604. shapes.push(tmpShape);
  23605. }
  23606. return shapes;
  23607. }
  23608. function isPointInsidePolygon(inPt, inPolygon) {
  23609. const polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  23610. // toggling of inside/outside at every single! intersection point of an edge
  23611. // with the horizontal line through inPt, left of inPt
  23612. // not counting lowerY endpoints of edges and whole edges on that line
  23613. let inside = false;
  23614. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  23615. let edgeLowPt = inPolygon[p];
  23616. let edgeHighPt = inPolygon[q];
  23617. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  23618. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  23619. if (Math.abs(edgeDy) > Number.EPSILON) {
  23620. // not parallel
  23621. if (edgeDy < 0) {
  23622. edgeLowPt = inPolygon[q];
  23623. edgeDx = -edgeDx;
  23624. edgeHighPt = inPolygon[p];
  23625. edgeDy = -edgeDy;
  23626. }
  23627. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  23628. if (inPt.y === edgeLowPt.y) {
  23629. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  23630. // continue; // no intersection or edgeLowPt => doesn't count !!!
  23631. } else {
  23632. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  23633. if (perpEdge === 0) return true; // inPt is on contour ?
  23634. if (perpEdge < 0) continue;
  23635. inside = !inside; // true intersection left of inPt
  23636. }
  23637. } else {
  23638. // parallel or collinear
  23639. if (inPt.y !== edgeLowPt.y) continue; // parallel
  23640. // edge lies on the same horizontal line as inPt
  23641. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  23642. // continue;
  23643. }
  23644. }
  23645. return inside;
  23646. }
  23647. const isClockWise = ShapeUtils.isClockWise;
  23648. const subPaths = this.subPaths;
  23649. if (subPaths.length === 0) return [];
  23650. if (noHoles === true) return toShapesNoHoles(subPaths);
  23651. let solid, tmpPath, tmpShape;
  23652. const shapes = [];
  23653. if (subPaths.length === 1) {
  23654. tmpPath = subPaths[0];
  23655. tmpShape = new Shape();
  23656. tmpShape.curves = tmpPath.curves;
  23657. shapes.push(tmpShape);
  23658. return shapes;
  23659. }
  23660. let holesFirst = !isClockWise(subPaths[0].getPoints());
  23661. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  23662. const betterShapeHoles = [];
  23663. const newShapes = [];
  23664. let newShapeHoles = [];
  23665. let mainIdx = 0;
  23666. let tmpPoints;
  23667. newShapes[mainIdx] = undefined;
  23668. newShapeHoles[mainIdx] = [];
  23669. for (let i = 0, l = subPaths.length; i < l; i++) {
  23670. tmpPath = subPaths[i];
  23671. tmpPoints = tmpPath.getPoints();
  23672. solid = isClockWise(tmpPoints);
  23673. solid = isCCW ? !solid : solid;
  23674. if (solid) {
  23675. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  23676. newShapes[mainIdx] = {
  23677. s: new Shape(),
  23678. p: tmpPoints
  23679. };
  23680. newShapes[mainIdx].s.curves = tmpPath.curves;
  23681. if (holesFirst) mainIdx++;
  23682. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  23683. } else {
  23684. newShapeHoles[mainIdx].push({
  23685. h: tmpPath,
  23686. p: tmpPoints[0]
  23687. }); //console.log('ccw', i);
  23688. }
  23689. } // only Holes? -> probably all Shapes with wrong orientation
  23690. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  23691. if (newShapes.length > 1) {
  23692. let ambiguous = false;
  23693. const toChange = [];
  23694. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  23695. betterShapeHoles[sIdx] = [];
  23696. }
  23697. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  23698. const sho = newShapeHoles[sIdx];
  23699. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  23700. const ho = sho[hIdx];
  23701. let hole_unassigned = true;
  23702. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  23703. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  23704. if (sIdx !== s2Idx) toChange.push({
  23705. froms: sIdx,
  23706. tos: s2Idx,
  23707. hole: hIdx
  23708. });
  23709. if (hole_unassigned) {
  23710. hole_unassigned = false;
  23711. betterShapeHoles[s2Idx].push(ho);
  23712. } else {
  23713. ambiguous = true;
  23714. }
  23715. }
  23716. }
  23717. if (hole_unassigned) {
  23718. betterShapeHoles[sIdx].push(ho);
  23719. }
  23720. }
  23721. } // console.log("ambiguous: ", ambiguous);
  23722. if (toChange.length > 0) {
  23723. // console.log("to change: ", toChange);
  23724. if (!ambiguous) newShapeHoles = betterShapeHoles;
  23725. }
  23726. }
  23727. let tmpHoles;
  23728. for (let i = 0, il = newShapes.length; i < il; i++) {
  23729. tmpShape = newShapes[i].s;
  23730. shapes.push(tmpShape);
  23731. tmpHoles = newShapeHoles[i];
  23732. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  23733. tmpShape.holes.push(tmpHoles[j].h);
  23734. }
  23735. } //console.log("shape", shapes);
  23736. return shapes;
  23737. }
  23738. }
  23739. class Font {
  23740. constructor(data) {
  23741. this.type = 'Font';
  23742. this.data = data;
  23743. }
  23744. generateShapes(text, size = 100) {
  23745. const shapes = [];
  23746. const paths = createPaths(text, size, this.data);
  23747. for (let p = 0, pl = paths.length; p < pl; p++) {
  23748. Array.prototype.push.apply(shapes, paths[p].toShapes());
  23749. }
  23750. return shapes;
  23751. }
  23752. }
  23753. function createPaths(text, size, data) {
  23754. const chars = Array.from(text);
  23755. const scale = size / data.resolution;
  23756. const line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  23757. const paths = [];
  23758. let offsetX = 0,
  23759. offsetY = 0;
  23760. for (let i = 0; i < chars.length; i++) {
  23761. const char = chars[i];
  23762. if (char === '\n') {
  23763. offsetX = 0;
  23764. offsetY -= line_height;
  23765. } else {
  23766. const ret = createPath(char, scale, offsetX, offsetY, data);
  23767. offsetX += ret.offsetX;
  23768. paths.push(ret.path);
  23769. }
  23770. }
  23771. return paths;
  23772. }
  23773. function createPath(char, scale, offsetX, offsetY, data) {
  23774. const glyph = data.glyphs[char] || data.glyphs['?'];
  23775. if (!glyph) {
  23776. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  23777. return;
  23778. }
  23779. const path = new ShapePath();
  23780. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  23781. if (glyph.o) {
  23782. const outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  23783. for (let i = 0, l = outline.length; i < l;) {
  23784. const action = outline[i++];
  23785. switch (action) {
  23786. case 'm':
  23787. // moveTo
  23788. x = outline[i++] * scale + offsetX;
  23789. y = outline[i++] * scale + offsetY;
  23790. path.moveTo(x, y);
  23791. break;
  23792. case 'l':
  23793. // lineTo
  23794. x = outline[i++] * scale + offsetX;
  23795. y = outline[i++] * scale + offsetY;
  23796. path.lineTo(x, y);
  23797. break;
  23798. case 'q':
  23799. // quadraticCurveTo
  23800. cpx = outline[i++] * scale + offsetX;
  23801. cpy = outline[i++] * scale + offsetY;
  23802. cpx1 = outline[i++] * scale + offsetX;
  23803. cpy1 = outline[i++] * scale + offsetY;
  23804. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  23805. break;
  23806. case 'b':
  23807. // bezierCurveTo
  23808. cpx = outline[i++] * scale + offsetX;
  23809. cpy = outline[i++] * scale + offsetY;
  23810. cpx1 = outline[i++] * scale + offsetX;
  23811. cpy1 = outline[i++] * scale + offsetY;
  23812. cpx2 = outline[i++] * scale + offsetX;
  23813. cpy2 = outline[i++] * scale + offsetY;
  23814. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  23815. break;
  23816. }
  23817. }
  23818. }
  23819. return {
  23820. offsetX: glyph.ha * scale,
  23821. path: path
  23822. };
  23823. }
  23824. Font.prototype.isFont = true;
  23825. class FontLoader extends Loader {
  23826. constructor(manager) {
  23827. super(manager);
  23828. }
  23829. load(url, onLoad, onProgress, onError) {
  23830. const scope = this;
  23831. const loader = new FileLoader(this.manager);
  23832. loader.setPath(this.path);
  23833. loader.setRequestHeader(this.requestHeader);
  23834. loader.setWithCredentials(scope.withCredentials);
  23835. loader.load(url, function (text) {
  23836. let json;
  23837. try {
  23838. json = JSON.parse(text);
  23839. } catch (e) {
  23840. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  23841. json = JSON.parse(text.substring(65, text.length - 2));
  23842. }
  23843. const font = scope.parse(json);
  23844. if (onLoad) onLoad(font);
  23845. }, onProgress, onError);
  23846. }
  23847. parse(json) {
  23848. return new Font(json);
  23849. }
  23850. }
  23851. let _context;
  23852. const AudioContext = {
  23853. getContext: function () {
  23854. if (_context === undefined) {
  23855. _context = new (window.AudioContext || window.webkitAudioContext)();
  23856. }
  23857. return _context;
  23858. },
  23859. setContext: function (value) {
  23860. _context = value;
  23861. }
  23862. };
  23863. class AudioLoader extends Loader {
  23864. constructor(manager) {
  23865. super(manager);
  23866. }
  23867. load(url, onLoad, onProgress, onError) {
  23868. const scope = this;
  23869. const loader = new FileLoader(this.manager);
  23870. loader.setResponseType('arraybuffer');
  23871. loader.setPath(this.path);
  23872. loader.setRequestHeader(this.requestHeader);
  23873. loader.setWithCredentials(this.withCredentials);
  23874. loader.load(url, function (buffer) {
  23875. try {
  23876. // Create a copy of the buffer. The `decodeAudioData` method
  23877. // detaches the buffer when complete, preventing reuse.
  23878. const bufferCopy = buffer.slice(0);
  23879. const context = AudioContext.getContext();
  23880. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  23881. onLoad(audioBuffer);
  23882. });
  23883. } catch (e) {
  23884. if (onError) {
  23885. onError(e);
  23886. } else {
  23887. console.error(e);
  23888. }
  23889. scope.manager.itemError(url);
  23890. }
  23891. }, onProgress, onError);
  23892. }
  23893. }
  23894. class HemisphereLightProbe extends LightProbe {
  23895. constructor(skyColor, groundColor, intensity = 1) {
  23896. super(undefined, intensity);
  23897. const color1 = new Color().set(skyColor);
  23898. const color2 = new Color().set(groundColor);
  23899. const sky = new Vector3(color1.r, color1.g, color1.b);
  23900. const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  23901. const c0 = Math.sqrt(Math.PI);
  23902. const c1 = c0 * Math.sqrt(0.75);
  23903. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  23904. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  23905. }
  23906. }
  23907. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  23908. class AmbientLightProbe extends LightProbe {
  23909. constructor(color, intensity = 1) {
  23910. super(undefined, intensity);
  23911. const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  23912. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  23913. }
  23914. }
  23915. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  23916. const _eyeRight = /*@__PURE__*/new Matrix4();
  23917. const _eyeLeft = /*@__PURE__*/new Matrix4();
  23918. class StereoCamera {
  23919. constructor() {
  23920. this.type = 'StereoCamera';
  23921. this.aspect = 1;
  23922. this.eyeSep = 0.064;
  23923. this.cameraL = new PerspectiveCamera();
  23924. this.cameraL.layers.enable(1);
  23925. this.cameraL.matrixAutoUpdate = false;
  23926. this.cameraR = new PerspectiveCamera();
  23927. this.cameraR.layers.enable(2);
  23928. this.cameraR.matrixAutoUpdate = false;
  23929. this._cache = {
  23930. focus: null,
  23931. fov: null,
  23932. aspect: null,
  23933. near: null,
  23934. far: null,
  23935. zoom: null,
  23936. eyeSep: null
  23937. };
  23938. }
  23939. update(camera) {
  23940. const cache = this._cache;
  23941. 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;
  23942. if (needsUpdate) {
  23943. cache.focus = camera.focus;
  23944. cache.fov = camera.fov;
  23945. cache.aspect = camera.aspect * this.aspect;
  23946. cache.near = camera.near;
  23947. cache.far = camera.far;
  23948. cache.zoom = camera.zoom;
  23949. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  23950. // http://paulbourke.net/stereographics/stereorender/
  23951. const projectionMatrix = camera.projectionMatrix.clone();
  23952. const eyeSepHalf = cache.eyeSep / 2;
  23953. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  23954. const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom;
  23955. let xmin, xmax; // translate xOffset
  23956. _eyeLeft.elements[12] = -eyeSepHalf;
  23957. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  23958. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  23959. xmax = ymax * cache.aspect + eyeSepOnProjection;
  23960. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  23961. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  23962. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  23963. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  23964. xmax = ymax * cache.aspect - eyeSepOnProjection;
  23965. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  23966. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  23967. this.cameraR.projectionMatrix.copy(projectionMatrix);
  23968. }
  23969. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  23970. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  23971. }
  23972. }
  23973. class Clock {
  23974. constructor(autoStart = true) {
  23975. this.autoStart = autoStart;
  23976. this.startTime = 0;
  23977. this.oldTime = 0;
  23978. this.elapsedTime = 0;
  23979. this.running = false;
  23980. }
  23981. start() {
  23982. this.startTime = now();
  23983. this.oldTime = this.startTime;
  23984. this.elapsedTime = 0;
  23985. this.running = true;
  23986. }
  23987. stop() {
  23988. this.getElapsedTime();
  23989. this.running = false;
  23990. this.autoStart = false;
  23991. }
  23992. getElapsedTime() {
  23993. this.getDelta();
  23994. return this.elapsedTime;
  23995. }
  23996. getDelta() {
  23997. let diff = 0;
  23998. if (this.autoStart && !this.running) {
  23999. this.start();
  24000. return 0;
  24001. }
  24002. if (this.running) {
  24003. const newTime = now();
  24004. diff = (newTime - this.oldTime) / 1000;
  24005. this.oldTime = newTime;
  24006. this.elapsedTime += diff;
  24007. }
  24008. return diff;
  24009. }
  24010. }
  24011. function now() {
  24012. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  24013. }
  24014. const _position$1 = /*@__PURE__*/new Vector3();
  24015. const _quaternion$1 = /*@__PURE__*/new Quaternion();
  24016. const _scale$1 = /*@__PURE__*/new Vector3();
  24017. const _orientation$1 = /*@__PURE__*/new Vector3();
  24018. class AudioListener extends Object3D {
  24019. constructor() {
  24020. super();
  24021. this.type = 'AudioListener';
  24022. this.context = AudioContext.getContext();
  24023. this.gain = this.context.createGain();
  24024. this.gain.connect(this.context.destination);
  24025. this.filter = null;
  24026. this.timeDelta = 0; // private
  24027. this._clock = new Clock();
  24028. }
  24029. getInput() {
  24030. return this.gain;
  24031. }
  24032. removeFilter() {
  24033. if (this.filter !== null) {
  24034. this.gain.disconnect(this.filter);
  24035. this.filter.disconnect(this.context.destination);
  24036. this.gain.connect(this.context.destination);
  24037. this.filter = null;
  24038. }
  24039. return this;
  24040. }
  24041. getFilter() {
  24042. return this.filter;
  24043. }
  24044. setFilter(value) {
  24045. if (this.filter !== null) {
  24046. this.gain.disconnect(this.filter);
  24047. this.filter.disconnect(this.context.destination);
  24048. } else {
  24049. this.gain.disconnect(this.context.destination);
  24050. }
  24051. this.filter = value;
  24052. this.gain.connect(this.filter);
  24053. this.filter.connect(this.context.destination);
  24054. return this;
  24055. }
  24056. getMasterVolume() {
  24057. return this.gain.gain.value;
  24058. }
  24059. setMasterVolume(value) {
  24060. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  24061. return this;
  24062. }
  24063. updateMatrixWorld(force) {
  24064. super.updateMatrixWorld(force);
  24065. const listener = this.context.listener;
  24066. const up = this.up;
  24067. this.timeDelta = this._clock.getDelta();
  24068. this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
  24069. _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
  24070. if (listener.positionX) {
  24071. // code path for Chrome (see #14393)
  24072. const endTime = this.context.currentTime + this.timeDelta;
  24073. listener.positionX.linearRampToValueAtTime(_position$1.x, endTime);
  24074. listener.positionY.linearRampToValueAtTime(_position$1.y, endTime);
  24075. listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime);
  24076. listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime);
  24077. listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
  24078. listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  24079. listener.upX.linearRampToValueAtTime(up.x, endTime);
  24080. listener.upY.linearRampToValueAtTime(up.y, endTime);
  24081. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  24082. } else {
  24083. listener.setPosition(_position$1.x, _position$1.y, _position$1.z);
  24084. listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
  24085. }
  24086. }
  24087. }
  24088. class Audio extends Object3D {
  24089. constructor(listener) {
  24090. super();
  24091. this.type = 'Audio';
  24092. this.listener = listener;
  24093. this.context = listener.context;
  24094. this.gain = this.context.createGain();
  24095. this.gain.connect(listener.getInput());
  24096. this.autoplay = false;
  24097. this.buffer = null;
  24098. this.detune = 0;
  24099. this.loop = false;
  24100. this.loopStart = 0;
  24101. this.loopEnd = 0;
  24102. this.offset = 0;
  24103. this.duration = undefined;
  24104. this.playbackRate = 1;
  24105. this.isPlaying = false;
  24106. this.hasPlaybackControl = true;
  24107. this.source = null;
  24108. this.sourceType = 'empty';
  24109. this._startedAt = 0;
  24110. this._progress = 0;
  24111. this._connected = false;
  24112. this.filters = [];
  24113. }
  24114. getOutput() {
  24115. return this.gain;
  24116. }
  24117. setNodeSource(audioNode) {
  24118. this.hasPlaybackControl = false;
  24119. this.sourceType = 'audioNode';
  24120. this.source = audioNode;
  24121. this.connect();
  24122. return this;
  24123. }
  24124. setMediaElementSource(mediaElement) {
  24125. this.hasPlaybackControl = false;
  24126. this.sourceType = 'mediaNode';
  24127. this.source = this.context.createMediaElementSource(mediaElement);
  24128. this.connect();
  24129. return this;
  24130. }
  24131. setMediaStreamSource(mediaStream) {
  24132. this.hasPlaybackControl = false;
  24133. this.sourceType = 'mediaStreamNode';
  24134. this.source = this.context.createMediaStreamSource(mediaStream);
  24135. this.connect();
  24136. return this;
  24137. }
  24138. setBuffer(audioBuffer) {
  24139. this.buffer = audioBuffer;
  24140. this.sourceType = 'buffer';
  24141. if (this.autoplay) this.play();
  24142. return this;
  24143. }
  24144. play(delay = 0) {
  24145. if (this.isPlaying === true) {
  24146. console.warn('THREE.Audio: Audio is already playing.');
  24147. return;
  24148. }
  24149. if (this.hasPlaybackControl === false) {
  24150. console.warn('THREE.Audio: this Audio has no playback control.');
  24151. return;
  24152. }
  24153. this._startedAt = this.context.currentTime + delay;
  24154. const source = this.context.createBufferSource();
  24155. source.buffer = this.buffer;
  24156. source.loop = this.loop;
  24157. source.loopStart = this.loopStart;
  24158. source.loopEnd = this.loopEnd;
  24159. source.onended = this.onEnded.bind(this);
  24160. source.start(this._startedAt, this._progress + this.offset, this.duration);
  24161. this.isPlaying = true;
  24162. this.source = source;
  24163. this.setDetune(this.detune);
  24164. this.setPlaybackRate(this.playbackRate);
  24165. return this.connect();
  24166. }
  24167. pause() {
  24168. if (this.hasPlaybackControl === false) {
  24169. console.warn('THREE.Audio: this Audio has no playback control.');
  24170. return;
  24171. }
  24172. if (this.isPlaying === true) {
  24173. // update current progress
  24174. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  24175. if (this.loop === true) {
  24176. // ensure _progress does not exceed duration with looped audios
  24177. this._progress = this._progress % (this.duration || this.buffer.duration);
  24178. }
  24179. this.source.stop();
  24180. this.source.onended = null;
  24181. this.isPlaying = false;
  24182. }
  24183. return this;
  24184. }
  24185. stop() {
  24186. if (this.hasPlaybackControl === false) {
  24187. console.warn('THREE.Audio: this Audio has no playback control.');
  24188. return;
  24189. }
  24190. this._progress = 0;
  24191. this.source.stop();
  24192. this.source.onended = null;
  24193. this.isPlaying = false;
  24194. return this;
  24195. }
  24196. connect() {
  24197. if (this.filters.length > 0) {
  24198. this.source.connect(this.filters[0]);
  24199. for (let i = 1, l = this.filters.length; i < l; i++) {
  24200. this.filters[i - 1].connect(this.filters[i]);
  24201. }
  24202. this.filters[this.filters.length - 1].connect(this.getOutput());
  24203. } else {
  24204. this.source.connect(this.getOutput());
  24205. }
  24206. this._connected = true;
  24207. return this;
  24208. }
  24209. disconnect() {
  24210. if (this.filters.length > 0) {
  24211. this.source.disconnect(this.filters[0]);
  24212. for (let i = 1, l = this.filters.length; i < l; i++) {
  24213. this.filters[i - 1].disconnect(this.filters[i]);
  24214. }
  24215. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  24216. } else {
  24217. this.source.disconnect(this.getOutput());
  24218. }
  24219. this._connected = false;
  24220. return this;
  24221. }
  24222. getFilters() {
  24223. return this.filters;
  24224. }
  24225. setFilters(value) {
  24226. if (!value) value = [];
  24227. if (this._connected === true) {
  24228. this.disconnect();
  24229. this.filters = value.slice();
  24230. this.connect();
  24231. } else {
  24232. this.filters = value.slice();
  24233. }
  24234. return this;
  24235. }
  24236. setDetune(value) {
  24237. this.detune = value;
  24238. if (this.source.detune === undefined) return; // only set detune when available
  24239. if (this.isPlaying === true) {
  24240. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  24241. }
  24242. return this;
  24243. }
  24244. getDetune() {
  24245. return this.detune;
  24246. }
  24247. getFilter() {
  24248. return this.getFilters()[0];
  24249. }
  24250. setFilter(filter) {
  24251. return this.setFilters(filter ? [filter] : []);
  24252. }
  24253. setPlaybackRate(value) {
  24254. if (this.hasPlaybackControl === false) {
  24255. console.warn('THREE.Audio: this Audio has no playback control.');
  24256. return;
  24257. }
  24258. this.playbackRate = value;
  24259. if (this.isPlaying === true) {
  24260. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  24261. }
  24262. return this;
  24263. }
  24264. getPlaybackRate() {
  24265. return this.playbackRate;
  24266. }
  24267. onEnded() {
  24268. this.isPlaying = false;
  24269. }
  24270. getLoop() {
  24271. if (this.hasPlaybackControl === false) {
  24272. console.warn('THREE.Audio: this Audio has no playback control.');
  24273. return false;
  24274. }
  24275. return this.loop;
  24276. }
  24277. setLoop(value) {
  24278. if (this.hasPlaybackControl === false) {
  24279. console.warn('THREE.Audio: this Audio has no playback control.');
  24280. return;
  24281. }
  24282. this.loop = value;
  24283. if (this.isPlaying === true) {
  24284. this.source.loop = this.loop;
  24285. }
  24286. return this;
  24287. }
  24288. setLoopStart(value) {
  24289. this.loopStart = value;
  24290. return this;
  24291. }
  24292. setLoopEnd(value) {
  24293. this.loopEnd = value;
  24294. return this;
  24295. }
  24296. getVolume() {
  24297. return this.gain.gain.value;
  24298. }
  24299. setVolume(value) {
  24300. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  24301. return this;
  24302. }
  24303. }
  24304. const _position = /*@__PURE__*/new Vector3();
  24305. const _quaternion = /*@__PURE__*/new Quaternion();
  24306. const _scale = /*@__PURE__*/new Vector3();
  24307. const _orientation = /*@__PURE__*/new Vector3();
  24308. class PositionalAudio extends Audio {
  24309. constructor(listener) {
  24310. super(listener);
  24311. this.panner = this.context.createPanner();
  24312. this.panner.panningModel = 'HRTF';
  24313. this.panner.connect(this.gain);
  24314. }
  24315. getOutput() {
  24316. return this.panner;
  24317. }
  24318. getRefDistance() {
  24319. return this.panner.refDistance;
  24320. }
  24321. setRefDistance(value) {
  24322. this.panner.refDistance = value;
  24323. return this;
  24324. }
  24325. getRolloffFactor() {
  24326. return this.panner.rolloffFactor;
  24327. }
  24328. setRolloffFactor(value) {
  24329. this.panner.rolloffFactor = value;
  24330. return this;
  24331. }
  24332. getDistanceModel() {
  24333. return this.panner.distanceModel;
  24334. }
  24335. setDistanceModel(value) {
  24336. this.panner.distanceModel = value;
  24337. return this;
  24338. }
  24339. getMaxDistance() {
  24340. return this.panner.maxDistance;
  24341. }
  24342. setMaxDistance(value) {
  24343. this.panner.maxDistance = value;
  24344. return this;
  24345. }
  24346. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  24347. this.panner.coneInnerAngle = coneInnerAngle;
  24348. this.panner.coneOuterAngle = coneOuterAngle;
  24349. this.panner.coneOuterGain = coneOuterGain;
  24350. return this;
  24351. }
  24352. updateMatrixWorld(force) {
  24353. super.updateMatrixWorld(force);
  24354. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  24355. this.matrixWorld.decompose(_position, _quaternion, _scale);
  24356. _orientation.set(0, 0, 1).applyQuaternion(_quaternion);
  24357. const panner = this.panner;
  24358. if (panner.positionX) {
  24359. // code path for Chrome and Firefox (see #14393)
  24360. const endTime = this.context.currentTime + this.listener.timeDelta;
  24361. panner.positionX.linearRampToValueAtTime(_position.x, endTime);
  24362. panner.positionY.linearRampToValueAtTime(_position.y, endTime);
  24363. panner.positionZ.linearRampToValueAtTime(_position.z, endTime);
  24364. panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime);
  24365. panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime);
  24366. panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime);
  24367. } else {
  24368. panner.setPosition(_position.x, _position.y, _position.z);
  24369. panner.setOrientation(_orientation.x, _orientation.y, _orientation.z);
  24370. }
  24371. }
  24372. }
  24373. class AudioAnalyser {
  24374. constructor(audio, fftSize = 2048) {
  24375. this.analyser = audio.context.createAnalyser();
  24376. this.analyser.fftSize = fftSize;
  24377. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  24378. audio.getOutput().connect(this.analyser);
  24379. }
  24380. getFrequencyData() {
  24381. this.analyser.getByteFrequencyData(this.data);
  24382. return this.data;
  24383. }
  24384. getAverageFrequency() {
  24385. let value = 0;
  24386. const data = this.getFrequencyData();
  24387. for (let i = 0; i < data.length; i++) {
  24388. value += data[i];
  24389. }
  24390. return value / data.length;
  24391. }
  24392. }
  24393. class PropertyMixer {
  24394. constructor(binding, typeName, valueSize) {
  24395. this.binding = binding;
  24396. this.valueSize = valueSize;
  24397. let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  24398. //
  24399. // interpolators can use .buffer as their .result
  24400. // the data then goes to 'incoming'
  24401. //
  24402. // 'accu0' and 'accu1' are used frame-interleaved for
  24403. // the cumulative result and are compared to detect
  24404. // changes
  24405. //
  24406. // 'orig' stores the original state of the property
  24407. //
  24408. // 'add' is used for additive cumulative results
  24409. //
  24410. // 'work' is optional and is only present for quaternion types. It is used
  24411. // to store intermediate quaternion multiplication results
  24412. switch (typeName) {
  24413. case 'quaternion':
  24414. mixFunction = this._slerp;
  24415. mixFunctionAdditive = this._slerpAdditive;
  24416. setIdentity = this._setAdditiveIdentityQuaternion;
  24417. this.buffer = new Float64Array(valueSize * 6);
  24418. this._workIndex = 5;
  24419. break;
  24420. case 'string':
  24421. case 'bool':
  24422. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  24423. // additive is not relevant for non-numeric types
  24424. mixFunctionAdditive = this._select;
  24425. setIdentity = this._setAdditiveIdentityOther;
  24426. this.buffer = new Array(valueSize * 5);
  24427. break;
  24428. default:
  24429. mixFunction = this._lerp;
  24430. mixFunctionAdditive = this._lerpAdditive;
  24431. setIdentity = this._setAdditiveIdentityNumeric;
  24432. this.buffer = new Float64Array(valueSize * 5);
  24433. }
  24434. this._mixBufferRegion = mixFunction;
  24435. this._mixBufferRegionAdditive = mixFunctionAdditive;
  24436. this._setIdentity = setIdentity;
  24437. this._origIndex = 3;
  24438. this._addIndex = 4;
  24439. this.cumulativeWeight = 0;
  24440. this.cumulativeWeightAdditive = 0;
  24441. this.useCount = 0;
  24442. this.referenceCount = 0;
  24443. } // accumulate data in the 'incoming' region into 'accu<i>'
  24444. accumulate(accuIndex, weight) {
  24445. // note: happily accumulating nothing when weight = 0, the caller knows
  24446. // the weight and shouldn't have made the call in the first place
  24447. const buffer = this.buffer,
  24448. stride = this.valueSize,
  24449. offset = accuIndex * stride + stride;
  24450. let currentWeight = this.cumulativeWeight;
  24451. if (currentWeight === 0) {
  24452. // accuN := incoming * weight
  24453. for (let i = 0; i !== stride; ++i) {
  24454. buffer[offset + i] = buffer[i];
  24455. }
  24456. currentWeight = weight;
  24457. } else {
  24458. // accuN := accuN + incoming * weight
  24459. currentWeight += weight;
  24460. const mix = weight / currentWeight;
  24461. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  24462. }
  24463. this.cumulativeWeight = currentWeight;
  24464. } // accumulate data in the 'incoming' region into 'add'
  24465. accumulateAdditive(weight) {
  24466. const buffer = this.buffer,
  24467. stride = this.valueSize,
  24468. offset = stride * this._addIndex;
  24469. if (this.cumulativeWeightAdditive === 0) {
  24470. // add = identity
  24471. this._setIdentity();
  24472. } // add := add + incoming * weight
  24473. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  24474. this.cumulativeWeightAdditive += weight;
  24475. } // apply the state of 'accu<i>' to the binding when accus differ
  24476. apply(accuIndex) {
  24477. const stride = this.valueSize,
  24478. buffer = this.buffer,
  24479. offset = accuIndex * stride + stride,
  24480. weight = this.cumulativeWeight,
  24481. weightAdditive = this.cumulativeWeightAdditive,
  24482. binding = this.binding;
  24483. this.cumulativeWeight = 0;
  24484. this.cumulativeWeightAdditive = 0;
  24485. if (weight < 1) {
  24486. // accuN := accuN + original * ( 1 - cumulativeWeight )
  24487. const originalValueOffset = stride * this._origIndex;
  24488. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  24489. }
  24490. if (weightAdditive > 0) {
  24491. // accuN := accuN + additive accuN
  24492. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  24493. }
  24494. for (let i = stride, e = stride + stride; i !== e; ++i) {
  24495. if (buffer[i] !== buffer[i + stride]) {
  24496. // value has changed -> update scene graph
  24497. binding.setValue(buffer, offset);
  24498. break;
  24499. }
  24500. }
  24501. } // remember the state of the bound property and copy it to both accus
  24502. saveOriginalState() {
  24503. const binding = this.binding;
  24504. const buffer = this.buffer,
  24505. stride = this.valueSize,
  24506. originalValueOffset = stride * this._origIndex;
  24507. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  24508. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  24509. buffer[i] = buffer[originalValueOffset + i % stride];
  24510. } // Add to identity for additive
  24511. this._setIdentity();
  24512. this.cumulativeWeight = 0;
  24513. this.cumulativeWeightAdditive = 0;
  24514. } // apply the state previously taken via 'saveOriginalState' to the binding
  24515. restoreOriginalState() {
  24516. const originalValueOffset = this.valueSize * 3;
  24517. this.binding.setValue(this.buffer, originalValueOffset);
  24518. }
  24519. _setAdditiveIdentityNumeric() {
  24520. const startIndex = this._addIndex * this.valueSize;
  24521. const endIndex = startIndex + this.valueSize;
  24522. for (let i = startIndex; i < endIndex; i++) {
  24523. this.buffer[i] = 0;
  24524. }
  24525. }
  24526. _setAdditiveIdentityQuaternion() {
  24527. this._setAdditiveIdentityNumeric();
  24528. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  24529. }
  24530. _setAdditiveIdentityOther() {
  24531. const startIndex = this._origIndex * this.valueSize;
  24532. const targetIndex = this._addIndex * this.valueSize;
  24533. for (let i = 0; i < this.valueSize; i++) {
  24534. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  24535. }
  24536. } // mix functions
  24537. _select(buffer, dstOffset, srcOffset, t, stride) {
  24538. if (t >= 0.5) {
  24539. for (let i = 0; i !== stride; ++i) {
  24540. buffer[dstOffset + i] = buffer[srcOffset + i];
  24541. }
  24542. }
  24543. }
  24544. _slerp(buffer, dstOffset, srcOffset, t) {
  24545. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  24546. }
  24547. _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  24548. const workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  24549. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  24550. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  24551. }
  24552. _lerp(buffer, dstOffset, srcOffset, t, stride) {
  24553. const s = 1 - t;
  24554. for (let i = 0; i !== stride; ++i) {
  24555. const j = dstOffset + i;
  24556. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  24557. }
  24558. }
  24559. _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  24560. for (let i = 0; i !== stride; ++i) {
  24561. const j = dstOffset + i;
  24562. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  24563. }
  24564. }
  24565. }
  24566. // Characters [].:/ are reserved for track binding syntax.
  24567. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  24568. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  24569. // only latin characters, and the unicode \p{L} is not yet supported. So
  24570. // instead, we exclude reserved characters and match everything else.
  24571. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  24572. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  24573. // be matched to parse the rest of the track name.
  24574. const _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  24575. const _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  24576. // characters. Accessor may contain any character except closing bracket.
  24577. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  24578. // contain any non-bracket characters.
  24579. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  24580. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  24581. const _supportedObjectNames = ['material', 'materials', 'bones'];
  24582. class Composite {
  24583. constructor(targetGroup, path, optionalParsedPath) {
  24584. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  24585. this._targetGroup = targetGroup;
  24586. this._bindings = targetGroup.subscribe_(path, parsedPath);
  24587. }
  24588. getValue(array, offset) {
  24589. this.bind(); // bind all binding
  24590. const firstValidIndex = this._targetGroup.nCachedObjects_,
  24591. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  24592. if (binding !== undefined) binding.getValue(array, offset);
  24593. }
  24594. setValue(array, offset) {
  24595. const bindings = this._bindings;
  24596. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  24597. bindings[i].setValue(array, offset);
  24598. }
  24599. }
  24600. bind() {
  24601. const bindings = this._bindings;
  24602. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  24603. bindings[i].bind();
  24604. }
  24605. }
  24606. unbind() {
  24607. const bindings = this._bindings;
  24608. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  24609. bindings[i].unbind();
  24610. }
  24611. }
  24612. } // Note: This class uses a State pattern on a per-method basis:
  24613. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  24614. // prototype version of these methods with one that represents
  24615. // the bound state. When the property is not found, the methods
  24616. // become no-ops.
  24617. class PropertyBinding {
  24618. constructor(rootNode, path, parsedPath) {
  24619. this.path = path;
  24620. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  24621. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  24622. this.rootNode = rootNode; // initial state of these methods that calls 'bind'
  24623. this.getValue = this._getValue_unbound;
  24624. this.setValue = this._setValue_unbound;
  24625. }
  24626. static create(root, path, parsedPath) {
  24627. if (!(root && root.isAnimationObjectGroup)) {
  24628. return new PropertyBinding(root, path, parsedPath);
  24629. } else {
  24630. return new PropertyBinding.Composite(root, path, parsedPath);
  24631. }
  24632. }
  24633. /**
  24634. * Replaces spaces with underscores and removes unsupported characters from
  24635. * node names, to ensure compatibility with parseTrackName().
  24636. *
  24637. * @param {string} name Node name to be sanitized.
  24638. * @return {string}
  24639. */
  24640. static sanitizeNodeName(name) {
  24641. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  24642. }
  24643. static parseTrackName(trackName) {
  24644. const matches = _trackRe.exec(trackName);
  24645. if (!matches) {
  24646. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  24647. }
  24648. const results = {
  24649. // directoryName: matches[ 1 ], // (tschw) currently unused
  24650. nodeName: matches[2],
  24651. objectName: matches[3],
  24652. objectIndex: matches[4],
  24653. propertyName: matches[5],
  24654. // required
  24655. propertyIndex: matches[6]
  24656. };
  24657. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  24658. if (lastDot !== undefined && lastDot !== -1) {
  24659. const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  24660. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  24661. // 'bar' could be the objectName, or part of a nodeName (which can
  24662. // include '.' characters).
  24663. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  24664. results.nodeName = results.nodeName.substring(0, lastDot);
  24665. results.objectName = objectName;
  24666. }
  24667. }
  24668. if (results.propertyName === null || results.propertyName.length === 0) {
  24669. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  24670. }
  24671. return results;
  24672. }
  24673. static findNode(root, nodeName) {
  24674. if (!nodeName || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  24675. return root;
  24676. } // search into skeleton bones.
  24677. if (root.skeleton) {
  24678. const bone = root.skeleton.getBoneByName(nodeName);
  24679. if (bone !== undefined) {
  24680. return bone;
  24681. }
  24682. } // search into node subtree.
  24683. if (root.children) {
  24684. const searchNodeSubtree = function (children) {
  24685. for (let i = 0; i < children.length; i++) {
  24686. const childNode = children[i];
  24687. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  24688. return childNode;
  24689. }
  24690. const result = searchNodeSubtree(childNode.children);
  24691. if (result) return result;
  24692. }
  24693. return null;
  24694. };
  24695. const subTreeNode = searchNodeSubtree(root.children);
  24696. if (subTreeNode) {
  24697. return subTreeNode;
  24698. }
  24699. }
  24700. return null;
  24701. } // these are used to "bind" a nonexistent property
  24702. _getValue_unavailable() {}
  24703. _setValue_unavailable() {} // Getters
  24704. _getValue_direct(buffer, offset) {
  24705. buffer[offset] = this.node[this.propertyName];
  24706. }
  24707. _getValue_array(buffer, offset) {
  24708. const source = this.resolvedProperty;
  24709. for (let i = 0, n = source.length; i !== n; ++i) {
  24710. buffer[offset++] = source[i];
  24711. }
  24712. }
  24713. _getValue_arrayElement(buffer, offset) {
  24714. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  24715. }
  24716. _getValue_toArray(buffer, offset) {
  24717. this.resolvedProperty.toArray(buffer, offset);
  24718. } // Direct
  24719. _setValue_direct(buffer, offset) {
  24720. this.targetObject[this.propertyName] = buffer[offset];
  24721. }
  24722. _setValue_direct_setNeedsUpdate(buffer, offset) {
  24723. this.targetObject[this.propertyName] = buffer[offset];
  24724. this.targetObject.needsUpdate = true;
  24725. }
  24726. _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  24727. this.targetObject[this.propertyName] = buffer[offset];
  24728. this.targetObject.matrixWorldNeedsUpdate = true;
  24729. } // EntireArray
  24730. _setValue_array(buffer, offset) {
  24731. const dest = this.resolvedProperty;
  24732. for (let i = 0, n = dest.length; i !== n; ++i) {
  24733. dest[i] = buffer[offset++];
  24734. }
  24735. }
  24736. _setValue_array_setNeedsUpdate(buffer, offset) {
  24737. const dest = this.resolvedProperty;
  24738. for (let i = 0, n = dest.length; i !== n; ++i) {
  24739. dest[i] = buffer[offset++];
  24740. }
  24741. this.targetObject.needsUpdate = true;
  24742. }
  24743. _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  24744. const dest = this.resolvedProperty;
  24745. for (let i = 0, n = dest.length; i !== n; ++i) {
  24746. dest[i] = buffer[offset++];
  24747. }
  24748. this.targetObject.matrixWorldNeedsUpdate = true;
  24749. } // ArrayElement
  24750. _setValue_arrayElement(buffer, offset) {
  24751. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  24752. }
  24753. _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  24754. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  24755. this.targetObject.needsUpdate = true;
  24756. }
  24757. _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  24758. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  24759. this.targetObject.matrixWorldNeedsUpdate = true;
  24760. } // HasToFromArray
  24761. _setValue_fromArray(buffer, offset) {
  24762. this.resolvedProperty.fromArray(buffer, offset);
  24763. }
  24764. _setValue_fromArray_setNeedsUpdate(buffer, offset) {
  24765. this.resolvedProperty.fromArray(buffer, offset);
  24766. this.targetObject.needsUpdate = true;
  24767. }
  24768. _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  24769. this.resolvedProperty.fromArray(buffer, offset);
  24770. this.targetObject.matrixWorldNeedsUpdate = true;
  24771. }
  24772. _getValue_unbound(targetArray, offset) {
  24773. this.bind();
  24774. this.getValue(targetArray, offset);
  24775. }
  24776. _setValue_unbound(sourceArray, offset) {
  24777. this.bind();
  24778. this.setValue(sourceArray, offset);
  24779. } // create getter / setter pair for a property in the scene graph
  24780. bind() {
  24781. let targetObject = this.node;
  24782. const parsedPath = this.parsedPath;
  24783. const objectName = parsedPath.objectName;
  24784. const propertyName = parsedPath.propertyName;
  24785. let propertyIndex = parsedPath.propertyIndex;
  24786. if (!targetObject) {
  24787. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  24788. this.node = targetObject;
  24789. } // set fail state so we can just 'return' on error
  24790. this.getValue = this._getValue_unavailable;
  24791. this.setValue = this._setValue_unavailable; // ensure there is a value node
  24792. if (!targetObject) {
  24793. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  24794. return;
  24795. }
  24796. if (objectName) {
  24797. let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  24798. switch (objectName) {
  24799. case 'materials':
  24800. if (!targetObject.material) {
  24801. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  24802. return;
  24803. }
  24804. if (!targetObject.material.materials) {
  24805. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  24806. return;
  24807. }
  24808. targetObject = targetObject.material.materials;
  24809. break;
  24810. case 'bones':
  24811. if (!targetObject.skeleton) {
  24812. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  24813. return;
  24814. } // potential future optimization: skip this if propertyIndex is already an integer
  24815. // and convert the integer string to a true integer.
  24816. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  24817. for (let i = 0; i < targetObject.length; i++) {
  24818. if (targetObject[i].name === objectIndex) {
  24819. objectIndex = i;
  24820. break;
  24821. }
  24822. }
  24823. break;
  24824. default:
  24825. if (targetObject[objectName] === undefined) {
  24826. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  24827. return;
  24828. }
  24829. targetObject = targetObject[objectName];
  24830. }
  24831. if (objectIndex !== undefined) {
  24832. if (targetObject[objectIndex] === undefined) {
  24833. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  24834. return;
  24835. }
  24836. targetObject = targetObject[objectIndex];
  24837. }
  24838. } // resolve property
  24839. const nodeProperty = targetObject[propertyName];
  24840. if (nodeProperty === undefined) {
  24841. const nodeName = parsedPath.nodeName;
  24842. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  24843. return;
  24844. } // determine versioning scheme
  24845. let versioning = this.Versioning.None;
  24846. this.targetObject = targetObject;
  24847. if (targetObject.needsUpdate !== undefined) {
  24848. // material
  24849. versioning = this.Versioning.NeedsUpdate;
  24850. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  24851. // node transform
  24852. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  24853. } // determine how the property gets bound
  24854. let bindingType = this.BindingType.Direct;
  24855. if (propertyIndex !== undefined) {
  24856. // access a sub element of the property array (only primitives are supported right now)
  24857. if (propertyName === 'morphTargetInfluences') {
  24858. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  24859. // support resolving morphTarget names into indices.
  24860. if (!targetObject.geometry) {
  24861. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  24862. return;
  24863. }
  24864. if (targetObject.geometry.isBufferGeometry) {
  24865. if (!targetObject.geometry.morphAttributes) {
  24866. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  24867. return;
  24868. }
  24869. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  24870. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  24871. }
  24872. } else {
  24873. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
  24874. return;
  24875. }
  24876. }
  24877. bindingType = this.BindingType.ArrayElement;
  24878. this.resolvedProperty = nodeProperty;
  24879. this.propertyIndex = propertyIndex;
  24880. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  24881. // must use copy for Object3D.Euler/Quaternion
  24882. bindingType = this.BindingType.HasFromToArray;
  24883. this.resolvedProperty = nodeProperty;
  24884. } else if (Array.isArray(nodeProperty)) {
  24885. bindingType = this.BindingType.EntireArray;
  24886. this.resolvedProperty = nodeProperty;
  24887. } else {
  24888. this.propertyName = propertyName;
  24889. } // select getter / setter
  24890. this.getValue = this.GetterByBindingType[bindingType];
  24891. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  24892. }
  24893. unbind() {
  24894. this.node = null; // back to the prototype version of getValue / setValue
  24895. // note: avoiding to mutate the shape of 'this' via 'delete'
  24896. this.getValue = this._getValue_unbound;
  24897. this.setValue = this._setValue_unbound;
  24898. }
  24899. }
  24900. PropertyBinding.Composite = Composite;
  24901. PropertyBinding.prototype.BindingType = {
  24902. Direct: 0,
  24903. EntireArray: 1,
  24904. ArrayElement: 2,
  24905. HasFromToArray: 3
  24906. };
  24907. PropertyBinding.prototype.Versioning = {
  24908. None: 0,
  24909. NeedsUpdate: 1,
  24910. MatrixWorldNeedsUpdate: 2
  24911. };
  24912. PropertyBinding.prototype.GetterByBindingType = [PropertyBinding.prototype._getValue_direct, PropertyBinding.prototype._getValue_array, PropertyBinding.prototype._getValue_arrayElement, PropertyBinding.prototype._getValue_toArray];
  24913. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [[// Direct
  24914. PropertyBinding.prototype._setValue_direct, PropertyBinding.prototype._setValue_direct_setNeedsUpdate, PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate], [// EntireArray
  24915. PropertyBinding.prototype._setValue_array, PropertyBinding.prototype._setValue_array_setNeedsUpdate, PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate], [// ArrayElement
  24916. PropertyBinding.prototype._setValue_arrayElement, PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate], [// HasToFromArray
  24917. PropertyBinding.prototype._setValue_fromArray, PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];
  24918. /**
  24919. *
  24920. * A group of objects that receives a shared animation state.
  24921. *
  24922. * Usage:
  24923. *
  24924. * - Add objects you would otherwise pass as 'root' to the
  24925. * constructor or the .clipAction method of AnimationMixer.
  24926. *
  24927. * - Instead pass this object as 'root'.
  24928. *
  24929. * - You can also add and remove objects later when the mixer
  24930. * is running.
  24931. *
  24932. * Note:
  24933. *
  24934. * Objects of this class appear as one object to the mixer,
  24935. * so cache control of the individual objects must be done
  24936. * on the group.
  24937. *
  24938. * Limitation:
  24939. *
  24940. * - The animated properties must be compatible among the
  24941. * all objects in the group.
  24942. *
  24943. * - A single property can either be controlled through a
  24944. * target group or directly, but not both.
  24945. */
  24946. class AnimationObjectGroup {
  24947. constructor() {
  24948. this.uuid = generateUUID(); // cached objects followed by the active ones
  24949. this._objects = Array.prototype.slice.call(arguments);
  24950. this.nCachedObjects_ = 0; // threshold
  24951. // note: read by PropertyBinding.Composite
  24952. const indices = {};
  24953. this._indicesByUUID = indices; // for bookkeeping
  24954. for (let i = 0, n = arguments.length; i !== n; ++i) {
  24955. indices[arguments[i].uuid] = i;
  24956. }
  24957. this._paths = []; // inside: string
  24958. this._parsedPaths = []; // inside: { we don't care, here }
  24959. this._bindings = []; // inside: Array< PropertyBinding >
  24960. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  24961. const scope = this;
  24962. this.stats = {
  24963. objects: {
  24964. get total() {
  24965. return scope._objects.length;
  24966. },
  24967. get inUse() {
  24968. return this.total - scope.nCachedObjects_;
  24969. }
  24970. },
  24971. get bindingsPerObject() {
  24972. return scope._bindings.length;
  24973. }
  24974. };
  24975. }
  24976. add() {
  24977. const objects = this._objects,
  24978. indicesByUUID = this._indicesByUUID,
  24979. paths = this._paths,
  24980. parsedPaths = this._parsedPaths,
  24981. bindings = this._bindings,
  24982. nBindings = bindings.length;
  24983. let knownObject = undefined,
  24984. nObjects = objects.length,
  24985. nCachedObjects = this.nCachedObjects_;
  24986. for (let i = 0, n = arguments.length; i !== n; ++i) {
  24987. const object = arguments[i],
  24988. uuid = object.uuid;
  24989. let index = indicesByUUID[uuid];
  24990. if (index === undefined) {
  24991. // unknown object -> add it to the ACTIVE region
  24992. index = nObjects++;
  24993. indicesByUUID[uuid] = index;
  24994. objects.push(object); // accounting is done, now do the same for all bindings
  24995. for (let j = 0, m = nBindings; j !== m; ++j) {
  24996. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  24997. }
  24998. } else if (index < nCachedObjects) {
  24999. knownObject = objects[index]; // move existing object to the ACTIVE region
  25000. const firstActiveIndex = --nCachedObjects,
  25001. lastCachedObject = objects[firstActiveIndex];
  25002. indicesByUUID[lastCachedObject.uuid] = index;
  25003. objects[index] = lastCachedObject;
  25004. indicesByUUID[uuid] = firstActiveIndex;
  25005. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  25006. for (let j = 0, m = nBindings; j !== m; ++j) {
  25007. const bindingsForPath = bindings[j],
  25008. lastCached = bindingsForPath[firstActiveIndex];
  25009. let binding = bindingsForPath[index];
  25010. bindingsForPath[index] = lastCached;
  25011. if (binding === undefined) {
  25012. // since we do not bother to create new bindings
  25013. // for objects that are cached, the binding may
  25014. // or may not exist
  25015. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  25016. }
  25017. bindingsForPath[firstActiveIndex] = binding;
  25018. }
  25019. } else if (objects[index] !== knownObject) {
  25020. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  25021. } // else the object is already where we want it to be
  25022. } // for arguments
  25023. this.nCachedObjects_ = nCachedObjects;
  25024. }
  25025. remove() {
  25026. const objects = this._objects,
  25027. indicesByUUID = this._indicesByUUID,
  25028. bindings = this._bindings,
  25029. nBindings = bindings.length;
  25030. let nCachedObjects = this.nCachedObjects_;
  25031. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25032. const object = arguments[i],
  25033. uuid = object.uuid,
  25034. index = indicesByUUID[uuid];
  25035. if (index !== undefined && index >= nCachedObjects) {
  25036. // move existing object into the CACHED region
  25037. const lastCachedIndex = nCachedObjects++,
  25038. firstActiveObject = objects[lastCachedIndex];
  25039. indicesByUUID[firstActiveObject.uuid] = index;
  25040. objects[index] = firstActiveObject;
  25041. indicesByUUID[uuid] = lastCachedIndex;
  25042. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  25043. for (let j = 0, m = nBindings; j !== m; ++j) {
  25044. const bindingsForPath = bindings[j],
  25045. firstActive = bindingsForPath[lastCachedIndex],
  25046. binding = bindingsForPath[index];
  25047. bindingsForPath[index] = firstActive;
  25048. bindingsForPath[lastCachedIndex] = binding;
  25049. }
  25050. }
  25051. } // for arguments
  25052. this.nCachedObjects_ = nCachedObjects;
  25053. } // remove & forget
  25054. uncache() {
  25055. const objects = this._objects,
  25056. indicesByUUID = this._indicesByUUID,
  25057. bindings = this._bindings,
  25058. nBindings = bindings.length;
  25059. let nCachedObjects = this.nCachedObjects_,
  25060. nObjects = objects.length;
  25061. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25062. const object = arguments[i],
  25063. uuid = object.uuid,
  25064. index = indicesByUUID[uuid];
  25065. if (index !== undefined) {
  25066. delete indicesByUUID[uuid];
  25067. if (index < nCachedObjects) {
  25068. // object is cached, shrink the CACHED region
  25069. const firstActiveIndex = --nCachedObjects,
  25070. lastCachedObject = objects[firstActiveIndex],
  25071. lastIndex = --nObjects,
  25072. lastObject = objects[lastIndex]; // last cached object takes this object's place
  25073. indicesByUUID[lastCachedObject.uuid] = index;
  25074. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  25075. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  25076. objects[firstActiveIndex] = lastObject;
  25077. objects.pop(); // accounting is done, now do the same for all bindings
  25078. for (let j = 0, m = nBindings; j !== m; ++j) {
  25079. const bindingsForPath = bindings[j],
  25080. lastCached = bindingsForPath[firstActiveIndex],
  25081. last = bindingsForPath[lastIndex];
  25082. bindingsForPath[index] = lastCached;
  25083. bindingsForPath[firstActiveIndex] = last;
  25084. bindingsForPath.pop();
  25085. }
  25086. } else {
  25087. // object is active, just swap with the last and pop
  25088. const lastIndex = --nObjects,
  25089. lastObject = objects[lastIndex];
  25090. if (lastIndex > 0) {
  25091. indicesByUUID[lastObject.uuid] = index;
  25092. }
  25093. objects[index] = lastObject;
  25094. objects.pop(); // accounting is done, now do the same for all bindings
  25095. for (let j = 0, m = nBindings; j !== m; ++j) {
  25096. const bindingsForPath = bindings[j];
  25097. bindingsForPath[index] = bindingsForPath[lastIndex];
  25098. bindingsForPath.pop();
  25099. }
  25100. } // cached or active
  25101. } // if object is known
  25102. } // for arguments
  25103. this.nCachedObjects_ = nCachedObjects;
  25104. } // Internal interface used by befriended PropertyBinding.Composite:
  25105. subscribe_(path, parsedPath) {
  25106. // returns an array of bindings for the given path that is changed
  25107. // according to the contained objects in the group
  25108. const indicesByPath = this._bindingsIndicesByPath;
  25109. let index = indicesByPath[path];
  25110. const bindings = this._bindings;
  25111. if (index !== undefined) return bindings[index];
  25112. const paths = this._paths,
  25113. parsedPaths = this._parsedPaths,
  25114. objects = this._objects,
  25115. nObjects = objects.length,
  25116. nCachedObjects = this.nCachedObjects_,
  25117. bindingsForPath = new Array(nObjects);
  25118. index = bindings.length;
  25119. indicesByPath[path] = index;
  25120. paths.push(path);
  25121. parsedPaths.push(parsedPath);
  25122. bindings.push(bindingsForPath);
  25123. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  25124. const object = objects[i];
  25125. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  25126. }
  25127. return bindingsForPath;
  25128. }
  25129. unsubscribe_(path) {
  25130. // tells the group to forget about a property path and no longer
  25131. // update the array previously obtained with 'subscribe_'
  25132. const indicesByPath = this._bindingsIndicesByPath,
  25133. index = indicesByPath[path];
  25134. if (index !== undefined) {
  25135. const paths = this._paths,
  25136. parsedPaths = this._parsedPaths,
  25137. bindings = this._bindings,
  25138. lastBindingsIndex = bindings.length - 1,
  25139. lastBindings = bindings[lastBindingsIndex],
  25140. lastBindingsPath = path[lastBindingsIndex];
  25141. indicesByPath[lastBindingsPath] = index;
  25142. bindings[index] = lastBindings;
  25143. bindings.pop();
  25144. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  25145. parsedPaths.pop();
  25146. paths[index] = paths[lastBindingsIndex];
  25147. paths.pop();
  25148. }
  25149. }
  25150. }
  25151. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  25152. class AnimationAction {
  25153. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  25154. this._mixer = mixer;
  25155. this._clip = clip;
  25156. this._localRoot = localRoot;
  25157. this.blendMode = blendMode;
  25158. const tracks = clip.tracks,
  25159. nTracks = tracks.length,
  25160. interpolants = new Array(nTracks);
  25161. const interpolantSettings = {
  25162. endingStart: ZeroCurvatureEnding,
  25163. endingEnd: ZeroCurvatureEnding
  25164. };
  25165. for (let i = 0; i !== nTracks; ++i) {
  25166. const interpolant = tracks[i].createInterpolant(null);
  25167. interpolants[i] = interpolant;
  25168. interpolant.settings = interpolantSettings;
  25169. }
  25170. this._interpolantSettings = interpolantSettings;
  25171. this._interpolants = interpolants; // bound by the mixer
  25172. // inside: PropertyMixer (managed by the mixer)
  25173. this._propertyBindings = new Array(nTracks);
  25174. this._cacheIndex = null; // for the memory manager
  25175. this._byClipCacheIndex = null; // for the memory manager
  25176. this._timeScaleInterpolant = null;
  25177. this._weightInterpolant = null;
  25178. this.loop = LoopRepeat;
  25179. this._loopCount = -1; // global mixer time when the action is to be started
  25180. // it's set back to 'null' upon start of the action
  25181. this._startTime = null; // scaled local time of the action
  25182. // gets clamped or wrapped to 0..clip.duration according to loop
  25183. this.time = 0;
  25184. this.timeScale = 1;
  25185. this._effectiveTimeScale = 1;
  25186. this.weight = 1;
  25187. this._effectiveWeight = 1;
  25188. this.repetitions = Infinity; // no. of repetitions when looping
  25189. this.paused = false; // true -> zero effective time scale
  25190. this.enabled = true; // false -> zero effective weight
  25191. this.clampWhenFinished = false; // keep feeding the last frame?
  25192. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  25193. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  25194. } // State & Scheduling
  25195. play() {
  25196. this._mixer._activateAction(this);
  25197. return this;
  25198. }
  25199. stop() {
  25200. this._mixer._deactivateAction(this);
  25201. return this.reset();
  25202. }
  25203. reset() {
  25204. this.paused = false;
  25205. this.enabled = true;
  25206. this.time = 0; // restart clip
  25207. this._loopCount = -1; // forget previous loops
  25208. this._startTime = null; // forget scheduling
  25209. return this.stopFading().stopWarping();
  25210. }
  25211. isRunning() {
  25212. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  25213. } // return true when play has been called
  25214. isScheduled() {
  25215. return this._mixer._isActiveAction(this);
  25216. }
  25217. startAt(time) {
  25218. this._startTime = time;
  25219. return this;
  25220. }
  25221. setLoop(mode, repetitions) {
  25222. this.loop = mode;
  25223. this.repetitions = repetitions;
  25224. return this;
  25225. } // Weight
  25226. // set the weight stopping any scheduled fading
  25227. // although .enabled = false yields an effective weight of zero, this
  25228. // method does *not* change .enabled, because it would be confusing
  25229. setEffectiveWeight(weight) {
  25230. this.weight = weight; // note: same logic as when updated at runtime
  25231. this._effectiveWeight = this.enabled ? weight : 0;
  25232. return this.stopFading();
  25233. } // return the weight considering fading and .enabled
  25234. getEffectiveWeight() {
  25235. return this._effectiveWeight;
  25236. }
  25237. fadeIn(duration) {
  25238. return this._scheduleFading(duration, 0, 1);
  25239. }
  25240. fadeOut(duration) {
  25241. return this._scheduleFading(duration, 1, 0);
  25242. }
  25243. crossFadeFrom(fadeOutAction, duration, warp) {
  25244. fadeOutAction.fadeOut(duration);
  25245. this.fadeIn(duration);
  25246. if (warp) {
  25247. const fadeInDuration = this._clip.duration,
  25248. fadeOutDuration = fadeOutAction._clip.duration,
  25249. startEndRatio = fadeOutDuration / fadeInDuration,
  25250. endStartRatio = fadeInDuration / fadeOutDuration;
  25251. fadeOutAction.warp(1.0, startEndRatio, duration);
  25252. this.warp(endStartRatio, 1.0, duration);
  25253. }
  25254. return this;
  25255. }
  25256. crossFadeTo(fadeInAction, duration, warp) {
  25257. return fadeInAction.crossFadeFrom(this, duration, warp);
  25258. }
  25259. stopFading() {
  25260. const weightInterpolant = this._weightInterpolant;
  25261. if (weightInterpolant !== null) {
  25262. this._weightInterpolant = null;
  25263. this._mixer._takeBackControlInterpolant(weightInterpolant);
  25264. }
  25265. return this;
  25266. } // Time Scale Control
  25267. // set the time scale stopping any scheduled warping
  25268. // although .paused = true yields an effective time scale of zero, this
  25269. // method does *not* change .paused, because it would be confusing
  25270. setEffectiveTimeScale(timeScale) {
  25271. this.timeScale = timeScale;
  25272. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  25273. return this.stopWarping();
  25274. } // return the time scale considering warping and .paused
  25275. getEffectiveTimeScale() {
  25276. return this._effectiveTimeScale;
  25277. }
  25278. setDuration(duration) {
  25279. this.timeScale = this._clip.duration / duration;
  25280. return this.stopWarping();
  25281. }
  25282. syncWith(action) {
  25283. this.time = action.time;
  25284. this.timeScale = action.timeScale;
  25285. return this.stopWarping();
  25286. }
  25287. halt(duration) {
  25288. return this.warp(this._effectiveTimeScale, 0, duration);
  25289. }
  25290. warp(startTimeScale, endTimeScale, duration) {
  25291. const mixer = this._mixer,
  25292. now = mixer.time,
  25293. timeScale = this.timeScale;
  25294. let interpolant = this._timeScaleInterpolant;
  25295. if (interpolant === null) {
  25296. interpolant = mixer._lendControlInterpolant();
  25297. this._timeScaleInterpolant = interpolant;
  25298. }
  25299. const times = interpolant.parameterPositions,
  25300. values = interpolant.sampleValues;
  25301. times[0] = now;
  25302. times[1] = now + duration;
  25303. values[0] = startTimeScale / timeScale;
  25304. values[1] = endTimeScale / timeScale;
  25305. return this;
  25306. }
  25307. stopWarping() {
  25308. const timeScaleInterpolant = this._timeScaleInterpolant;
  25309. if (timeScaleInterpolant !== null) {
  25310. this._timeScaleInterpolant = null;
  25311. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  25312. }
  25313. return this;
  25314. } // Object Accessors
  25315. getMixer() {
  25316. return this._mixer;
  25317. }
  25318. getClip() {
  25319. return this._clip;
  25320. }
  25321. getRoot() {
  25322. return this._localRoot || this._mixer._root;
  25323. } // Interna
  25324. _update(time, deltaTime, timeDirection, accuIndex) {
  25325. // called by the mixer
  25326. if (!this.enabled) {
  25327. // call ._updateWeight() to update ._effectiveWeight
  25328. this._updateWeight(time);
  25329. return;
  25330. }
  25331. const startTime = this._startTime;
  25332. if (startTime !== null) {
  25333. // check for scheduled start of action
  25334. const timeRunning = (time - startTime) * timeDirection;
  25335. if (timeRunning < 0 || timeDirection === 0) {
  25336. return; // yet to come / don't decide when delta = 0
  25337. } // start
  25338. this._startTime = null; // unschedule
  25339. deltaTime = timeDirection * timeRunning;
  25340. } // apply time scale and advance time
  25341. deltaTime *= this._updateTimeScale(time);
  25342. const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  25343. // an effective weight of 0
  25344. const weight = this._updateWeight(time);
  25345. if (weight > 0) {
  25346. const interpolants = this._interpolants;
  25347. const propertyMixers = this._propertyBindings;
  25348. switch (this.blendMode) {
  25349. case AdditiveAnimationBlendMode:
  25350. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  25351. interpolants[j].evaluate(clipTime);
  25352. propertyMixers[j].accumulateAdditive(weight);
  25353. }
  25354. break;
  25355. case NormalAnimationBlendMode:
  25356. default:
  25357. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  25358. interpolants[j].evaluate(clipTime);
  25359. propertyMixers[j].accumulate(accuIndex, weight);
  25360. }
  25361. }
  25362. }
  25363. }
  25364. _updateWeight(time) {
  25365. let weight = 0;
  25366. if (this.enabled) {
  25367. weight = this.weight;
  25368. const interpolant = this._weightInterpolant;
  25369. if (interpolant !== null) {
  25370. const interpolantValue = interpolant.evaluate(time)[0];
  25371. weight *= interpolantValue;
  25372. if (time > interpolant.parameterPositions[1]) {
  25373. this.stopFading();
  25374. if (interpolantValue === 0) {
  25375. // faded out, disable
  25376. this.enabled = false;
  25377. }
  25378. }
  25379. }
  25380. }
  25381. this._effectiveWeight = weight;
  25382. return weight;
  25383. }
  25384. _updateTimeScale(time) {
  25385. let timeScale = 0;
  25386. if (!this.paused) {
  25387. timeScale = this.timeScale;
  25388. const interpolant = this._timeScaleInterpolant;
  25389. if (interpolant !== null) {
  25390. const interpolantValue = interpolant.evaluate(time)[0];
  25391. timeScale *= interpolantValue;
  25392. if (time > interpolant.parameterPositions[1]) {
  25393. this.stopWarping();
  25394. if (timeScale === 0) {
  25395. // motion has halted, pause
  25396. this.paused = true;
  25397. } else {
  25398. // warp done - apply final time scale
  25399. this.timeScale = timeScale;
  25400. }
  25401. }
  25402. }
  25403. }
  25404. this._effectiveTimeScale = timeScale;
  25405. return timeScale;
  25406. }
  25407. _updateTime(deltaTime) {
  25408. const duration = this._clip.duration;
  25409. const loop = this.loop;
  25410. let time = this.time + deltaTime;
  25411. let loopCount = this._loopCount;
  25412. const pingPong = loop === LoopPingPong;
  25413. if (deltaTime === 0) {
  25414. if (loopCount === -1) return time;
  25415. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  25416. }
  25417. if (loop === LoopOnce) {
  25418. if (loopCount === -1) {
  25419. // just started
  25420. this._loopCount = 0;
  25421. this._setEndings(true, true, false);
  25422. }
  25423. handle_stop: {
  25424. if (time >= duration) {
  25425. time = duration;
  25426. } else if (time < 0) {
  25427. time = 0;
  25428. } else {
  25429. this.time = time;
  25430. break handle_stop;
  25431. }
  25432. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  25433. this.time = time;
  25434. this._mixer.dispatchEvent({
  25435. type: 'finished',
  25436. action: this,
  25437. direction: deltaTime < 0 ? -1 : 1
  25438. });
  25439. }
  25440. } else {
  25441. // repetitive Repeat or PingPong
  25442. if (loopCount === -1) {
  25443. // just started
  25444. if (deltaTime >= 0) {
  25445. loopCount = 0;
  25446. this._setEndings(true, this.repetitions === 0, pingPong);
  25447. } else {
  25448. // when looping in reverse direction, the initial
  25449. // transition through zero counts as a repetition,
  25450. // so leave loopCount at -1
  25451. this._setEndings(this.repetitions === 0, true, pingPong);
  25452. }
  25453. }
  25454. if (time >= duration || time < 0) {
  25455. // wrap around
  25456. const loopDelta = Math.floor(time / duration); // signed
  25457. time -= duration * loopDelta;
  25458. loopCount += Math.abs(loopDelta);
  25459. const pending = this.repetitions - loopCount;
  25460. if (pending <= 0) {
  25461. // have to stop (switch state, clamp time, fire event)
  25462. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  25463. time = deltaTime > 0 ? duration : 0;
  25464. this.time = time;
  25465. this._mixer.dispatchEvent({
  25466. type: 'finished',
  25467. action: this,
  25468. direction: deltaTime > 0 ? 1 : -1
  25469. });
  25470. } else {
  25471. // keep running
  25472. if (pending === 1) {
  25473. // entering the last round
  25474. const atStart = deltaTime < 0;
  25475. this._setEndings(atStart, !atStart, pingPong);
  25476. } else {
  25477. this._setEndings(false, false, pingPong);
  25478. }
  25479. this._loopCount = loopCount;
  25480. this.time = time;
  25481. this._mixer.dispatchEvent({
  25482. type: 'loop',
  25483. action: this,
  25484. loopDelta: loopDelta
  25485. });
  25486. }
  25487. } else {
  25488. this.time = time;
  25489. }
  25490. if (pingPong && (loopCount & 1) === 1) {
  25491. // invert time for the "pong round"
  25492. return duration - time;
  25493. }
  25494. }
  25495. return time;
  25496. }
  25497. _setEndings(atStart, atEnd, pingPong) {
  25498. const settings = this._interpolantSettings;
  25499. if (pingPong) {
  25500. settings.endingStart = ZeroSlopeEnding;
  25501. settings.endingEnd = ZeroSlopeEnding;
  25502. } else {
  25503. // assuming for LoopOnce atStart == atEnd == true
  25504. if (atStart) {
  25505. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  25506. } else {
  25507. settings.endingStart = WrapAroundEnding;
  25508. }
  25509. if (atEnd) {
  25510. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  25511. } else {
  25512. settings.endingEnd = WrapAroundEnding;
  25513. }
  25514. }
  25515. }
  25516. _scheduleFading(duration, weightNow, weightThen) {
  25517. const mixer = this._mixer,
  25518. now = mixer.time;
  25519. let interpolant = this._weightInterpolant;
  25520. if (interpolant === null) {
  25521. interpolant = mixer._lendControlInterpolant();
  25522. this._weightInterpolant = interpolant;
  25523. }
  25524. const times = interpolant.parameterPositions,
  25525. values = interpolant.sampleValues;
  25526. times[0] = now;
  25527. values[0] = weightNow;
  25528. times[1] = now + duration;
  25529. values[1] = weightThen;
  25530. return this;
  25531. }
  25532. }
  25533. class AnimationMixer extends EventDispatcher {
  25534. constructor(root) {
  25535. super();
  25536. this._root = root;
  25537. this._initMemoryManager();
  25538. this._accuIndex = 0;
  25539. this.time = 0;
  25540. this.timeScale = 1.0;
  25541. }
  25542. _bindAction(action, prototypeAction) {
  25543. const root = action._localRoot || this._root,
  25544. tracks = action._clip.tracks,
  25545. nTracks = tracks.length,
  25546. bindings = action._propertyBindings,
  25547. interpolants = action._interpolants,
  25548. rootUuid = root.uuid,
  25549. bindingsByRoot = this._bindingsByRootAndName;
  25550. let bindingsByName = bindingsByRoot[rootUuid];
  25551. if (bindingsByName === undefined) {
  25552. bindingsByName = {};
  25553. bindingsByRoot[rootUuid] = bindingsByName;
  25554. }
  25555. for (let i = 0; i !== nTracks; ++i) {
  25556. const track = tracks[i],
  25557. trackName = track.name;
  25558. let binding = bindingsByName[trackName];
  25559. if (binding !== undefined) {
  25560. bindings[i] = binding;
  25561. } else {
  25562. binding = bindings[i];
  25563. if (binding !== undefined) {
  25564. // existing binding, make sure the cache knows
  25565. if (binding._cacheIndex === null) {
  25566. ++binding.referenceCount;
  25567. this._addInactiveBinding(binding, rootUuid, trackName);
  25568. }
  25569. continue;
  25570. }
  25571. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  25572. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  25573. ++binding.referenceCount;
  25574. this._addInactiveBinding(binding, rootUuid, trackName);
  25575. bindings[i] = binding;
  25576. }
  25577. interpolants[i].resultBuffer = binding.buffer;
  25578. }
  25579. }
  25580. _activateAction(action) {
  25581. if (!this._isActiveAction(action)) {
  25582. if (action._cacheIndex === null) {
  25583. // this action has been forgotten by the cache, but the user
  25584. // appears to be still using it -> rebind
  25585. const rootUuid = (action._localRoot || this._root).uuid,
  25586. clipUuid = action._clip.uuid,
  25587. actionsForClip = this._actionsByClip[clipUuid];
  25588. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  25589. this._addInactiveAction(action, clipUuid, rootUuid);
  25590. }
  25591. const bindings = action._propertyBindings; // increment reference counts / sort out state
  25592. for (let i = 0, n = bindings.length; i !== n; ++i) {
  25593. const binding = bindings[i];
  25594. if (binding.useCount++ === 0) {
  25595. this._lendBinding(binding);
  25596. binding.saveOriginalState();
  25597. }
  25598. }
  25599. this._lendAction(action);
  25600. }
  25601. }
  25602. _deactivateAction(action) {
  25603. if (this._isActiveAction(action)) {
  25604. const bindings = action._propertyBindings; // decrement reference counts / sort out state
  25605. for (let i = 0, n = bindings.length; i !== n; ++i) {
  25606. const binding = bindings[i];
  25607. if (--binding.useCount === 0) {
  25608. binding.restoreOriginalState();
  25609. this._takeBackBinding(binding);
  25610. }
  25611. }
  25612. this._takeBackAction(action);
  25613. }
  25614. } // Memory manager
  25615. _initMemoryManager() {
  25616. this._actions = []; // 'nActiveActions' followed by inactive ones
  25617. this._nActiveActions = 0;
  25618. this._actionsByClip = {}; // inside:
  25619. // {
  25620. // knownActions: Array< AnimationAction > - used as prototypes
  25621. // actionByRoot: AnimationAction - lookup
  25622. // }
  25623. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  25624. this._nActiveBindings = 0;
  25625. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  25626. this._controlInterpolants = []; // same game as above
  25627. this._nActiveControlInterpolants = 0;
  25628. const scope = this;
  25629. this.stats = {
  25630. actions: {
  25631. get total() {
  25632. return scope._actions.length;
  25633. },
  25634. get inUse() {
  25635. return scope._nActiveActions;
  25636. }
  25637. },
  25638. bindings: {
  25639. get total() {
  25640. return scope._bindings.length;
  25641. },
  25642. get inUse() {
  25643. return scope._nActiveBindings;
  25644. }
  25645. },
  25646. controlInterpolants: {
  25647. get total() {
  25648. return scope._controlInterpolants.length;
  25649. },
  25650. get inUse() {
  25651. return scope._nActiveControlInterpolants;
  25652. }
  25653. }
  25654. };
  25655. } // Memory management for AnimationAction objects
  25656. _isActiveAction(action) {
  25657. const index = action._cacheIndex;
  25658. return index !== null && index < this._nActiveActions;
  25659. }
  25660. _addInactiveAction(action, clipUuid, rootUuid) {
  25661. const actions = this._actions,
  25662. actionsByClip = this._actionsByClip;
  25663. let actionsForClip = actionsByClip[clipUuid];
  25664. if (actionsForClip === undefined) {
  25665. actionsForClip = {
  25666. knownActions: [action],
  25667. actionByRoot: {}
  25668. };
  25669. action._byClipCacheIndex = 0;
  25670. actionsByClip[clipUuid] = actionsForClip;
  25671. } else {
  25672. const knownActions = actionsForClip.knownActions;
  25673. action._byClipCacheIndex = knownActions.length;
  25674. knownActions.push(action);
  25675. }
  25676. action._cacheIndex = actions.length;
  25677. actions.push(action);
  25678. actionsForClip.actionByRoot[rootUuid] = action;
  25679. }
  25680. _removeInactiveAction(action) {
  25681. const actions = this._actions,
  25682. lastInactiveAction = actions[actions.length - 1],
  25683. cacheIndex = action._cacheIndex;
  25684. lastInactiveAction._cacheIndex = cacheIndex;
  25685. actions[cacheIndex] = lastInactiveAction;
  25686. actions.pop();
  25687. action._cacheIndex = null;
  25688. const clipUuid = action._clip.uuid,
  25689. actionsByClip = this._actionsByClip,
  25690. actionsForClip = actionsByClip[clipUuid],
  25691. knownActionsForClip = actionsForClip.knownActions,
  25692. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  25693. byClipCacheIndex = action._byClipCacheIndex;
  25694. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  25695. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  25696. knownActionsForClip.pop();
  25697. action._byClipCacheIndex = null;
  25698. const actionByRoot = actionsForClip.actionByRoot,
  25699. rootUuid = (action._localRoot || this._root).uuid;
  25700. delete actionByRoot[rootUuid];
  25701. if (knownActionsForClip.length === 0) {
  25702. delete actionsByClip[clipUuid];
  25703. }
  25704. this._removeInactiveBindingsForAction(action);
  25705. }
  25706. _removeInactiveBindingsForAction(action) {
  25707. const bindings = action._propertyBindings;
  25708. for (let i = 0, n = bindings.length; i !== n; ++i) {
  25709. const binding = bindings[i];
  25710. if (--binding.referenceCount === 0) {
  25711. this._removeInactiveBinding(binding);
  25712. }
  25713. }
  25714. }
  25715. _lendAction(action) {
  25716. // [ active actions | inactive actions ]
  25717. // [ active actions >| inactive actions ]
  25718. // s a
  25719. // <-swap->
  25720. // a s
  25721. const actions = this._actions,
  25722. prevIndex = action._cacheIndex,
  25723. lastActiveIndex = this._nActiveActions++,
  25724. firstInactiveAction = actions[lastActiveIndex];
  25725. action._cacheIndex = lastActiveIndex;
  25726. actions[lastActiveIndex] = action;
  25727. firstInactiveAction._cacheIndex = prevIndex;
  25728. actions[prevIndex] = firstInactiveAction;
  25729. }
  25730. _takeBackAction(action) {
  25731. // [ active actions | inactive actions ]
  25732. // [ active actions |< inactive actions ]
  25733. // a s
  25734. // <-swap->
  25735. // s a
  25736. const actions = this._actions,
  25737. prevIndex = action._cacheIndex,
  25738. firstInactiveIndex = --this._nActiveActions,
  25739. lastActiveAction = actions[firstInactiveIndex];
  25740. action._cacheIndex = firstInactiveIndex;
  25741. actions[firstInactiveIndex] = action;
  25742. lastActiveAction._cacheIndex = prevIndex;
  25743. actions[prevIndex] = lastActiveAction;
  25744. } // Memory management for PropertyMixer objects
  25745. _addInactiveBinding(binding, rootUuid, trackName) {
  25746. const bindingsByRoot = this._bindingsByRootAndName,
  25747. bindings = this._bindings;
  25748. let bindingByName = bindingsByRoot[rootUuid];
  25749. if (bindingByName === undefined) {
  25750. bindingByName = {};
  25751. bindingsByRoot[rootUuid] = bindingByName;
  25752. }
  25753. bindingByName[trackName] = binding;
  25754. binding._cacheIndex = bindings.length;
  25755. bindings.push(binding);
  25756. }
  25757. _removeInactiveBinding(binding) {
  25758. const bindings = this._bindings,
  25759. propBinding = binding.binding,
  25760. rootUuid = propBinding.rootNode.uuid,
  25761. trackName = propBinding.path,
  25762. bindingsByRoot = this._bindingsByRootAndName,
  25763. bindingByName = bindingsByRoot[rootUuid],
  25764. lastInactiveBinding = bindings[bindings.length - 1],
  25765. cacheIndex = binding._cacheIndex;
  25766. lastInactiveBinding._cacheIndex = cacheIndex;
  25767. bindings[cacheIndex] = lastInactiveBinding;
  25768. bindings.pop();
  25769. delete bindingByName[trackName];
  25770. if (Object.keys(bindingByName).length === 0) {
  25771. delete bindingsByRoot[rootUuid];
  25772. }
  25773. }
  25774. _lendBinding(binding) {
  25775. const bindings = this._bindings,
  25776. prevIndex = binding._cacheIndex,
  25777. lastActiveIndex = this._nActiveBindings++,
  25778. firstInactiveBinding = bindings[lastActiveIndex];
  25779. binding._cacheIndex = lastActiveIndex;
  25780. bindings[lastActiveIndex] = binding;
  25781. firstInactiveBinding._cacheIndex = prevIndex;
  25782. bindings[prevIndex] = firstInactiveBinding;
  25783. }
  25784. _takeBackBinding(binding) {
  25785. const bindings = this._bindings,
  25786. prevIndex = binding._cacheIndex,
  25787. firstInactiveIndex = --this._nActiveBindings,
  25788. lastActiveBinding = bindings[firstInactiveIndex];
  25789. binding._cacheIndex = firstInactiveIndex;
  25790. bindings[firstInactiveIndex] = binding;
  25791. lastActiveBinding._cacheIndex = prevIndex;
  25792. bindings[prevIndex] = lastActiveBinding;
  25793. } // Memory management of Interpolants for weight and time scale
  25794. _lendControlInterpolant() {
  25795. const interpolants = this._controlInterpolants,
  25796. lastActiveIndex = this._nActiveControlInterpolants++;
  25797. let interpolant = interpolants[lastActiveIndex];
  25798. if (interpolant === undefined) {
  25799. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  25800. interpolant.__cacheIndex = lastActiveIndex;
  25801. interpolants[lastActiveIndex] = interpolant;
  25802. }
  25803. return interpolant;
  25804. }
  25805. _takeBackControlInterpolant(interpolant) {
  25806. const interpolants = this._controlInterpolants,
  25807. prevIndex = interpolant.__cacheIndex,
  25808. firstInactiveIndex = --this._nActiveControlInterpolants,
  25809. lastActiveInterpolant = interpolants[firstInactiveIndex];
  25810. interpolant.__cacheIndex = firstInactiveIndex;
  25811. interpolants[firstInactiveIndex] = interpolant;
  25812. lastActiveInterpolant.__cacheIndex = prevIndex;
  25813. interpolants[prevIndex] = lastActiveInterpolant;
  25814. } // return an action for a clip optionally using a custom root target
  25815. // object (this method allocates a lot of dynamic memory in case a
  25816. // previously unknown clip/root combination is specified)
  25817. clipAction(clip, optionalRoot, blendMode) {
  25818. const root = optionalRoot || this._root,
  25819. rootUuid = root.uuid;
  25820. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  25821. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  25822. const actionsForClip = this._actionsByClip[clipUuid];
  25823. let prototypeAction = null;
  25824. if (blendMode === undefined) {
  25825. if (clipObject !== null) {
  25826. blendMode = clipObject.blendMode;
  25827. } else {
  25828. blendMode = NormalAnimationBlendMode;
  25829. }
  25830. }
  25831. if (actionsForClip !== undefined) {
  25832. const existingAction = actionsForClip.actionByRoot[rootUuid];
  25833. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  25834. return existingAction;
  25835. } // we know the clip, so we don't have to parse all
  25836. // the bindings again but can just copy
  25837. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  25838. if (clipObject === null) clipObject = prototypeAction._clip;
  25839. } // clip must be known when specified via string
  25840. if (clipObject === null) return null; // allocate all resources required to run it
  25841. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  25842. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  25843. this._addInactiveAction(newAction, clipUuid, rootUuid);
  25844. return newAction;
  25845. } // get an existing action
  25846. existingAction(clip, optionalRoot) {
  25847. const root = optionalRoot || this._root,
  25848. rootUuid = root.uuid,
  25849. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  25850. clipUuid = clipObject ? clipObject.uuid : clip,
  25851. actionsForClip = this._actionsByClip[clipUuid];
  25852. if (actionsForClip !== undefined) {
  25853. return actionsForClip.actionByRoot[rootUuid] || null;
  25854. }
  25855. return null;
  25856. } // deactivates all previously scheduled actions
  25857. stopAllAction() {
  25858. const actions = this._actions,
  25859. nActions = this._nActiveActions;
  25860. for (let i = nActions - 1; i >= 0; --i) {
  25861. actions[i].stop();
  25862. }
  25863. return this;
  25864. } // advance the time and update apply the animation
  25865. update(deltaTime) {
  25866. deltaTime *= this.timeScale;
  25867. const actions = this._actions,
  25868. nActions = this._nActiveActions,
  25869. time = this.time += deltaTime,
  25870. timeDirection = Math.sign(deltaTime),
  25871. accuIndex = this._accuIndex ^= 1; // run active actions
  25872. for (let i = 0; i !== nActions; ++i) {
  25873. const action = actions[i];
  25874. action._update(time, deltaTime, timeDirection, accuIndex);
  25875. } // update scene graph
  25876. const bindings = this._bindings,
  25877. nBindings = this._nActiveBindings;
  25878. for (let i = 0; i !== nBindings; ++i) {
  25879. bindings[i].apply(accuIndex);
  25880. }
  25881. return this;
  25882. } // Allows you to seek to a specific time in an animation.
  25883. setTime(timeInSeconds) {
  25884. this.time = 0; // Zero out time attribute for AnimationMixer object;
  25885. for (let i = 0; i < this._actions.length; i++) {
  25886. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  25887. }
  25888. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  25889. } // return this mixer's root target object
  25890. getRoot() {
  25891. return this._root;
  25892. } // free all resources specific to a particular clip
  25893. uncacheClip(clip) {
  25894. const actions = this._actions,
  25895. clipUuid = clip.uuid,
  25896. actionsByClip = this._actionsByClip,
  25897. actionsForClip = actionsByClip[clipUuid];
  25898. if (actionsForClip !== undefined) {
  25899. // note: just calling _removeInactiveAction would mess up the
  25900. // iteration state and also require updating the state we can
  25901. // just throw away
  25902. const actionsToRemove = actionsForClip.knownActions;
  25903. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  25904. const action = actionsToRemove[i];
  25905. this._deactivateAction(action);
  25906. const cacheIndex = action._cacheIndex,
  25907. lastInactiveAction = actions[actions.length - 1];
  25908. action._cacheIndex = null;
  25909. action._byClipCacheIndex = null;
  25910. lastInactiveAction._cacheIndex = cacheIndex;
  25911. actions[cacheIndex] = lastInactiveAction;
  25912. actions.pop();
  25913. this._removeInactiveBindingsForAction(action);
  25914. }
  25915. delete actionsByClip[clipUuid];
  25916. }
  25917. } // free all resources specific to a particular root target object
  25918. uncacheRoot(root) {
  25919. const rootUuid = root.uuid,
  25920. actionsByClip = this._actionsByClip;
  25921. for (const clipUuid in actionsByClip) {
  25922. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  25923. action = actionByRoot[rootUuid];
  25924. if (action !== undefined) {
  25925. this._deactivateAction(action);
  25926. this._removeInactiveAction(action);
  25927. }
  25928. }
  25929. const bindingsByRoot = this._bindingsByRootAndName,
  25930. bindingByName = bindingsByRoot[rootUuid];
  25931. if (bindingByName !== undefined) {
  25932. for (const trackName in bindingByName) {
  25933. const binding = bindingByName[trackName];
  25934. binding.restoreOriginalState();
  25935. this._removeInactiveBinding(binding);
  25936. }
  25937. }
  25938. } // remove a targeted clip from the cache
  25939. uncacheAction(clip, optionalRoot) {
  25940. const action = this.existingAction(clip, optionalRoot);
  25941. if (action !== null) {
  25942. this._deactivateAction(action);
  25943. this._removeInactiveAction(action);
  25944. }
  25945. }
  25946. }
  25947. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array(1);
  25948. class Uniform {
  25949. constructor(value) {
  25950. if (typeof value === 'string') {
  25951. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  25952. value = arguments[1];
  25953. }
  25954. this.value = value;
  25955. }
  25956. clone() {
  25957. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  25958. }
  25959. }
  25960. class InstancedInterleavedBuffer extends InterleavedBuffer {
  25961. constructor(array, stride, meshPerAttribute = 1) {
  25962. super(array, stride);
  25963. this.meshPerAttribute = meshPerAttribute;
  25964. }
  25965. copy(source) {
  25966. super.copy(source);
  25967. this.meshPerAttribute = source.meshPerAttribute;
  25968. return this;
  25969. }
  25970. clone(data) {
  25971. const ib = super.clone(data);
  25972. ib.meshPerAttribute = this.meshPerAttribute;
  25973. return ib;
  25974. }
  25975. toJSON(data) {
  25976. const json = super.toJSON(data);
  25977. json.isInstancedInterleavedBuffer = true;
  25978. json.meshPerAttribute = this.meshPerAttribute;
  25979. return json;
  25980. }
  25981. }
  25982. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  25983. class GLBufferAttribute {
  25984. constructor(buffer, type, itemSize, elementSize, count) {
  25985. this.buffer = buffer;
  25986. this.type = type;
  25987. this.itemSize = itemSize;
  25988. this.elementSize = elementSize;
  25989. this.count = count;
  25990. this.version = 0;
  25991. }
  25992. set needsUpdate(value) {
  25993. if (value === true) this.version++;
  25994. }
  25995. setBuffer(buffer) {
  25996. this.buffer = buffer;
  25997. return this;
  25998. }
  25999. setType(type, elementSize) {
  26000. this.type = type;
  26001. this.elementSize = elementSize;
  26002. return this;
  26003. }
  26004. setItemSize(itemSize) {
  26005. this.itemSize = itemSize;
  26006. return this;
  26007. }
  26008. setCount(count) {
  26009. this.count = count;
  26010. return this;
  26011. }
  26012. }
  26013. GLBufferAttribute.prototype.isGLBufferAttribute = true;
  26014. class Raycaster {
  26015. constructor(origin, direction, near = 0, far = Infinity) {
  26016. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  26017. this.near = near;
  26018. this.far = far;
  26019. this.camera = null;
  26020. this.layers = new Layers();
  26021. this.params = {
  26022. Mesh: {},
  26023. Line: {
  26024. threshold: 1
  26025. },
  26026. LOD: {},
  26027. Points: {
  26028. threshold: 1
  26029. },
  26030. Sprite: {}
  26031. };
  26032. }
  26033. set(origin, direction) {
  26034. // direction is assumed to be normalized (for accurate distance calculations)
  26035. this.ray.set(origin, direction);
  26036. }
  26037. setFromCamera(coords, camera) {
  26038. if (camera && camera.isPerspectiveCamera) {
  26039. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  26040. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  26041. this.camera = camera;
  26042. } else if (camera && camera.isOrthographicCamera) {
  26043. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  26044. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  26045. this.camera = camera;
  26046. } else {
  26047. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  26048. }
  26049. }
  26050. intersectObject(object, recursive = false, intersects = []) {
  26051. intersectObject(object, this, intersects, recursive);
  26052. intersects.sort(ascSort);
  26053. return intersects;
  26054. }
  26055. intersectObjects(objects, recursive = false, intersects = []) {
  26056. for (let i = 0, l = objects.length; i < l; i++) {
  26057. intersectObject(objects[i], this, intersects, recursive);
  26058. }
  26059. intersects.sort(ascSort);
  26060. return intersects;
  26061. }
  26062. }
  26063. function ascSort(a, b) {
  26064. return a.distance - b.distance;
  26065. }
  26066. function intersectObject(object, raycaster, intersects, recursive) {
  26067. if (object.layers.test(raycaster.layers)) {
  26068. object.raycast(raycaster, intersects);
  26069. }
  26070. if (recursive === true) {
  26071. const children = object.children;
  26072. for (let i = 0, l = children.length; i < l; i++) {
  26073. intersectObject(children[i], raycaster, intersects, true);
  26074. }
  26075. }
  26076. }
  26077. /**
  26078. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  26079. *
  26080. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  26081. * The azimuthal angle (theta) is measured from the positive z-axis.
  26082. */
  26083. class Spherical {
  26084. constructor(radius = 1, phi = 0, theta = 0) {
  26085. this.radius = radius;
  26086. this.phi = phi; // polar angle
  26087. this.theta = theta; // azimuthal angle
  26088. return this;
  26089. }
  26090. set(radius, phi, theta) {
  26091. this.radius = radius;
  26092. this.phi = phi;
  26093. this.theta = theta;
  26094. return this;
  26095. }
  26096. copy(other) {
  26097. this.radius = other.radius;
  26098. this.phi = other.phi;
  26099. this.theta = other.theta;
  26100. return this;
  26101. } // restrict phi to be betwee EPS and PI-EPS
  26102. makeSafe() {
  26103. const EPS = 0.000001;
  26104. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  26105. return this;
  26106. }
  26107. setFromVector3(v) {
  26108. return this.setFromCartesianCoords(v.x, v.y, v.z);
  26109. }
  26110. setFromCartesianCoords(x, y, z) {
  26111. this.radius = Math.sqrt(x * x + y * y + z * z);
  26112. if (this.radius === 0) {
  26113. this.theta = 0;
  26114. this.phi = 0;
  26115. } else {
  26116. this.theta = Math.atan2(x, z);
  26117. this.phi = Math.acos(clamp(y / this.radius, -1, 1));
  26118. }
  26119. return this;
  26120. }
  26121. clone() {
  26122. return new this.constructor().copy(this);
  26123. }
  26124. }
  26125. /**
  26126. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  26127. */
  26128. class Cylindrical {
  26129. constructor(radius = 1, theta = 0, y = 0) {
  26130. this.radius = radius; // distance from the origin to a point in the x-z plane
  26131. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  26132. this.y = y; // height above the x-z plane
  26133. return this;
  26134. }
  26135. set(radius, theta, y) {
  26136. this.radius = radius;
  26137. this.theta = theta;
  26138. this.y = y;
  26139. return this;
  26140. }
  26141. copy(other) {
  26142. this.radius = other.radius;
  26143. this.theta = other.theta;
  26144. this.y = other.y;
  26145. return this;
  26146. }
  26147. setFromVector3(v) {
  26148. return this.setFromCartesianCoords(v.x, v.y, v.z);
  26149. }
  26150. setFromCartesianCoords(x, y, z) {
  26151. this.radius = Math.sqrt(x * x + z * z);
  26152. this.theta = Math.atan2(x, z);
  26153. this.y = y;
  26154. return this;
  26155. }
  26156. clone() {
  26157. return new this.constructor().copy(this);
  26158. }
  26159. }
  26160. const _vector$4 = /*@__PURE__*/new Vector2();
  26161. class Box2 {
  26162. constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) {
  26163. this.min = min;
  26164. this.max = max;
  26165. }
  26166. set(min, max) {
  26167. this.min.copy(min);
  26168. this.max.copy(max);
  26169. return this;
  26170. }
  26171. setFromPoints(points) {
  26172. this.makeEmpty();
  26173. for (let i = 0, il = points.length; i < il; i++) {
  26174. this.expandByPoint(points[i]);
  26175. }
  26176. return this;
  26177. }
  26178. setFromCenterAndSize(center, size) {
  26179. const halfSize = _vector$4.copy(size).multiplyScalar(0.5);
  26180. this.min.copy(center).sub(halfSize);
  26181. this.max.copy(center).add(halfSize);
  26182. return this;
  26183. }
  26184. clone() {
  26185. return new this.constructor().copy(this);
  26186. }
  26187. copy(box) {
  26188. this.min.copy(box.min);
  26189. this.max.copy(box.max);
  26190. return this;
  26191. }
  26192. makeEmpty() {
  26193. this.min.x = this.min.y = +Infinity;
  26194. this.max.x = this.max.y = -Infinity;
  26195. return this;
  26196. }
  26197. isEmpty() {
  26198. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  26199. return this.max.x < this.min.x || this.max.y < this.min.y;
  26200. }
  26201. getCenter(target) {
  26202. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  26203. }
  26204. getSize(target) {
  26205. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  26206. }
  26207. expandByPoint(point) {
  26208. this.min.min(point);
  26209. this.max.max(point);
  26210. return this;
  26211. }
  26212. expandByVector(vector) {
  26213. this.min.sub(vector);
  26214. this.max.add(vector);
  26215. return this;
  26216. }
  26217. expandByScalar(scalar) {
  26218. this.min.addScalar(-scalar);
  26219. this.max.addScalar(scalar);
  26220. return this;
  26221. }
  26222. containsPoint(point) {
  26223. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  26224. }
  26225. containsBox(box) {
  26226. 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;
  26227. }
  26228. getParameter(point, target) {
  26229. // This can potentially have a divide by zero if the box
  26230. // has a size dimension of 0.
  26231. 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));
  26232. }
  26233. intersectsBox(box) {
  26234. // using 4 splitting planes to rule out intersections
  26235. 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;
  26236. }
  26237. clampPoint(point, target) {
  26238. return target.copy(point).clamp(this.min, this.max);
  26239. }
  26240. distanceToPoint(point) {
  26241. const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max);
  26242. return clampedPoint.sub(point).length();
  26243. }
  26244. intersect(box) {
  26245. this.min.max(box.min);
  26246. this.max.min(box.max);
  26247. return this;
  26248. }
  26249. union(box) {
  26250. this.min.min(box.min);
  26251. this.max.max(box.max);
  26252. return this;
  26253. }
  26254. translate(offset) {
  26255. this.min.add(offset);
  26256. this.max.add(offset);
  26257. return this;
  26258. }
  26259. equals(box) {
  26260. return box.min.equals(this.min) && box.max.equals(this.max);
  26261. }
  26262. }
  26263. Box2.prototype.isBox2 = true;
  26264. const _startP = /*@__PURE__*/new Vector3();
  26265. const _startEnd = /*@__PURE__*/new Vector3();
  26266. class Line3 {
  26267. constructor(start = new Vector3(), end = new Vector3()) {
  26268. this.start = start;
  26269. this.end = end;
  26270. }
  26271. set(start, end) {
  26272. this.start.copy(start);
  26273. this.end.copy(end);
  26274. return this;
  26275. }
  26276. copy(line) {
  26277. this.start.copy(line.start);
  26278. this.end.copy(line.end);
  26279. return this;
  26280. }
  26281. getCenter(target) {
  26282. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  26283. }
  26284. delta(target) {
  26285. return target.subVectors(this.end, this.start);
  26286. }
  26287. distanceSq() {
  26288. return this.start.distanceToSquared(this.end);
  26289. }
  26290. distance() {
  26291. return this.start.distanceTo(this.end);
  26292. }
  26293. at(t, target) {
  26294. return this.delta(target).multiplyScalar(t).add(this.start);
  26295. }
  26296. closestPointToPointParameter(point, clampToLine) {
  26297. _startP.subVectors(point, this.start);
  26298. _startEnd.subVectors(this.end, this.start);
  26299. const startEnd2 = _startEnd.dot(_startEnd);
  26300. const startEnd_startP = _startEnd.dot(_startP);
  26301. let t = startEnd_startP / startEnd2;
  26302. if (clampToLine) {
  26303. t = clamp(t, 0, 1);
  26304. }
  26305. return t;
  26306. }
  26307. closestPointToPoint(point, clampToLine, target) {
  26308. const t = this.closestPointToPointParameter(point, clampToLine);
  26309. return this.delta(target).multiplyScalar(t).add(this.start);
  26310. }
  26311. applyMatrix4(matrix) {
  26312. this.start.applyMatrix4(matrix);
  26313. this.end.applyMatrix4(matrix);
  26314. return this;
  26315. }
  26316. equals(line) {
  26317. return line.start.equals(this.start) && line.end.equals(this.end);
  26318. }
  26319. clone() {
  26320. return new this.constructor().copy(this);
  26321. }
  26322. }
  26323. class ImmediateRenderObject extends Object3D {
  26324. constructor(material) {
  26325. super();
  26326. this.material = material;
  26327. this.render = function ()
  26328. /* renderCallback */
  26329. {};
  26330. this.hasPositions = false;
  26331. this.hasNormals = false;
  26332. this.hasColors = false;
  26333. this.hasUvs = false;
  26334. this.positionArray = null;
  26335. this.normalArray = null;
  26336. this.colorArray = null;
  26337. this.uvArray = null;
  26338. this.count = 0;
  26339. }
  26340. }
  26341. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  26342. const _vector$3 = /*@__PURE__*/new Vector3();
  26343. class SpotLightHelper extends Object3D {
  26344. constructor(light, color) {
  26345. super();
  26346. this.light = light;
  26347. this.light.updateMatrixWorld();
  26348. this.matrix = light.matrixWorld;
  26349. this.matrixAutoUpdate = false;
  26350. this.color = color;
  26351. const geometry = new BufferGeometry();
  26352. 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];
  26353. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  26354. const p1 = i / l * Math.PI * 2;
  26355. const p2 = j / l * Math.PI * 2;
  26356. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  26357. }
  26358. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  26359. const material = new LineBasicMaterial({
  26360. fog: false,
  26361. toneMapped: false
  26362. });
  26363. this.cone = new LineSegments(geometry, material);
  26364. this.add(this.cone);
  26365. this.update();
  26366. }
  26367. dispose() {
  26368. this.cone.geometry.dispose();
  26369. this.cone.material.dispose();
  26370. }
  26371. update() {
  26372. this.light.updateMatrixWorld();
  26373. const coneLength = this.light.distance ? this.light.distance : 1000;
  26374. const coneWidth = coneLength * Math.tan(this.light.angle);
  26375. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  26376. _vector$3.setFromMatrixPosition(this.light.target.matrixWorld);
  26377. this.cone.lookAt(_vector$3);
  26378. if (this.color !== undefined) {
  26379. this.cone.material.color.set(this.color);
  26380. } else {
  26381. this.cone.material.color.copy(this.light.color);
  26382. }
  26383. }
  26384. }
  26385. const _vector$2 = /*@__PURE__*/new Vector3();
  26386. const _boneMatrix = /*@__PURE__*/new Matrix4();
  26387. const _matrixWorldInv = /*@__PURE__*/new Matrix4();
  26388. class SkeletonHelper extends LineSegments {
  26389. constructor(object) {
  26390. const bones = getBoneList(object);
  26391. const geometry = new BufferGeometry();
  26392. const vertices = [];
  26393. const colors = [];
  26394. const color1 = new Color(0, 0, 1);
  26395. const color2 = new Color(0, 1, 0);
  26396. for (let i = 0; i < bones.length; i++) {
  26397. const bone = bones[i];
  26398. if (bone.parent && bone.parent.isBone) {
  26399. vertices.push(0, 0, 0);
  26400. vertices.push(0, 0, 0);
  26401. colors.push(color1.r, color1.g, color1.b);
  26402. colors.push(color2.r, color2.g, color2.b);
  26403. }
  26404. }
  26405. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26406. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26407. const material = new LineBasicMaterial({
  26408. vertexColors: true,
  26409. depthTest: false,
  26410. depthWrite: false,
  26411. toneMapped: false,
  26412. transparent: true
  26413. });
  26414. super(geometry, material);
  26415. this.type = 'SkeletonHelper';
  26416. this.isSkeletonHelper = true;
  26417. this.root = object;
  26418. this.bones = bones;
  26419. this.matrix = object.matrixWorld;
  26420. this.matrixAutoUpdate = false;
  26421. }
  26422. updateMatrixWorld(force) {
  26423. const bones = this.bones;
  26424. const geometry = this.geometry;
  26425. const position = geometry.getAttribute('position');
  26426. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  26427. for (let i = 0, j = 0; i < bones.length; i++) {
  26428. const bone = bones[i];
  26429. if (bone.parent && bone.parent.isBone) {
  26430. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  26431. _vector$2.setFromMatrixPosition(_boneMatrix);
  26432. position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z);
  26433. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  26434. _vector$2.setFromMatrixPosition(_boneMatrix);
  26435. position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z);
  26436. j += 2;
  26437. }
  26438. }
  26439. geometry.getAttribute('position').needsUpdate = true;
  26440. super.updateMatrixWorld(force);
  26441. }
  26442. }
  26443. function getBoneList(object) {
  26444. const boneList = [];
  26445. if (object && object.isBone) {
  26446. boneList.push(object);
  26447. }
  26448. for (let i = 0; i < object.children.length; i++) {
  26449. boneList.push.apply(boneList, getBoneList(object.children[i]));
  26450. }
  26451. return boneList;
  26452. }
  26453. class PointLightHelper extends Mesh {
  26454. constructor(light, sphereSize, color) {
  26455. const geometry = new SphereGeometry(sphereSize, 4, 2);
  26456. const material = new MeshBasicMaterial({
  26457. wireframe: true,
  26458. fog: false,
  26459. toneMapped: false
  26460. });
  26461. super(geometry, material);
  26462. this.light = light;
  26463. this.light.updateMatrixWorld();
  26464. this.color = color;
  26465. this.type = 'PointLightHelper';
  26466. this.matrix = this.light.matrixWorld;
  26467. this.matrixAutoUpdate = false;
  26468. this.update();
  26469. /*
  26470. // TODO: delete this comment?
  26471. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  26472. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  26473. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  26474. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  26475. const d = light.distance;
  26476. if ( d === 0.0 ) {
  26477. this.lightDistance.visible = false;
  26478. } else {
  26479. this.lightDistance.scale.set( d, d, d );
  26480. }
  26481. this.add( this.lightDistance );
  26482. */
  26483. }
  26484. dispose() {
  26485. this.geometry.dispose();
  26486. this.material.dispose();
  26487. }
  26488. update() {
  26489. if (this.color !== undefined) {
  26490. this.material.color.set(this.color);
  26491. } else {
  26492. this.material.color.copy(this.light.color);
  26493. }
  26494. /*
  26495. const d = this.light.distance;
  26496. if ( d === 0.0 ) {
  26497. this.lightDistance.visible = false;
  26498. } else {
  26499. this.lightDistance.visible = true;
  26500. this.lightDistance.scale.set( d, d, d );
  26501. }
  26502. */
  26503. }
  26504. }
  26505. const _vector$1 = /*@__PURE__*/new Vector3();
  26506. const _color1 = /*@__PURE__*/new Color();
  26507. const _color2 = /*@__PURE__*/new Color();
  26508. class HemisphereLightHelper extends Object3D {
  26509. constructor(light, size, color) {
  26510. super();
  26511. this.light = light;
  26512. this.light.updateMatrixWorld();
  26513. this.matrix = light.matrixWorld;
  26514. this.matrixAutoUpdate = false;
  26515. this.color = color;
  26516. const geometry = new OctahedronGeometry(size);
  26517. geometry.rotateY(Math.PI * 0.5);
  26518. this.material = new MeshBasicMaterial({
  26519. wireframe: true,
  26520. fog: false,
  26521. toneMapped: false
  26522. });
  26523. if (this.color === undefined) this.material.vertexColors = true;
  26524. const position = geometry.getAttribute('position');
  26525. const colors = new Float32Array(position.count * 3);
  26526. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  26527. this.add(new Mesh(geometry, this.material));
  26528. this.update();
  26529. }
  26530. dispose() {
  26531. this.children[0].geometry.dispose();
  26532. this.children[0].material.dispose();
  26533. }
  26534. update() {
  26535. const mesh = this.children[0];
  26536. if (this.color !== undefined) {
  26537. this.material.color.set(this.color);
  26538. } else {
  26539. const colors = mesh.geometry.getAttribute('color');
  26540. _color1.copy(this.light.color);
  26541. _color2.copy(this.light.groundColor);
  26542. for (let i = 0, l = colors.count; i < l; i++) {
  26543. const color = i < l / 2 ? _color1 : _color2;
  26544. colors.setXYZ(i, color.r, color.g, color.b);
  26545. }
  26546. colors.needsUpdate = true;
  26547. }
  26548. mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
  26549. }
  26550. }
  26551. class GridHelper extends LineSegments {
  26552. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  26553. color1 = new Color(color1);
  26554. color2 = new Color(color2);
  26555. const center = divisions / 2;
  26556. const step = size / divisions;
  26557. const halfSize = size / 2;
  26558. const vertices = [],
  26559. colors = [];
  26560. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  26561. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  26562. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  26563. const color = i === center ? color1 : color2;
  26564. color.toArray(colors, j);
  26565. j += 3;
  26566. color.toArray(colors, j);
  26567. j += 3;
  26568. color.toArray(colors, j);
  26569. j += 3;
  26570. color.toArray(colors, j);
  26571. j += 3;
  26572. }
  26573. const geometry = new BufferGeometry();
  26574. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26575. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26576. const material = new LineBasicMaterial({
  26577. vertexColors: true,
  26578. toneMapped: false
  26579. });
  26580. super(geometry, material);
  26581. this.type = 'GridHelper';
  26582. }
  26583. }
  26584. class PolarGridHelper extends LineSegments {
  26585. constructor(radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  26586. color1 = new Color(color1);
  26587. color2 = new Color(color2);
  26588. const vertices = [];
  26589. const colors = []; // create the radials
  26590. for (let i = 0; i <= radials; i++) {
  26591. const v = i / radials * (Math.PI * 2);
  26592. const x = Math.sin(v) * radius;
  26593. const z = Math.cos(v) * radius;
  26594. vertices.push(0, 0, 0);
  26595. vertices.push(x, 0, z);
  26596. const color = i & 1 ? color1 : color2;
  26597. colors.push(color.r, color.g, color.b);
  26598. colors.push(color.r, color.g, color.b);
  26599. } // create the circles
  26600. for (let i = 0; i <= circles; i++) {
  26601. const color = i & 1 ? color1 : color2;
  26602. const r = radius - radius / circles * i;
  26603. for (let j = 0; j < divisions; j++) {
  26604. // first vertex
  26605. let v = j / divisions * (Math.PI * 2);
  26606. let x = Math.sin(v) * r;
  26607. let z = Math.cos(v) * r;
  26608. vertices.push(x, 0, z);
  26609. colors.push(color.r, color.g, color.b); // second vertex
  26610. v = (j + 1) / divisions * (Math.PI * 2);
  26611. x = Math.sin(v) * r;
  26612. z = Math.cos(v) * r;
  26613. vertices.push(x, 0, z);
  26614. colors.push(color.r, color.g, color.b);
  26615. }
  26616. }
  26617. const geometry = new BufferGeometry();
  26618. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26619. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26620. const material = new LineBasicMaterial({
  26621. vertexColors: true,
  26622. toneMapped: false
  26623. });
  26624. super(geometry, material);
  26625. this.type = 'PolarGridHelper';
  26626. }
  26627. }
  26628. const _v1 = /*@__PURE__*/new Vector3();
  26629. const _v2 = /*@__PURE__*/new Vector3();
  26630. const _v3 = /*@__PURE__*/new Vector3();
  26631. class DirectionalLightHelper extends Object3D {
  26632. constructor(light, size, color) {
  26633. super();
  26634. this.light = light;
  26635. this.light.updateMatrixWorld();
  26636. this.matrix = light.matrixWorld;
  26637. this.matrixAutoUpdate = false;
  26638. this.color = color;
  26639. if (size === undefined) size = 1;
  26640. let geometry = new BufferGeometry();
  26641. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  26642. const material = new LineBasicMaterial({
  26643. fog: false,
  26644. toneMapped: false
  26645. });
  26646. this.lightPlane = new Line(geometry, material);
  26647. this.add(this.lightPlane);
  26648. geometry = new BufferGeometry();
  26649. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  26650. this.targetLine = new Line(geometry, material);
  26651. this.add(this.targetLine);
  26652. this.update();
  26653. }
  26654. dispose() {
  26655. this.lightPlane.geometry.dispose();
  26656. this.lightPlane.material.dispose();
  26657. this.targetLine.geometry.dispose();
  26658. this.targetLine.material.dispose();
  26659. }
  26660. update() {
  26661. _v1.setFromMatrixPosition(this.light.matrixWorld);
  26662. _v2.setFromMatrixPosition(this.light.target.matrixWorld);
  26663. _v3.subVectors(_v2, _v1);
  26664. this.lightPlane.lookAt(_v2);
  26665. if (this.color !== undefined) {
  26666. this.lightPlane.material.color.set(this.color);
  26667. this.targetLine.material.color.set(this.color);
  26668. } else {
  26669. this.lightPlane.material.color.copy(this.light.color);
  26670. this.targetLine.material.color.copy(this.light.color);
  26671. }
  26672. this.targetLine.lookAt(_v2);
  26673. this.targetLine.scale.z = _v3.length();
  26674. }
  26675. }
  26676. const _vector = /*@__PURE__*/new Vector3();
  26677. const _camera = /*@__PURE__*/new Camera();
  26678. /**
  26679. * - shows frustum, line of sight and up of the camera
  26680. * - suitable for fast updates
  26681. * - based on frustum visualization in lightgl.js shadowmap example
  26682. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  26683. */
  26684. class CameraHelper extends LineSegments {
  26685. constructor(camera) {
  26686. const geometry = new BufferGeometry();
  26687. const material = new LineBasicMaterial({
  26688. color: 0xffffff,
  26689. vertexColors: true,
  26690. toneMapped: false
  26691. });
  26692. const vertices = [];
  26693. const colors = [];
  26694. const pointMap = {}; // colors
  26695. const colorFrustum = new Color(0xffaa00);
  26696. const colorCone = new Color(0xff0000);
  26697. const colorUp = new Color(0x00aaff);
  26698. const colorTarget = new Color(0xffffff);
  26699. const colorCross = new Color(0x333333); // near
  26700. addLine('n1', 'n2', colorFrustum);
  26701. addLine('n2', 'n4', colorFrustum);
  26702. addLine('n4', 'n3', colorFrustum);
  26703. addLine('n3', 'n1', colorFrustum); // far
  26704. addLine('f1', 'f2', colorFrustum);
  26705. addLine('f2', 'f4', colorFrustum);
  26706. addLine('f4', 'f3', colorFrustum);
  26707. addLine('f3', 'f1', colorFrustum); // sides
  26708. addLine('n1', 'f1', colorFrustum);
  26709. addLine('n2', 'f2', colorFrustum);
  26710. addLine('n3', 'f3', colorFrustum);
  26711. addLine('n4', 'f4', colorFrustum); // cone
  26712. addLine('p', 'n1', colorCone);
  26713. addLine('p', 'n2', colorCone);
  26714. addLine('p', 'n3', colorCone);
  26715. addLine('p', 'n4', colorCone); // up
  26716. addLine('u1', 'u2', colorUp);
  26717. addLine('u2', 'u3', colorUp);
  26718. addLine('u3', 'u1', colorUp); // target
  26719. addLine('c', 't', colorTarget);
  26720. addLine('p', 'c', colorCross); // cross
  26721. addLine('cn1', 'cn2', colorCross);
  26722. addLine('cn3', 'cn4', colorCross);
  26723. addLine('cf1', 'cf2', colorCross);
  26724. addLine('cf3', 'cf4', colorCross);
  26725. function addLine(a, b, color) {
  26726. addPoint(a, color);
  26727. addPoint(b, color);
  26728. }
  26729. function addPoint(id, color) {
  26730. vertices.push(0, 0, 0);
  26731. colors.push(color.r, color.g, color.b);
  26732. if (pointMap[id] === undefined) {
  26733. pointMap[id] = [];
  26734. }
  26735. pointMap[id].push(vertices.length / 3 - 1);
  26736. }
  26737. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26738. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26739. super(geometry, material);
  26740. this.type = 'CameraHelper';
  26741. this.camera = camera;
  26742. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  26743. this.matrix = camera.matrixWorld;
  26744. this.matrixAutoUpdate = false;
  26745. this.pointMap = pointMap;
  26746. this.update();
  26747. }
  26748. update() {
  26749. const geometry = this.geometry;
  26750. const pointMap = this.pointMap;
  26751. const w = 1,
  26752. h = 1; // we need just camera projection matrix inverse
  26753. // world matrix must be identity
  26754. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  26755. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  26756. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  26757. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  26758. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  26759. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  26760. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  26761. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  26762. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  26763. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  26764. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  26765. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  26766. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  26767. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  26768. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  26769. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  26770. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  26771. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  26772. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  26773. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  26774. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  26775. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  26776. geometry.getAttribute('position').needsUpdate = true;
  26777. }
  26778. dispose() {
  26779. this.geometry.dispose();
  26780. this.material.dispose();
  26781. }
  26782. }
  26783. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  26784. _vector.set(x, y, z).unproject(camera);
  26785. const points = pointMap[point];
  26786. if (points !== undefined) {
  26787. const position = geometry.getAttribute('position');
  26788. for (let i = 0, l = points.length; i < l; i++) {
  26789. position.setXYZ(points[i], _vector.x, _vector.y, _vector.z);
  26790. }
  26791. }
  26792. }
  26793. const _box = /*@__PURE__*/new Box3();
  26794. class BoxHelper extends LineSegments {
  26795. constructor(object, color = 0xffff00) {
  26796. 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]);
  26797. const positions = new Float32Array(8 * 3);
  26798. const geometry = new BufferGeometry();
  26799. geometry.setIndex(new BufferAttribute(indices, 1));
  26800. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  26801. super(geometry, new LineBasicMaterial({
  26802. color: color,
  26803. toneMapped: false
  26804. }));
  26805. this.object = object;
  26806. this.type = 'BoxHelper';
  26807. this.matrixAutoUpdate = false;
  26808. this.update();
  26809. }
  26810. update(object) {
  26811. if (object !== undefined) {
  26812. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  26813. }
  26814. if (this.object !== undefined) {
  26815. _box.setFromObject(this.object);
  26816. }
  26817. if (_box.isEmpty()) return;
  26818. const min = _box.min;
  26819. const max = _box.max;
  26820. /*
  26821. 5____4
  26822. 1/___0/|
  26823. | 6__|_7
  26824. 2/___3/
  26825. 0: max.x, max.y, max.z
  26826. 1: min.x, max.y, max.z
  26827. 2: min.x, min.y, max.z
  26828. 3: max.x, min.y, max.z
  26829. 4: max.x, max.y, min.z
  26830. 5: min.x, max.y, min.z
  26831. 6: min.x, min.y, min.z
  26832. 7: max.x, min.y, min.z
  26833. */
  26834. const position = this.geometry.attributes.position;
  26835. const array = position.array;
  26836. array[0] = max.x;
  26837. array[1] = max.y;
  26838. array[2] = max.z;
  26839. array[3] = min.x;
  26840. array[4] = max.y;
  26841. array[5] = max.z;
  26842. array[6] = min.x;
  26843. array[7] = min.y;
  26844. array[8] = max.z;
  26845. array[9] = max.x;
  26846. array[10] = min.y;
  26847. array[11] = max.z;
  26848. array[12] = max.x;
  26849. array[13] = max.y;
  26850. array[14] = min.z;
  26851. array[15] = min.x;
  26852. array[16] = max.y;
  26853. array[17] = min.z;
  26854. array[18] = min.x;
  26855. array[19] = min.y;
  26856. array[20] = min.z;
  26857. array[21] = max.x;
  26858. array[22] = min.y;
  26859. array[23] = min.z;
  26860. position.needsUpdate = true;
  26861. this.geometry.computeBoundingSphere();
  26862. }
  26863. setFromObject(object) {
  26864. this.object = object;
  26865. this.update();
  26866. return this;
  26867. }
  26868. copy(source) {
  26869. LineSegments.prototype.copy.call(this, source);
  26870. this.object = source.object;
  26871. return this;
  26872. }
  26873. }
  26874. class Box3Helper extends LineSegments {
  26875. constructor(box, color = 0xffff00) {
  26876. 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]);
  26877. 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];
  26878. const geometry = new BufferGeometry();
  26879. geometry.setIndex(new BufferAttribute(indices, 1));
  26880. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  26881. super(geometry, new LineBasicMaterial({
  26882. color: color,
  26883. toneMapped: false
  26884. }));
  26885. this.box = box;
  26886. this.type = 'Box3Helper';
  26887. this.geometry.computeBoundingSphere();
  26888. }
  26889. updateMatrixWorld(force) {
  26890. const box = this.box;
  26891. if (box.isEmpty()) return;
  26892. box.getCenter(this.position);
  26893. box.getSize(this.scale);
  26894. this.scale.multiplyScalar(0.5);
  26895. super.updateMatrixWorld(force);
  26896. }
  26897. }
  26898. class PlaneHelper extends Line {
  26899. constructor(plane, size = 1, hex = 0xffff00) {
  26900. const color = hex;
  26901. 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];
  26902. const geometry = new BufferGeometry();
  26903. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  26904. geometry.computeBoundingSphere();
  26905. super(geometry, new LineBasicMaterial({
  26906. color: color,
  26907. toneMapped: false
  26908. }));
  26909. this.type = 'PlaneHelper';
  26910. this.plane = plane;
  26911. this.size = size;
  26912. const positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  26913. const geometry2 = new BufferGeometry();
  26914. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  26915. geometry2.computeBoundingSphere();
  26916. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  26917. color: color,
  26918. opacity: 0.2,
  26919. transparent: true,
  26920. depthWrite: false,
  26921. toneMapped: false
  26922. })));
  26923. }
  26924. updateMatrixWorld(force) {
  26925. let scale = -this.plane.constant;
  26926. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  26927. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  26928. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  26929. this.lookAt(this.plane.normal);
  26930. super.updateMatrixWorld(force);
  26931. }
  26932. }
  26933. const _axis = /*@__PURE__*/new Vector3();
  26934. let _lineGeometry, _coneGeometry;
  26935. class ArrowHelper extends Object3D {
  26936. // dir is assumed to be normalized
  26937. 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) {
  26938. super();
  26939. this.type = 'ArrowHelper';
  26940. if (_lineGeometry === undefined) {
  26941. _lineGeometry = new BufferGeometry();
  26942. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  26943. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  26944. _coneGeometry.translate(0, -0.5, 0);
  26945. }
  26946. this.position.copy(origin);
  26947. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  26948. color: color,
  26949. toneMapped: false
  26950. }));
  26951. this.line.matrixAutoUpdate = false;
  26952. this.add(this.line);
  26953. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  26954. color: color,
  26955. toneMapped: false
  26956. }));
  26957. this.cone.matrixAutoUpdate = false;
  26958. this.add(this.cone);
  26959. this.setDirection(dir);
  26960. this.setLength(length, headLength, headWidth);
  26961. }
  26962. setDirection(dir) {
  26963. // dir is assumed to be normalized
  26964. if (dir.y > 0.99999) {
  26965. this.quaternion.set(0, 0, 0, 1);
  26966. } else if (dir.y < -0.99999) {
  26967. this.quaternion.set(1, 0, 0, 0);
  26968. } else {
  26969. _axis.set(dir.z, 0, -dir.x).normalize();
  26970. const radians = Math.acos(dir.y);
  26971. this.quaternion.setFromAxisAngle(_axis, radians);
  26972. }
  26973. }
  26974. setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
  26975. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  26976. this.line.updateMatrix();
  26977. this.cone.scale.set(headWidth, headLength, headWidth);
  26978. this.cone.position.y = length;
  26979. this.cone.updateMatrix();
  26980. }
  26981. setColor(color) {
  26982. this.line.material.color.set(color);
  26983. this.cone.material.color.set(color);
  26984. }
  26985. copy(source) {
  26986. super.copy(source, false);
  26987. this.line.copy(source.line);
  26988. this.cone.copy(source.cone);
  26989. return this;
  26990. }
  26991. }
  26992. class AxesHelper extends LineSegments {
  26993. constructor(size = 1) {
  26994. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  26995. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  26996. const geometry = new BufferGeometry();
  26997. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26998. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26999. const material = new LineBasicMaterial({
  27000. vertexColors: true,
  27001. toneMapped: false
  27002. });
  27003. super(geometry, material);
  27004. this.type = 'AxesHelper';
  27005. }
  27006. setColors(xAxisColor, yAxisColor, zAxisColor) {
  27007. const color = new Color();
  27008. const array = this.geometry.attributes.color.array;
  27009. color.set(xAxisColor);
  27010. color.toArray(array, 0);
  27011. color.toArray(array, 3);
  27012. color.set(yAxisColor);
  27013. color.toArray(array, 6);
  27014. color.toArray(array, 9);
  27015. color.set(zAxisColor);
  27016. color.toArray(array, 12);
  27017. color.toArray(array, 15);
  27018. this.geometry.attributes.color.needsUpdate = true;
  27019. return this;
  27020. }
  27021. dispose() {
  27022. this.geometry.dispose();
  27023. this.material.dispose();
  27024. }
  27025. }
  27026. const _floatView = new Float32Array(1);
  27027. const _int32View = new Int32Array(_floatView.buffer);
  27028. class DataUtils {
  27029. // Converts float32 to float16 (stored as uint16 value).
  27030. static toHalfFloat(val) {
  27031. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  27032. /* This method is faster than the OpenEXR implementation (very often
  27033. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  27034. * by James Tursa?s half-precision code. */
  27035. _floatView[0] = val;
  27036. const x = _int32View[0];
  27037. let bits = x >> 16 & 0x8000;
  27038. /* Get the sign */
  27039. let m = x >> 12 & 0x07ff;
  27040. /* Keep one extra bit for rounding */
  27041. const e = x >> 23 & 0xff;
  27042. /* Using int is faster here */
  27043. /* If zero, or denormal, or exponent underflows too much for a denormal
  27044. * half, return signed zero. */
  27045. if (e < 103) return bits;
  27046. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  27047. if (e > 142) {
  27048. bits |= 0x7c00;
  27049. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  27050. * not Inf, so make sure we set one mantissa bit too. */
  27051. bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
  27052. return bits;
  27053. }
  27054. /* If exponent underflows but not too much, return a denormal */
  27055. if (e < 113) {
  27056. m |= 0x0800;
  27057. /* Extra rounding may overflow and set mantissa to 0 and exponent
  27058. * to 1, which is OK. */
  27059. bits |= (m >> 114 - e) + (m >> 113 - e & 1);
  27060. return bits;
  27061. }
  27062. bits |= e - 112 << 10 | m >> 1;
  27063. /* Extra rounding. An overflow will set mantissa to 0 and increment
  27064. * the exponent, which is OK. */
  27065. bits += m & 1;
  27066. return bits;
  27067. }
  27068. }
  27069. const LOD_MIN = 4;
  27070. const LOD_MAX = 8;
  27071. const SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
  27072. // chosen to approximate a Trowbridge-Reitz distribution function times the
  27073. // geometric shadowing function. These sigma values squared must match the
  27074. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  27075. const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  27076. 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
  27077. // samples and exit early, but not recompile the shader.
  27078. const MAX_SAMPLES = 20;
  27079. const ENCODINGS = {
  27080. [LinearEncoding]: 0,
  27081. [sRGBEncoding]: 1,
  27082. [RGBEEncoding]: 2,
  27083. [RGBM7Encoding]: 3,
  27084. [RGBM16Encoding]: 4,
  27085. [RGBDEncoding]: 5,
  27086. [GammaEncoding]: 6
  27087. };
  27088. const backgroundMaterial = new MeshBasicMaterial({
  27089. side: BackSide,
  27090. depthWrite: false,
  27091. depthTest: false
  27092. });
  27093. const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
  27094. const _flatCamera = /*@__PURE__*/new OrthographicCamera();
  27095. const {
  27096. _lodPlanes,
  27097. _sizeLods,
  27098. _sigmas
  27099. } = /*@__PURE__*/_createPlanes();
  27100. const _clearColor = /*@__PURE__*/new Color();
  27101. let _oldTarget = null; // Golden Ratio
  27102. const PHI = (1 + Math.sqrt(5)) / 2;
  27103. const INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  27104. // same axis), used as axis directions evenly spread on a sphere.
  27105. 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)];
  27106. /**
  27107. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  27108. * (PMREM) from a cubeMap environment texture. This allows different levels of
  27109. * blur to be quickly accessed based on material roughness. It is packed into a
  27110. * special CubeUV format that allows us to perform custom interpolation so that
  27111. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  27112. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  27113. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  27114. * higher roughness levels. In this way we maintain resolution to smoothly
  27115. * interpolate diffuse lighting while limiting sampling computation.
  27116. *
  27117. * Paper: Fast, Accurate Image-Based Lighting
  27118. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  27119. */
  27120. function convertLinearToRGBE(color) {
  27121. const maxComponent = Math.max(color.r, color.g, color.b);
  27122. const fExp = Math.min(Math.max(Math.ceil(Math.log2(maxComponent)), -128.0), 127.0);
  27123. color.multiplyScalar(Math.pow(2.0, -fExp));
  27124. const alpha = (fExp + 128.0) / 255.0;
  27125. return alpha;
  27126. }
  27127. class PMREMGenerator {
  27128. constructor(renderer) {
  27129. this._renderer = renderer;
  27130. this._pingPongRenderTarget = null;
  27131. this._blurMaterial = _getBlurShader(MAX_SAMPLES);
  27132. this._equirectShader = null;
  27133. this._cubemapShader = null;
  27134. this._compileMaterial(this._blurMaterial);
  27135. }
  27136. /**
  27137. * Generates a PMREM from a supplied Scene, which can be faster than using an
  27138. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  27139. * in radians to be applied to the scene before PMREM generation. Optional near
  27140. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  27141. * is placed at the origin).
  27142. */
  27143. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  27144. _oldTarget = this._renderer.getRenderTarget();
  27145. const cubeUVRenderTarget = this._allocateTargets();
  27146. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  27147. if (sigma > 0) {
  27148. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  27149. }
  27150. this._applyPMREM(cubeUVRenderTarget);
  27151. this._cleanup(cubeUVRenderTarget);
  27152. return cubeUVRenderTarget;
  27153. }
  27154. /**
  27155. * Generates a PMREM from an equirectangular texture, which can be either LDR
  27156. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  27157. * as this matches best with the 256 x 256 cubemap output.
  27158. */
  27159. fromEquirectangular(equirectangular) {
  27160. return this._fromTexture(equirectangular);
  27161. }
  27162. /**
  27163. * Generates a PMREM from an cubemap texture, which can be either LDR
  27164. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  27165. * as this matches best with the 256 x 256 cubemap output.
  27166. */
  27167. fromCubemap(cubemap) {
  27168. return this._fromTexture(cubemap);
  27169. }
  27170. /**
  27171. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  27172. * your texture's network fetch for increased concurrency.
  27173. */
  27174. compileCubemapShader() {
  27175. if (this._cubemapShader === null) {
  27176. this._cubemapShader = _getCubemapShader();
  27177. this._compileMaterial(this._cubemapShader);
  27178. }
  27179. }
  27180. /**
  27181. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  27182. * your texture's network fetch for increased concurrency.
  27183. */
  27184. compileEquirectangularShader() {
  27185. if (this._equirectShader === null) {
  27186. this._equirectShader = _getEquirectShader();
  27187. this._compileMaterial(this._equirectShader);
  27188. }
  27189. }
  27190. /**
  27191. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  27192. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  27193. * one of them will cause any others to also become unusable.
  27194. */
  27195. dispose() {
  27196. this._blurMaterial.dispose();
  27197. if (this._cubemapShader !== null) this._cubemapShader.dispose();
  27198. if (this._equirectShader !== null) this._equirectShader.dispose();
  27199. for (let i = 0; i < _lodPlanes.length; i++) {
  27200. _lodPlanes[i].dispose();
  27201. }
  27202. } // private interface
  27203. _cleanup(outputTarget) {
  27204. this._pingPongRenderTarget.dispose();
  27205. this._renderer.setRenderTarget(_oldTarget);
  27206. outputTarget.scissorTest = false;
  27207. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  27208. }
  27209. _fromTexture(texture) {
  27210. _oldTarget = this._renderer.getRenderTarget();
  27211. const cubeUVRenderTarget = this._allocateTargets(texture);
  27212. this._textureToCubeUV(texture, cubeUVRenderTarget);
  27213. this._applyPMREM(cubeUVRenderTarget);
  27214. this._cleanup(cubeUVRenderTarget);
  27215. return cubeUVRenderTarget;
  27216. }
  27217. _allocateTargets(texture) {
  27218. // warning: null texture is valid
  27219. const params = {
  27220. magFilter: NearestFilter,
  27221. minFilter: NearestFilter,
  27222. generateMipmaps: false,
  27223. type: UnsignedByteType,
  27224. format: RGBEFormat,
  27225. encoding: _isLDR(texture) ? texture.encoding : RGBEEncoding,
  27226. depthBuffer: false
  27227. };
  27228. const cubeUVRenderTarget = _createRenderTarget(params);
  27229. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  27230. this._pingPongRenderTarget = _createRenderTarget(params);
  27231. return cubeUVRenderTarget;
  27232. }
  27233. _compileMaterial(material) {
  27234. const tmpMesh = new Mesh(_lodPlanes[0], material);
  27235. this._renderer.compile(tmpMesh, _flatCamera);
  27236. }
  27237. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  27238. const fov = 90;
  27239. const aspect = 1;
  27240. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  27241. const upSign = [1, -1, 1, 1, 1, 1];
  27242. const forwardSign = [1, 1, 1, -1, -1, -1];
  27243. const renderer = this._renderer;
  27244. const originalAutoClear = renderer.autoClear;
  27245. const outputEncoding = renderer.outputEncoding;
  27246. const toneMapping = renderer.toneMapping;
  27247. renderer.getClearColor(_clearColor);
  27248. renderer.toneMapping = NoToneMapping;
  27249. renderer.outputEncoding = LinearEncoding;
  27250. renderer.autoClear = false;
  27251. let useSolidColor = false;
  27252. const background = scene.background;
  27253. if (background) {
  27254. if (background.isColor) {
  27255. backgroundMaterial.color.copy(background).convertSRGBToLinear();
  27256. scene.background = null;
  27257. const alpha = convertLinearToRGBE(backgroundMaterial.color);
  27258. backgroundMaterial.opacity = alpha;
  27259. useSolidColor = true;
  27260. }
  27261. } else {
  27262. backgroundMaterial.color.copy(_clearColor).convertSRGBToLinear();
  27263. const alpha = convertLinearToRGBE(backgroundMaterial.color);
  27264. backgroundMaterial.opacity = alpha;
  27265. useSolidColor = true;
  27266. }
  27267. for (let i = 0; i < 6; i++) {
  27268. const col = i % 3;
  27269. if (col == 0) {
  27270. cubeCamera.up.set(0, upSign[i], 0);
  27271. cubeCamera.lookAt(forwardSign[i], 0, 0);
  27272. } else if (col == 1) {
  27273. cubeCamera.up.set(0, 0, upSign[i]);
  27274. cubeCamera.lookAt(0, forwardSign[i], 0);
  27275. } else {
  27276. cubeCamera.up.set(0, upSign[i], 0);
  27277. cubeCamera.lookAt(0, 0, forwardSign[i]);
  27278. }
  27279. _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
  27280. renderer.setRenderTarget(cubeUVRenderTarget);
  27281. if (useSolidColor) {
  27282. renderer.render(backgroundBox, cubeCamera);
  27283. }
  27284. renderer.render(scene, cubeCamera);
  27285. }
  27286. renderer.toneMapping = toneMapping;
  27287. renderer.outputEncoding = outputEncoding;
  27288. renderer.autoClear = originalAutoClear;
  27289. }
  27290. _textureToCubeUV(texture, cubeUVRenderTarget) {
  27291. const renderer = this._renderer;
  27292. if (texture.isCubeTexture) {
  27293. if (this._cubemapShader == null) {
  27294. this._cubemapShader = _getCubemapShader();
  27295. }
  27296. } else {
  27297. if (this._equirectShader == null) {
  27298. this._equirectShader = _getEquirectShader();
  27299. }
  27300. }
  27301. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  27302. const mesh = new Mesh(_lodPlanes[0], material);
  27303. const uniforms = material.uniforms;
  27304. uniforms['envMap'].value = texture;
  27305. if (!texture.isCubeTexture) {
  27306. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  27307. }
  27308. uniforms['inputEncoding'].value = ENCODINGS[texture.encoding];
  27309. uniforms['outputEncoding'].value = ENCODINGS[cubeUVRenderTarget.texture.encoding];
  27310. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  27311. renderer.setRenderTarget(cubeUVRenderTarget);
  27312. renderer.render(mesh, _flatCamera);
  27313. }
  27314. _applyPMREM(cubeUVRenderTarget) {
  27315. const renderer = this._renderer;
  27316. const autoClear = renderer.autoClear;
  27317. renderer.autoClear = false;
  27318. for (let i = 1; i < TOTAL_LODS; i++) {
  27319. const sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  27320. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  27321. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  27322. }
  27323. renderer.autoClear = autoClear;
  27324. }
  27325. /**
  27326. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  27327. * vertically and horizontally, but this breaks down on a cube. Here we apply
  27328. * the blur latitudinally (around the poles), and then longitudinally (towards
  27329. * the poles) to approximate the orthogonally-separable blur. It is least
  27330. * accurate at the poles, but still does a decent job.
  27331. */
  27332. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  27333. const pingPongRenderTarget = this._pingPongRenderTarget;
  27334. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  27335. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  27336. }
  27337. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  27338. const renderer = this._renderer;
  27339. const blurMaterial = this._blurMaterial;
  27340. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  27341. console.error('blur direction must be either latitudinal or longitudinal!');
  27342. } // Number of standard deviations at which to cut off the discrete approximation.
  27343. const STANDARD_DEVIATIONS = 3;
  27344. const blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
  27345. const blurUniforms = blurMaterial.uniforms;
  27346. const pixels = _sizeLods[lodIn] - 1;
  27347. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  27348. const sigmaPixels = sigmaRadians / radiansPerPixel;
  27349. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  27350. if (samples > MAX_SAMPLES) {
  27351. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  27352. }
  27353. const weights = [];
  27354. let sum = 0;
  27355. for (let i = 0; i < MAX_SAMPLES; ++i) {
  27356. const x = i / sigmaPixels;
  27357. const weight = Math.exp(-x * x / 2);
  27358. weights.push(weight);
  27359. if (i == 0) {
  27360. sum += weight;
  27361. } else if (i < samples) {
  27362. sum += 2 * weight;
  27363. }
  27364. }
  27365. for (let i = 0; i < weights.length; i++) {
  27366. weights[i] = weights[i] / sum;
  27367. }
  27368. blurUniforms['envMap'].value = targetIn.texture;
  27369. blurUniforms['samples'].value = samples;
  27370. blurUniforms['weights'].value = weights;
  27371. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  27372. if (poleAxis) {
  27373. blurUniforms['poleAxis'].value = poleAxis;
  27374. }
  27375. blurUniforms['dTheta'].value = radiansPerPixel;
  27376. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  27377. blurUniforms['inputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  27378. blurUniforms['outputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  27379. const outputSize = _sizeLods[lodOut];
  27380. const x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  27381. const y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  27382. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  27383. renderer.setRenderTarget(targetOut);
  27384. renderer.render(blurMesh, _flatCamera);
  27385. }
  27386. }
  27387. function _isLDR(texture) {
  27388. if (texture === undefined || texture.type !== UnsignedByteType) return false;
  27389. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  27390. }
  27391. function _createPlanes() {
  27392. const _lodPlanes = [];
  27393. const _sizeLods = [];
  27394. const _sigmas = [];
  27395. let lod = LOD_MAX;
  27396. for (let i = 0; i < TOTAL_LODS; i++) {
  27397. const sizeLod = Math.pow(2, lod);
  27398. _sizeLods.push(sizeLod);
  27399. let sigma = 1.0 / sizeLod;
  27400. if (i > LOD_MAX - LOD_MIN) {
  27401. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  27402. } else if (i == 0) {
  27403. sigma = 0;
  27404. }
  27405. _sigmas.push(sigma);
  27406. const texelSize = 1.0 / (sizeLod - 1);
  27407. const min = -texelSize / 2;
  27408. const max = 1 + texelSize / 2;
  27409. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  27410. const cubeFaces = 6;
  27411. const vertices = 6;
  27412. const positionSize = 3;
  27413. const uvSize = 2;
  27414. const faceIndexSize = 1;
  27415. const position = new Float32Array(positionSize * vertices * cubeFaces);
  27416. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  27417. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  27418. for (let face = 0; face < cubeFaces; face++) {
  27419. const x = face % 3 * 2 / 3 - 1;
  27420. const y = face > 2 ? 0 : -1;
  27421. 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];
  27422. position.set(coordinates, positionSize * vertices * face);
  27423. uv.set(uv1, uvSize * vertices * face);
  27424. const fill = [face, face, face, face, face, face];
  27425. faceIndex.set(fill, faceIndexSize * vertices * face);
  27426. }
  27427. const planes = new BufferGeometry();
  27428. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  27429. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  27430. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  27431. _lodPlanes.push(planes);
  27432. if (lod > LOD_MIN) {
  27433. lod--;
  27434. }
  27435. }
  27436. return {
  27437. _lodPlanes,
  27438. _sizeLods,
  27439. _sigmas
  27440. };
  27441. }
  27442. function _createRenderTarget(params) {
  27443. const cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  27444. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  27445. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  27446. cubeUVRenderTarget.scissorTest = true;
  27447. return cubeUVRenderTarget;
  27448. }
  27449. function _setViewport(target, x, y, width, height) {
  27450. target.viewport.set(x, y, width, height);
  27451. target.scissor.set(x, y, width, height);
  27452. }
  27453. function _getBlurShader(maxSamples) {
  27454. const weights = new Float32Array(maxSamples);
  27455. const poleAxis = new Vector3(0, 1, 0);
  27456. const shaderMaterial = new RawShaderMaterial({
  27457. name: 'SphericalGaussianBlur',
  27458. defines: {
  27459. 'n': maxSamples
  27460. },
  27461. uniforms: {
  27462. 'envMap': {
  27463. value: null
  27464. },
  27465. 'samples': {
  27466. value: 1
  27467. },
  27468. 'weights': {
  27469. value: weights
  27470. },
  27471. 'latitudinal': {
  27472. value: false
  27473. },
  27474. 'dTheta': {
  27475. value: 0
  27476. },
  27477. 'mipInt': {
  27478. value: 0
  27479. },
  27480. 'poleAxis': {
  27481. value: poleAxis
  27482. },
  27483. 'inputEncoding': {
  27484. value: ENCODINGS[LinearEncoding]
  27485. },
  27486. 'outputEncoding': {
  27487. value: ENCODINGS[LinearEncoding]
  27488. }
  27489. },
  27490. vertexShader: _getCommonVertexShader(),
  27491. fragmentShader:
  27492. /* glsl */
  27493. `
  27494. precision mediump float;
  27495. precision mediump int;
  27496. varying vec3 vOutputDirection;
  27497. uniform sampler2D envMap;
  27498. uniform int samples;
  27499. uniform float weights[ n ];
  27500. uniform bool latitudinal;
  27501. uniform float dTheta;
  27502. uniform float mipInt;
  27503. uniform vec3 poleAxis;
  27504. ${_getEncodings()}
  27505. #define ENVMAP_TYPE_CUBE_UV
  27506. #include <cube_uv_reflection_fragment>
  27507. vec3 getSample( float theta, vec3 axis ) {
  27508. float cosTheta = cos( theta );
  27509. // Rodrigues' axis-angle rotation
  27510. vec3 sampleDirection = vOutputDirection * cosTheta
  27511. + cross( axis, vOutputDirection ) * sin( theta )
  27512. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  27513. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  27514. }
  27515. void main() {
  27516. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  27517. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  27518. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  27519. }
  27520. axis = normalize( axis );
  27521. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  27522. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  27523. for ( int i = 1; i < n; i++ ) {
  27524. if ( i >= samples ) {
  27525. break;
  27526. }
  27527. float theta = dTheta * float( i );
  27528. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  27529. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  27530. }
  27531. gl_FragColor = linearToOutputTexel( gl_FragColor );
  27532. }
  27533. `,
  27534. blending: NoBlending,
  27535. depthTest: false,
  27536. depthWrite: false
  27537. });
  27538. return shaderMaterial;
  27539. }
  27540. function _getEquirectShader() {
  27541. const texelSize = new Vector2(1, 1);
  27542. const shaderMaterial = new RawShaderMaterial({
  27543. name: 'EquirectangularToCubeUV',
  27544. uniforms: {
  27545. 'envMap': {
  27546. value: null
  27547. },
  27548. 'texelSize': {
  27549. value: texelSize
  27550. },
  27551. 'inputEncoding': {
  27552. value: ENCODINGS[LinearEncoding]
  27553. },
  27554. 'outputEncoding': {
  27555. value: ENCODINGS[LinearEncoding]
  27556. }
  27557. },
  27558. vertexShader: _getCommonVertexShader(),
  27559. fragmentShader:
  27560. /* glsl */
  27561. `
  27562. precision mediump float;
  27563. precision mediump int;
  27564. varying vec3 vOutputDirection;
  27565. uniform sampler2D envMap;
  27566. uniform vec2 texelSize;
  27567. ${_getEncodings()}
  27568. #include <common>
  27569. void main() {
  27570. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  27571. vec3 outputDirection = normalize( vOutputDirection );
  27572. vec2 uv = equirectUv( outputDirection );
  27573. vec2 f = fract( uv / texelSize - 0.5 );
  27574. uv -= f * texelSize;
  27575. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27576. uv.x += texelSize.x;
  27577. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27578. uv.y += texelSize.y;
  27579. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27580. uv.x -= texelSize.x;
  27581. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27582. vec3 tm = mix( tl, tr, f.x );
  27583. vec3 bm = mix( bl, br, f.x );
  27584. gl_FragColor.rgb = mix( tm, bm, f.y );
  27585. gl_FragColor = linearToOutputTexel( gl_FragColor );
  27586. }
  27587. `,
  27588. blending: NoBlending,
  27589. depthTest: false,
  27590. depthWrite: false
  27591. });
  27592. return shaderMaterial;
  27593. }
  27594. function _getCubemapShader() {
  27595. const shaderMaterial = new RawShaderMaterial({
  27596. name: 'CubemapToCubeUV',
  27597. uniforms: {
  27598. 'envMap': {
  27599. value: null
  27600. },
  27601. 'inputEncoding': {
  27602. value: ENCODINGS[LinearEncoding]
  27603. },
  27604. 'outputEncoding': {
  27605. value: ENCODINGS[LinearEncoding]
  27606. }
  27607. },
  27608. vertexShader: _getCommonVertexShader(),
  27609. fragmentShader:
  27610. /* glsl */
  27611. `
  27612. precision mediump float;
  27613. precision mediump int;
  27614. varying vec3 vOutputDirection;
  27615. uniform samplerCube envMap;
  27616. ${_getEncodings()}
  27617. void main() {
  27618. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  27619. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  27620. gl_FragColor = linearToOutputTexel( gl_FragColor );
  27621. }
  27622. `,
  27623. blending: NoBlending,
  27624. depthTest: false,
  27625. depthWrite: false
  27626. });
  27627. return shaderMaterial;
  27628. }
  27629. function _getCommonVertexShader() {
  27630. return (
  27631. /* glsl */
  27632. `
  27633. precision mediump float;
  27634. precision mediump int;
  27635. attribute vec3 position;
  27636. attribute vec2 uv;
  27637. attribute float faceIndex;
  27638. varying vec3 vOutputDirection;
  27639. // RH coordinate system; PMREM face-indexing convention
  27640. vec3 getDirection( vec2 uv, float face ) {
  27641. uv = 2.0 * uv - 1.0;
  27642. vec3 direction = vec3( uv, 1.0 );
  27643. if ( face == 0.0 ) {
  27644. direction = direction.zyx; // ( 1, v, u ) pos x
  27645. } else if ( face == 1.0 ) {
  27646. direction = direction.xzy;
  27647. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  27648. } else if ( face == 2.0 ) {
  27649. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  27650. } else if ( face == 3.0 ) {
  27651. direction = direction.zyx;
  27652. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  27653. } else if ( face == 4.0 ) {
  27654. direction = direction.xzy;
  27655. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  27656. } else if ( face == 5.0 ) {
  27657. direction.z *= -1.0; // ( u, v, -1 ) neg z
  27658. }
  27659. return direction;
  27660. }
  27661. void main() {
  27662. vOutputDirection = getDirection( uv, faceIndex );
  27663. gl_Position = vec4( position, 1.0 );
  27664. }
  27665. `
  27666. );
  27667. }
  27668. function _getEncodings() {
  27669. return (
  27670. /* glsl */
  27671. `
  27672. uniform int inputEncoding;
  27673. uniform int outputEncoding;
  27674. #include <encodings_pars_fragment>
  27675. vec4 inputTexelToLinear( vec4 value ) {
  27676. if ( inputEncoding == 0 ) {
  27677. return value;
  27678. } else if ( inputEncoding == 1 ) {
  27679. return sRGBToLinear( value );
  27680. } else if ( inputEncoding == 2 ) {
  27681. return RGBEToLinear( value );
  27682. } else if ( inputEncoding == 3 ) {
  27683. return RGBMToLinear( value, 7.0 );
  27684. } else if ( inputEncoding == 4 ) {
  27685. return RGBMToLinear( value, 16.0 );
  27686. } else if ( inputEncoding == 5 ) {
  27687. return RGBDToLinear( value, 256.0 );
  27688. } else {
  27689. return GammaToLinear( value, 2.2 );
  27690. }
  27691. }
  27692. vec4 linearToOutputTexel( vec4 value ) {
  27693. if ( outputEncoding == 0 ) {
  27694. return value;
  27695. } else if ( outputEncoding == 1 ) {
  27696. return LinearTosRGB( value );
  27697. } else if ( outputEncoding == 2 ) {
  27698. return LinearToRGBE( value );
  27699. } else if ( outputEncoding == 3 ) {
  27700. return LinearToRGBM( value, 7.0 );
  27701. } else if ( outputEncoding == 4 ) {
  27702. return LinearToRGBM( value, 16.0 );
  27703. } else if ( outputEncoding == 5 ) {
  27704. return LinearToRGBD( value, 256.0 );
  27705. } else {
  27706. return LinearToGamma( value, 2.2 );
  27707. }
  27708. }
  27709. vec4 envMapTexelToLinear( vec4 color ) {
  27710. return inputTexelToLinear( color );
  27711. }
  27712. `
  27713. );
  27714. }
  27715. const LineStrip = 0;
  27716. const LinePieces = 1;
  27717. const NoColors = 0;
  27718. const FaceColors = 1;
  27719. const VertexColors = 2;
  27720. function MeshFaceMaterial(materials) {
  27721. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  27722. return materials;
  27723. }
  27724. function MultiMaterial(materials = []) {
  27725. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  27726. materials.isMultiMaterial = true;
  27727. materials.materials = materials;
  27728. materials.clone = function () {
  27729. return materials.slice();
  27730. };
  27731. return materials;
  27732. }
  27733. function PointCloud(geometry, material) {
  27734. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  27735. return new Points(geometry, material);
  27736. }
  27737. function Particle(material) {
  27738. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  27739. return new Sprite(material);
  27740. }
  27741. function ParticleSystem(geometry, material) {
  27742. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  27743. return new Points(geometry, material);
  27744. }
  27745. function PointCloudMaterial(parameters) {
  27746. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  27747. return new PointsMaterial(parameters);
  27748. }
  27749. function ParticleBasicMaterial(parameters) {
  27750. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  27751. return new PointsMaterial(parameters);
  27752. }
  27753. function ParticleSystemMaterial(parameters) {
  27754. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  27755. return new PointsMaterial(parameters);
  27756. }
  27757. function Vertex(x, y, z) {
  27758. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  27759. return new Vector3(x, y, z);
  27760. } //
  27761. function DynamicBufferAttribute(array, itemSize) {
  27762. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  27763. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  27764. }
  27765. function Int8Attribute(array, itemSize) {
  27766. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  27767. return new Int8BufferAttribute(array, itemSize);
  27768. }
  27769. function Uint8Attribute(array, itemSize) {
  27770. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  27771. return new Uint8BufferAttribute(array, itemSize);
  27772. }
  27773. function Uint8ClampedAttribute(array, itemSize) {
  27774. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  27775. return new Uint8ClampedBufferAttribute(array, itemSize);
  27776. }
  27777. function Int16Attribute(array, itemSize) {
  27778. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  27779. return new Int16BufferAttribute(array, itemSize);
  27780. }
  27781. function Uint16Attribute(array, itemSize) {
  27782. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  27783. return new Uint16BufferAttribute(array, itemSize);
  27784. }
  27785. function Int32Attribute(array, itemSize) {
  27786. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  27787. return new Int32BufferAttribute(array, itemSize);
  27788. }
  27789. function Uint32Attribute(array, itemSize) {
  27790. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  27791. return new Uint32BufferAttribute(array, itemSize);
  27792. }
  27793. function Float32Attribute(array, itemSize) {
  27794. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  27795. return new Float32BufferAttribute(array, itemSize);
  27796. }
  27797. function Float64Attribute(array, itemSize) {
  27798. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  27799. return new Float64BufferAttribute(array, itemSize);
  27800. } //
  27801. Curve.create = function (construct, getPoint) {
  27802. console.log('THREE.Curve.create() has been deprecated');
  27803. construct.prototype = Object.create(Curve.prototype);
  27804. construct.prototype.constructor = construct;
  27805. construct.prototype.getPoint = getPoint;
  27806. return construct;
  27807. }; //
  27808. Path.prototype.fromPoints = function (points) {
  27809. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  27810. return this.setFromPoints(points);
  27811. }; //
  27812. function AxisHelper(size) {
  27813. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  27814. return new AxesHelper(size);
  27815. }
  27816. function BoundingBoxHelper(object, color) {
  27817. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  27818. return new BoxHelper(object, color);
  27819. }
  27820. function EdgesHelper(object, hex) {
  27821. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  27822. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  27823. color: hex !== undefined ? hex : 0xffffff
  27824. }));
  27825. }
  27826. GridHelper.prototype.setColors = function () {
  27827. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  27828. };
  27829. SkeletonHelper.prototype.update = function () {
  27830. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  27831. };
  27832. function WireframeHelper(object, hex) {
  27833. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  27834. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  27835. color: hex !== undefined ? hex : 0xffffff
  27836. }));
  27837. } //
  27838. Loader.prototype.extractUrlBase = function (url) {
  27839. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  27840. return LoaderUtils.extractUrlBase(url);
  27841. };
  27842. Loader.Handlers = {
  27843. add: function ()
  27844. /* regex, loader */
  27845. {
  27846. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  27847. },
  27848. get: function ()
  27849. /* file */
  27850. {
  27851. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  27852. }
  27853. };
  27854. function XHRLoader(manager) {
  27855. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  27856. return new FileLoader(manager);
  27857. }
  27858. function BinaryTextureLoader(manager) {
  27859. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  27860. return new DataTextureLoader(manager);
  27861. } //
  27862. Box2.prototype.center = function (optionalTarget) {
  27863. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  27864. return this.getCenter(optionalTarget);
  27865. };
  27866. Box2.prototype.empty = function () {
  27867. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  27868. return this.isEmpty();
  27869. };
  27870. Box2.prototype.isIntersectionBox = function (box) {
  27871. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  27872. return this.intersectsBox(box);
  27873. };
  27874. Box2.prototype.size = function (optionalTarget) {
  27875. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  27876. return this.getSize(optionalTarget);
  27877. }; //
  27878. Box3.prototype.center = function (optionalTarget) {
  27879. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  27880. return this.getCenter(optionalTarget);
  27881. };
  27882. Box3.prototype.empty = function () {
  27883. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  27884. return this.isEmpty();
  27885. };
  27886. Box3.prototype.isIntersectionBox = function (box) {
  27887. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  27888. return this.intersectsBox(box);
  27889. };
  27890. Box3.prototype.isIntersectionSphere = function (sphere) {
  27891. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  27892. return this.intersectsSphere(sphere);
  27893. };
  27894. Box3.prototype.size = function (optionalTarget) {
  27895. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  27896. return this.getSize(optionalTarget);
  27897. }; //
  27898. Sphere.prototype.empty = function () {
  27899. console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
  27900. return this.isEmpty();
  27901. }; //
  27902. Frustum.prototype.setFromMatrix = function (m) {
  27903. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  27904. return this.setFromProjectionMatrix(m);
  27905. }; //
  27906. Line3.prototype.center = function (optionalTarget) {
  27907. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  27908. return this.getCenter(optionalTarget);
  27909. }; //
  27910. Matrix3.prototype.flattenToArrayOffset = function (array, offset) {
  27911. console.warn('THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  27912. return this.toArray(array, offset);
  27913. };
  27914. Matrix3.prototype.multiplyVector3 = function (vector) {
  27915. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  27916. return vector.applyMatrix3(this);
  27917. };
  27918. Matrix3.prototype.multiplyVector3Array = function ()
  27919. /* a */
  27920. {
  27921. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  27922. };
  27923. Matrix3.prototype.applyToBufferAttribute = function (attribute) {
  27924. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  27925. return attribute.applyMatrix3(this);
  27926. };
  27927. Matrix3.prototype.applyToVector3Array = function ()
  27928. /* array, offset, length */
  27929. {
  27930. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  27931. };
  27932. Matrix3.prototype.getInverse = function (matrix) {
  27933. console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  27934. return this.copy(matrix).invert();
  27935. }; //
  27936. Matrix4.prototype.extractPosition = function (m) {
  27937. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  27938. return this.copyPosition(m);
  27939. };
  27940. Matrix4.prototype.flattenToArrayOffset = function (array, offset) {
  27941. console.warn('THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  27942. return this.toArray(array, offset);
  27943. };
  27944. Matrix4.prototype.getPosition = function () {
  27945. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  27946. return new Vector3().setFromMatrixColumn(this, 3);
  27947. };
  27948. Matrix4.prototype.setRotationFromQuaternion = function (q) {
  27949. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  27950. return this.makeRotationFromQuaternion(q);
  27951. };
  27952. Matrix4.prototype.multiplyToArray = function () {
  27953. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  27954. };
  27955. Matrix4.prototype.multiplyVector3 = function (vector) {
  27956. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  27957. return vector.applyMatrix4(this);
  27958. };
  27959. Matrix4.prototype.multiplyVector4 = function (vector) {
  27960. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  27961. return vector.applyMatrix4(this);
  27962. };
  27963. Matrix4.prototype.multiplyVector3Array = function ()
  27964. /* a */
  27965. {
  27966. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  27967. };
  27968. Matrix4.prototype.rotateAxis = function (v) {
  27969. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  27970. v.transformDirection(this);
  27971. };
  27972. Matrix4.prototype.crossVector = function (vector) {
  27973. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  27974. return vector.applyMatrix4(this);
  27975. };
  27976. Matrix4.prototype.translate = function () {
  27977. console.error('THREE.Matrix4: .translate() has been removed.');
  27978. };
  27979. Matrix4.prototype.rotateX = function () {
  27980. console.error('THREE.Matrix4: .rotateX() has been removed.');
  27981. };
  27982. Matrix4.prototype.rotateY = function () {
  27983. console.error('THREE.Matrix4: .rotateY() has been removed.');
  27984. };
  27985. Matrix4.prototype.rotateZ = function () {
  27986. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  27987. };
  27988. Matrix4.prototype.rotateByAxis = function () {
  27989. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  27990. };
  27991. Matrix4.prototype.applyToBufferAttribute = function (attribute) {
  27992. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  27993. return attribute.applyMatrix4(this);
  27994. };
  27995. Matrix4.prototype.applyToVector3Array = function ()
  27996. /* array, offset, length */
  27997. {
  27998. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  27999. };
  28000. Matrix4.prototype.makeFrustum = function (left, right, bottom, top, near, far) {
  28001. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  28002. return this.makePerspective(left, right, top, bottom, near, far);
  28003. };
  28004. Matrix4.prototype.getInverse = function (matrix) {
  28005. console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  28006. return this.copy(matrix).invert();
  28007. }; //
  28008. Plane.prototype.isIntersectionLine = function (line) {
  28009. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  28010. return this.intersectsLine(line);
  28011. }; //
  28012. Quaternion.prototype.multiplyVector3 = function (vector) {
  28013. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  28014. return vector.applyQuaternion(this);
  28015. };
  28016. Quaternion.prototype.inverse = function () {
  28017. console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
  28018. return this.invert();
  28019. }; //
  28020. Ray.prototype.isIntersectionBox = function (box) {
  28021. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  28022. return this.intersectsBox(box);
  28023. };
  28024. Ray.prototype.isIntersectionPlane = function (plane) {
  28025. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  28026. return this.intersectsPlane(plane);
  28027. };
  28028. Ray.prototype.isIntersectionSphere = function (sphere) {
  28029. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28030. return this.intersectsSphere(sphere);
  28031. }; //
  28032. Triangle.prototype.area = function () {
  28033. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  28034. return this.getArea();
  28035. };
  28036. Triangle.prototype.barycoordFromPoint = function (point, target) {
  28037. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28038. return this.getBarycoord(point, target);
  28039. };
  28040. Triangle.prototype.midpoint = function (target) {
  28041. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  28042. return this.getMidpoint(target);
  28043. };
  28044. Triangle.prototypenormal = function (target) {
  28045. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28046. return this.getNormal(target);
  28047. };
  28048. Triangle.prototype.plane = function (target) {
  28049. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  28050. return this.getPlane(target);
  28051. };
  28052. Triangle.barycoordFromPoint = function (point, a, b, c, target) {
  28053. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28054. return Triangle.getBarycoord(point, a, b, c, target);
  28055. };
  28056. Triangle.normal = function (a, b, c, target) {
  28057. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28058. return Triangle.getNormal(a, b, c, target);
  28059. }; //
  28060. Shape.prototype.extractAllPoints = function (divisions) {
  28061. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  28062. return this.extractPoints(divisions);
  28063. };
  28064. Shape.prototype.extrude = function (options) {
  28065. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  28066. return new ExtrudeGeometry(this, options);
  28067. };
  28068. Shape.prototype.makeGeometry = function (options) {
  28069. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  28070. return new ShapeGeometry(this, options);
  28071. }; //
  28072. Vector2.prototype.fromAttribute = function (attribute, index, offset) {
  28073. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28074. return this.fromBufferAttribute(attribute, index, offset);
  28075. };
  28076. Vector2.prototype.distanceToManhattan = function (v) {
  28077. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28078. return this.manhattanDistanceTo(v);
  28079. };
  28080. Vector2.prototype.lengthManhattan = function () {
  28081. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  28082. return this.manhattanLength();
  28083. }; //
  28084. Vector3.prototype.setEulerFromRotationMatrix = function () {
  28085. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  28086. };
  28087. Vector3.prototype.setEulerFromQuaternion = function () {
  28088. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  28089. };
  28090. Vector3.prototype.getPositionFromMatrix = function (m) {
  28091. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  28092. return this.setFromMatrixPosition(m);
  28093. };
  28094. Vector3.prototype.getScaleFromMatrix = function (m) {
  28095. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  28096. return this.setFromMatrixScale(m);
  28097. };
  28098. Vector3.prototype.getColumnFromMatrix = function (index, matrix) {
  28099. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  28100. return this.setFromMatrixColumn(matrix, index);
  28101. };
  28102. Vector3.prototype.applyProjection = function (m) {
  28103. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  28104. return this.applyMatrix4(m);
  28105. };
  28106. Vector3.prototype.fromAttribute = function (attribute, index, offset) {
  28107. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28108. return this.fromBufferAttribute(attribute, index, offset);
  28109. };
  28110. Vector3.prototype.distanceToManhattan = function (v) {
  28111. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28112. return this.manhattanDistanceTo(v);
  28113. };
  28114. Vector3.prototype.lengthManhattan = function () {
  28115. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  28116. return this.manhattanLength();
  28117. }; //
  28118. Vector4.prototype.fromAttribute = function (attribute, index, offset) {
  28119. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28120. return this.fromBufferAttribute(attribute, index, offset);
  28121. };
  28122. Vector4.prototype.lengthManhattan = function () {
  28123. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  28124. return this.manhattanLength();
  28125. }; //
  28126. Object3D.prototype.getChildByName = function (name) {
  28127. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  28128. return this.getObjectByName(name);
  28129. };
  28130. Object3D.prototype.renderDepth = function () {
  28131. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  28132. };
  28133. Object3D.prototype.translate = function (distance, axis) {
  28134. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  28135. return this.translateOnAxis(axis, distance);
  28136. };
  28137. Object3D.prototype.getWorldRotation = function () {
  28138. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  28139. };
  28140. Object3D.prototype.applyMatrix = function (matrix) {
  28141. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  28142. return this.applyMatrix4(matrix);
  28143. };
  28144. Object.defineProperties(Object3D.prototype, {
  28145. eulerOrder: {
  28146. get: function () {
  28147. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28148. return this.rotation.order;
  28149. },
  28150. set: function (value) {
  28151. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28152. this.rotation.order = value;
  28153. }
  28154. },
  28155. useQuaternion: {
  28156. get: function () {
  28157. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28158. },
  28159. set: function () {
  28160. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28161. }
  28162. }
  28163. });
  28164. Mesh.prototype.setDrawMode = function () {
  28165. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28166. };
  28167. Object.defineProperties(Mesh.prototype, {
  28168. drawMode: {
  28169. get: function () {
  28170. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  28171. return TrianglesDrawMode;
  28172. },
  28173. set: function () {
  28174. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28175. }
  28176. }
  28177. });
  28178. SkinnedMesh.prototype.initBones = function () {
  28179. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  28180. }; //
  28181. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  28182. console.warn('THREE.PerspectiveCamera.setLens is deprecated. ' + 'Use .setFocalLength and .filmGauge for a photographic setup.');
  28183. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  28184. this.setFocalLength(focalLength);
  28185. }; //
  28186. Object.defineProperties(Light.prototype, {
  28187. onlyShadow: {
  28188. set: function () {
  28189. console.warn('THREE.Light: .onlyShadow has been removed.');
  28190. }
  28191. },
  28192. shadowCameraFov: {
  28193. set: function (value) {
  28194. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  28195. this.shadow.camera.fov = value;
  28196. }
  28197. },
  28198. shadowCameraLeft: {
  28199. set: function (value) {
  28200. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  28201. this.shadow.camera.left = value;
  28202. }
  28203. },
  28204. shadowCameraRight: {
  28205. set: function (value) {
  28206. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  28207. this.shadow.camera.right = value;
  28208. }
  28209. },
  28210. shadowCameraTop: {
  28211. set: function (value) {
  28212. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  28213. this.shadow.camera.top = value;
  28214. }
  28215. },
  28216. shadowCameraBottom: {
  28217. set: function (value) {
  28218. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  28219. this.shadow.camera.bottom = value;
  28220. }
  28221. },
  28222. shadowCameraNear: {
  28223. set: function (value) {
  28224. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  28225. this.shadow.camera.near = value;
  28226. }
  28227. },
  28228. shadowCameraFar: {
  28229. set: function (value) {
  28230. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  28231. this.shadow.camera.far = value;
  28232. }
  28233. },
  28234. shadowCameraVisible: {
  28235. set: function () {
  28236. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  28237. }
  28238. },
  28239. shadowBias: {
  28240. set: function (value) {
  28241. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  28242. this.shadow.bias = value;
  28243. }
  28244. },
  28245. shadowDarkness: {
  28246. set: function () {
  28247. console.warn('THREE.Light: .shadowDarkness has been removed.');
  28248. }
  28249. },
  28250. shadowMapWidth: {
  28251. set: function (value) {
  28252. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  28253. this.shadow.mapSize.width = value;
  28254. }
  28255. },
  28256. shadowMapHeight: {
  28257. set: function (value) {
  28258. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  28259. this.shadow.mapSize.height = value;
  28260. }
  28261. }
  28262. }); //
  28263. Object.defineProperties(BufferAttribute.prototype, {
  28264. length: {
  28265. get: function () {
  28266. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  28267. return this.array.length;
  28268. }
  28269. },
  28270. dynamic: {
  28271. get: function () {
  28272. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28273. return this.usage === DynamicDrawUsage;
  28274. },
  28275. set: function ()
  28276. /* value */
  28277. {
  28278. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28279. this.setUsage(DynamicDrawUsage);
  28280. }
  28281. }
  28282. });
  28283. BufferAttribute.prototype.setDynamic = function (value) {
  28284. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28285. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28286. return this;
  28287. };
  28288. BufferAttribute.prototype.copyIndicesArray = function ()
  28289. /* indices */
  28290. {
  28291. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  28292. }, BufferAttribute.prototype.setArray = function ()
  28293. /* array */
  28294. {
  28295. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28296. }; //
  28297. BufferGeometry.prototype.addIndex = function (index) {
  28298. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  28299. this.setIndex(index);
  28300. };
  28301. BufferGeometry.prototype.addAttribute = function (name, attribute) {
  28302. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  28303. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  28304. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  28305. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  28306. }
  28307. if (name === 'index') {
  28308. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  28309. this.setIndex(attribute);
  28310. return this;
  28311. }
  28312. return this.setAttribute(name, attribute);
  28313. };
  28314. BufferGeometry.prototype.addDrawCall = function (start, count, indexOffset) {
  28315. if (indexOffset !== undefined) {
  28316. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  28317. }
  28318. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  28319. this.addGroup(start, count);
  28320. };
  28321. BufferGeometry.prototype.clearDrawCalls = function () {
  28322. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  28323. this.clearGroups();
  28324. };
  28325. BufferGeometry.prototype.computeOffsets = function () {
  28326. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  28327. };
  28328. BufferGeometry.prototype.removeAttribute = function (name) {
  28329. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  28330. return this.deleteAttribute(name);
  28331. };
  28332. BufferGeometry.prototype.applyMatrix = function (matrix) {
  28333. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  28334. return this.applyMatrix4(matrix);
  28335. };
  28336. Object.defineProperties(BufferGeometry.prototype, {
  28337. drawcalls: {
  28338. get: function () {
  28339. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  28340. return this.groups;
  28341. }
  28342. },
  28343. offsets: {
  28344. get: function () {
  28345. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  28346. return this.groups;
  28347. }
  28348. }
  28349. });
  28350. InterleavedBuffer.prototype.setDynamic = function (value) {
  28351. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28352. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28353. return this;
  28354. };
  28355. InterleavedBuffer.prototype.setArray = function ()
  28356. /* array */
  28357. {
  28358. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28359. }; //
  28360. ExtrudeGeometry.prototype.getArrays = function () {
  28361. console.error('THREE.ExtrudeGeometry: .getArrays() has been removed.');
  28362. };
  28363. ExtrudeGeometry.prototype.addShapeList = function () {
  28364. console.error('THREE.ExtrudeGeometry: .addShapeList() has been removed.');
  28365. };
  28366. ExtrudeGeometry.prototype.addShape = function () {
  28367. console.error('THREE.ExtrudeGeometry: .addShape() has been removed.');
  28368. }; //
  28369. Scene.prototype.dispose = function () {
  28370. console.error('THREE.Scene: .dispose() has been removed.');
  28371. }; //
  28372. Uniform.prototype.onUpdate = function () {
  28373. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  28374. return this;
  28375. }; //
  28376. Object.defineProperties(Material.prototype, {
  28377. wrapAround: {
  28378. get: function () {
  28379. console.warn('THREE.Material: .wrapAround has been removed.');
  28380. },
  28381. set: function () {
  28382. console.warn('THREE.Material: .wrapAround has been removed.');
  28383. }
  28384. },
  28385. overdraw: {
  28386. get: function () {
  28387. console.warn('THREE.Material: .overdraw has been removed.');
  28388. },
  28389. set: function () {
  28390. console.warn('THREE.Material: .overdraw has been removed.');
  28391. }
  28392. },
  28393. wrapRGB: {
  28394. get: function () {
  28395. console.warn('THREE.Material: .wrapRGB has been removed.');
  28396. return new Color();
  28397. }
  28398. },
  28399. shading: {
  28400. get: function () {
  28401. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28402. },
  28403. set: function (value) {
  28404. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28405. this.flatShading = value === FlatShading;
  28406. }
  28407. },
  28408. stencilMask: {
  28409. get: function () {
  28410. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28411. return this.stencilFuncMask;
  28412. },
  28413. set: function (value) {
  28414. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28415. this.stencilFuncMask = value;
  28416. }
  28417. }
  28418. });
  28419. Object.defineProperties(ShaderMaterial.prototype, {
  28420. derivatives: {
  28421. get: function () {
  28422. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28423. return this.extensions.derivatives;
  28424. },
  28425. set: function (value) {
  28426. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28427. this.extensions.derivatives = value;
  28428. }
  28429. }
  28430. }); //
  28431. WebGLRenderer.prototype.clearTarget = function (renderTarget, color, depth, stencil) {
  28432. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  28433. this.setRenderTarget(renderTarget);
  28434. this.clear(color, depth, stencil);
  28435. };
  28436. WebGLRenderer.prototype.animate = function (callback) {
  28437. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  28438. this.setAnimationLoop(callback);
  28439. };
  28440. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  28441. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  28442. return this.getRenderTarget();
  28443. };
  28444. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  28445. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  28446. return this.capabilities.getMaxAnisotropy();
  28447. };
  28448. WebGLRenderer.prototype.getPrecision = function () {
  28449. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  28450. return this.capabilities.precision;
  28451. };
  28452. WebGLRenderer.prototype.resetGLState = function () {
  28453. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  28454. return this.state.reset();
  28455. };
  28456. WebGLRenderer.prototype.supportsFloatTextures = function () {
  28457. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  28458. return this.extensions.get('OES_texture_float');
  28459. };
  28460. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  28461. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  28462. return this.extensions.get('OES_texture_half_float');
  28463. };
  28464. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  28465. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  28466. return this.extensions.get('OES_standard_derivatives');
  28467. };
  28468. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  28469. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  28470. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  28471. };
  28472. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  28473. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  28474. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  28475. };
  28476. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  28477. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  28478. return this.extensions.get('EXT_blend_minmax');
  28479. };
  28480. WebGLRenderer.prototype.supportsVertexTextures = function () {
  28481. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  28482. return this.capabilities.vertexTextures;
  28483. };
  28484. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  28485. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  28486. return this.extensions.get('ANGLE_instanced_arrays');
  28487. };
  28488. WebGLRenderer.prototype.enableScissorTest = function (boolean) {
  28489. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  28490. this.setScissorTest(boolean);
  28491. };
  28492. WebGLRenderer.prototype.initMaterial = function () {
  28493. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  28494. };
  28495. WebGLRenderer.prototype.addPrePlugin = function () {
  28496. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  28497. };
  28498. WebGLRenderer.prototype.addPostPlugin = function () {
  28499. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  28500. };
  28501. WebGLRenderer.prototype.updateShadowMap = function () {
  28502. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  28503. };
  28504. WebGLRenderer.prototype.setFaceCulling = function () {
  28505. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  28506. };
  28507. WebGLRenderer.prototype.allocTextureUnit = function () {
  28508. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  28509. };
  28510. WebGLRenderer.prototype.setTexture = function () {
  28511. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  28512. };
  28513. WebGLRenderer.prototype.setTexture2D = function () {
  28514. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  28515. };
  28516. WebGLRenderer.prototype.setTextureCube = function () {
  28517. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  28518. };
  28519. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  28520. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  28521. return this.getActiveMipmapLevel();
  28522. };
  28523. Object.defineProperties(WebGLRenderer.prototype, {
  28524. shadowMapEnabled: {
  28525. get: function () {
  28526. return this.shadowMap.enabled;
  28527. },
  28528. set: function (value) {
  28529. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  28530. this.shadowMap.enabled = value;
  28531. }
  28532. },
  28533. shadowMapType: {
  28534. get: function () {
  28535. return this.shadowMap.type;
  28536. },
  28537. set: function (value) {
  28538. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  28539. this.shadowMap.type = value;
  28540. }
  28541. },
  28542. shadowMapCullFace: {
  28543. get: function () {
  28544. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28545. return undefined;
  28546. },
  28547. set: function ()
  28548. /* value */
  28549. {
  28550. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28551. }
  28552. },
  28553. context: {
  28554. get: function () {
  28555. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  28556. return this.getContext();
  28557. }
  28558. },
  28559. vr: {
  28560. get: function () {
  28561. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  28562. return this.xr;
  28563. }
  28564. },
  28565. gammaInput: {
  28566. get: function () {
  28567. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  28568. return false;
  28569. },
  28570. set: function () {
  28571. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  28572. }
  28573. },
  28574. gammaOutput: {
  28575. get: function () {
  28576. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  28577. return false;
  28578. },
  28579. set: function (value) {
  28580. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  28581. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  28582. }
  28583. },
  28584. toneMappingWhitePoint: {
  28585. get: function () {
  28586. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  28587. return 1.0;
  28588. },
  28589. set: function () {
  28590. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  28591. }
  28592. }
  28593. });
  28594. Object.defineProperties(WebGLShadowMap.prototype, {
  28595. cullFace: {
  28596. get: function () {
  28597. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  28598. return undefined;
  28599. },
  28600. set: function ()
  28601. /* cullFace */
  28602. {
  28603. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  28604. }
  28605. },
  28606. renderReverseSided: {
  28607. get: function () {
  28608. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  28609. return undefined;
  28610. },
  28611. set: function () {
  28612. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  28613. }
  28614. },
  28615. renderSingleSided: {
  28616. get: function () {
  28617. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  28618. return undefined;
  28619. },
  28620. set: function () {
  28621. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  28622. }
  28623. }
  28624. });
  28625. function WebGLRenderTargetCube(width, height, options) {
  28626. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  28627. return new WebGLCubeRenderTarget(width, options);
  28628. } //
  28629. Object.defineProperties(WebGLRenderTarget.prototype, {
  28630. wrapS: {
  28631. get: function () {
  28632. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  28633. return this.texture.wrapS;
  28634. },
  28635. set: function (value) {
  28636. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  28637. this.texture.wrapS = value;
  28638. }
  28639. },
  28640. wrapT: {
  28641. get: function () {
  28642. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  28643. return this.texture.wrapT;
  28644. },
  28645. set: function (value) {
  28646. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  28647. this.texture.wrapT = value;
  28648. }
  28649. },
  28650. magFilter: {
  28651. get: function () {
  28652. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  28653. return this.texture.magFilter;
  28654. },
  28655. set: function (value) {
  28656. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  28657. this.texture.magFilter = value;
  28658. }
  28659. },
  28660. minFilter: {
  28661. get: function () {
  28662. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  28663. return this.texture.minFilter;
  28664. },
  28665. set: function (value) {
  28666. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  28667. this.texture.minFilter = value;
  28668. }
  28669. },
  28670. anisotropy: {
  28671. get: function () {
  28672. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  28673. return this.texture.anisotropy;
  28674. },
  28675. set: function (value) {
  28676. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  28677. this.texture.anisotropy = value;
  28678. }
  28679. },
  28680. offset: {
  28681. get: function () {
  28682. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  28683. return this.texture.offset;
  28684. },
  28685. set: function (value) {
  28686. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  28687. this.texture.offset = value;
  28688. }
  28689. },
  28690. repeat: {
  28691. get: function () {
  28692. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  28693. return this.texture.repeat;
  28694. },
  28695. set: function (value) {
  28696. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  28697. this.texture.repeat = value;
  28698. }
  28699. },
  28700. format: {
  28701. get: function () {
  28702. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  28703. return this.texture.format;
  28704. },
  28705. set: function (value) {
  28706. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  28707. this.texture.format = value;
  28708. }
  28709. },
  28710. type: {
  28711. get: function () {
  28712. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  28713. return this.texture.type;
  28714. },
  28715. set: function (value) {
  28716. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  28717. this.texture.type = value;
  28718. }
  28719. },
  28720. generateMipmaps: {
  28721. get: function () {
  28722. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  28723. return this.texture.generateMipmaps;
  28724. },
  28725. set: function (value) {
  28726. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  28727. this.texture.generateMipmaps = value;
  28728. }
  28729. }
  28730. }); //
  28731. Audio.prototype.load = function (file) {
  28732. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  28733. const scope = this;
  28734. const audioLoader = new AudioLoader();
  28735. audioLoader.load(file, function (buffer) {
  28736. scope.setBuffer(buffer);
  28737. });
  28738. return this;
  28739. };
  28740. AudioAnalyser.prototype.getData = function () {
  28741. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  28742. return this.getFrequencyData();
  28743. }; //
  28744. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  28745. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  28746. return this.update(renderer, scene);
  28747. };
  28748. CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
  28749. console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
  28750. return this.renderTarget.clear(renderer, color, depth, stencil);
  28751. };
  28752. ImageUtils.crossOrigin = undefined;
  28753. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  28754. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  28755. const loader = new TextureLoader();
  28756. loader.setCrossOrigin(this.crossOrigin);
  28757. const texture = loader.load(url, onLoad, undefined, onError);
  28758. if (mapping) texture.mapping = mapping;
  28759. return texture;
  28760. };
  28761. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  28762. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  28763. const loader = new CubeTextureLoader();
  28764. loader.setCrossOrigin(this.crossOrigin);
  28765. const texture = loader.load(urls, onLoad, undefined, onError);
  28766. if (mapping) texture.mapping = mapping;
  28767. return texture;
  28768. };
  28769. ImageUtils.loadCompressedTexture = function () {
  28770. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  28771. };
  28772. ImageUtils.loadCompressedTextureCube = function () {
  28773. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  28774. }; //
  28775. function CanvasRenderer() {
  28776. console.error('THREE.CanvasRenderer has been removed');
  28777. } //
  28778. function JSONLoader() {
  28779. console.error('THREE.JSONLoader has been removed.');
  28780. } //
  28781. const SceneUtils = {
  28782. createMultiMaterialObject: function ()
  28783. /* geometry, materials */
  28784. {
  28785. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28786. },
  28787. detach: function ()
  28788. /* child, parent, scene */
  28789. {
  28790. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28791. },
  28792. attach: function ()
  28793. /* child, scene, parent */
  28794. {
  28795. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28796. }
  28797. }; //
  28798. function LensFlare() {
  28799. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  28800. }
  28801. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  28802. /* eslint-disable no-undef */
  28803. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  28804. detail: {
  28805. revision: REVISION
  28806. }
  28807. }));
  28808. /* eslint-enable no-undef */
  28809. }
  28810. if (typeof window !== 'undefined') {
  28811. if (window.__THREE__) {
  28812. console.warn('WARNING: Multiple instances of Three.js being imported.');
  28813. } else {
  28814. window.__THREE__ = REVISION;
  28815. }
  28816. }
  28817. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  28818. exports.AddEquation = AddEquation;
  28819. exports.AddOperation = AddOperation;
  28820. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  28821. exports.AdditiveBlending = AdditiveBlending;
  28822. exports.AlphaFormat = AlphaFormat;
  28823. exports.AlwaysDepth = AlwaysDepth;
  28824. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  28825. exports.AmbientLight = AmbientLight;
  28826. exports.AmbientLightProbe = AmbientLightProbe;
  28827. exports.AnimationClip = AnimationClip;
  28828. exports.AnimationLoader = AnimationLoader;
  28829. exports.AnimationMixer = AnimationMixer;
  28830. exports.AnimationObjectGroup = AnimationObjectGroup;
  28831. exports.AnimationUtils = AnimationUtils;
  28832. exports.ArcCurve = ArcCurve;
  28833. exports.ArrayCamera = ArrayCamera;
  28834. exports.ArrowHelper = ArrowHelper;
  28835. exports.Audio = Audio;
  28836. exports.AudioAnalyser = AudioAnalyser;
  28837. exports.AudioContext = AudioContext;
  28838. exports.AudioListener = AudioListener;
  28839. exports.AudioLoader = AudioLoader;
  28840. exports.AxesHelper = AxesHelper;
  28841. exports.AxisHelper = AxisHelper;
  28842. exports.BackSide = BackSide;
  28843. exports.BasicDepthPacking = BasicDepthPacking;
  28844. exports.BasicShadowMap = BasicShadowMap;
  28845. exports.BinaryTextureLoader = BinaryTextureLoader;
  28846. exports.Bone = Bone;
  28847. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  28848. exports.BoundingBoxHelper = BoundingBoxHelper;
  28849. exports.Box2 = Box2;
  28850. exports.Box3 = Box3;
  28851. exports.Box3Helper = Box3Helper;
  28852. exports.BoxBufferGeometry = BoxGeometry;
  28853. exports.BoxGeometry = BoxGeometry;
  28854. exports.BoxHelper = BoxHelper;
  28855. exports.BufferAttribute = BufferAttribute;
  28856. exports.BufferGeometry = BufferGeometry;
  28857. exports.BufferGeometryLoader = BufferGeometryLoader;
  28858. exports.ByteType = ByteType;
  28859. exports.Cache = Cache;
  28860. exports.Camera = Camera;
  28861. exports.CameraHelper = CameraHelper;
  28862. exports.CanvasRenderer = CanvasRenderer;
  28863. exports.CanvasTexture = CanvasTexture;
  28864. exports.CatmullRomCurve3 = CatmullRomCurve3;
  28865. exports.CineonToneMapping = CineonToneMapping;
  28866. exports.CircleBufferGeometry = CircleGeometry;
  28867. exports.CircleGeometry = CircleGeometry;
  28868. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  28869. exports.Clock = Clock;
  28870. exports.Color = Color;
  28871. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  28872. exports.CompressedTexture = CompressedTexture;
  28873. exports.CompressedTextureLoader = CompressedTextureLoader;
  28874. exports.ConeBufferGeometry = ConeGeometry;
  28875. exports.ConeGeometry = ConeGeometry;
  28876. exports.CubeCamera = CubeCamera;
  28877. exports.CubeReflectionMapping = CubeReflectionMapping;
  28878. exports.CubeRefractionMapping = CubeRefractionMapping;
  28879. exports.CubeTexture = CubeTexture;
  28880. exports.CubeTextureLoader = CubeTextureLoader;
  28881. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  28882. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  28883. exports.CubicBezierCurve = CubicBezierCurve;
  28884. exports.CubicBezierCurve3 = CubicBezierCurve3;
  28885. exports.CubicInterpolant = CubicInterpolant;
  28886. exports.CullFaceBack = CullFaceBack;
  28887. exports.CullFaceFront = CullFaceFront;
  28888. exports.CullFaceFrontBack = CullFaceFrontBack;
  28889. exports.CullFaceNone = CullFaceNone;
  28890. exports.Curve = Curve;
  28891. exports.CurvePath = CurvePath;
  28892. exports.CustomBlending = CustomBlending;
  28893. exports.CustomToneMapping = CustomToneMapping;
  28894. exports.CylinderBufferGeometry = CylinderGeometry;
  28895. exports.CylinderGeometry = CylinderGeometry;
  28896. exports.Cylindrical = Cylindrical;
  28897. exports.DataTexture = DataTexture;
  28898. exports.DataTexture2DArray = DataTexture2DArray;
  28899. exports.DataTexture3D = DataTexture3D;
  28900. exports.DataTextureLoader = DataTextureLoader;
  28901. exports.DataUtils = DataUtils;
  28902. exports.DecrementStencilOp = DecrementStencilOp;
  28903. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  28904. exports.DefaultLoadingManager = DefaultLoadingManager;
  28905. exports.DepthFormat = DepthFormat;
  28906. exports.DepthStencilFormat = DepthStencilFormat;
  28907. exports.DepthTexture = DepthTexture;
  28908. exports.DirectionalLight = DirectionalLight;
  28909. exports.DirectionalLightHelper = DirectionalLightHelper;
  28910. exports.DiscreteInterpolant = DiscreteInterpolant;
  28911. exports.DodecahedronBufferGeometry = DodecahedronGeometry;
  28912. exports.DodecahedronGeometry = DodecahedronGeometry;
  28913. exports.DoubleSide = DoubleSide;
  28914. exports.DstAlphaFactor = DstAlphaFactor;
  28915. exports.DstColorFactor = DstColorFactor;
  28916. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  28917. exports.DynamicCopyUsage = DynamicCopyUsage;
  28918. exports.DynamicDrawUsage = DynamicDrawUsage;
  28919. exports.DynamicReadUsage = DynamicReadUsage;
  28920. exports.EdgesGeometry = EdgesGeometry;
  28921. exports.EdgesHelper = EdgesHelper;
  28922. exports.EllipseCurve = EllipseCurve;
  28923. exports.EqualDepth = EqualDepth;
  28924. exports.EqualStencilFunc = EqualStencilFunc;
  28925. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  28926. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  28927. exports.Euler = Euler;
  28928. exports.EventDispatcher = EventDispatcher;
  28929. exports.ExtrudeBufferGeometry = ExtrudeGeometry;
  28930. exports.ExtrudeGeometry = ExtrudeGeometry;
  28931. exports.FaceColors = FaceColors;
  28932. exports.FileLoader = FileLoader;
  28933. exports.FlatShading = FlatShading;
  28934. exports.Float16BufferAttribute = Float16BufferAttribute;
  28935. exports.Float32Attribute = Float32Attribute;
  28936. exports.Float32BufferAttribute = Float32BufferAttribute;
  28937. exports.Float64Attribute = Float64Attribute;
  28938. exports.Float64BufferAttribute = Float64BufferAttribute;
  28939. exports.FloatType = FloatType;
  28940. exports.Fog = Fog;
  28941. exports.FogExp2 = FogExp2;
  28942. exports.Font = Font;
  28943. exports.FontLoader = FontLoader;
  28944. exports.FrontSide = FrontSide;
  28945. exports.Frustum = Frustum;
  28946. exports.GLBufferAttribute = GLBufferAttribute;
  28947. exports.GLSL1 = GLSL1;
  28948. exports.GLSL3 = GLSL3;
  28949. exports.GammaEncoding = GammaEncoding;
  28950. exports.GreaterDepth = GreaterDepth;
  28951. exports.GreaterEqualDepth = GreaterEqualDepth;
  28952. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  28953. exports.GreaterStencilFunc = GreaterStencilFunc;
  28954. exports.GridHelper = GridHelper;
  28955. exports.Group = Group;
  28956. exports.HalfFloatType = HalfFloatType;
  28957. exports.HemisphereLight = HemisphereLight;
  28958. exports.HemisphereLightHelper = HemisphereLightHelper;
  28959. exports.HemisphereLightProbe = HemisphereLightProbe;
  28960. exports.IcosahedronBufferGeometry = IcosahedronGeometry;
  28961. exports.IcosahedronGeometry = IcosahedronGeometry;
  28962. exports.ImageBitmapLoader = ImageBitmapLoader;
  28963. exports.ImageLoader = ImageLoader;
  28964. exports.ImageUtils = ImageUtils;
  28965. exports.ImmediateRenderObject = ImmediateRenderObject;
  28966. exports.IncrementStencilOp = IncrementStencilOp;
  28967. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  28968. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  28969. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  28970. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  28971. exports.InstancedMesh = InstancedMesh;
  28972. exports.Int16Attribute = Int16Attribute;
  28973. exports.Int16BufferAttribute = Int16BufferAttribute;
  28974. exports.Int32Attribute = Int32Attribute;
  28975. exports.Int32BufferAttribute = Int32BufferAttribute;
  28976. exports.Int8Attribute = Int8Attribute;
  28977. exports.Int8BufferAttribute = Int8BufferAttribute;
  28978. exports.IntType = IntType;
  28979. exports.InterleavedBuffer = InterleavedBuffer;
  28980. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  28981. exports.Interpolant = Interpolant;
  28982. exports.InterpolateDiscrete = InterpolateDiscrete;
  28983. exports.InterpolateLinear = InterpolateLinear;
  28984. exports.InterpolateSmooth = InterpolateSmooth;
  28985. exports.InvertStencilOp = InvertStencilOp;
  28986. exports.JSONLoader = JSONLoader;
  28987. exports.KeepStencilOp = KeepStencilOp;
  28988. exports.KeyframeTrack = KeyframeTrack;
  28989. exports.LOD = LOD;
  28990. exports.LatheBufferGeometry = LatheGeometry;
  28991. exports.LatheGeometry = LatheGeometry;
  28992. exports.Layers = Layers;
  28993. exports.LensFlare = LensFlare;
  28994. exports.LessDepth = LessDepth;
  28995. exports.LessEqualDepth = LessEqualDepth;
  28996. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  28997. exports.LessStencilFunc = LessStencilFunc;
  28998. exports.Light = Light;
  28999. exports.LightProbe = LightProbe;
  29000. exports.Line = Line;
  29001. exports.Line3 = Line3;
  29002. exports.LineBasicMaterial = LineBasicMaterial;
  29003. exports.LineCurve = LineCurve;
  29004. exports.LineCurve3 = LineCurve3;
  29005. exports.LineDashedMaterial = LineDashedMaterial;
  29006. exports.LineLoop = LineLoop;
  29007. exports.LinePieces = LinePieces;
  29008. exports.LineSegments = LineSegments;
  29009. exports.LineStrip = LineStrip;
  29010. exports.LinearEncoding = LinearEncoding;
  29011. exports.LinearFilter = LinearFilter;
  29012. exports.LinearInterpolant = LinearInterpolant;
  29013. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  29014. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  29015. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  29016. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  29017. exports.LinearToneMapping = LinearToneMapping;
  29018. exports.Loader = Loader;
  29019. exports.LoaderUtils = LoaderUtils;
  29020. exports.LoadingManager = LoadingManager;
  29021. exports.LogLuvEncoding = LogLuvEncoding;
  29022. exports.LoopOnce = LoopOnce;
  29023. exports.LoopPingPong = LoopPingPong;
  29024. exports.LoopRepeat = LoopRepeat;
  29025. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  29026. exports.LuminanceFormat = LuminanceFormat;
  29027. exports.MOUSE = MOUSE;
  29028. exports.Material = Material;
  29029. exports.MaterialLoader = MaterialLoader;
  29030. exports.Math = MathUtils;
  29031. exports.MathUtils = MathUtils;
  29032. exports.Matrix3 = Matrix3;
  29033. exports.Matrix4 = Matrix4;
  29034. exports.MaxEquation = MaxEquation;
  29035. exports.Mesh = Mesh;
  29036. exports.MeshBasicMaterial = MeshBasicMaterial;
  29037. exports.MeshDepthMaterial = MeshDepthMaterial;
  29038. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  29039. exports.MeshFaceMaterial = MeshFaceMaterial;
  29040. exports.MeshLambertMaterial = MeshLambertMaterial;
  29041. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  29042. exports.MeshNormalMaterial = MeshNormalMaterial;
  29043. exports.MeshPhongMaterial = MeshPhongMaterial;
  29044. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  29045. exports.MeshStandardMaterial = MeshStandardMaterial;
  29046. exports.MeshToonMaterial = MeshToonMaterial;
  29047. exports.MinEquation = MinEquation;
  29048. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  29049. exports.MixOperation = MixOperation;
  29050. exports.MultiMaterial = MultiMaterial;
  29051. exports.MultiplyBlending = MultiplyBlending;
  29052. exports.MultiplyOperation = MultiplyOperation;
  29053. exports.NearestFilter = NearestFilter;
  29054. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  29055. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  29056. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  29057. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  29058. exports.NeverDepth = NeverDepth;
  29059. exports.NeverStencilFunc = NeverStencilFunc;
  29060. exports.NoBlending = NoBlending;
  29061. exports.NoColors = NoColors;
  29062. exports.NoToneMapping = NoToneMapping;
  29063. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  29064. exports.NormalBlending = NormalBlending;
  29065. exports.NotEqualDepth = NotEqualDepth;
  29066. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  29067. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  29068. exports.Object3D = Object3D;
  29069. exports.ObjectLoader = ObjectLoader;
  29070. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  29071. exports.OctahedronBufferGeometry = OctahedronGeometry;
  29072. exports.OctahedronGeometry = OctahedronGeometry;
  29073. exports.OneFactor = OneFactor;
  29074. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  29075. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  29076. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  29077. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  29078. exports.OrthographicCamera = OrthographicCamera;
  29079. exports.PCFShadowMap = PCFShadowMap;
  29080. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  29081. exports.PMREMGenerator = PMREMGenerator;
  29082. exports.ParametricBufferGeometry = ParametricGeometry;
  29083. exports.ParametricGeometry = ParametricGeometry;
  29084. exports.Particle = Particle;
  29085. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  29086. exports.ParticleSystem = ParticleSystem;
  29087. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  29088. exports.Path = Path;
  29089. exports.PerspectiveCamera = PerspectiveCamera;
  29090. exports.Plane = Plane;
  29091. exports.PlaneBufferGeometry = PlaneGeometry;
  29092. exports.PlaneGeometry = PlaneGeometry;
  29093. exports.PlaneHelper = PlaneHelper;
  29094. exports.PointCloud = PointCloud;
  29095. exports.PointCloudMaterial = PointCloudMaterial;
  29096. exports.PointLight = PointLight;
  29097. exports.PointLightHelper = PointLightHelper;
  29098. exports.Points = Points;
  29099. exports.PointsMaterial = PointsMaterial;
  29100. exports.PolarGridHelper = PolarGridHelper;
  29101. exports.PolyhedronBufferGeometry = PolyhedronGeometry;
  29102. exports.PolyhedronGeometry = PolyhedronGeometry;
  29103. exports.PositionalAudio = PositionalAudio;
  29104. exports.PropertyBinding = PropertyBinding;
  29105. exports.PropertyMixer = PropertyMixer;
  29106. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  29107. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  29108. exports.Quaternion = Quaternion;
  29109. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  29110. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  29111. exports.REVISION = REVISION;
  29112. exports.RGBADepthPacking = RGBADepthPacking;
  29113. exports.RGBAFormat = RGBAFormat;
  29114. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  29115. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  29116. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  29117. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  29118. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  29119. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  29120. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  29121. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  29122. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  29123. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  29124. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  29125. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  29126. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  29127. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  29128. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  29129. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  29130. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  29131. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  29132. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  29133. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  29134. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  29135. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  29136. exports.RGBDEncoding = RGBDEncoding;
  29137. exports.RGBEEncoding = RGBEEncoding;
  29138. exports.RGBEFormat = RGBEFormat;
  29139. exports.RGBFormat = RGBFormat;
  29140. exports.RGBIntegerFormat = RGBIntegerFormat;
  29141. exports.RGBM16Encoding = RGBM16Encoding;
  29142. exports.RGBM7Encoding = RGBM7Encoding;
  29143. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  29144. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  29145. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  29146. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  29147. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  29148. exports.RGFormat = RGFormat;
  29149. exports.RGIntegerFormat = RGIntegerFormat;
  29150. exports.RawShaderMaterial = RawShaderMaterial;
  29151. exports.Ray = Ray;
  29152. exports.Raycaster = Raycaster;
  29153. exports.RectAreaLight = RectAreaLight;
  29154. exports.RedFormat = RedFormat;
  29155. exports.RedIntegerFormat = RedIntegerFormat;
  29156. exports.ReinhardToneMapping = ReinhardToneMapping;
  29157. exports.RepeatWrapping = RepeatWrapping;
  29158. exports.ReplaceStencilOp = ReplaceStencilOp;
  29159. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  29160. exports.RingBufferGeometry = RingGeometry;
  29161. exports.RingGeometry = RingGeometry;
  29162. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  29163. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  29164. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  29165. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  29166. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  29167. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  29168. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  29169. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  29170. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  29171. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  29172. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  29173. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  29174. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  29175. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  29176. exports.Scene = Scene;
  29177. exports.SceneUtils = SceneUtils;
  29178. exports.ShaderChunk = ShaderChunk;
  29179. exports.ShaderLib = ShaderLib;
  29180. exports.ShaderMaterial = ShaderMaterial;
  29181. exports.ShadowMaterial = ShadowMaterial;
  29182. exports.Shape = Shape;
  29183. exports.ShapeBufferGeometry = ShapeGeometry;
  29184. exports.ShapeGeometry = ShapeGeometry;
  29185. exports.ShapePath = ShapePath;
  29186. exports.ShapeUtils = ShapeUtils;
  29187. exports.ShortType = ShortType;
  29188. exports.Skeleton = Skeleton;
  29189. exports.SkeletonHelper = SkeletonHelper;
  29190. exports.SkinnedMesh = SkinnedMesh;
  29191. exports.SmoothShading = SmoothShading;
  29192. exports.Sphere = Sphere;
  29193. exports.SphereBufferGeometry = SphereGeometry;
  29194. exports.SphereGeometry = SphereGeometry;
  29195. exports.Spherical = Spherical;
  29196. exports.SphericalHarmonics3 = SphericalHarmonics3;
  29197. exports.SplineCurve = SplineCurve;
  29198. exports.SpotLight = SpotLight;
  29199. exports.SpotLightHelper = SpotLightHelper;
  29200. exports.Sprite = Sprite;
  29201. exports.SpriteMaterial = SpriteMaterial;
  29202. exports.SrcAlphaFactor = SrcAlphaFactor;
  29203. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  29204. exports.SrcColorFactor = SrcColorFactor;
  29205. exports.StaticCopyUsage = StaticCopyUsage;
  29206. exports.StaticDrawUsage = StaticDrawUsage;
  29207. exports.StaticReadUsage = StaticReadUsage;
  29208. exports.StereoCamera = StereoCamera;
  29209. exports.StreamCopyUsage = StreamCopyUsage;
  29210. exports.StreamDrawUsage = StreamDrawUsage;
  29211. exports.StreamReadUsage = StreamReadUsage;
  29212. exports.StringKeyframeTrack = StringKeyframeTrack;
  29213. exports.SubtractEquation = SubtractEquation;
  29214. exports.SubtractiveBlending = SubtractiveBlending;
  29215. exports.TOUCH = TOUCH;
  29216. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  29217. exports.TetrahedronBufferGeometry = TetrahedronGeometry;
  29218. exports.TetrahedronGeometry = TetrahedronGeometry;
  29219. exports.TextBufferGeometry = TextGeometry;
  29220. exports.TextGeometry = TextGeometry;
  29221. exports.Texture = Texture;
  29222. exports.TextureLoader = TextureLoader;
  29223. exports.TorusBufferGeometry = TorusGeometry;
  29224. exports.TorusGeometry = TorusGeometry;
  29225. exports.TorusKnotBufferGeometry = TorusKnotGeometry;
  29226. exports.TorusKnotGeometry = TorusKnotGeometry;
  29227. exports.Triangle = Triangle;
  29228. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  29229. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  29230. exports.TrianglesDrawMode = TrianglesDrawMode;
  29231. exports.TubeBufferGeometry = TubeGeometry;
  29232. exports.TubeGeometry = TubeGeometry;
  29233. exports.UVMapping = UVMapping;
  29234. exports.Uint16Attribute = Uint16Attribute;
  29235. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  29236. exports.Uint32Attribute = Uint32Attribute;
  29237. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  29238. exports.Uint8Attribute = Uint8Attribute;
  29239. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  29240. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  29241. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  29242. exports.Uniform = Uniform;
  29243. exports.UniformsLib = UniformsLib;
  29244. exports.UniformsUtils = UniformsUtils;
  29245. exports.UnsignedByteType = UnsignedByteType;
  29246. exports.UnsignedInt248Type = UnsignedInt248Type;
  29247. exports.UnsignedIntType = UnsignedIntType;
  29248. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  29249. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  29250. exports.UnsignedShort565Type = UnsignedShort565Type;
  29251. exports.UnsignedShortType = UnsignedShortType;
  29252. exports.VSMShadowMap = VSMShadowMap;
  29253. exports.Vector2 = Vector2;
  29254. exports.Vector3 = Vector3;
  29255. exports.Vector4 = Vector4;
  29256. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  29257. exports.Vertex = Vertex;
  29258. exports.VertexColors = VertexColors;
  29259. exports.VideoTexture = VideoTexture;
  29260. exports.WebGL1Renderer = WebGL1Renderer;
  29261. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  29262. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  29263. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  29264. exports.WebGLRenderTarget = WebGLRenderTarget;
  29265. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  29266. exports.WebGLRenderer = WebGLRenderer;
  29267. exports.WebGLUtils = WebGLUtils;
  29268. exports.WireframeGeometry = WireframeGeometry;
  29269. exports.WireframeHelper = WireframeHelper;
  29270. exports.WrapAroundEnding = WrapAroundEnding;
  29271. exports.XHRLoader = XHRLoader;
  29272. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  29273. exports.ZeroFactor = ZeroFactor;
  29274. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  29275. exports.ZeroStencilOp = ZeroStencilOp;
  29276. exports.sRGBEncoding = sRGBEncoding;
  29277. Object.defineProperty(exports, '__esModule', { value: true });
  29278. })));
粤ICP备19079148号