three.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414
  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 = '133';
  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. let _seed = 1234567;
  262. const DEG2RAD = Math.PI / 180;
  263. const RAD2DEG = 180 / Math.PI; //
  264. const _lut = [];
  265. for (let i = 0; i < 256; i++) {
  266. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  267. }
  268. const hasRandomUUID = typeof crypto !== 'undefined' && 'randomUUID' in crypto;
  269. function generateUUID() {
  270. if (hasRandomUUID) {
  271. return crypto.randomUUID().toUpperCase();
  272. } // TODO Remove this code when crypto.randomUUID() is available everywhere
  273. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  274. const d0 = Math.random() * 0xffffffff | 0;
  275. const d1 = Math.random() * 0xffffffff | 0;
  276. const d2 = Math.random() * 0xffffffff | 0;
  277. const d3 = Math.random() * 0xffffffff | 0;
  278. 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.
  279. return uuid.toUpperCase();
  280. }
  281. function clamp(value, min, max) {
  282. return Math.max(min, Math.min(max, value));
  283. } // compute euclidian modulo of m % n
  284. // https://en.wikipedia.org/wiki/Modulo_operation
  285. function euclideanModulo(n, m) {
  286. return (n % m + m) % m;
  287. } // Linear mapping from range <a1, a2> to range <b1, b2>
  288. function mapLinear(x, a1, a2, b1, b2) {
  289. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  290. } // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  291. function inverseLerp(x, y, value) {
  292. if (x !== y) {
  293. return (value - x) / (y - x);
  294. } else {
  295. return 0;
  296. }
  297. } // https://en.wikipedia.org/wiki/Linear_interpolation
  298. function lerp(x, y, t) {
  299. return (1 - t) * x + t * y;
  300. } // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  301. function damp(x, y, lambda, dt) {
  302. return lerp(x, y, 1 - Math.exp(-lambda * dt));
  303. } // https://www.desmos.com/calculator/vcsjnyz7x4
  304. function pingpong(x, length = 1) {
  305. return length - Math.abs(euclideanModulo(x, length * 2) - length);
  306. } // http://en.wikipedia.org/wiki/Smoothstep
  307. function smoothstep(x, min, max) {
  308. if (x <= min) return 0;
  309. if (x >= max) return 1;
  310. x = (x - min) / (max - min);
  311. return x * x * (3 - 2 * x);
  312. }
  313. function smootherstep(x, min, max) {
  314. if (x <= min) return 0;
  315. if (x >= max) return 1;
  316. x = (x - min) / (max - min);
  317. return x * x * x * (x * (x * 6 - 15) + 10);
  318. } // Random integer from <low, high> interval
  319. function randInt(low, high) {
  320. return low + Math.floor(Math.random() * (high - low + 1));
  321. } // Random float from <low, high> interval
  322. function randFloat(low, high) {
  323. return low + Math.random() * (high - low);
  324. } // Random float from <-range/2, range/2> interval
  325. function randFloatSpread(range) {
  326. return range * (0.5 - Math.random());
  327. } // Deterministic pseudo-random float in the interval [ 0, 1 ]
  328. function seededRandom(s) {
  329. if (s !== undefined) _seed = s % 2147483647; // Park-Miller algorithm
  330. _seed = _seed * 16807 % 2147483647;
  331. return (_seed - 1) / 2147483646;
  332. }
  333. function degToRad(degrees) {
  334. return degrees * DEG2RAD;
  335. }
  336. function radToDeg(radians) {
  337. return radians * RAD2DEG;
  338. }
  339. function isPowerOfTwo(value) {
  340. return (value & value - 1) === 0 && value !== 0;
  341. }
  342. function ceilPowerOfTwo(value) {
  343. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  344. }
  345. function floorPowerOfTwo(value) {
  346. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  347. }
  348. function setQuaternionFromProperEuler(q, a, b, c, order) {
  349. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  350. // rotations are applied to the axes in the order specified by 'order'
  351. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  352. // angles are in radians
  353. const cos = Math.cos;
  354. const sin = Math.sin;
  355. const c2 = cos(b / 2);
  356. const s2 = sin(b / 2);
  357. const c13 = cos((a + c) / 2);
  358. const s13 = sin((a + c) / 2);
  359. const c1_3 = cos((a - c) / 2);
  360. const s1_3 = sin((a - c) / 2);
  361. const c3_1 = cos((c - a) / 2);
  362. const s3_1 = sin((c - a) / 2);
  363. switch (order) {
  364. case 'XYX':
  365. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  366. break;
  367. case 'YZY':
  368. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  369. break;
  370. case 'ZXZ':
  371. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  372. break;
  373. case 'XZX':
  374. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  375. break;
  376. case 'YXY':
  377. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  378. break;
  379. case 'ZYZ':
  380. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  381. break;
  382. default:
  383. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
  384. }
  385. }
  386. var MathUtils = /*#__PURE__*/Object.freeze({
  387. __proto__: null,
  388. DEG2RAD: DEG2RAD,
  389. RAD2DEG: RAD2DEG,
  390. generateUUID: generateUUID,
  391. clamp: clamp,
  392. euclideanModulo: euclideanModulo,
  393. mapLinear: mapLinear,
  394. inverseLerp: inverseLerp,
  395. lerp: lerp,
  396. damp: damp,
  397. pingpong: pingpong,
  398. smoothstep: smoothstep,
  399. smootherstep: smootherstep,
  400. randInt: randInt,
  401. randFloat: randFloat,
  402. randFloatSpread: randFloatSpread,
  403. seededRandom: seededRandom,
  404. degToRad: degToRad,
  405. radToDeg: radToDeg,
  406. isPowerOfTwo: isPowerOfTwo,
  407. ceilPowerOfTwo: ceilPowerOfTwo,
  408. floorPowerOfTwo: floorPowerOfTwo,
  409. setQuaternionFromProperEuler: setQuaternionFromProperEuler
  410. });
  411. class Vector2 {
  412. constructor(x = 0, y = 0) {
  413. this.x = x;
  414. this.y = y;
  415. }
  416. get width() {
  417. return this.x;
  418. }
  419. set width(value) {
  420. this.x = value;
  421. }
  422. get height() {
  423. return this.y;
  424. }
  425. set height(value) {
  426. this.y = value;
  427. }
  428. set(x, y) {
  429. this.x = x;
  430. this.y = y;
  431. return this;
  432. }
  433. setScalar(scalar) {
  434. this.x = scalar;
  435. this.y = scalar;
  436. return this;
  437. }
  438. setX(x) {
  439. this.x = x;
  440. return this;
  441. }
  442. setY(y) {
  443. this.y = y;
  444. return this;
  445. }
  446. setComponent(index, value) {
  447. switch (index) {
  448. case 0:
  449. this.x = value;
  450. break;
  451. case 1:
  452. this.y = value;
  453. break;
  454. default:
  455. throw new Error('index is out of range: ' + index);
  456. }
  457. return this;
  458. }
  459. getComponent(index) {
  460. switch (index) {
  461. case 0:
  462. return this.x;
  463. case 1:
  464. return this.y;
  465. default:
  466. throw new Error('index is out of range: ' + index);
  467. }
  468. }
  469. clone() {
  470. return new this.constructor(this.x, this.y);
  471. }
  472. copy(v) {
  473. this.x = v.x;
  474. this.y = v.y;
  475. return this;
  476. }
  477. add(v, w) {
  478. if (w !== undefined) {
  479. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  480. return this.addVectors(v, w);
  481. }
  482. this.x += v.x;
  483. this.y += v.y;
  484. return this;
  485. }
  486. addScalar(s) {
  487. this.x += s;
  488. this.y += s;
  489. return this;
  490. }
  491. addVectors(a, b) {
  492. this.x = a.x + b.x;
  493. this.y = a.y + b.y;
  494. return this;
  495. }
  496. addScaledVector(v, s) {
  497. this.x += v.x * s;
  498. this.y += v.y * s;
  499. return this;
  500. }
  501. sub(v, w) {
  502. if (w !== undefined) {
  503. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  504. return this.subVectors(v, w);
  505. }
  506. this.x -= v.x;
  507. this.y -= v.y;
  508. return this;
  509. }
  510. subScalar(s) {
  511. this.x -= s;
  512. this.y -= s;
  513. return this;
  514. }
  515. subVectors(a, b) {
  516. this.x = a.x - b.x;
  517. this.y = a.y - b.y;
  518. return this;
  519. }
  520. multiply(v) {
  521. this.x *= v.x;
  522. this.y *= v.y;
  523. return this;
  524. }
  525. multiplyScalar(scalar) {
  526. this.x *= scalar;
  527. this.y *= scalar;
  528. return this;
  529. }
  530. divide(v) {
  531. this.x /= v.x;
  532. this.y /= v.y;
  533. return this;
  534. }
  535. divideScalar(scalar) {
  536. return this.multiplyScalar(1 / scalar);
  537. }
  538. applyMatrix3(m) {
  539. const x = this.x,
  540. y = this.y;
  541. const e = m.elements;
  542. this.x = e[0] * x + e[3] * y + e[6];
  543. this.y = e[1] * x + e[4] * y + e[7];
  544. return this;
  545. }
  546. min(v) {
  547. this.x = Math.min(this.x, v.x);
  548. this.y = Math.min(this.y, v.y);
  549. return this;
  550. }
  551. max(v) {
  552. this.x = Math.max(this.x, v.x);
  553. this.y = Math.max(this.y, v.y);
  554. return this;
  555. }
  556. clamp(min, max) {
  557. // assumes min < max, componentwise
  558. this.x = Math.max(min.x, Math.min(max.x, this.x));
  559. this.y = Math.max(min.y, Math.min(max.y, this.y));
  560. return this;
  561. }
  562. clampScalar(minVal, maxVal) {
  563. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  564. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  565. return this;
  566. }
  567. clampLength(min, max) {
  568. const length = this.length();
  569. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  570. }
  571. floor() {
  572. this.x = Math.floor(this.x);
  573. this.y = Math.floor(this.y);
  574. return this;
  575. }
  576. ceil() {
  577. this.x = Math.ceil(this.x);
  578. this.y = Math.ceil(this.y);
  579. return this;
  580. }
  581. round() {
  582. this.x = Math.round(this.x);
  583. this.y = Math.round(this.y);
  584. return this;
  585. }
  586. roundToZero() {
  587. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  588. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  589. return this;
  590. }
  591. negate() {
  592. this.x = -this.x;
  593. this.y = -this.y;
  594. return this;
  595. }
  596. dot(v) {
  597. return this.x * v.x + this.y * v.y;
  598. }
  599. cross(v) {
  600. return this.x * v.y - this.y * v.x;
  601. }
  602. lengthSq() {
  603. return this.x * this.x + this.y * this.y;
  604. }
  605. length() {
  606. return Math.sqrt(this.x * this.x + this.y * this.y);
  607. }
  608. manhattanLength() {
  609. return Math.abs(this.x) + Math.abs(this.y);
  610. }
  611. normalize() {
  612. return this.divideScalar(this.length() || 1);
  613. }
  614. angle() {
  615. // computes the angle in radians with respect to the positive x-axis
  616. const angle = Math.atan2(-this.y, -this.x) + Math.PI;
  617. return angle;
  618. }
  619. distanceTo(v) {
  620. return Math.sqrt(this.distanceToSquared(v));
  621. }
  622. distanceToSquared(v) {
  623. const dx = this.x - v.x,
  624. dy = this.y - v.y;
  625. return dx * dx + dy * dy;
  626. }
  627. manhattanDistanceTo(v) {
  628. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  629. }
  630. setLength(length) {
  631. return this.normalize().multiplyScalar(length);
  632. }
  633. lerp(v, alpha) {
  634. this.x += (v.x - this.x) * alpha;
  635. this.y += (v.y - this.y) * alpha;
  636. return this;
  637. }
  638. lerpVectors(v1, v2, alpha) {
  639. this.x = v1.x + (v2.x - v1.x) * alpha;
  640. this.y = v1.y + (v2.y - v1.y) * alpha;
  641. return this;
  642. }
  643. equals(v) {
  644. return v.x === this.x && v.y === this.y;
  645. }
  646. fromArray(array, offset = 0) {
  647. this.x = array[offset];
  648. this.y = array[offset + 1];
  649. return this;
  650. }
  651. toArray(array = [], offset = 0) {
  652. array[offset] = this.x;
  653. array[offset + 1] = this.y;
  654. return array;
  655. }
  656. fromBufferAttribute(attribute, index, offset) {
  657. if (offset !== undefined) {
  658. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  659. }
  660. this.x = attribute.getX(index);
  661. this.y = attribute.getY(index);
  662. return this;
  663. }
  664. rotateAround(center, angle) {
  665. const c = Math.cos(angle),
  666. s = Math.sin(angle);
  667. const x = this.x - center.x;
  668. const y = this.y - center.y;
  669. this.x = x * c - y * s + center.x;
  670. this.y = x * s + y * c + center.y;
  671. return this;
  672. }
  673. random() {
  674. this.x = Math.random();
  675. this.y = Math.random();
  676. return this;
  677. }
  678. *[Symbol.iterator]() {
  679. yield this.x;
  680. yield this.y;
  681. }
  682. }
  683. Vector2.prototype.isVector2 = true;
  684. class Matrix3 {
  685. constructor() {
  686. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  687. if (arguments.length > 0) {
  688. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  689. }
  690. }
  691. set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  692. const te = this.elements;
  693. te[0] = n11;
  694. te[1] = n21;
  695. te[2] = n31;
  696. te[3] = n12;
  697. te[4] = n22;
  698. te[5] = n32;
  699. te[6] = n13;
  700. te[7] = n23;
  701. te[8] = n33;
  702. return this;
  703. }
  704. identity() {
  705. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  706. return this;
  707. }
  708. copy(m) {
  709. const te = this.elements;
  710. const me = m.elements;
  711. te[0] = me[0];
  712. te[1] = me[1];
  713. te[2] = me[2];
  714. te[3] = me[3];
  715. te[4] = me[4];
  716. te[5] = me[5];
  717. te[6] = me[6];
  718. te[7] = me[7];
  719. te[8] = me[8];
  720. return this;
  721. }
  722. extractBasis(xAxis, yAxis, zAxis) {
  723. xAxis.setFromMatrix3Column(this, 0);
  724. yAxis.setFromMatrix3Column(this, 1);
  725. zAxis.setFromMatrix3Column(this, 2);
  726. return this;
  727. }
  728. setFromMatrix4(m) {
  729. const me = m.elements;
  730. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  731. return this;
  732. }
  733. multiply(m) {
  734. return this.multiplyMatrices(this, m);
  735. }
  736. premultiply(m) {
  737. return this.multiplyMatrices(m, this);
  738. }
  739. multiplyMatrices(a, b) {
  740. const ae = a.elements;
  741. const be = b.elements;
  742. const te = this.elements;
  743. const a11 = ae[0],
  744. a12 = ae[3],
  745. a13 = ae[6];
  746. const a21 = ae[1],
  747. a22 = ae[4],
  748. a23 = ae[7];
  749. const a31 = ae[2],
  750. a32 = ae[5],
  751. a33 = ae[8];
  752. const b11 = be[0],
  753. b12 = be[3],
  754. b13 = be[6];
  755. const b21 = be[1],
  756. b22 = be[4],
  757. b23 = be[7];
  758. const b31 = be[2],
  759. b32 = be[5],
  760. b33 = be[8];
  761. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  762. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  763. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  764. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  765. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  766. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  767. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  768. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  769. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  770. return this;
  771. }
  772. multiplyScalar(s) {
  773. const te = this.elements;
  774. te[0] *= s;
  775. te[3] *= s;
  776. te[6] *= s;
  777. te[1] *= s;
  778. te[4] *= s;
  779. te[7] *= s;
  780. te[2] *= s;
  781. te[5] *= s;
  782. te[8] *= s;
  783. return this;
  784. }
  785. determinant() {
  786. const te = this.elements;
  787. const a = te[0],
  788. b = te[1],
  789. c = te[2],
  790. d = te[3],
  791. e = te[4],
  792. f = te[5],
  793. g = te[6],
  794. h = te[7],
  795. i = te[8];
  796. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  797. }
  798. invert() {
  799. const te = this.elements,
  800. n11 = te[0],
  801. n21 = te[1],
  802. n31 = te[2],
  803. n12 = te[3],
  804. n22 = te[4],
  805. n32 = te[5],
  806. n13 = te[6],
  807. n23 = te[7],
  808. n33 = te[8],
  809. t11 = n33 * n22 - n32 * n23,
  810. t12 = n32 * n13 - n33 * n12,
  811. t13 = n23 * n12 - n22 * n13,
  812. det = n11 * t11 + n21 * t12 + n31 * t13;
  813. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  814. const detInv = 1 / det;
  815. te[0] = t11 * detInv;
  816. te[1] = (n31 * n23 - n33 * n21) * detInv;
  817. te[2] = (n32 * n21 - n31 * n22) * detInv;
  818. te[3] = t12 * detInv;
  819. te[4] = (n33 * n11 - n31 * n13) * detInv;
  820. te[5] = (n31 * n12 - n32 * n11) * detInv;
  821. te[6] = t13 * detInv;
  822. te[7] = (n21 * n13 - n23 * n11) * detInv;
  823. te[8] = (n22 * n11 - n21 * n12) * detInv;
  824. return this;
  825. }
  826. transpose() {
  827. let tmp;
  828. const m = this.elements;
  829. tmp = m[1];
  830. m[1] = m[3];
  831. m[3] = tmp;
  832. tmp = m[2];
  833. m[2] = m[6];
  834. m[6] = tmp;
  835. tmp = m[5];
  836. m[5] = m[7];
  837. m[7] = tmp;
  838. return this;
  839. }
  840. getNormalMatrix(matrix4) {
  841. return this.setFromMatrix4(matrix4).invert().transpose();
  842. }
  843. transposeIntoArray(r) {
  844. const m = this.elements;
  845. r[0] = m[0];
  846. r[1] = m[3];
  847. r[2] = m[6];
  848. r[3] = m[1];
  849. r[4] = m[4];
  850. r[5] = m[7];
  851. r[6] = m[2];
  852. r[7] = m[5];
  853. r[8] = m[8];
  854. return this;
  855. }
  856. setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
  857. const c = Math.cos(rotation);
  858. const s = Math.sin(rotation);
  859. 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);
  860. return this;
  861. }
  862. scale(sx, sy) {
  863. const te = this.elements;
  864. te[0] *= sx;
  865. te[3] *= sx;
  866. te[6] *= sx;
  867. te[1] *= sy;
  868. te[4] *= sy;
  869. te[7] *= sy;
  870. return this;
  871. }
  872. rotate(theta) {
  873. const c = Math.cos(theta);
  874. const s = Math.sin(theta);
  875. const te = this.elements;
  876. const a11 = te[0],
  877. a12 = te[3],
  878. a13 = te[6];
  879. const a21 = te[1],
  880. a22 = te[4],
  881. a23 = te[7];
  882. te[0] = c * a11 + s * a21;
  883. te[3] = c * a12 + s * a22;
  884. te[6] = c * a13 + s * a23;
  885. te[1] = -s * a11 + c * a21;
  886. te[4] = -s * a12 + c * a22;
  887. te[7] = -s * a13 + c * a23;
  888. return this;
  889. }
  890. translate(tx, ty) {
  891. const te = this.elements;
  892. te[0] += tx * te[2];
  893. te[3] += tx * te[5];
  894. te[6] += tx * te[8];
  895. te[1] += ty * te[2];
  896. te[4] += ty * te[5];
  897. te[7] += ty * te[8];
  898. return this;
  899. }
  900. equals(matrix) {
  901. const te = this.elements;
  902. const me = matrix.elements;
  903. for (let i = 0; i < 9; i++) {
  904. if (te[i] !== me[i]) return false;
  905. }
  906. return true;
  907. }
  908. fromArray(array, offset = 0) {
  909. for (let i = 0; i < 9; i++) {
  910. this.elements[i] = array[i + offset];
  911. }
  912. return this;
  913. }
  914. toArray(array = [], offset = 0) {
  915. const te = this.elements;
  916. array[offset] = te[0];
  917. array[offset + 1] = te[1];
  918. array[offset + 2] = te[2];
  919. array[offset + 3] = te[3];
  920. array[offset + 4] = te[4];
  921. array[offset + 5] = te[5];
  922. array[offset + 6] = te[6];
  923. array[offset + 7] = te[7];
  924. array[offset + 8] = te[8];
  925. return array;
  926. }
  927. clone() {
  928. return new this.constructor().fromArray(this.elements);
  929. }
  930. }
  931. Matrix3.prototype.isMatrix3 = true;
  932. function arrayMax(array) {
  933. if (array.length === 0) return -Infinity;
  934. let max = array[0];
  935. for (let i = 1, l = array.length; i < l; ++i) {
  936. if (array[i] > max) max = array[i];
  937. }
  938. return max;
  939. }
  940. const TYPED_ARRAYS = {
  941. Int8Array: Int8Array,
  942. Uint8Array: Uint8Array,
  943. Uint8ClampedArray: Uint8ClampedArray,
  944. Int16Array: Int16Array,
  945. Uint16Array: Uint16Array,
  946. Int32Array: Int32Array,
  947. Uint32Array: Uint32Array,
  948. Float32Array: Float32Array,
  949. Float64Array: Float64Array
  950. };
  951. function getTypedArray(type, buffer) {
  952. return new TYPED_ARRAYS[type](buffer);
  953. }
  954. function createElementNS(name) {
  955. return document.createElementNS('http://www.w3.org/1999/xhtml', name);
  956. }
  957. let _canvas;
  958. class ImageUtils {
  959. static getDataURL(image) {
  960. if (/^data:/i.test(image.src)) {
  961. return image.src;
  962. }
  963. if (typeof HTMLCanvasElement == 'undefined') {
  964. return image.src;
  965. }
  966. let canvas;
  967. if (image instanceof HTMLCanvasElement) {
  968. canvas = image;
  969. } else {
  970. if (_canvas === undefined) _canvas = createElementNS('canvas');
  971. _canvas.width = image.width;
  972. _canvas.height = image.height;
  973. const context = _canvas.getContext('2d');
  974. if (image instanceof ImageData) {
  975. context.putImageData(image, 0, 0);
  976. } else {
  977. context.drawImage(image, 0, 0, image.width, image.height);
  978. }
  979. canvas = _canvas;
  980. }
  981. if (canvas.width > 2048 || canvas.height > 2048) {
  982. console.warn('THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image);
  983. return canvas.toDataURL('image/jpeg', 0.6);
  984. } else {
  985. return canvas.toDataURL('image/png');
  986. }
  987. }
  988. }
  989. let textureId = 0;
  990. class Texture extends EventDispatcher {
  991. 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) {
  992. super();
  993. Object.defineProperty(this, 'id', {
  994. value: textureId++
  995. });
  996. this.uuid = generateUUID();
  997. this.name = '';
  998. this.image = image;
  999. this.mipmaps = [];
  1000. this.mapping = mapping;
  1001. this.wrapS = wrapS;
  1002. this.wrapT = wrapT;
  1003. this.magFilter = magFilter;
  1004. this.minFilter = minFilter;
  1005. this.anisotropy = anisotropy;
  1006. this.format = format;
  1007. this.internalFormat = null;
  1008. this.type = type;
  1009. this.offset = new Vector2(0, 0);
  1010. this.repeat = new Vector2(1, 1);
  1011. this.center = new Vector2(0, 0);
  1012. this.rotation = 0;
  1013. this.matrixAutoUpdate = true;
  1014. this.matrix = new Matrix3();
  1015. this.generateMipmaps = true;
  1016. this.premultiplyAlpha = false;
  1017. this.flipY = true;
  1018. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1019. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1020. //
  1021. // Also changing the encoding after already used by a Material will not automatically make the Material
  1022. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1023. this.encoding = encoding;
  1024. this.version = 0;
  1025. this.onUpdate = null;
  1026. this.isRenderTargetTexture = false;
  1027. }
  1028. updateMatrix() {
  1029. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  1030. }
  1031. clone() {
  1032. return new this.constructor().copy(this);
  1033. }
  1034. copy(source) {
  1035. this.name = source.name;
  1036. this.image = source.image;
  1037. this.mipmaps = source.mipmaps.slice(0);
  1038. this.mapping = source.mapping;
  1039. this.wrapS = source.wrapS;
  1040. this.wrapT = source.wrapT;
  1041. this.magFilter = source.magFilter;
  1042. this.minFilter = source.minFilter;
  1043. this.anisotropy = source.anisotropy;
  1044. this.format = source.format;
  1045. this.internalFormat = source.internalFormat;
  1046. this.type = source.type;
  1047. this.offset.copy(source.offset);
  1048. this.repeat.copy(source.repeat);
  1049. this.center.copy(source.center);
  1050. this.rotation = source.rotation;
  1051. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1052. this.matrix.copy(source.matrix);
  1053. this.generateMipmaps = source.generateMipmaps;
  1054. this.premultiplyAlpha = source.premultiplyAlpha;
  1055. this.flipY = source.flipY;
  1056. this.unpackAlignment = source.unpackAlignment;
  1057. this.encoding = source.encoding;
  1058. return this;
  1059. }
  1060. toJSON(meta) {
  1061. const isRootObject = meta === undefined || typeof meta === 'string';
  1062. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1063. return meta.textures[this.uuid];
  1064. }
  1065. const output = {
  1066. metadata: {
  1067. version: 4.5,
  1068. type: 'Texture',
  1069. generator: 'Texture.toJSON'
  1070. },
  1071. uuid: this.uuid,
  1072. name: this.name,
  1073. mapping: this.mapping,
  1074. repeat: [this.repeat.x, this.repeat.y],
  1075. offset: [this.offset.x, this.offset.y],
  1076. center: [this.center.x, this.center.y],
  1077. rotation: this.rotation,
  1078. wrap: [this.wrapS, this.wrapT],
  1079. format: this.format,
  1080. type: this.type,
  1081. encoding: this.encoding,
  1082. minFilter: this.minFilter,
  1083. magFilter: this.magFilter,
  1084. anisotropy: this.anisotropy,
  1085. flipY: this.flipY,
  1086. premultiplyAlpha: this.premultiplyAlpha,
  1087. unpackAlignment: this.unpackAlignment
  1088. };
  1089. if (this.image !== undefined) {
  1090. // TODO: Move to THREE.Image
  1091. const image = this.image;
  1092. if (image.uuid === undefined) {
  1093. image.uuid = generateUUID(); // UGH
  1094. }
  1095. if (!isRootObject && meta.images[image.uuid] === undefined) {
  1096. let url;
  1097. if (Array.isArray(image)) {
  1098. // process array of images e.g. CubeTexture
  1099. url = [];
  1100. for (let i = 0, l = image.length; i < l; i++) {
  1101. // check cube texture with data textures
  1102. if (image[i].isDataTexture) {
  1103. url.push(serializeImage(image[i].image));
  1104. } else {
  1105. url.push(serializeImage(image[i]));
  1106. }
  1107. }
  1108. } else {
  1109. // process single image
  1110. url = serializeImage(image);
  1111. }
  1112. meta.images[image.uuid] = {
  1113. uuid: image.uuid,
  1114. url: url
  1115. };
  1116. }
  1117. output.image = image.uuid;
  1118. }
  1119. if (!isRootObject) {
  1120. meta.textures[this.uuid] = output;
  1121. }
  1122. return output;
  1123. }
  1124. dispose() {
  1125. this.dispatchEvent({
  1126. type: 'dispose'
  1127. });
  1128. }
  1129. transformUv(uv) {
  1130. if (this.mapping !== UVMapping) return uv;
  1131. uv.applyMatrix3(this.matrix);
  1132. if (uv.x < 0 || uv.x > 1) {
  1133. switch (this.wrapS) {
  1134. case RepeatWrapping:
  1135. uv.x = uv.x - Math.floor(uv.x);
  1136. break;
  1137. case ClampToEdgeWrapping:
  1138. uv.x = uv.x < 0 ? 0 : 1;
  1139. break;
  1140. case MirroredRepeatWrapping:
  1141. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1142. uv.x = Math.ceil(uv.x) - uv.x;
  1143. } else {
  1144. uv.x = uv.x - Math.floor(uv.x);
  1145. }
  1146. break;
  1147. }
  1148. }
  1149. if (uv.y < 0 || uv.y > 1) {
  1150. switch (this.wrapT) {
  1151. case RepeatWrapping:
  1152. uv.y = uv.y - Math.floor(uv.y);
  1153. break;
  1154. case ClampToEdgeWrapping:
  1155. uv.y = uv.y < 0 ? 0 : 1;
  1156. break;
  1157. case MirroredRepeatWrapping:
  1158. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1159. uv.y = Math.ceil(uv.y) - uv.y;
  1160. } else {
  1161. uv.y = uv.y - Math.floor(uv.y);
  1162. }
  1163. break;
  1164. }
  1165. }
  1166. if (this.flipY) {
  1167. uv.y = 1 - uv.y;
  1168. }
  1169. return uv;
  1170. }
  1171. set needsUpdate(value) {
  1172. if (value === true) this.version++;
  1173. }
  1174. }
  1175. Texture.DEFAULT_IMAGE = undefined;
  1176. Texture.DEFAULT_MAPPING = UVMapping;
  1177. Texture.prototype.isTexture = true;
  1178. function serializeImage(image) {
  1179. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1180. // default images
  1181. return ImageUtils.getDataURL(image);
  1182. } else {
  1183. if (image.data) {
  1184. // images of DataTexture
  1185. return {
  1186. data: Array.prototype.slice.call(image.data),
  1187. width: image.width,
  1188. height: image.height,
  1189. type: image.data.constructor.name
  1190. };
  1191. } else {
  1192. console.warn('THREE.Texture: Unable to serialize Texture.');
  1193. return {};
  1194. }
  1195. }
  1196. }
  1197. class Vector4 {
  1198. constructor(x = 0, y = 0, z = 0, w = 1) {
  1199. this.x = x;
  1200. this.y = y;
  1201. this.z = z;
  1202. this.w = w;
  1203. }
  1204. get width() {
  1205. return this.z;
  1206. }
  1207. set width(value) {
  1208. this.z = value;
  1209. }
  1210. get height() {
  1211. return this.w;
  1212. }
  1213. set height(value) {
  1214. this.w = value;
  1215. }
  1216. set(x, y, z, w) {
  1217. this.x = x;
  1218. this.y = y;
  1219. this.z = z;
  1220. this.w = w;
  1221. return this;
  1222. }
  1223. setScalar(scalar) {
  1224. this.x = scalar;
  1225. this.y = scalar;
  1226. this.z = scalar;
  1227. this.w = scalar;
  1228. return this;
  1229. }
  1230. setX(x) {
  1231. this.x = x;
  1232. return this;
  1233. }
  1234. setY(y) {
  1235. this.y = y;
  1236. return this;
  1237. }
  1238. setZ(z) {
  1239. this.z = z;
  1240. return this;
  1241. }
  1242. setW(w) {
  1243. this.w = w;
  1244. return this;
  1245. }
  1246. setComponent(index, value) {
  1247. switch (index) {
  1248. case 0:
  1249. this.x = value;
  1250. break;
  1251. case 1:
  1252. this.y = value;
  1253. break;
  1254. case 2:
  1255. this.z = value;
  1256. break;
  1257. case 3:
  1258. this.w = value;
  1259. break;
  1260. default:
  1261. throw new Error('index is out of range: ' + index);
  1262. }
  1263. return this;
  1264. }
  1265. getComponent(index) {
  1266. switch (index) {
  1267. case 0:
  1268. return this.x;
  1269. case 1:
  1270. return this.y;
  1271. case 2:
  1272. return this.z;
  1273. case 3:
  1274. return this.w;
  1275. default:
  1276. throw new Error('index is out of range: ' + index);
  1277. }
  1278. }
  1279. clone() {
  1280. return new this.constructor(this.x, this.y, this.z, this.w);
  1281. }
  1282. copy(v) {
  1283. this.x = v.x;
  1284. this.y = v.y;
  1285. this.z = v.z;
  1286. this.w = v.w !== undefined ? v.w : 1;
  1287. return this;
  1288. }
  1289. add(v, w) {
  1290. if (w !== undefined) {
  1291. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  1292. return this.addVectors(v, w);
  1293. }
  1294. this.x += v.x;
  1295. this.y += v.y;
  1296. this.z += v.z;
  1297. this.w += v.w;
  1298. return this;
  1299. }
  1300. addScalar(s) {
  1301. this.x += s;
  1302. this.y += s;
  1303. this.z += s;
  1304. this.w += s;
  1305. return this;
  1306. }
  1307. addVectors(a, b) {
  1308. this.x = a.x + b.x;
  1309. this.y = a.y + b.y;
  1310. this.z = a.z + b.z;
  1311. this.w = a.w + b.w;
  1312. return this;
  1313. }
  1314. addScaledVector(v, s) {
  1315. this.x += v.x * s;
  1316. this.y += v.y * s;
  1317. this.z += v.z * s;
  1318. this.w += v.w * s;
  1319. return this;
  1320. }
  1321. sub(v, w) {
  1322. if (w !== undefined) {
  1323. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  1324. return this.subVectors(v, w);
  1325. }
  1326. this.x -= v.x;
  1327. this.y -= v.y;
  1328. this.z -= v.z;
  1329. this.w -= v.w;
  1330. return this;
  1331. }
  1332. subScalar(s) {
  1333. this.x -= s;
  1334. this.y -= s;
  1335. this.z -= s;
  1336. this.w -= s;
  1337. return this;
  1338. }
  1339. subVectors(a, b) {
  1340. this.x = a.x - b.x;
  1341. this.y = a.y - b.y;
  1342. this.z = a.z - b.z;
  1343. this.w = a.w - b.w;
  1344. return this;
  1345. }
  1346. multiply(v) {
  1347. this.x *= v.x;
  1348. this.y *= v.y;
  1349. this.z *= v.z;
  1350. this.w *= v.w;
  1351. return this;
  1352. }
  1353. multiplyScalar(scalar) {
  1354. this.x *= scalar;
  1355. this.y *= scalar;
  1356. this.z *= scalar;
  1357. this.w *= scalar;
  1358. return this;
  1359. }
  1360. applyMatrix4(m) {
  1361. const x = this.x,
  1362. y = this.y,
  1363. z = this.z,
  1364. w = this.w;
  1365. const e = m.elements;
  1366. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1367. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1368. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1369. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1370. return this;
  1371. }
  1372. divideScalar(scalar) {
  1373. return this.multiplyScalar(1 / scalar);
  1374. }
  1375. setAxisAngleFromQuaternion(q) {
  1376. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1377. // q is assumed to be normalized
  1378. this.w = 2 * Math.acos(q.w);
  1379. const s = Math.sqrt(1 - q.w * q.w);
  1380. if (s < 0.0001) {
  1381. this.x = 1;
  1382. this.y = 0;
  1383. this.z = 0;
  1384. } else {
  1385. this.x = q.x / s;
  1386. this.y = q.y / s;
  1387. this.z = q.z / s;
  1388. }
  1389. return this;
  1390. }
  1391. setAxisAngleFromRotationMatrix(m) {
  1392. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1393. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1394. let angle, x, y, z; // variables for result
  1395. const epsilon = 0.01,
  1396. // margin to allow for rounding errors
  1397. epsilon2 = 0.1,
  1398. // margin to distinguish between 0 and 180 degrees
  1399. te = m.elements,
  1400. m11 = te[0],
  1401. m12 = te[4],
  1402. m13 = te[8],
  1403. m21 = te[1],
  1404. m22 = te[5],
  1405. m23 = te[9],
  1406. m31 = te[2],
  1407. m32 = te[6],
  1408. m33 = te[10];
  1409. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  1410. // singularity found
  1411. // first check for identity matrix which must have +1 for all terms
  1412. // in leading diagonal and zero in other terms
  1413. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  1414. // this singularity is identity matrix so angle = 0
  1415. this.set(1, 0, 0, 0);
  1416. return this; // zero angle, arbitrary axis
  1417. } // otherwise this singularity is angle = 180
  1418. angle = Math.PI;
  1419. const xx = (m11 + 1) / 2;
  1420. const yy = (m22 + 1) / 2;
  1421. const zz = (m33 + 1) / 2;
  1422. const xy = (m12 + m21) / 4;
  1423. const xz = (m13 + m31) / 4;
  1424. const yz = (m23 + m32) / 4;
  1425. if (xx > yy && xx > zz) {
  1426. // m11 is the largest diagonal term
  1427. if (xx < epsilon) {
  1428. x = 0;
  1429. y = 0.707106781;
  1430. z = 0.707106781;
  1431. } else {
  1432. x = Math.sqrt(xx);
  1433. y = xy / x;
  1434. z = xz / x;
  1435. }
  1436. } else if (yy > zz) {
  1437. // m22 is the largest diagonal term
  1438. if (yy < epsilon) {
  1439. x = 0.707106781;
  1440. y = 0;
  1441. z = 0.707106781;
  1442. } else {
  1443. y = Math.sqrt(yy);
  1444. x = xy / y;
  1445. z = yz / y;
  1446. }
  1447. } else {
  1448. // m33 is the largest diagonal term so base result on this
  1449. if (zz < epsilon) {
  1450. x = 0.707106781;
  1451. y = 0.707106781;
  1452. z = 0;
  1453. } else {
  1454. z = Math.sqrt(zz);
  1455. x = xz / z;
  1456. y = yz / z;
  1457. }
  1458. }
  1459. this.set(x, y, z, angle);
  1460. return this; // return 180 deg rotation
  1461. } // as we have reached here there are no singularities so we can handle normally
  1462. let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  1463. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1464. // caught by singularity test above, but I've left it in just in case
  1465. this.x = (m32 - m23) / s;
  1466. this.y = (m13 - m31) / s;
  1467. this.z = (m21 - m12) / s;
  1468. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  1469. return this;
  1470. }
  1471. min(v) {
  1472. this.x = Math.min(this.x, v.x);
  1473. this.y = Math.min(this.y, v.y);
  1474. this.z = Math.min(this.z, v.z);
  1475. this.w = Math.min(this.w, v.w);
  1476. return this;
  1477. }
  1478. max(v) {
  1479. this.x = Math.max(this.x, v.x);
  1480. this.y = Math.max(this.y, v.y);
  1481. this.z = Math.max(this.z, v.z);
  1482. this.w = Math.max(this.w, v.w);
  1483. return this;
  1484. }
  1485. clamp(min, max) {
  1486. // assumes min < max, componentwise
  1487. this.x = Math.max(min.x, Math.min(max.x, this.x));
  1488. this.y = Math.max(min.y, Math.min(max.y, this.y));
  1489. this.z = Math.max(min.z, Math.min(max.z, this.z));
  1490. this.w = Math.max(min.w, Math.min(max.w, this.w));
  1491. return this;
  1492. }
  1493. clampScalar(minVal, maxVal) {
  1494. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  1495. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  1496. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  1497. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  1498. return this;
  1499. }
  1500. clampLength(min, max) {
  1501. const length = this.length();
  1502. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1503. }
  1504. floor() {
  1505. this.x = Math.floor(this.x);
  1506. this.y = Math.floor(this.y);
  1507. this.z = Math.floor(this.z);
  1508. this.w = Math.floor(this.w);
  1509. return this;
  1510. }
  1511. ceil() {
  1512. this.x = Math.ceil(this.x);
  1513. this.y = Math.ceil(this.y);
  1514. this.z = Math.ceil(this.z);
  1515. this.w = Math.ceil(this.w);
  1516. return this;
  1517. }
  1518. round() {
  1519. this.x = Math.round(this.x);
  1520. this.y = Math.round(this.y);
  1521. this.z = Math.round(this.z);
  1522. this.w = Math.round(this.w);
  1523. return this;
  1524. }
  1525. roundToZero() {
  1526. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1527. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1528. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  1529. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  1530. return this;
  1531. }
  1532. negate() {
  1533. this.x = -this.x;
  1534. this.y = -this.y;
  1535. this.z = -this.z;
  1536. this.w = -this.w;
  1537. return this;
  1538. }
  1539. dot(v) {
  1540. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1541. }
  1542. lengthSq() {
  1543. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1544. }
  1545. length() {
  1546. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1547. }
  1548. manhattanLength() {
  1549. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  1550. }
  1551. normalize() {
  1552. return this.divideScalar(this.length() || 1);
  1553. }
  1554. setLength(length) {
  1555. return this.normalize().multiplyScalar(length);
  1556. }
  1557. lerp(v, alpha) {
  1558. this.x += (v.x - this.x) * alpha;
  1559. this.y += (v.y - this.y) * alpha;
  1560. this.z += (v.z - this.z) * alpha;
  1561. this.w += (v.w - this.w) * alpha;
  1562. return this;
  1563. }
  1564. lerpVectors(v1, v2, alpha) {
  1565. this.x = v1.x + (v2.x - v1.x) * alpha;
  1566. this.y = v1.y + (v2.y - v1.y) * alpha;
  1567. this.z = v1.z + (v2.z - v1.z) * alpha;
  1568. this.w = v1.w + (v2.w - v1.w) * alpha;
  1569. return this;
  1570. }
  1571. equals(v) {
  1572. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  1573. }
  1574. fromArray(array, offset = 0) {
  1575. this.x = array[offset];
  1576. this.y = array[offset + 1];
  1577. this.z = array[offset + 2];
  1578. this.w = array[offset + 3];
  1579. return this;
  1580. }
  1581. toArray(array = [], offset = 0) {
  1582. array[offset] = this.x;
  1583. array[offset + 1] = this.y;
  1584. array[offset + 2] = this.z;
  1585. array[offset + 3] = this.w;
  1586. return array;
  1587. }
  1588. fromBufferAttribute(attribute, index, offset) {
  1589. if (offset !== undefined) {
  1590. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  1591. }
  1592. this.x = attribute.getX(index);
  1593. this.y = attribute.getY(index);
  1594. this.z = attribute.getZ(index);
  1595. this.w = attribute.getW(index);
  1596. return this;
  1597. }
  1598. random() {
  1599. this.x = Math.random();
  1600. this.y = Math.random();
  1601. this.z = Math.random();
  1602. this.w = Math.random();
  1603. return this;
  1604. }
  1605. *[Symbol.iterator]() {
  1606. yield this.x;
  1607. yield this.y;
  1608. yield this.z;
  1609. yield this.w;
  1610. }
  1611. }
  1612. Vector4.prototype.isVector4 = true;
  1613. /*
  1614. In options, we can specify:
  1615. * Texture parameters for an auto-generated target texture
  1616. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1617. */
  1618. class WebGLRenderTarget extends EventDispatcher {
  1619. constructor(width, height, options = {}) {
  1620. super();
  1621. this.width = width;
  1622. this.height = height;
  1623. this.depth = 1;
  1624. this.scissor = new Vector4(0, 0, width, height);
  1625. this.scissorTest = false;
  1626. this.viewport = new Vector4(0, 0, width, height);
  1627. this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  1628. this.texture.isRenderTargetTexture = true;
  1629. this.texture.image = {
  1630. width: width,
  1631. height: height,
  1632. depth: 1
  1633. };
  1634. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1635. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  1636. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1637. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1638. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1639. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1640. }
  1641. setTexture(texture) {
  1642. texture.image = {
  1643. width: this.width,
  1644. height: this.height,
  1645. depth: this.depth
  1646. };
  1647. this.texture = texture;
  1648. }
  1649. setSize(width, height, depth = 1) {
  1650. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1651. this.width = width;
  1652. this.height = height;
  1653. this.depth = depth;
  1654. this.texture.image.width = width;
  1655. this.texture.image.height = height;
  1656. this.texture.image.depth = depth;
  1657. this.dispose();
  1658. }
  1659. this.viewport.set(0, 0, width, height);
  1660. this.scissor.set(0, 0, width, height);
  1661. }
  1662. clone() {
  1663. return new this.constructor().copy(this);
  1664. }
  1665. copy(source) {
  1666. this.width = source.width;
  1667. this.height = source.height;
  1668. this.depth = source.depth;
  1669. this.viewport.copy(source.viewport);
  1670. this.texture = source.texture.clone();
  1671. this.texture.image = { ...this.texture.image
  1672. }; // See #20328.
  1673. this.depthBuffer = source.depthBuffer;
  1674. this.stencilBuffer = source.stencilBuffer;
  1675. this.depthTexture = source.depthTexture;
  1676. return this;
  1677. }
  1678. dispose() {
  1679. this.dispatchEvent({
  1680. type: 'dispose'
  1681. });
  1682. }
  1683. }
  1684. WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
  1685. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1686. constructor(width, height, count) {
  1687. super(width, height);
  1688. const texture = this.texture;
  1689. this.texture = [];
  1690. for (let i = 0; i < count; i++) {
  1691. this.texture[i] = texture.clone();
  1692. }
  1693. }
  1694. setSize(width, height, depth = 1) {
  1695. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1696. this.width = width;
  1697. this.height = height;
  1698. this.depth = depth;
  1699. for (let i = 0, il = this.texture.length; i < il; i++) {
  1700. this.texture[i].image.width = width;
  1701. this.texture[i].image.height = height;
  1702. this.texture[i].image.depth = depth;
  1703. }
  1704. this.dispose();
  1705. }
  1706. this.viewport.set(0, 0, width, height);
  1707. this.scissor.set(0, 0, width, height);
  1708. return this;
  1709. }
  1710. copy(source) {
  1711. this.dispose();
  1712. this.width = source.width;
  1713. this.height = source.height;
  1714. this.depth = source.depth;
  1715. this.viewport.set(0, 0, this.width, this.height);
  1716. this.scissor.set(0, 0, this.width, this.height);
  1717. this.depthBuffer = source.depthBuffer;
  1718. this.stencilBuffer = source.stencilBuffer;
  1719. this.depthTexture = source.depthTexture;
  1720. this.texture.length = 0;
  1721. for (let i = 0, il = source.texture.length; i < il; i++) {
  1722. this.texture[i] = source.texture[i].clone();
  1723. }
  1724. return this;
  1725. }
  1726. }
  1727. WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true;
  1728. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  1729. constructor(width, height, options) {
  1730. super(width, height, options);
  1731. this.samples = 4;
  1732. }
  1733. copy(source) {
  1734. super.copy.call(this, source);
  1735. this.samples = source.samples;
  1736. return this;
  1737. }
  1738. }
  1739. WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true;
  1740. class Quaternion {
  1741. constructor(x = 0, y = 0, z = 0, w = 1) {
  1742. this._x = x;
  1743. this._y = y;
  1744. this._z = z;
  1745. this._w = w;
  1746. }
  1747. static slerp(qa, qb, qm, t) {
  1748. console.warn('THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.');
  1749. return qm.slerpQuaternions(qa, qb, t);
  1750. }
  1751. static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  1752. // fuzz-free, array-based Quaternion SLERP operation
  1753. let x0 = src0[srcOffset0 + 0],
  1754. y0 = src0[srcOffset0 + 1],
  1755. z0 = src0[srcOffset0 + 2],
  1756. w0 = src0[srcOffset0 + 3];
  1757. const x1 = src1[srcOffset1 + 0],
  1758. y1 = src1[srcOffset1 + 1],
  1759. z1 = src1[srcOffset1 + 2],
  1760. w1 = src1[srcOffset1 + 3];
  1761. if (t === 0) {
  1762. dst[dstOffset + 0] = x0;
  1763. dst[dstOffset + 1] = y0;
  1764. dst[dstOffset + 2] = z0;
  1765. dst[dstOffset + 3] = w0;
  1766. return;
  1767. }
  1768. if (t === 1) {
  1769. dst[dstOffset + 0] = x1;
  1770. dst[dstOffset + 1] = y1;
  1771. dst[dstOffset + 2] = z1;
  1772. dst[dstOffset + 3] = w1;
  1773. return;
  1774. }
  1775. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  1776. let s = 1 - t;
  1777. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1778. dir = cos >= 0 ? 1 : -1,
  1779. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  1780. if (sqrSin > Number.EPSILON) {
  1781. const sin = Math.sqrt(sqrSin),
  1782. len = Math.atan2(sin, cos * dir);
  1783. s = Math.sin(s * len) / sin;
  1784. t = Math.sin(t * len) / sin;
  1785. }
  1786. const tDir = t * dir;
  1787. x0 = x0 * s + x1 * tDir;
  1788. y0 = y0 * s + y1 * tDir;
  1789. z0 = z0 * s + z1 * tDir;
  1790. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  1791. if (s === 1 - t) {
  1792. const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  1793. x0 *= f;
  1794. y0 *= f;
  1795. z0 *= f;
  1796. w0 *= f;
  1797. }
  1798. }
  1799. dst[dstOffset] = x0;
  1800. dst[dstOffset + 1] = y0;
  1801. dst[dstOffset + 2] = z0;
  1802. dst[dstOffset + 3] = w0;
  1803. }
  1804. static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  1805. const x0 = src0[srcOffset0];
  1806. const y0 = src0[srcOffset0 + 1];
  1807. const z0 = src0[srcOffset0 + 2];
  1808. const w0 = src0[srcOffset0 + 3];
  1809. const x1 = src1[srcOffset1];
  1810. const y1 = src1[srcOffset1 + 1];
  1811. const z1 = src1[srcOffset1 + 2];
  1812. const w1 = src1[srcOffset1 + 3];
  1813. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1814. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1815. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1816. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1817. return dst;
  1818. }
  1819. get x() {
  1820. return this._x;
  1821. }
  1822. set x(value) {
  1823. this._x = value;
  1824. this._onChangeCallback();
  1825. }
  1826. get y() {
  1827. return this._y;
  1828. }
  1829. set y(value) {
  1830. this._y = value;
  1831. this._onChangeCallback();
  1832. }
  1833. get z() {
  1834. return this._z;
  1835. }
  1836. set z(value) {
  1837. this._z = value;
  1838. this._onChangeCallback();
  1839. }
  1840. get w() {
  1841. return this._w;
  1842. }
  1843. set w(value) {
  1844. this._w = value;
  1845. this._onChangeCallback();
  1846. }
  1847. set(x, y, z, w) {
  1848. this._x = x;
  1849. this._y = y;
  1850. this._z = z;
  1851. this._w = w;
  1852. this._onChangeCallback();
  1853. return this;
  1854. }
  1855. clone() {
  1856. return new this.constructor(this._x, this._y, this._z, this._w);
  1857. }
  1858. copy(quaternion) {
  1859. this._x = quaternion.x;
  1860. this._y = quaternion.y;
  1861. this._z = quaternion.z;
  1862. this._w = quaternion.w;
  1863. this._onChangeCallback();
  1864. return this;
  1865. }
  1866. setFromEuler(euler, update) {
  1867. if (!(euler && euler.isEuler)) {
  1868. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  1869. }
  1870. const x = euler._x,
  1871. y = euler._y,
  1872. z = euler._z,
  1873. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  1874. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1875. // content/SpinCalc.m
  1876. const cos = Math.cos;
  1877. const sin = Math.sin;
  1878. const c1 = cos(x / 2);
  1879. const c2 = cos(y / 2);
  1880. const c3 = cos(z / 2);
  1881. const s1 = sin(x / 2);
  1882. const s2 = sin(y / 2);
  1883. const s3 = sin(z / 2);
  1884. switch (order) {
  1885. case 'XYZ':
  1886. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1887. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1888. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1889. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1890. break;
  1891. case 'YXZ':
  1892. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1893. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1894. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1895. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1896. break;
  1897. case 'ZXY':
  1898. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1899. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1900. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1901. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1902. break;
  1903. case 'ZYX':
  1904. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1905. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1906. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1907. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1908. break;
  1909. case 'YZX':
  1910. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1911. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1912. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1913. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1914. break;
  1915. case 'XZY':
  1916. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1917. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1918. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1919. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1920. break;
  1921. default:
  1922. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  1923. }
  1924. if (update !== false) this._onChangeCallback();
  1925. return this;
  1926. }
  1927. setFromAxisAngle(axis, angle) {
  1928. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1929. // assumes axis is normalized
  1930. const halfAngle = angle / 2,
  1931. s = Math.sin(halfAngle);
  1932. this._x = axis.x * s;
  1933. this._y = axis.y * s;
  1934. this._z = axis.z * s;
  1935. this._w = Math.cos(halfAngle);
  1936. this._onChangeCallback();
  1937. return this;
  1938. }
  1939. setFromRotationMatrix(m) {
  1940. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1941. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1942. const te = m.elements,
  1943. m11 = te[0],
  1944. m12 = te[4],
  1945. m13 = te[8],
  1946. m21 = te[1],
  1947. m22 = te[5],
  1948. m23 = te[9],
  1949. m31 = te[2],
  1950. m32 = te[6],
  1951. m33 = te[10],
  1952. trace = m11 + m22 + m33;
  1953. if (trace > 0) {
  1954. const s = 0.5 / Math.sqrt(trace + 1.0);
  1955. this._w = 0.25 / s;
  1956. this._x = (m32 - m23) * s;
  1957. this._y = (m13 - m31) * s;
  1958. this._z = (m21 - m12) * s;
  1959. } else if (m11 > m22 && m11 > m33) {
  1960. const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1961. this._w = (m32 - m23) / s;
  1962. this._x = 0.25 * s;
  1963. this._y = (m12 + m21) / s;
  1964. this._z = (m13 + m31) / s;
  1965. } else if (m22 > m33) {
  1966. const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1967. this._w = (m13 - m31) / s;
  1968. this._x = (m12 + m21) / s;
  1969. this._y = 0.25 * s;
  1970. this._z = (m23 + m32) / s;
  1971. } else {
  1972. const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1973. this._w = (m21 - m12) / s;
  1974. this._x = (m13 + m31) / s;
  1975. this._y = (m23 + m32) / s;
  1976. this._z = 0.25 * s;
  1977. }
  1978. this._onChangeCallback();
  1979. return this;
  1980. }
  1981. setFromUnitVectors(vFrom, vTo) {
  1982. // assumes direction vectors vFrom and vTo are normalized
  1983. let r = vFrom.dot(vTo) + 1;
  1984. if (r < Number.EPSILON) {
  1985. // vFrom and vTo point in opposite directions
  1986. r = 0;
  1987. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  1988. this._x = -vFrom.y;
  1989. this._y = vFrom.x;
  1990. this._z = 0;
  1991. this._w = r;
  1992. } else {
  1993. this._x = 0;
  1994. this._y = -vFrom.z;
  1995. this._z = vFrom.y;
  1996. this._w = r;
  1997. }
  1998. } else {
  1999. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2000. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2001. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2002. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2003. this._w = r;
  2004. }
  2005. return this.normalize();
  2006. }
  2007. angleTo(q) {
  2008. return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1)));
  2009. }
  2010. rotateTowards(q, step) {
  2011. const angle = this.angleTo(q);
  2012. if (angle === 0) return this;
  2013. const t = Math.min(1, step / angle);
  2014. this.slerp(q, t);
  2015. return this;
  2016. }
  2017. identity() {
  2018. return this.set(0, 0, 0, 1);
  2019. }
  2020. invert() {
  2021. // quaternion is assumed to have unit length
  2022. return this.conjugate();
  2023. }
  2024. conjugate() {
  2025. this._x *= -1;
  2026. this._y *= -1;
  2027. this._z *= -1;
  2028. this._onChangeCallback();
  2029. return this;
  2030. }
  2031. dot(v) {
  2032. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2033. }
  2034. lengthSq() {
  2035. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2036. }
  2037. length() {
  2038. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  2039. }
  2040. normalize() {
  2041. let l = this.length();
  2042. if (l === 0) {
  2043. this._x = 0;
  2044. this._y = 0;
  2045. this._z = 0;
  2046. this._w = 1;
  2047. } else {
  2048. l = 1 / l;
  2049. this._x = this._x * l;
  2050. this._y = this._y * l;
  2051. this._z = this._z * l;
  2052. this._w = this._w * l;
  2053. }
  2054. this._onChangeCallback();
  2055. return this;
  2056. }
  2057. multiply(q, p) {
  2058. if (p !== undefined) {
  2059. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2060. return this.multiplyQuaternions(q, p);
  2061. }
  2062. return this.multiplyQuaternions(this, q);
  2063. }
  2064. premultiply(q) {
  2065. return this.multiplyQuaternions(q, this);
  2066. }
  2067. multiplyQuaternions(a, b) {
  2068. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2069. const qax = a._x,
  2070. qay = a._y,
  2071. qaz = a._z,
  2072. qaw = a._w;
  2073. const qbx = b._x,
  2074. qby = b._y,
  2075. qbz = b._z,
  2076. qbw = b._w;
  2077. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2078. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2079. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2080. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2081. this._onChangeCallback();
  2082. return this;
  2083. }
  2084. slerp(qb, t) {
  2085. if (t === 0) return this;
  2086. if (t === 1) return this.copy(qb);
  2087. const x = this._x,
  2088. y = this._y,
  2089. z = this._z,
  2090. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2091. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2092. if (cosHalfTheta < 0) {
  2093. this._w = -qb._w;
  2094. this._x = -qb._x;
  2095. this._y = -qb._y;
  2096. this._z = -qb._z;
  2097. cosHalfTheta = -cosHalfTheta;
  2098. } else {
  2099. this.copy(qb);
  2100. }
  2101. if (cosHalfTheta >= 1.0) {
  2102. this._w = w;
  2103. this._x = x;
  2104. this._y = y;
  2105. this._z = z;
  2106. return this;
  2107. }
  2108. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2109. if (sqrSinHalfTheta <= Number.EPSILON) {
  2110. const s = 1 - t;
  2111. this._w = s * w + t * this._w;
  2112. this._x = s * x + t * this._x;
  2113. this._y = s * y + t * this._y;
  2114. this._z = s * z + t * this._z;
  2115. this.normalize();
  2116. this._onChangeCallback();
  2117. return this;
  2118. }
  2119. const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2120. const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2121. const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2122. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2123. this._w = w * ratioA + this._w * ratioB;
  2124. this._x = x * ratioA + this._x * ratioB;
  2125. this._y = y * ratioA + this._y * ratioB;
  2126. this._z = z * ratioA + this._z * ratioB;
  2127. this._onChangeCallback();
  2128. return this;
  2129. }
  2130. slerpQuaternions(qa, qb, t) {
  2131. this.copy(qa).slerp(qb, t);
  2132. }
  2133. random() {
  2134. // Derived from http://planning.cs.uiuc.edu/node198.html
  2135. // Note, this source uses w, x, y, z ordering,
  2136. // so we swap the order below.
  2137. const u1 = Math.random();
  2138. const sqrt1u1 = Math.sqrt(1 - u1);
  2139. const sqrtu1 = Math.sqrt(u1);
  2140. const u2 = 2 * Math.PI * Math.random();
  2141. const u3 = 2 * Math.PI * Math.random();
  2142. return this.set(sqrt1u1 * Math.cos(u2), sqrtu1 * Math.sin(u3), sqrtu1 * Math.cos(u3), sqrt1u1 * Math.sin(u2));
  2143. }
  2144. equals(quaternion) {
  2145. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2146. }
  2147. fromArray(array, offset = 0) {
  2148. this._x = array[offset];
  2149. this._y = array[offset + 1];
  2150. this._z = array[offset + 2];
  2151. this._w = array[offset + 3];
  2152. this._onChangeCallback();
  2153. return this;
  2154. }
  2155. toArray(array = [], offset = 0) {
  2156. array[offset] = this._x;
  2157. array[offset + 1] = this._y;
  2158. array[offset + 2] = this._z;
  2159. array[offset + 3] = this._w;
  2160. return array;
  2161. }
  2162. fromBufferAttribute(attribute, index) {
  2163. this._x = attribute.getX(index);
  2164. this._y = attribute.getY(index);
  2165. this._z = attribute.getZ(index);
  2166. this._w = attribute.getW(index);
  2167. return this;
  2168. }
  2169. _onChange(callback) {
  2170. this._onChangeCallback = callback;
  2171. return this;
  2172. }
  2173. _onChangeCallback() {}
  2174. }
  2175. Quaternion.prototype.isQuaternion = true;
  2176. class Vector3 {
  2177. constructor(x = 0, y = 0, z = 0) {
  2178. this.x = x;
  2179. this.y = y;
  2180. this.z = z;
  2181. }
  2182. set(x, y, z) {
  2183. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  2184. this.x = x;
  2185. this.y = y;
  2186. this.z = z;
  2187. return this;
  2188. }
  2189. setScalar(scalar) {
  2190. this.x = scalar;
  2191. this.y = scalar;
  2192. this.z = scalar;
  2193. return this;
  2194. }
  2195. setX(x) {
  2196. this.x = x;
  2197. return this;
  2198. }
  2199. setY(y) {
  2200. this.y = y;
  2201. return this;
  2202. }
  2203. setZ(z) {
  2204. this.z = z;
  2205. return this;
  2206. }
  2207. setComponent(index, value) {
  2208. switch (index) {
  2209. case 0:
  2210. this.x = value;
  2211. break;
  2212. case 1:
  2213. this.y = value;
  2214. break;
  2215. case 2:
  2216. this.z = value;
  2217. break;
  2218. default:
  2219. throw new Error('index is out of range: ' + index);
  2220. }
  2221. return this;
  2222. }
  2223. getComponent(index) {
  2224. switch (index) {
  2225. case 0:
  2226. return this.x;
  2227. case 1:
  2228. return this.y;
  2229. case 2:
  2230. return this.z;
  2231. default:
  2232. throw new Error('index is out of range: ' + index);
  2233. }
  2234. }
  2235. clone() {
  2236. return new this.constructor(this.x, this.y, this.z);
  2237. }
  2238. copy(v) {
  2239. this.x = v.x;
  2240. this.y = v.y;
  2241. this.z = v.z;
  2242. return this;
  2243. }
  2244. add(v, w) {
  2245. if (w !== undefined) {
  2246. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2247. return this.addVectors(v, w);
  2248. }
  2249. this.x += v.x;
  2250. this.y += v.y;
  2251. this.z += v.z;
  2252. return this;
  2253. }
  2254. addScalar(s) {
  2255. this.x += s;
  2256. this.y += s;
  2257. this.z += s;
  2258. return this;
  2259. }
  2260. addVectors(a, b) {
  2261. this.x = a.x + b.x;
  2262. this.y = a.y + b.y;
  2263. this.z = a.z + b.z;
  2264. return this;
  2265. }
  2266. addScaledVector(v, s) {
  2267. this.x += v.x * s;
  2268. this.y += v.y * s;
  2269. this.z += v.z * s;
  2270. return this;
  2271. }
  2272. sub(v, w) {
  2273. if (w !== undefined) {
  2274. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2275. return this.subVectors(v, w);
  2276. }
  2277. this.x -= v.x;
  2278. this.y -= v.y;
  2279. this.z -= v.z;
  2280. return this;
  2281. }
  2282. subScalar(s) {
  2283. this.x -= s;
  2284. this.y -= s;
  2285. this.z -= s;
  2286. return this;
  2287. }
  2288. subVectors(a, b) {
  2289. this.x = a.x - b.x;
  2290. this.y = a.y - b.y;
  2291. this.z = a.z - b.z;
  2292. return this;
  2293. }
  2294. multiply(v, w) {
  2295. if (w !== undefined) {
  2296. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2297. return this.multiplyVectors(v, w);
  2298. }
  2299. this.x *= v.x;
  2300. this.y *= v.y;
  2301. this.z *= v.z;
  2302. return this;
  2303. }
  2304. multiplyScalar(scalar) {
  2305. this.x *= scalar;
  2306. this.y *= scalar;
  2307. this.z *= scalar;
  2308. return this;
  2309. }
  2310. multiplyVectors(a, b) {
  2311. this.x = a.x * b.x;
  2312. this.y = a.y * b.y;
  2313. this.z = a.z * b.z;
  2314. return this;
  2315. }
  2316. applyEuler(euler) {
  2317. if (!(euler && euler.isEuler)) {
  2318. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2319. }
  2320. return this.applyQuaternion(_quaternion$4.setFromEuler(euler));
  2321. }
  2322. applyAxisAngle(axis, angle) {
  2323. return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle));
  2324. }
  2325. applyMatrix3(m) {
  2326. const x = this.x,
  2327. y = this.y,
  2328. z = this.z;
  2329. const e = m.elements;
  2330. this.x = e[0] * x + e[3] * y + e[6] * z;
  2331. this.y = e[1] * x + e[4] * y + e[7] * z;
  2332. this.z = e[2] * x + e[5] * y + e[8] * z;
  2333. return this;
  2334. }
  2335. applyNormalMatrix(m) {
  2336. return this.applyMatrix3(m).normalize();
  2337. }
  2338. applyMatrix4(m) {
  2339. const x = this.x,
  2340. y = this.y,
  2341. z = this.z;
  2342. const e = m.elements;
  2343. const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2344. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2345. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2346. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2347. return this;
  2348. }
  2349. applyQuaternion(q) {
  2350. const x = this.x,
  2351. y = this.y,
  2352. z = this.z;
  2353. const qx = q.x,
  2354. qy = q.y,
  2355. qz = q.z,
  2356. qw = q.w; // calculate quat * vector
  2357. const ix = qw * x + qy * z - qz * y;
  2358. const iy = qw * y + qz * x - qx * z;
  2359. const iz = qw * z + qx * y - qy * x;
  2360. const iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2361. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2362. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2363. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2364. return this;
  2365. }
  2366. project(camera) {
  2367. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2368. }
  2369. unproject(camera) {
  2370. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2371. }
  2372. transformDirection(m) {
  2373. // input: THREE.Matrix4 affine matrix
  2374. // vector interpreted as a direction
  2375. const x = this.x,
  2376. y = this.y,
  2377. z = this.z;
  2378. const e = m.elements;
  2379. this.x = e[0] * x + e[4] * y + e[8] * z;
  2380. this.y = e[1] * x + e[5] * y + e[9] * z;
  2381. this.z = e[2] * x + e[6] * y + e[10] * z;
  2382. return this.normalize();
  2383. }
  2384. divide(v) {
  2385. this.x /= v.x;
  2386. this.y /= v.y;
  2387. this.z /= v.z;
  2388. return this;
  2389. }
  2390. divideScalar(scalar) {
  2391. return this.multiplyScalar(1 / scalar);
  2392. }
  2393. min(v) {
  2394. this.x = Math.min(this.x, v.x);
  2395. this.y = Math.min(this.y, v.y);
  2396. this.z = Math.min(this.z, v.z);
  2397. return this;
  2398. }
  2399. max(v) {
  2400. this.x = Math.max(this.x, v.x);
  2401. this.y = Math.max(this.y, v.y);
  2402. this.z = Math.max(this.z, v.z);
  2403. return this;
  2404. }
  2405. clamp(min, max) {
  2406. // assumes min < max, componentwise
  2407. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2408. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2409. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2410. return this;
  2411. }
  2412. clampScalar(minVal, maxVal) {
  2413. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2414. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2415. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2416. return this;
  2417. }
  2418. clampLength(min, max) {
  2419. const length = this.length();
  2420. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2421. }
  2422. floor() {
  2423. this.x = Math.floor(this.x);
  2424. this.y = Math.floor(this.y);
  2425. this.z = Math.floor(this.z);
  2426. return this;
  2427. }
  2428. ceil() {
  2429. this.x = Math.ceil(this.x);
  2430. this.y = Math.ceil(this.y);
  2431. this.z = Math.ceil(this.z);
  2432. return this;
  2433. }
  2434. round() {
  2435. this.x = Math.round(this.x);
  2436. this.y = Math.round(this.y);
  2437. this.z = Math.round(this.z);
  2438. return this;
  2439. }
  2440. roundToZero() {
  2441. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2442. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2443. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2444. return this;
  2445. }
  2446. negate() {
  2447. this.x = -this.x;
  2448. this.y = -this.y;
  2449. this.z = -this.z;
  2450. return this;
  2451. }
  2452. dot(v) {
  2453. return this.x * v.x + this.y * v.y + this.z * v.z;
  2454. } // TODO lengthSquared?
  2455. lengthSq() {
  2456. return this.x * this.x + this.y * this.y + this.z * this.z;
  2457. }
  2458. length() {
  2459. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2460. }
  2461. manhattanLength() {
  2462. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2463. }
  2464. normalize() {
  2465. return this.divideScalar(this.length() || 1);
  2466. }
  2467. setLength(length) {
  2468. return this.normalize().multiplyScalar(length);
  2469. }
  2470. lerp(v, alpha) {
  2471. this.x += (v.x - this.x) * alpha;
  2472. this.y += (v.y - this.y) * alpha;
  2473. this.z += (v.z - this.z) * alpha;
  2474. return this;
  2475. }
  2476. lerpVectors(v1, v2, alpha) {
  2477. this.x = v1.x + (v2.x - v1.x) * alpha;
  2478. this.y = v1.y + (v2.y - v1.y) * alpha;
  2479. this.z = v1.z + (v2.z - v1.z) * alpha;
  2480. return this;
  2481. }
  2482. cross(v, w) {
  2483. if (w !== undefined) {
  2484. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2485. return this.crossVectors(v, w);
  2486. }
  2487. return this.crossVectors(this, v);
  2488. }
  2489. crossVectors(a, b) {
  2490. const ax = a.x,
  2491. ay = a.y,
  2492. az = a.z;
  2493. const bx = b.x,
  2494. by = b.y,
  2495. bz = b.z;
  2496. this.x = ay * bz - az * by;
  2497. this.y = az * bx - ax * bz;
  2498. this.z = ax * by - ay * bx;
  2499. return this;
  2500. }
  2501. projectOnVector(v) {
  2502. const denominator = v.lengthSq();
  2503. if (denominator === 0) return this.set(0, 0, 0);
  2504. const scalar = v.dot(this) / denominator;
  2505. return this.copy(v).multiplyScalar(scalar);
  2506. }
  2507. projectOnPlane(planeNormal) {
  2508. _vector$c.copy(this).projectOnVector(planeNormal);
  2509. return this.sub(_vector$c);
  2510. }
  2511. reflect(normal) {
  2512. // reflect incident vector off plane orthogonal to normal
  2513. // normal is assumed to have unit length
  2514. return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal)));
  2515. }
  2516. angleTo(v) {
  2517. const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  2518. if (denominator === 0) return Math.PI / 2;
  2519. const theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  2520. return Math.acos(clamp(theta, -1, 1));
  2521. }
  2522. distanceTo(v) {
  2523. return Math.sqrt(this.distanceToSquared(v));
  2524. }
  2525. distanceToSquared(v) {
  2526. const dx = this.x - v.x,
  2527. dy = this.y - v.y,
  2528. dz = this.z - v.z;
  2529. return dx * dx + dy * dy + dz * dz;
  2530. }
  2531. manhattanDistanceTo(v) {
  2532. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  2533. }
  2534. setFromSpherical(s) {
  2535. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  2536. }
  2537. setFromSphericalCoords(radius, phi, theta) {
  2538. const sinPhiRadius = Math.sin(phi) * radius;
  2539. this.x = sinPhiRadius * Math.sin(theta);
  2540. this.y = Math.cos(phi) * radius;
  2541. this.z = sinPhiRadius * Math.cos(theta);
  2542. return this;
  2543. }
  2544. setFromCylindrical(c) {
  2545. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  2546. }
  2547. setFromCylindricalCoords(radius, theta, y) {
  2548. this.x = radius * Math.sin(theta);
  2549. this.y = y;
  2550. this.z = radius * Math.cos(theta);
  2551. return this;
  2552. }
  2553. setFromMatrixPosition(m) {
  2554. const e = m.elements;
  2555. this.x = e[12];
  2556. this.y = e[13];
  2557. this.z = e[14];
  2558. return this;
  2559. }
  2560. setFromMatrixScale(m) {
  2561. const sx = this.setFromMatrixColumn(m, 0).length();
  2562. const sy = this.setFromMatrixColumn(m, 1).length();
  2563. const sz = this.setFromMatrixColumn(m, 2).length();
  2564. this.x = sx;
  2565. this.y = sy;
  2566. this.z = sz;
  2567. return this;
  2568. }
  2569. setFromMatrixColumn(m, index) {
  2570. return this.fromArray(m.elements, index * 4);
  2571. }
  2572. setFromMatrix3Column(m, index) {
  2573. return this.fromArray(m.elements, index * 3);
  2574. }
  2575. equals(v) {
  2576. return v.x === this.x && v.y === this.y && v.z === this.z;
  2577. }
  2578. fromArray(array, offset = 0) {
  2579. this.x = array[offset];
  2580. this.y = array[offset + 1];
  2581. this.z = array[offset + 2];
  2582. return this;
  2583. }
  2584. toArray(array = [], offset = 0) {
  2585. array[offset] = this.x;
  2586. array[offset + 1] = this.y;
  2587. array[offset + 2] = this.z;
  2588. return array;
  2589. }
  2590. fromBufferAttribute(attribute, index, offset) {
  2591. if (offset !== undefined) {
  2592. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  2593. }
  2594. this.x = attribute.getX(index);
  2595. this.y = attribute.getY(index);
  2596. this.z = attribute.getZ(index);
  2597. return this;
  2598. }
  2599. random() {
  2600. this.x = Math.random();
  2601. this.y = Math.random();
  2602. this.z = Math.random();
  2603. return this;
  2604. }
  2605. randomDirection() {
  2606. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  2607. const u = (Math.random() - 0.5) * 2;
  2608. const t = Math.random() * Math.PI * 2;
  2609. const f = Math.sqrt(1 - u ** 2);
  2610. this.x = f * Math.cos(t);
  2611. this.y = f * Math.sin(t);
  2612. this.z = u;
  2613. return this;
  2614. }
  2615. *[Symbol.iterator]() {
  2616. yield this.x;
  2617. yield this.y;
  2618. yield this.z;
  2619. }
  2620. }
  2621. Vector3.prototype.isVector3 = true;
  2622. const _vector$c = /*@__PURE__*/new Vector3();
  2623. const _quaternion$4 = /*@__PURE__*/new Quaternion();
  2624. class Box3 {
  2625. constructor(min = new Vector3(+Infinity, +Infinity, +Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) {
  2626. this.min = min;
  2627. this.max = max;
  2628. }
  2629. set(min, max) {
  2630. this.min.copy(min);
  2631. this.max.copy(max);
  2632. return this;
  2633. }
  2634. setFromArray(array) {
  2635. let minX = +Infinity;
  2636. let minY = +Infinity;
  2637. let minZ = +Infinity;
  2638. let maxX = -Infinity;
  2639. let maxY = -Infinity;
  2640. let maxZ = -Infinity;
  2641. for (let i = 0, l = array.length; i < l; i += 3) {
  2642. const x = array[i];
  2643. const y = array[i + 1];
  2644. const z = array[i + 2];
  2645. if (x < minX) minX = x;
  2646. if (y < minY) minY = y;
  2647. if (z < minZ) minZ = z;
  2648. if (x > maxX) maxX = x;
  2649. if (y > maxY) maxY = y;
  2650. if (z > maxZ) maxZ = z;
  2651. }
  2652. this.min.set(minX, minY, minZ);
  2653. this.max.set(maxX, maxY, maxZ);
  2654. return this;
  2655. }
  2656. setFromBufferAttribute(attribute) {
  2657. let minX = +Infinity;
  2658. let minY = +Infinity;
  2659. let minZ = +Infinity;
  2660. let maxX = -Infinity;
  2661. let maxY = -Infinity;
  2662. let maxZ = -Infinity;
  2663. for (let i = 0, l = attribute.count; i < l; i++) {
  2664. const x = attribute.getX(i);
  2665. const y = attribute.getY(i);
  2666. const z = attribute.getZ(i);
  2667. if (x < minX) minX = x;
  2668. if (y < minY) minY = y;
  2669. if (z < minZ) minZ = z;
  2670. if (x > maxX) maxX = x;
  2671. if (y > maxY) maxY = y;
  2672. if (z > maxZ) maxZ = z;
  2673. }
  2674. this.min.set(minX, minY, minZ);
  2675. this.max.set(maxX, maxY, maxZ);
  2676. return this;
  2677. }
  2678. setFromPoints(points) {
  2679. this.makeEmpty();
  2680. for (let i = 0, il = points.length; i < il; i++) {
  2681. this.expandByPoint(points[i]);
  2682. }
  2683. return this;
  2684. }
  2685. setFromCenterAndSize(center, size) {
  2686. const halfSize = _vector$b.copy(size).multiplyScalar(0.5);
  2687. this.min.copy(center).sub(halfSize);
  2688. this.max.copy(center).add(halfSize);
  2689. return this;
  2690. }
  2691. setFromObject(object) {
  2692. this.makeEmpty();
  2693. return this.expandByObject(object);
  2694. }
  2695. clone() {
  2696. return new this.constructor().copy(this);
  2697. }
  2698. copy(box) {
  2699. this.min.copy(box.min);
  2700. this.max.copy(box.max);
  2701. return this;
  2702. }
  2703. makeEmpty() {
  2704. this.min.x = this.min.y = this.min.z = +Infinity;
  2705. this.max.x = this.max.y = this.max.z = -Infinity;
  2706. return this;
  2707. }
  2708. isEmpty() {
  2709. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2710. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  2711. }
  2712. getCenter(target) {
  2713. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  2714. }
  2715. getSize(target) {
  2716. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  2717. }
  2718. expandByPoint(point) {
  2719. this.min.min(point);
  2720. this.max.max(point);
  2721. return this;
  2722. }
  2723. expandByVector(vector) {
  2724. this.min.sub(vector);
  2725. this.max.add(vector);
  2726. return this;
  2727. }
  2728. expandByScalar(scalar) {
  2729. this.min.addScalar(-scalar);
  2730. this.max.addScalar(scalar);
  2731. return this;
  2732. }
  2733. expandByObject(object) {
  2734. // Computes the world-axis-aligned bounding box of an object (including its children),
  2735. // accounting for both the object's, and children's, world transforms
  2736. object.updateWorldMatrix(false, false);
  2737. const geometry = object.geometry;
  2738. if (geometry !== undefined) {
  2739. if (geometry.boundingBox === null) {
  2740. geometry.computeBoundingBox();
  2741. }
  2742. _box$3.copy(geometry.boundingBox);
  2743. _box$3.applyMatrix4(object.matrixWorld);
  2744. this.union(_box$3);
  2745. }
  2746. const children = object.children;
  2747. for (let i = 0, l = children.length; i < l; i++) {
  2748. this.expandByObject(children[i]);
  2749. }
  2750. return this;
  2751. }
  2752. containsPoint(point) {
  2753. 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;
  2754. }
  2755. containsBox(box) {
  2756. 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;
  2757. }
  2758. getParameter(point, target) {
  2759. // This can potentially have a divide by zero if the box
  2760. // has a size dimension of 0.
  2761. 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));
  2762. }
  2763. intersectsBox(box) {
  2764. // using 6 splitting planes to rule out intersections.
  2765. 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;
  2766. }
  2767. intersectsSphere(sphere) {
  2768. // Find the point on the AABB closest to the sphere center.
  2769. this.clampPoint(sphere.center, _vector$b); // If that point is inside the sphere, the AABB and sphere intersect.
  2770. return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  2771. }
  2772. intersectsPlane(plane) {
  2773. // We compute the minimum and maximum dot product values. If those values
  2774. // are on the same side (back or front) of the plane, then there is no intersection.
  2775. let min, max;
  2776. if (plane.normal.x > 0) {
  2777. min = plane.normal.x * this.min.x;
  2778. max = plane.normal.x * this.max.x;
  2779. } else {
  2780. min = plane.normal.x * this.max.x;
  2781. max = plane.normal.x * this.min.x;
  2782. }
  2783. if (plane.normal.y > 0) {
  2784. min += plane.normal.y * this.min.y;
  2785. max += plane.normal.y * this.max.y;
  2786. } else {
  2787. min += plane.normal.y * this.max.y;
  2788. max += plane.normal.y * this.min.y;
  2789. }
  2790. if (plane.normal.z > 0) {
  2791. min += plane.normal.z * this.min.z;
  2792. max += plane.normal.z * this.max.z;
  2793. } else {
  2794. min += plane.normal.z * this.max.z;
  2795. max += plane.normal.z * this.min.z;
  2796. }
  2797. return min <= -plane.constant && max >= -plane.constant;
  2798. }
  2799. intersectsTriangle(triangle) {
  2800. if (this.isEmpty()) {
  2801. return false;
  2802. } // compute box center and extents
  2803. this.getCenter(_center);
  2804. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  2805. _v0$2.subVectors(triangle.a, _center);
  2806. _v1$7.subVectors(triangle.b, _center);
  2807. _v2$3.subVectors(triangle.c, _center); // compute edge vectors for triangle
  2808. _f0.subVectors(_v1$7, _v0$2);
  2809. _f1.subVectors(_v2$3, _v1$7);
  2810. _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
  2811. // 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
  2812. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2813. 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];
  2814. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2815. return false;
  2816. } // test 3 face normals from the aabb
  2817. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  2818. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2819. return false;
  2820. } // finally testing the face normal of the triangle
  2821. // use already existing triangle edge vectors here
  2822. _triangleNormal.crossVectors(_f0, _f1);
  2823. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  2824. return satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents);
  2825. }
  2826. clampPoint(point, target) {
  2827. return target.copy(point).clamp(this.min, this.max);
  2828. }
  2829. distanceToPoint(point) {
  2830. const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max);
  2831. return clampedPoint.sub(point).length();
  2832. }
  2833. getBoundingSphere(target) {
  2834. this.getCenter(target.center);
  2835. target.radius = this.getSize(_vector$b).length() * 0.5;
  2836. return target;
  2837. }
  2838. intersect(box) {
  2839. this.min.max(box.min);
  2840. 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.
  2841. if (this.isEmpty()) this.makeEmpty();
  2842. return this;
  2843. }
  2844. union(box) {
  2845. this.min.min(box.min);
  2846. this.max.max(box.max);
  2847. return this;
  2848. }
  2849. applyMatrix4(matrix) {
  2850. // transform of empty box is an empty box.
  2851. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2852. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  2853. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  2854. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  2855. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  2856. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  2857. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  2858. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  2859. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  2860. this.setFromPoints(_points);
  2861. return this;
  2862. }
  2863. translate(offset) {
  2864. this.min.add(offset);
  2865. this.max.add(offset);
  2866. return this;
  2867. }
  2868. equals(box) {
  2869. return box.min.equals(this.min) && box.max.equals(this.max);
  2870. }
  2871. }
  2872. Box3.prototype.isBox3 = true;
  2873. 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()];
  2874. const _vector$b = /*@__PURE__*/new Vector3();
  2875. const _box$3 = /*@__PURE__*/new Box3(); // triangle centered vertices
  2876. const _v0$2 = /*@__PURE__*/new Vector3();
  2877. const _v1$7 = /*@__PURE__*/new Vector3();
  2878. const _v2$3 = /*@__PURE__*/new Vector3(); // triangle edge vectors
  2879. const _f0 = /*@__PURE__*/new Vector3();
  2880. const _f1 = /*@__PURE__*/new Vector3();
  2881. const _f2 = /*@__PURE__*/new Vector3();
  2882. const _center = /*@__PURE__*/new Vector3();
  2883. const _extents = /*@__PURE__*/new Vector3();
  2884. const _triangleNormal = /*@__PURE__*/new Vector3();
  2885. const _testAxis = /*@__PURE__*/new Vector3();
  2886. function satForAxes(axes, v0, v1, v2, extents) {
  2887. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  2888. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  2889. 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
  2890. const p0 = v0.dot(_testAxis);
  2891. const p1 = v1.dot(_testAxis);
  2892. const p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  2893. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  2894. // points of the projected triangle are outside the projected half-length of the aabb
  2895. // the axis is seperating and we can exit
  2896. return false;
  2897. }
  2898. }
  2899. return true;
  2900. }
  2901. const _box$2 = /*@__PURE__*/new Box3();
  2902. const _v1$6 = /*@__PURE__*/new Vector3();
  2903. const _toFarthestPoint = /*@__PURE__*/new Vector3();
  2904. const _toPoint = /*@__PURE__*/new Vector3();
  2905. class Sphere {
  2906. constructor(center = new Vector3(), radius = -1) {
  2907. this.center = center;
  2908. this.radius = radius;
  2909. }
  2910. set(center, radius) {
  2911. this.center.copy(center);
  2912. this.radius = radius;
  2913. return this;
  2914. }
  2915. setFromPoints(points, optionalCenter) {
  2916. const center = this.center;
  2917. if (optionalCenter !== undefined) {
  2918. center.copy(optionalCenter);
  2919. } else {
  2920. _box$2.setFromPoints(points).getCenter(center);
  2921. }
  2922. let maxRadiusSq = 0;
  2923. for (let i = 0, il = points.length; i < il; i++) {
  2924. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  2925. }
  2926. this.radius = Math.sqrt(maxRadiusSq);
  2927. return this;
  2928. }
  2929. copy(sphere) {
  2930. this.center.copy(sphere.center);
  2931. this.radius = sphere.radius;
  2932. return this;
  2933. }
  2934. isEmpty() {
  2935. return this.radius < 0;
  2936. }
  2937. makeEmpty() {
  2938. this.center.set(0, 0, 0);
  2939. this.radius = -1;
  2940. return this;
  2941. }
  2942. containsPoint(point) {
  2943. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  2944. }
  2945. distanceToPoint(point) {
  2946. return point.distanceTo(this.center) - this.radius;
  2947. }
  2948. intersectsSphere(sphere) {
  2949. const radiusSum = this.radius + sphere.radius;
  2950. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  2951. }
  2952. intersectsBox(box) {
  2953. return box.intersectsSphere(this);
  2954. }
  2955. intersectsPlane(plane) {
  2956. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  2957. }
  2958. clampPoint(point, target) {
  2959. const deltaLengthSq = this.center.distanceToSquared(point);
  2960. target.copy(point);
  2961. if (deltaLengthSq > this.radius * this.radius) {
  2962. target.sub(this.center).normalize();
  2963. target.multiplyScalar(this.radius).add(this.center);
  2964. }
  2965. return target;
  2966. }
  2967. getBoundingBox(target) {
  2968. if (this.isEmpty()) {
  2969. // Empty sphere produces empty bounding box
  2970. target.makeEmpty();
  2971. return target;
  2972. }
  2973. target.set(this.center, this.center);
  2974. target.expandByScalar(this.radius);
  2975. return target;
  2976. }
  2977. applyMatrix4(matrix) {
  2978. this.center.applyMatrix4(matrix);
  2979. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2980. return this;
  2981. }
  2982. translate(offset) {
  2983. this.center.add(offset);
  2984. return this;
  2985. }
  2986. expandByPoint(point) {
  2987. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  2988. _toPoint.subVectors(point, this.center);
  2989. const lengthSq = _toPoint.lengthSq();
  2990. if (lengthSq > this.radius * this.radius) {
  2991. const length = Math.sqrt(lengthSq);
  2992. const missingRadiusHalf = (length - this.radius) * 0.5; // Nudge this sphere towards the target point. Add half the missing distance to radius,
  2993. // and the other half to position. This gives a tighter enclosure, instead of if
  2994. // the whole missing distance were just added to radius.
  2995. this.center.add(_toPoint.multiplyScalar(missingRadiusHalf / length));
  2996. this.radius += missingRadiusHalf;
  2997. }
  2998. return this;
  2999. }
  3000. union(sphere) {
  3001. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  3002. // To enclose another sphere into this sphere, we only need to enclose two points:
  3003. // 1) Enclose the farthest point on the other sphere into this sphere.
  3004. // 2) Enclose the opposite point of the farthest point into this sphere.
  3005. _toFarthestPoint.subVectors(sphere.center, this.center).normalize().multiplyScalar(sphere.radius);
  3006. this.expandByPoint(_v1$6.copy(sphere.center).add(_toFarthestPoint));
  3007. this.expandByPoint(_v1$6.copy(sphere.center).sub(_toFarthestPoint));
  3008. return this;
  3009. }
  3010. equals(sphere) {
  3011. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  3012. }
  3013. clone() {
  3014. return new this.constructor().copy(this);
  3015. }
  3016. }
  3017. const _vector$a = /*@__PURE__*/new Vector3();
  3018. const _segCenter = /*@__PURE__*/new Vector3();
  3019. const _segDir = /*@__PURE__*/new Vector3();
  3020. const _diff = /*@__PURE__*/new Vector3();
  3021. const _edge1 = /*@__PURE__*/new Vector3();
  3022. const _edge2 = /*@__PURE__*/new Vector3();
  3023. const _normal$1 = /*@__PURE__*/new Vector3();
  3024. class Ray {
  3025. constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) {
  3026. this.origin = origin;
  3027. this.direction = direction;
  3028. }
  3029. set(origin, direction) {
  3030. this.origin.copy(origin);
  3031. this.direction.copy(direction);
  3032. return this;
  3033. }
  3034. copy(ray) {
  3035. this.origin.copy(ray.origin);
  3036. this.direction.copy(ray.direction);
  3037. return this;
  3038. }
  3039. at(t, target) {
  3040. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  3041. }
  3042. lookAt(v) {
  3043. this.direction.copy(v).sub(this.origin).normalize();
  3044. return this;
  3045. }
  3046. recast(t) {
  3047. this.origin.copy(this.at(t, _vector$a));
  3048. return this;
  3049. }
  3050. closestPointToPoint(point, target) {
  3051. target.subVectors(point, this.origin);
  3052. const directionDistance = target.dot(this.direction);
  3053. if (directionDistance < 0) {
  3054. return target.copy(this.origin);
  3055. }
  3056. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3057. }
  3058. distanceToPoint(point) {
  3059. return Math.sqrt(this.distanceSqToPoint(point));
  3060. }
  3061. distanceSqToPoint(point) {
  3062. const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  3063. if (directionDistance < 0) {
  3064. return this.origin.distanceToSquared(point);
  3065. }
  3066. _vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3067. return _vector$a.distanceToSquared(point);
  3068. }
  3069. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  3070. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3071. // It returns the min distance between the ray and the segment
  3072. // defined by v0 and v1
  3073. // It can also set two optional targets :
  3074. // - The closest point on the ray
  3075. // - The closest point on the segment
  3076. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  3077. _segDir.copy(v1).sub(v0).normalize();
  3078. _diff.copy(this.origin).sub(_segCenter);
  3079. const segExtent = v0.distanceTo(v1) * 0.5;
  3080. const a01 = -this.direction.dot(_segDir);
  3081. const b0 = _diff.dot(this.direction);
  3082. const b1 = -_diff.dot(_segDir);
  3083. const c = _diff.lengthSq();
  3084. const det = Math.abs(1 - a01 * a01);
  3085. let s0, s1, sqrDist, extDet;
  3086. if (det > 0) {
  3087. // The ray and segment are not parallel.
  3088. s0 = a01 * b1 - b0;
  3089. s1 = a01 * b0 - b1;
  3090. extDet = segExtent * det;
  3091. if (s0 >= 0) {
  3092. if (s1 >= -extDet) {
  3093. if (s1 <= extDet) {
  3094. // region 0
  3095. // Minimum at interior points of ray and segment.
  3096. const invDet = 1 / det;
  3097. s0 *= invDet;
  3098. s1 *= invDet;
  3099. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  3100. } else {
  3101. // region 1
  3102. s1 = segExtent;
  3103. s0 = Math.max(0, -(a01 * s1 + b0));
  3104. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3105. }
  3106. } else {
  3107. // region 5
  3108. s1 = -segExtent;
  3109. s0 = Math.max(0, -(a01 * s1 + b0));
  3110. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3111. }
  3112. } else {
  3113. if (s1 <= -extDet) {
  3114. // region 4
  3115. s0 = Math.max(0, -(-a01 * segExtent + b0));
  3116. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3117. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3118. } else if (s1 <= extDet) {
  3119. // region 3
  3120. s0 = 0;
  3121. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  3122. sqrDist = s1 * (s1 + 2 * b1) + c;
  3123. } else {
  3124. // region 2
  3125. s0 = Math.max(0, -(a01 * segExtent + b0));
  3126. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3127. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3128. }
  3129. }
  3130. } else {
  3131. // Ray and segment are parallel.
  3132. s1 = a01 > 0 ? -segExtent : segExtent;
  3133. s0 = Math.max(0, -(a01 * s1 + b0));
  3134. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3135. }
  3136. if (optionalPointOnRay) {
  3137. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  3138. }
  3139. if (optionalPointOnSegment) {
  3140. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  3141. }
  3142. return sqrDist;
  3143. }
  3144. intersectSphere(sphere, target) {
  3145. _vector$a.subVectors(sphere.center, this.origin);
  3146. const tca = _vector$a.dot(this.direction);
  3147. const d2 = _vector$a.dot(_vector$a) - tca * tca;
  3148. const radius2 = sphere.radius * sphere.radius;
  3149. if (d2 > radius2) return null;
  3150. const thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  3151. const t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  3152. const t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  3153. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  3154. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3155. // in order to always return an intersect point that is in front of the ray.
  3156. 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
  3157. return this.at(t0, target);
  3158. }
  3159. intersectsSphere(sphere) {
  3160. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  3161. }
  3162. distanceToPlane(plane) {
  3163. const denominator = plane.normal.dot(this.direction);
  3164. if (denominator === 0) {
  3165. // line is coplanar, return origin
  3166. if (plane.distanceToPoint(this.origin) === 0) {
  3167. return 0;
  3168. } // Null is preferable to undefined since undefined means.... it is undefined
  3169. return null;
  3170. }
  3171. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  3172. return t >= 0 ? t : null;
  3173. }
  3174. intersectPlane(plane, target) {
  3175. const t = this.distanceToPlane(plane);
  3176. if (t === null) {
  3177. return null;
  3178. }
  3179. return this.at(t, target);
  3180. }
  3181. intersectsPlane(plane) {
  3182. // check if the ray lies on the plane first
  3183. const distToPoint = plane.distanceToPoint(this.origin);
  3184. if (distToPoint === 0) {
  3185. return true;
  3186. }
  3187. const denominator = plane.normal.dot(this.direction);
  3188. if (denominator * distToPoint < 0) {
  3189. return true;
  3190. } // ray origin is behind the plane (and is pointing behind it)
  3191. return false;
  3192. }
  3193. intersectBox(box, target) {
  3194. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3195. const invdirx = 1 / this.direction.x,
  3196. invdiry = 1 / this.direction.y,
  3197. invdirz = 1 / this.direction.z;
  3198. const origin = this.origin;
  3199. if (invdirx >= 0) {
  3200. tmin = (box.min.x - origin.x) * invdirx;
  3201. tmax = (box.max.x - origin.x) * invdirx;
  3202. } else {
  3203. tmin = (box.max.x - origin.x) * invdirx;
  3204. tmax = (box.min.x - origin.x) * invdirx;
  3205. }
  3206. if (invdiry >= 0) {
  3207. tymin = (box.min.y - origin.y) * invdiry;
  3208. tymax = (box.max.y - origin.y) * invdiry;
  3209. } else {
  3210. tymin = (box.max.y - origin.y) * invdiry;
  3211. tymax = (box.min.y - origin.y) * invdiry;
  3212. }
  3213. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  3214. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3215. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  3216. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  3217. if (invdirz >= 0) {
  3218. tzmin = (box.min.z - origin.z) * invdirz;
  3219. tzmax = (box.max.z - origin.z) * invdirz;
  3220. } else {
  3221. tzmin = (box.max.z - origin.z) * invdirz;
  3222. tzmax = (box.min.z - origin.z) * invdirz;
  3223. }
  3224. if (tmin > tzmax || tzmin > tmax) return null;
  3225. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  3226. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  3227. if (tmax < 0) return null;
  3228. return this.at(tmin >= 0 ? tmin : tmax, target);
  3229. }
  3230. intersectsBox(box) {
  3231. return this.intersectBox(box, _vector$a) !== null;
  3232. }
  3233. intersectTriangle(a, b, c, backfaceCulling, target) {
  3234. // Compute the offset origin, edges, and normal.
  3235. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3236. _edge1.subVectors(b, a);
  3237. _edge2.subVectors(c, a);
  3238. _normal$1.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3239. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3240. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3241. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3242. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3243. let DdN = this.direction.dot(_normal$1);
  3244. let sign;
  3245. if (DdN > 0) {
  3246. if (backfaceCulling) return null;
  3247. sign = 1;
  3248. } else if (DdN < 0) {
  3249. sign = -1;
  3250. DdN = -DdN;
  3251. } else {
  3252. return null;
  3253. }
  3254. _diff.subVectors(this.origin, a);
  3255. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  3256. if (DdQxE2 < 0) {
  3257. return null;
  3258. }
  3259. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  3260. if (DdE1xQ < 0) {
  3261. return null;
  3262. } // b1+b2 > 1, no intersection
  3263. if (DdQxE2 + DdE1xQ > DdN) {
  3264. return null;
  3265. } // Line intersects triangle, check if ray does.
  3266. const QdN = -sign * _diff.dot(_normal$1); // t < 0, no intersection
  3267. if (QdN < 0) {
  3268. return null;
  3269. } // Ray intersects triangle.
  3270. return this.at(QdN / DdN, target);
  3271. }
  3272. applyMatrix4(matrix4) {
  3273. this.origin.applyMatrix4(matrix4);
  3274. this.direction.transformDirection(matrix4);
  3275. return this;
  3276. }
  3277. equals(ray) {
  3278. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  3279. }
  3280. clone() {
  3281. return new this.constructor().copy(this);
  3282. }
  3283. }
  3284. class Matrix4 {
  3285. constructor() {
  3286. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3287. if (arguments.length > 0) {
  3288. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  3289. }
  3290. }
  3291. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3292. const te = this.elements;
  3293. te[0] = n11;
  3294. te[4] = n12;
  3295. te[8] = n13;
  3296. te[12] = n14;
  3297. te[1] = n21;
  3298. te[5] = n22;
  3299. te[9] = n23;
  3300. te[13] = n24;
  3301. te[2] = n31;
  3302. te[6] = n32;
  3303. te[10] = n33;
  3304. te[14] = n34;
  3305. te[3] = n41;
  3306. te[7] = n42;
  3307. te[11] = n43;
  3308. te[15] = n44;
  3309. return this;
  3310. }
  3311. identity() {
  3312. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3313. return this;
  3314. }
  3315. clone() {
  3316. return new Matrix4().fromArray(this.elements);
  3317. }
  3318. copy(m) {
  3319. const te = this.elements;
  3320. const me = m.elements;
  3321. te[0] = me[0];
  3322. te[1] = me[1];
  3323. te[2] = me[2];
  3324. te[3] = me[3];
  3325. te[4] = me[4];
  3326. te[5] = me[5];
  3327. te[6] = me[6];
  3328. te[7] = me[7];
  3329. te[8] = me[8];
  3330. te[9] = me[9];
  3331. te[10] = me[10];
  3332. te[11] = me[11];
  3333. te[12] = me[12];
  3334. te[13] = me[13];
  3335. te[14] = me[14];
  3336. te[15] = me[15];
  3337. return this;
  3338. }
  3339. copyPosition(m) {
  3340. const te = this.elements,
  3341. me = m.elements;
  3342. te[12] = me[12];
  3343. te[13] = me[13];
  3344. te[14] = me[14];
  3345. return this;
  3346. }
  3347. setFromMatrix3(m) {
  3348. const me = m.elements;
  3349. 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);
  3350. return this;
  3351. }
  3352. extractBasis(xAxis, yAxis, zAxis) {
  3353. xAxis.setFromMatrixColumn(this, 0);
  3354. yAxis.setFromMatrixColumn(this, 1);
  3355. zAxis.setFromMatrixColumn(this, 2);
  3356. return this;
  3357. }
  3358. makeBasis(xAxis, yAxis, zAxis) {
  3359. 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);
  3360. return this;
  3361. }
  3362. extractRotation(m) {
  3363. // this method does not support reflection matrices
  3364. const te = this.elements;
  3365. const me = m.elements;
  3366. const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length();
  3367. const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length();
  3368. const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length();
  3369. te[0] = me[0] * scaleX;
  3370. te[1] = me[1] * scaleX;
  3371. te[2] = me[2] * scaleX;
  3372. te[3] = 0;
  3373. te[4] = me[4] * scaleY;
  3374. te[5] = me[5] * scaleY;
  3375. te[6] = me[6] * scaleY;
  3376. te[7] = 0;
  3377. te[8] = me[8] * scaleZ;
  3378. te[9] = me[9] * scaleZ;
  3379. te[10] = me[10] * scaleZ;
  3380. te[11] = 0;
  3381. te[12] = 0;
  3382. te[13] = 0;
  3383. te[14] = 0;
  3384. te[15] = 1;
  3385. return this;
  3386. }
  3387. makeRotationFromEuler(euler) {
  3388. if (!(euler && euler.isEuler)) {
  3389. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  3390. }
  3391. const te = this.elements;
  3392. const x = euler.x,
  3393. y = euler.y,
  3394. z = euler.z;
  3395. const a = Math.cos(x),
  3396. b = Math.sin(x);
  3397. const c = Math.cos(y),
  3398. d = Math.sin(y);
  3399. const e = Math.cos(z),
  3400. f = Math.sin(z);
  3401. if (euler.order === 'XYZ') {
  3402. const ae = a * e,
  3403. af = a * f,
  3404. be = b * e,
  3405. bf = b * f;
  3406. te[0] = c * e;
  3407. te[4] = -c * f;
  3408. te[8] = d;
  3409. te[1] = af + be * d;
  3410. te[5] = ae - bf * d;
  3411. te[9] = -b * c;
  3412. te[2] = bf - ae * d;
  3413. te[6] = be + af * d;
  3414. te[10] = a * c;
  3415. } else if (euler.order === 'YXZ') {
  3416. const ce = c * e,
  3417. cf = c * f,
  3418. de = d * e,
  3419. df = d * f;
  3420. te[0] = ce + df * b;
  3421. te[4] = de * b - cf;
  3422. te[8] = a * d;
  3423. te[1] = a * f;
  3424. te[5] = a * e;
  3425. te[9] = -b;
  3426. te[2] = cf * b - de;
  3427. te[6] = df + ce * b;
  3428. te[10] = a * c;
  3429. } else if (euler.order === 'ZXY') {
  3430. const ce = c * e,
  3431. cf = c * f,
  3432. de = d * e,
  3433. df = d * f;
  3434. te[0] = ce - df * b;
  3435. te[4] = -a * f;
  3436. te[8] = de + cf * b;
  3437. te[1] = cf + de * b;
  3438. te[5] = a * e;
  3439. te[9] = df - ce * b;
  3440. te[2] = -a * d;
  3441. te[6] = b;
  3442. te[10] = a * c;
  3443. } else if (euler.order === 'ZYX') {
  3444. const ae = a * e,
  3445. af = a * f,
  3446. be = b * e,
  3447. bf = b * f;
  3448. te[0] = c * e;
  3449. te[4] = be * d - af;
  3450. te[8] = ae * d + bf;
  3451. te[1] = c * f;
  3452. te[5] = bf * d + ae;
  3453. te[9] = af * d - be;
  3454. te[2] = -d;
  3455. te[6] = b * c;
  3456. te[10] = a * c;
  3457. } else if (euler.order === 'YZX') {
  3458. const ac = a * c,
  3459. ad = a * d,
  3460. bc = b * c,
  3461. bd = b * d;
  3462. te[0] = c * e;
  3463. te[4] = bd - ac * f;
  3464. te[8] = bc * f + ad;
  3465. te[1] = f;
  3466. te[5] = a * e;
  3467. te[9] = -b * e;
  3468. te[2] = -d * e;
  3469. te[6] = ad * f + bc;
  3470. te[10] = ac - bd * f;
  3471. } else if (euler.order === 'XZY') {
  3472. const ac = a * c,
  3473. ad = a * d,
  3474. bc = b * c,
  3475. bd = b * d;
  3476. te[0] = c * e;
  3477. te[4] = -f;
  3478. te[8] = d * e;
  3479. te[1] = ac * f + bd;
  3480. te[5] = a * e;
  3481. te[9] = ad * f - bc;
  3482. te[2] = bc * f - ad;
  3483. te[6] = b * e;
  3484. te[10] = bd * f + ac;
  3485. } // bottom row
  3486. te[3] = 0;
  3487. te[7] = 0;
  3488. te[11] = 0; // last column
  3489. te[12] = 0;
  3490. te[13] = 0;
  3491. te[14] = 0;
  3492. te[15] = 1;
  3493. return this;
  3494. }
  3495. makeRotationFromQuaternion(q) {
  3496. return this.compose(_zero, q, _one);
  3497. }
  3498. lookAt(eye, target, up) {
  3499. const te = this.elements;
  3500. _z.subVectors(eye, target);
  3501. if (_z.lengthSq() === 0) {
  3502. // eye and target are in the same position
  3503. _z.z = 1;
  3504. }
  3505. _z.normalize();
  3506. _x.crossVectors(up, _z);
  3507. if (_x.lengthSq() === 0) {
  3508. // up and z are parallel
  3509. if (Math.abs(up.z) === 1) {
  3510. _z.x += 0.0001;
  3511. } else {
  3512. _z.z += 0.0001;
  3513. }
  3514. _z.normalize();
  3515. _x.crossVectors(up, _z);
  3516. }
  3517. _x.normalize();
  3518. _y.crossVectors(_z, _x);
  3519. te[0] = _x.x;
  3520. te[4] = _y.x;
  3521. te[8] = _z.x;
  3522. te[1] = _x.y;
  3523. te[5] = _y.y;
  3524. te[9] = _z.y;
  3525. te[2] = _x.z;
  3526. te[6] = _y.z;
  3527. te[10] = _z.z;
  3528. return this;
  3529. }
  3530. multiply(m, n) {
  3531. if (n !== undefined) {
  3532. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  3533. return this.multiplyMatrices(m, n);
  3534. }
  3535. return this.multiplyMatrices(this, m);
  3536. }
  3537. premultiply(m) {
  3538. return this.multiplyMatrices(m, this);
  3539. }
  3540. multiplyMatrices(a, b) {
  3541. const ae = a.elements;
  3542. const be = b.elements;
  3543. const te = this.elements;
  3544. const a11 = ae[0],
  3545. a12 = ae[4],
  3546. a13 = ae[8],
  3547. a14 = ae[12];
  3548. const a21 = ae[1],
  3549. a22 = ae[5],
  3550. a23 = ae[9],
  3551. a24 = ae[13];
  3552. const a31 = ae[2],
  3553. a32 = ae[6],
  3554. a33 = ae[10],
  3555. a34 = ae[14];
  3556. const a41 = ae[3],
  3557. a42 = ae[7],
  3558. a43 = ae[11],
  3559. a44 = ae[15];
  3560. const b11 = be[0],
  3561. b12 = be[4],
  3562. b13 = be[8],
  3563. b14 = be[12];
  3564. const b21 = be[1],
  3565. b22 = be[5],
  3566. b23 = be[9],
  3567. b24 = be[13];
  3568. const b31 = be[2],
  3569. b32 = be[6],
  3570. b33 = be[10],
  3571. b34 = be[14];
  3572. const b41 = be[3],
  3573. b42 = be[7],
  3574. b43 = be[11],
  3575. b44 = be[15];
  3576. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3577. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3578. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3579. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3580. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3581. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3582. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3583. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3584. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3585. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3586. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3587. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3588. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3589. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3590. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3591. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3592. return this;
  3593. }
  3594. multiplyScalar(s) {
  3595. const te = this.elements;
  3596. te[0] *= s;
  3597. te[4] *= s;
  3598. te[8] *= s;
  3599. te[12] *= s;
  3600. te[1] *= s;
  3601. te[5] *= s;
  3602. te[9] *= s;
  3603. te[13] *= s;
  3604. te[2] *= s;
  3605. te[6] *= s;
  3606. te[10] *= s;
  3607. te[14] *= s;
  3608. te[3] *= s;
  3609. te[7] *= s;
  3610. te[11] *= s;
  3611. te[15] *= s;
  3612. return this;
  3613. }
  3614. determinant() {
  3615. const te = this.elements;
  3616. const n11 = te[0],
  3617. n12 = te[4],
  3618. n13 = te[8],
  3619. n14 = te[12];
  3620. const n21 = te[1],
  3621. n22 = te[5],
  3622. n23 = te[9],
  3623. n24 = te[13];
  3624. const n31 = te[2],
  3625. n32 = te[6],
  3626. n33 = te[10],
  3627. n34 = te[14];
  3628. const n41 = te[3],
  3629. n42 = te[7],
  3630. n43 = te[11],
  3631. n44 = te[15]; //TODO: make this more efficient
  3632. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3633. 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);
  3634. }
  3635. transpose() {
  3636. const te = this.elements;
  3637. let tmp;
  3638. tmp = te[1];
  3639. te[1] = te[4];
  3640. te[4] = tmp;
  3641. tmp = te[2];
  3642. te[2] = te[8];
  3643. te[8] = tmp;
  3644. tmp = te[6];
  3645. te[6] = te[9];
  3646. te[9] = tmp;
  3647. tmp = te[3];
  3648. te[3] = te[12];
  3649. te[12] = tmp;
  3650. tmp = te[7];
  3651. te[7] = te[13];
  3652. te[13] = tmp;
  3653. tmp = te[11];
  3654. te[11] = te[14];
  3655. te[14] = tmp;
  3656. return this;
  3657. }
  3658. setPosition(x, y, z) {
  3659. const te = this.elements;
  3660. if (x.isVector3) {
  3661. te[12] = x.x;
  3662. te[13] = x.y;
  3663. te[14] = x.z;
  3664. } else {
  3665. te[12] = x;
  3666. te[13] = y;
  3667. te[14] = z;
  3668. }
  3669. return this;
  3670. }
  3671. invert() {
  3672. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3673. const te = this.elements,
  3674. n11 = te[0],
  3675. n21 = te[1],
  3676. n31 = te[2],
  3677. n41 = te[3],
  3678. n12 = te[4],
  3679. n22 = te[5],
  3680. n32 = te[6],
  3681. n42 = te[7],
  3682. n13 = te[8],
  3683. n23 = te[9],
  3684. n33 = te[10],
  3685. n43 = te[11],
  3686. n14 = te[12],
  3687. n24 = te[13],
  3688. n34 = te[14],
  3689. n44 = te[15],
  3690. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3691. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3692. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3693. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3694. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3695. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  3696. const detInv = 1 / det;
  3697. te[0] = t11 * detInv;
  3698. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  3699. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  3700. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  3701. te[4] = t12 * detInv;
  3702. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  3703. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  3704. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  3705. te[8] = t13 * detInv;
  3706. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  3707. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  3708. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  3709. te[12] = t14 * detInv;
  3710. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  3711. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  3712. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  3713. return this;
  3714. }
  3715. scale(v) {
  3716. const te = this.elements;
  3717. const x = v.x,
  3718. y = v.y,
  3719. z = v.z;
  3720. te[0] *= x;
  3721. te[4] *= y;
  3722. te[8] *= z;
  3723. te[1] *= x;
  3724. te[5] *= y;
  3725. te[9] *= z;
  3726. te[2] *= x;
  3727. te[6] *= y;
  3728. te[10] *= z;
  3729. te[3] *= x;
  3730. te[7] *= y;
  3731. te[11] *= z;
  3732. return this;
  3733. }
  3734. getMaxScaleOnAxis() {
  3735. const te = this.elements;
  3736. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  3737. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  3738. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  3739. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  3740. }
  3741. makeTranslation(x, y, z) {
  3742. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  3743. return this;
  3744. }
  3745. makeRotationX(theta) {
  3746. const c = Math.cos(theta),
  3747. s = Math.sin(theta);
  3748. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  3749. return this;
  3750. }
  3751. makeRotationY(theta) {
  3752. const c = Math.cos(theta),
  3753. s = Math.sin(theta);
  3754. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  3755. return this;
  3756. }
  3757. makeRotationZ(theta) {
  3758. const c = Math.cos(theta),
  3759. s = Math.sin(theta);
  3760. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3761. return this;
  3762. }
  3763. makeRotationAxis(axis, angle) {
  3764. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3765. const c = Math.cos(angle);
  3766. const s = Math.sin(angle);
  3767. const t = 1 - c;
  3768. const x = axis.x,
  3769. y = axis.y,
  3770. z = axis.z;
  3771. const tx = t * x,
  3772. ty = t * y;
  3773. 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);
  3774. return this;
  3775. }
  3776. makeScale(x, y, z) {
  3777. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  3778. return this;
  3779. }
  3780. makeShear(xy, xz, yx, yz, zx, zy) {
  3781. this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1);
  3782. return this;
  3783. }
  3784. compose(position, quaternion, scale) {
  3785. const te = this.elements;
  3786. const x = quaternion._x,
  3787. y = quaternion._y,
  3788. z = quaternion._z,
  3789. w = quaternion._w;
  3790. const x2 = x + x,
  3791. y2 = y + y,
  3792. z2 = z + z;
  3793. const xx = x * x2,
  3794. xy = x * y2,
  3795. xz = x * z2;
  3796. const yy = y * y2,
  3797. yz = y * z2,
  3798. zz = z * z2;
  3799. const wx = w * x2,
  3800. wy = w * y2,
  3801. wz = w * z2;
  3802. const sx = scale.x,
  3803. sy = scale.y,
  3804. sz = scale.z;
  3805. te[0] = (1 - (yy + zz)) * sx;
  3806. te[1] = (xy + wz) * sx;
  3807. te[2] = (xz - wy) * sx;
  3808. te[3] = 0;
  3809. te[4] = (xy - wz) * sy;
  3810. te[5] = (1 - (xx + zz)) * sy;
  3811. te[6] = (yz + wx) * sy;
  3812. te[7] = 0;
  3813. te[8] = (xz + wy) * sz;
  3814. te[9] = (yz - wx) * sz;
  3815. te[10] = (1 - (xx + yy)) * sz;
  3816. te[11] = 0;
  3817. te[12] = position.x;
  3818. te[13] = position.y;
  3819. te[14] = position.z;
  3820. te[15] = 1;
  3821. return this;
  3822. }
  3823. decompose(position, quaternion, scale) {
  3824. const te = this.elements;
  3825. let sx = _v1$5.set(te[0], te[1], te[2]).length();
  3826. const sy = _v1$5.set(te[4], te[5], te[6]).length();
  3827. const sz = _v1$5.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  3828. const det = this.determinant();
  3829. if (det < 0) sx = -sx;
  3830. position.x = te[12];
  3831. position.y = te[13];
  3832. position.z = te[14]; // scale the rotation part
  3833. _m1$2.copy(this);
  3834. const invSX = 1 / sx;
  3835. const invSY = 1 / sy;
  3836. const invSZ = 1 / sz;
  3837. _m1$2.elements[0] *= invSX;
  3838. _m1$2.elements[1] *= invSX;
  3839. _m1$2.elements[2] *= invSX;
  3840. _m1$2.elements[4] *= invSY;
  3841. _m1$2.elements[5] *= invSY;
  3842. _m1$2.elements[6] *= invSY;
  3843. _m1$2.elements[8] *= invSZ;
  3844. _m1$2.elements[9] *= invSZ;
  3845. _m1$2.elements[10] *= invSZ;
  3846. quaternion.setFromRotationMatrix(_m1$2);
  3847. scale.x = sx;
  3848. scale.y = sy;
  3849. scale.z = sz;
  3850. return this;
  3851. }
  3852. makePerspective(left, right, top, bottom, near, far) {
  3853. if (far === undefined) {
  3854. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  3855. }
  3856. const te = this.elements;
  3857. const x = 2 * near / (right - left);
  3858. const y = 2 * near / (top - bottom);
  3859. const a = (right + left) / (right - left);
  3860. const b = (top + bottom) / (top - bottom);
  3861. const c = -(far + near) / (far - near);
  3862. const d = -2 * far * near / (far - near);
  3863. te[0] = x;
  3864. te[4] = 0;
  3865. te[8] = a;
  3866. te[12] = 0;
  3867. te[1] = 0;
  3868. te[5] = y;
  3869. te[9] = b;
  3870. te[13] = 0;
  3871. te[2] = 0;
  3872. te[6] = 0;
  3873. te[10] = c;
  3874. te[14] = d;
  3875. te[3] = 0;
  3876. te[7] = 0;
  3877. te[11] = -1;
  3878. te[15] = 0;
  3879. return this;
  3880. }
  3881. makeOrthographic(left, right, top, bottom, near, far) {
  3882. const te = this.elements;
  3883. const w = 1.0 / (right - left);
  3884. const h = 1.0 / (top - bottom);
  3885. const p = 1.0 / (far - near);
  3886. const x = (right + left) * w;
  3887. const y = (top + bottom) * h;
  3888. const z = (far + near) * p;
  3889. te[0] = 2 * w;
  3890. te[4] = 0;
  3891. te[8] = 0;
  3892. te[12] = -x;
  3893. te[1] = 0;
  3894. te[5] = 2 * h;
  3895. te[9] = 0;
  3896. te[13] = -y;
  3897. te[2] = 0;
  3898. te[6] = 0;
  3899. te[10] = -2 * p;
  3900. te[14] = -z;
  3901. te[3] = 0;
  3902. te[7] = 0;
  3903. te[11] = 0;
  3904. te[15] = 1;
  3905. return this;
  3906. }
  3907. equals(matrix) {
  3908. const te = this.elements;
  3909. const me = matrix.elements;
  3910. for (let i = 0; i < 16; i++) {
  3911. if (te[i] !== me[i]) return false;
  3912. }
  3913. return true;
  3914. }
  3915. fromArray(array, offset = 0) {
  3916. for (let i = 0; i < 16; i++) {
  3917. this.elements[i] = array[i + offset];
  3918. }
  3919. return this;
  3920. }
  3921. toArray(array = [], offset = 0) {
  3922. const te = this.elements;
  3923. array[offset] = te[0];
  3924. array[offset + 1] = te[1];
  3925. array[offset + 2] = te[2];
  3926. array[offset + 3] = te[3];
  3927. array[offset + 4] = te[4];
  3928. array[offset + 5] = te[5];
  3929. array[offset + 6] = te[6];
  3930. array[offset + 7] = te[7];
  3931. array[offset + 8] = te[8];
  3932. array[offset + 9] = te[9];
  3933. array[offset + 10] = te[10];
  3934. array[offset + 11] = te[11];
  3935. array[offset + 12] = te[12];
  3936. array[offset + 13] = te[13];
  3937. array[offset + 14] = te[14];
  3938. array[offset + 15] = te[15];
  3939. return array;
  3940. }
  3941. }
  3942. Matrix4.prototype.isMatrix4 = true;
  3943. const _v1$5 = /*@__PURE__*/new Vector3();
  3944. const _m1$2 = /*@__PURE__*/new Matrix4();
  3945. const _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  3946. const _one = /*@__PURE__*/new Vector3(1, 1, 1);
  3947. const _x = /*@__PURE__*/new Vector3();
  3948. const _y = /*@__PURE__*/new Vector3();
  3949. const _z = /*@__PURE__*/new Vector3();
  3950. const _matrix$1 = /*@__PURE__*/new Matrix4();
  3951. const _quaternion$3 = /*@__PURE__*/new Quaternion();
  3952. class Euler {
  3953. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  3954. this._x = x;
  3955. this._y = y;
  3956. this._z = z;
  3957. this._order = order;
  3958. }
  3959. get x() {
  3960. return this._x;
  3961. }
  3962. set x(value) {
  3963. this._x = value;
  3964. this._onChangeCallback();
  3965. }
  3966. get y() {
  3967. return this._y;
  3968. }
  3969. set y(value) {
  3970. this._y = value;
  3971. this._onChangeCallback();
  3972. }
  3973. get z() {
  3974. return this._z;
  3975. }
  3976. set z(value) {
  3977. this._z = value;
  3978. this._onChangeCallback();
  3979. }
  3980. get order() {
  3981. return this._order;
  3982. }
  3983. set order(value) {
  3984. this._order = value;
  3985. this._onChangeCallback();
  3986. }
  3987. set(x, y, z, order = this._order) {
  3988. this._x = x;
  3989. this._y = y;
  3990. this._z = z;
  3991. this._order = order;
  3992. this._onChangeCallback();
  3993. return this;
  3994. }
  3995. clone() {
  3996. return new this.constructor(this._x, this._y, this._z, this._order);
  3997. }
  3998. copy(euler) {
  3999. this._x = euler._x;
  4000. this._y = euler._y;
  4001. this._z = euler._z;
  4002. this._order = euler._order;
  4003. this._onChangeCallback();
  4004. return this;
  4005. }
  4006. setFromRotationMatrix(m, order = this._order, update = true) {
  4007. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4008. const te = m.elements;
  4009. const m11 = te[0],
  4010. m12 = te[4],
  4011. m13 = te[8];
  4012. const m21 = te[1],
  4013. m22 = te[5],
  4014. m23 = te[9];
  4015. const m31 = te[2],
  4016. m32 = te[6],
  4017. m33 = te[10];
  4018. switch (order) {
  4019. case 'XYZ':
  4020. this._y = Math.asin(clamp(m13, -1, 1));
  4021. if (Math.abs(m13) < 0.9999999) {
  4022. this._x = Math.atan2(-m23, m33);
  4023. this._z = Math.atan2(-m12, m11);
  4024. } else {
  4025. this._x = Math.atan2(m32, m22);
  4026. this._z = 0;
  4027. }
  4028. break;
  4029. case 'YXZ':
  4030. this._x = Math.asin(-clamp(m23, -1, 1));
  4031. if (Math.abs(m23) < 0.9999999) {
  4032. this._y = Math.atan2(m13, m33);
  4033. this._z = Math.atan2(m21, m22);
  4034. } else {
  4035. this._y = Math.atan2(-m31, m11);
  4036. this._z = 0;
  4037. }
  4038. break;
  4039. case 'ZXY':
  4040. this._x = Math.asin(clamp(m32, -1, 1));
  4041. if (Math.abs(m32) < 0.9999999) {
  4042. this._y = Math.atan2(-m31, m33);
  4043. this._z = Math.atan2(-m12, m22);
  4044. } else {
  4045. this._y = 0;
  4046. this._z = Math.atan2(m21, m11);
  4047. }
  4048. break;
  4049. case 'ZYX':
  4050. this._y = Math.asin(-clamp(m31, -1, 1));
  4051. if (Math.abs(m31) < 0.9999999) {
  4052. this._x = Math.atan2(m32, m33);
  4053. this._z = Math.atan2(m21, m11);
  4054. } else {
  4055. this._x = 0;
  4056. this._z = Math.atan2(-m12, m22);
  4057. }
  4058. break;
  4059. case 'YZX':
  4060. this._z = Math.asin(clamp(m21, -1, 1));
  4061. if (Math.abs(m21) < 0.9999999) {
  4062. this._x = Math.atan2(-m23, m22);
  4063. this._y = Math.atan2(-m31, m11);
  4064. } else {
  4065. this._x = 0;
  4066. this._y = Math.atan2(m13, m33);
  4067. }
  4068. break;
  4069. case 'XZY':
  4070. this._z = Math.asin(-clamp(m12, -1, 1));
  4071. if (Math.abs(m12) < 0.9999999) {
  4072. this._x = Math.atan2(m32, m22);
  4073. this._y = Math.atan2(m13, m11);
  4074. } else {
  4075. this._x = Math.atan2(-m23, m33);
  4076. this._y = 0;
  4077. }
  4078. break;
  4079. default:
  4080. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  4081. }
  4082. this._order = order;
  4083. if (update === true) this._onChangeCallback();
  4084. return this;
  4085. }
  4086. setFromQuaternion(q, order, update) {
  4087. _matrix$1.makeRotationFromQuaternion(q);
  4088. return this.setFromRotationMatrix(_matrix$1, order, update);
  4089. }
  4090. setFromVector3(v, order = this._order) {
  4091. return this.set(v.x, v.y, v.z, order);
  4092. }
  4093. reorder(newOrder) {
  4094. // WARNING: this discards revolution information -bhouston
  4095. _quaternion$3.setFromEuler(this);
  4096. return this.setFromQuaternion(_quaternion$3, newOrder);
  4097. }
  4098. equals(euler) {
  4099. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4100. }
  4101. fromArray(array) {
  4102. this._x = array[0];
  4103. this._y = array[1];
  4104. this._z = array[2];
  4105. if (array[3] !== undefined) this._order = array[3];
  4106. this._onChangeCallback();
  4107. return this;
  4108. }
  4109. toArray(array = [], offset = 0) {
  4110. array[offset] = this._x;
  4111. array[offset + 1] = this._y;
  4112. array[offset + 2] = this._z;
  4113. array[offset + 3] = this._order;
  4114. return array;
  4115. }
  4116. toVector3(optionalResult) {
  4117. if (optionalResult) {
  4118. return optionalResult.set(this._x, this._y, this._z);
  4119. } else {
  4120. return new Vector3(this._x, this._y, this._z);
  4121. }
  4122. }
  4123. _onChange(callback) {
  4124. this._onChangeCallback = callback;
  4125. return this;
  4126. }
  4127. _onChangeCallback() {}
  4128. }
  4129. Euler.prototype.isEuler = true;
  4130. Euler.DefaultOrder = 'XYZ';
  4131. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4132. class Layers {
  4133. constructor() {
  4134. this.mask = 1 | 0;
  4135. }
  4136. set(channel) {
  4137. this.mask = 1 << channel | 0;
  4138. }
  4139. enable(channel) {
  4140. this.mask |= 1 << channel | 0;
  4141. }
  4142. enableAll() {
  4143. this.mask = 0xffffffff | 0;
  4144. }
  4145. toggle(channel) {
  4146. this.mask ^= 1 << channel | 0;
  4147. }
  4148. disable(channel) {
  4149. this.mask &= ~(1 << channel | 0);
  4150. }
  4151. disableAll() {
  4152. this.mask = 0;
  4153. }
  4154. test(layers) {
  4155. return (this.mask & layers.mask) !== 0;
  4156. }
  4157. }
  4158. let _object3DId = 0;
  4159. const _v1$4 = /*@__PURE__*/new Vector3();
  4160. const _q1 = /*@__PURE__*/new Quaternion();
  4161. const _m1$1 = /*@__PURE__*/new Matrix4();
  4162. const _target = /*@__PURE__*/new Vector3();
  4163. const _position$3 = /*@__PURE__*/new Vector3();
  4164. const _scale$2 = /*@__PURE__*/new Vector3();
  4165. const _quaternion$2 = /*@__PURE__*/new Quaternion();
  4166. const _xAxis = /*@__PURE__*/new Vector3(1, 0, 0);
  4167. const _yAxis = /*@__PURE__*/new Vector3(0, 1, 0);
  4168. const _zAxis = /*@__PURE__*/new Vector3(0, 0, 1);
  4169. const _addedEvent = {
  4170. type: 'added'
  4171. };
  4172. const _removedEvent = {
  4173. type: 'removed'
  4174. };
  4175. class Object3D extends EventDispatcher {
  4176. constructor() {
  4177. super();
  4178. Object.defineProperty(this, 'id', {
  4179. value: _object3DId++
  4180. });
  4181. this.uuid = generateUUID();
  4182. this.name = '';
  4183. this.type = 'Object3D';
  4184. this.parent = null;
  4185. this.children = [];
  4186. this.up = Object3D.DefaultUp.clone();
  4187. const position = new Vector3();
  4188. const rotation = new Euler();
  4189. const quaternion = new Quaternion();
  4190. const scale = new Vector3(1, 1, 1);
  4191. function onRotationChange() {
  4192. quaternion.setFromEuler(rotation, false);
  4193. }
  4194. function onQuaternionChange() {
  4195. rotation.setFromQuaternion(quaternion, undefined, false);
  4196. }
  4197. rotation._onChange(onRotationChange);
  4198. quaternion._onChange(onQuaternionChange);
  4199. Object.defineProperties(this, {
  4200. position: {
  4201. configurable: true,
  4202. enumerable: true,
  4203. value: position
  4204. },
  4205. rotation: {
  4206. configurable: true,
  4207. enumerable: true,
  4208. value: rotation
  4209. },
  4210. quaternion: {
  4211. configurable: true,
  4212. enumerable: true,
  4213. value: quaternion
  4214. },
  4215. scale: {
  4216. configurable: true,
  4217. enumerable: true,
  4218. value: scale
  4219. },
  4220. modelViewMatrix: {
  4221. value: new Matrix4()
  4222. },
  4223. normalMatrix: {
  4224. value: new Matrix3()
  4225. }
  4226. });
  4227. this.matrix = new Matrix4();
  4228. this.matrixWorld = new Matrix4();
  4229. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4230. this.matrixWorldNeedsUpdate = false;
  4231. this.layers = new Layers();
  4232. this.visible = true;
  4233. this.castShadow = false;
  4234. this.receiveShadow = false;
  4235. this.frustumCulled = true;
  4236. this.renderOrder = 0;
  4237. this.animations = [];
  4238. this.userData = {};
  4239. }
  4240. onBeforeRender() {}
  4241. onAfterRender() {}
  4242. applyMatrix4(matrix) {
  4243. if (this.matrixAutoUpdate) this.updateMatrix();
  4244. this.matrix.premultiply(matrix);
  4245. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4246. }
  4247. applyQuaternion(q) {
  4248. this.quaternion.premultiply(q);
  4249. return this;
  4250. }
  4251. setRotationFromAxisAngle(axis, angle) {
  4252. // assumes axis is normalized
  4253. this.quaternion.setFromAxisAngle(axis, angle);
  4254. }
  4255. setRotationFromEuler(euler) {
  4256. this.quaternion.setFromEuler(euler, true);
  4257. }
  4258. setRotationFromMatrix(m) {
  4259. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4260. this.quaternion.setFromRotationMatrix(m);
  4261. }
  4262. setRotationFromQuaternion(q) {
  4263. // assumes q is normalized
  4264. this.quaternion.copy(q);
  4265. }
  4266. rotateOnAxis(axis, angle) {
  4267. // rotate object on axis in object space
  4268. // axis is assumed to be normalized
  4269. _q1.setFromAxisAngle(axis, angle);
  4270. this.quaternion.multiply(_q1);
  4271. return this;
  4272. }
  4273. rotateOnWorldAxis(axis, angle) {
  4274. // rotate object on axis in world space
  4275. // axis is assumed to be normalized
  4276. // method assumes no rotated parent
  4277. _q1.setFromAxisAngle(axis, angle);
  4278. this.quaternion.premultiply(_q1);
  4279. return this;
  4280. }
  4281. rotateX(angle) {
  4282. return this.rotateOnAxis(_xAxis, angle);
  4283. }
  4284. rotateY(angle) {
  4285. return this.rotateOnAxis(_yAxis, angle);
  4286. }
  4287. rotateZ(angle) {
  4288. return this.rotateOnAxis(_zAxis, angle);
  4289. }
  4290. translateOnAxis(axis, distance) {
  4291. // translate object by distance along axis in object space
  4292. // axis is assumed to be normalized
  4293. _v1$4.copy(axis).applyQuaternion(this.quaternion);
  4294. this.position.add(_v1$4.multiplyScalar(distance));
  4295. return this;
  4296. }
  4297. translateX(distance) {
  4298. return this.translateOnAxis(_xAxis, distance);
  4299. }
  4300. translateY(distance) {
  4301. return this.translateOnAxis(_yAxis, distance);
  4302. }
  4303. translateZ(distance) {
  4304. return this.translateOnAxis(_zAxis, distance);
  4305. }
  4306. localToWorld(vector) {
  4307. return vector.applyMatrix4(this.matrixWorld);
  4308. }
  4309. worldToLocal(vector) {
  4310. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  4311. }
  4312. lookAt(x, y, z) {
  4313. // This method does not support objects having non-uniformly-scaled parent(s)
  4314. if (x.isVector3) {
  4315. _target.copy(x);
  4316. } else {
  4317. _target.set(x, y, z);
  4318. }
  4319. const parent = this.parent;
  4320. this.updateWorldMatrix(true, false);
  4321. _position$3.setFromMatrixPosition(this.matrixWorld);
  4322. if (this.isCamera || this.isLight) {
  4323. _m1$1.lookAt(_position$3, _target, this.up);
  4324. } else {
  4325. _m1$1.lookAt(_target, _position$3, this.up);
  4326. }
  4327. this.quaternion.setFromRotationMatrix(_m1$1);
  4328. if (parent) {
  4329. _m1$1.extractRotation(parent.matrixWorld);
  4330. _q1.setFromRotationMatrix(_m1$1);
  4331. this.quaternion.premultiply(_q1.invert());
  4332. }
  4333. }
  4334. add(object) {
  4335. if (arguments.length > 1) {
  4336. for (let i = 0; i < arguments.length; i++) {
  4337. this.add(arguments[i]);
  4338. }
  4339. return this;
  4340. }
  4341. if (object === this) {
  4342. console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
  4343. return this;
  4344. }
  4345. if (object && object.isObject3D) {
  4346. if (object.parent !== null) {
  4347. object.parent.remove(object);
  4348. }
  4349. object.parent = this;
  4350. this.children.push(object);
  4351. object.dispatchEvent(_addedEvent);
  4352. } else {
  4353. console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
  4354. }
  4355. return this;
  4356. }
  4357. remove(object) {
  4358. if (arguments.length > 1) {
  4359. for (let i = 0; i < arguments.length; i++) {
  4360. this.remove(arguments[i]);
  4361. }
  4362. return this;
  4363. }
  4364. const index = this.children.indexOf(object);
  4365. if (index !== -1) {
  4366. object.parent = null;
  4367. this.children.splice(index, 1);
  4368. object.dispatchEvent(_removedEvent);
  4369. }
  4370. return this;
  4371. }
  4372. removeFromParent() {
  4373. const parent = this.parent;
  4374. if (parent !== null) {
  4375. parent.remove(this);
  4376. }
  4377. return this;
  4378. }
  4379. clear() {
  4380. for (let i = 0; i < this.children.length; i++) {
  4381. const object = this.children[i];
  4382. object.parent = null;
  4383. object.dispatchEvent(_removedEvent);
  4384. }
  4385. this.children.length = 0;
  4386. return this;
  4387. }
  4388. attach(object) {
  4389. // adds object as a child of this, while maintaining the object's world transform
  4390. this.updateWorldMatrix(true, false);
  4391. _m1$1.copy(this.matrixWorld).invert();
  4392. if (object.parent !== null) {
  4393. object.parent.updateWorldMatrix(true, false);
  4394. _m1$1.multiply(object.parent.matrixWorld);
  4395. }
  4396. object.applyMatrix4(_m1$1);
  4397. this.add(object);
  4398. object.updateWorldMatrix(false, true);
  4399. return this;
  4400. }
  4401. getObjectById(id) {
  4402. return this.getObjectByProperty('id', id);
  4403. }
  4404. getObjectByName(name) {
  4405. return this.getObjectByProperty('name', name);
  4406. }
  4407. getObjectByProperty(name, value) {
  4408. if (this[name] === value) return this;
  4409. for (let i = 0, l = this.children.length; i < l; i++) {
  4410. const child = this.children[i];
  4411. const object = child.getObjectByProperty(name, value);
  4412. if (object !== undefined) {
  4413. return object;
  4414. }
  4415. }
  4416. return undefined;
  4417. }
  4418. getWorldPosition(target) {
  4419. this.updateWorldMatrix(true, false);
  4420. return target.setFromMatrixPosition(this.matrixWorld);
  4421. }
  4422. getWorldQuaternion(target) {
  4423. this.updateWorldMatrix(true, false);
  4424. this.matrixWorld.decompose(_position$3, target, _scale$2);
  4425. return target;
  4426. }
  4427. getWorldScale(target) {
  4428. this.updateWorldMatrix(true, false);
  4429. this.matrixWorld.decompose(_position$3, _quaternion$2, target);
  4430. return target;
  4431. }
  4432. getWorldDirection(target) {
  4433. this.updateWorldMatrix(true, false);
  4434. const e = this.matrixWorld.elements;
  4435. return target.set(e[8], e[9], e[10]).normalize();
  4436. }
  4437. raycast() {}
  4438. traverse(callback) {
  4439. callback(this);
  4440. const children = this.children;
  4441. for (let i = 0, l = children.length; i < l; i++) {
  4442. children[i].traverse(callback);
  4443. }
  4444. }
  4445. traverseVisible(callback) {
  4446. if (this.visible === false) return;
  4447. callback(this);
  4448. const children = this.children;
  4449. for (let i = 0, l = children.length; i < l; i++) {
  4450. children[i].traverseVisible(callback);
  4451. }
  4452. }
  4453. traverseAncestors(callback) {
  4454. const parent = this.parent;
  4455. if (parent !== null) {
  4456. callback(parent);
  4457. parent.traverseAncestors(callback);
  4458. }
  4459. }
  4460. updateMatrix() {
  4461. this.matrix.compose(this.position, this.quaternion, this.scale);
  4462. this.matrixWorldNeedsUpdate = true;
  4463. }
  4464. updateMatrixWorld(force) {
  4465. if (this.matrixAutoUpdate) this.updateMatrix();
  4466. if (this.matrixWorldNeedsUpdate || force) {
  4467. if (this.parent === null) {
  4468. this.matrixWorld.copy(this.matrix);
  4469. } else {
  4470. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4471. }
  4472. this.matrixWorldNeedsUpdate = false;
  4473. force = true;
  4474. } // update children
  4475. const children = this.children;
  4476. for (let i = 0, l = children.length; i < l; i++) {
  4477. children[i].updateMatrixWorld(force);
  4478. }
  4479. }
  4480. updateWorldMatrix(updateParents, updateChildren) {
  4481. const parent = this.parent;
  4482. if (updateParents === true && parent !== null) {
  4483. parent.updateWorldMatrix(true, false);
  4484. }
  4485. if (this.matrixAutoUpdate) this.updateMatrix();
  4486. if (this.parent === null) {
  4487. this.matrixWorld.copy(this.matrix);
  4488. } else {
  4489. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4490. } // update children
  4491. if (updateChildren === true) {
  4492. const children = this.children;
  4493. for (let i = 0, l = children.length; i < l; i++) {
  4494. children[i].updateWorldMatrix(false, true);
  4495. }
  4496. }
  4497. }
  4498. toJSON(meta) {
  4499. // meta is a string when called from JSON.stringify
  4500. const isRootObject = meta === undefined || typeof meta === 'string';
  4501. const output = {}; // meta is a hash used to collect geometries, materials.
  4502. // not providing it implies that this is the root object
  4503. // being serialized.
  4504. if (isRootObject) {
  4505. // initialize meta obj
  4506. meta = {
  4507. geometries: {},
  4508. materials: {},
  4509. textures: {},
  4510. images: {},
  4511. shapes: {},
  4512. skeletons: {},
  4513. animations: {}
  4514. };
  4515. output.metadata = {
  4516. version: 4.5,
  4517. type: 'Object',
  4518. generator: 'Object3D.toJSON'
  4519. };
  4520. } // standard Object3D serialization
  4521. const object = {};
  4522. object.uuid = this.uuid;
  4523. object.type = this.type;
  4524. if (this.name !== '') object.name = this.name;
  4525. if (this.castShadow === true) object.castShadow = true;
  4526. if (this.receiveShadow === true) object.receiveShadow = true;
  4527. if (this.visible === false) object.visible = false;
  4528. if (this.frustumCulled === false) object.frustumCulled = false;
  4529. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  4530. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  4531. object.layers = this.layers.mask;
  4532. object.matrix = this.matrix.toArray();
  4533. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  4534. if (this.isInstancedMesh) {
  4535. object.type = 'InstancedMesh';
  4536. object.count = this.count;
  4537. object.instanceMatrix = this.instanceMatrix.toJSON();
  4538. if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON();
  4539. } //
  4540. function serialize(library, element) {
  4541. if (library[element.uuid] === undefined) {
  4542. library[element.uuid] = element.toJSON(meta);
  4543. }
  4544. return element.uuid;
  4545. }
  4546. if (this.isScene) {
  4547. if (this.background) {
  4548. if (this.background.isColor) {
  4549. object.background = this.background.toJSON();
  4550. } else if (this.background.isTexture) {
  4551. object.background = this.background.toJSON(meta).uuid;
  4552. }
  4553. }
  4554. if (this.environment && this.environment.isTexture) {
  4555. object.environment = this.environment.toJSON(meta).uuid;
  4556. }
  4557. } else if (this.isMesh || this.isLine || this.isPoints) {
  4558. object.geometry = serialize(meta.geometries, this.geometry);
  4559. const parameters = this.geometry.parameters;
  4560. if (parameters !== undefined && parameters.shapes !== undefined) {
  4561. const shapes = parameters.shapes;
  4562. if (Array.isArray(shapes)) {
  4563. for (let i = 0, l = shapes.length; i < l; i++) {
  4564. const shape = shapes[i];
  4565. serialize(meta.shapes, shape);
  4566. }
  4567. } else {
  4568. serialize(meta.shapes, shapes);
  4569. }
  4570. }
  4571. }
  4572. if (this.isSkinnedMesh) {
  4573. object.bindMode = this.bindMode;
  4574. object.bindMatrix = this.bindMatrix.toArray();
  4575. if (this.skeleton !== undefined) {
  4576. serialize(meta.skeletons, this.skeleton);
  4577. object.skeleton = this.skeleton.uuid;
  4578. }
  4579. }
  4580. if (this.material !== undefined) {
  4581. if (Array.isArray(this.material)) {
  4582. const uuids = [];
  4583. for (let i = 0, l = this.material.length; i < l; i++) {
  4584. uuids.push(serialize(meta.materials, this.material[i]));
  4585. }
  4586. object.material = uuids;
  4587. } else {
  4588. object.material = serialize(meta.materials, this.material);
  4589. }
  4590. } //
  4591. if (this.children.length > 0) {
  4592. object.children = [];
  4593. for (let i = 0; i < this.children.length; i++) {
  4594. object.children.push(this.children[i].toJSON(meta).object);
  4595. }
  4596. } //
  4597. if (this.animations.length > 0) {
  4598. object.animations = [];
  4599. for (let i = 0; i < this.animations.length; i++) {
  4600. const animation = this.animations[i];
  4601. object.animations.push(serialize(meta.animations, animation));
  4602. }
  4603. }
  4604. if (isRootObject) {
  4605. const geometries = extractFromCache(meta.geometries);
  4606. const materials = extractFromCache(meta.materials);
  4607. const textures = extractFromCache(meta.textures);
  4608. const images = extractFromCache(meta.images);
  4609. const shapes = extractFromCache(meta.shapes);
  4610. const skeletons = extractFromCache(meta.skeletons);
  4611. const animations = extractFromCache(meta.animations);
  4612. if (geometries.length > 0) output.geometries = geometries;
  4613. if (materials.length > 0) output.materials = materials;
  4614. if (textures.length > 0) output.textures = textures;
  4615. if (images.length > 0) output.images = images;
  4616. if (shapes.length > 0) output.shapes = shapes;
  4617. if (skeletons.length > 0) output.skeletons = skeletons;
  4618. if (animations.length > 0) output.animations = animations;
  4619. }
  4620. output.object = object;
  4621. return output; // extract data from the cache hash
  4622. // remove metadata on each item
  4623. // and return as array
  4624. function extractFromCache(cache) {
  4625. const values = [];
  4626. for (const key in cache) {
  4627. const data = cache[key];
  4628. delete data.metadata;
  4629. values.push(data);
  4630. }
  4631. return values;
  4632. }
  4633. }
  4634. clone(recursive) {
  4635. return new this.constructor().copy(this, recursive);
  4636. }
  4637. copy(source, recursive = true) {
  4638. this.name = source.name;
  4639. this.up.copy(source.up);
  4640. this.position.copy(source.position);
  4641. this.rotation.order = source.rotation.order;
  4642. this.quaternion.copy(source.quaternion);
  4643. this.scale.copy(source.scale);
  4644. this.matrix.copy(source.matrix);
  4645. this.matrixWorld.copy(source.matrixWorld);
  4646. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4647. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4648. this.layers.mask = source.layers.mask;
  4649. this.visible = source.visible;
  4650. this.castShadow = source.castShadow;
  4651. this.receiveShadow = source.receiveShadow;
  4652. this.frustumCulled = source.frustumCulled;
  4653. this.renderOrder = source.renderOrder;
  4654. this.userData = JSON.parse(JSON.stringify(source.userData));
  4655. if (recursive === true) {
  4656. for (let i = 0; i < source.children.length; i++) {
  4657. const child = source.children[i];
  4658. this.add(child.clone());
  4659. }
  4660. }
  4661. return this;
  4662. }
  4663. }
  4664. Object3D.DefaultUp = new Vector3(0, 1, 0);
  4665. Object3D.DefaultMatrixAutoUpdate = true;
  4666. Object3D.prototype.isObject3D = true;
  4667. const _v0$1 = /*@__PURE__*/new Vector3();
  4668. const _v1$3 = /*@__PURE__*/new Vector3();
  4669. const _v2$2 = /*@__PURE__*/new Vector3();
  4670. const _v3$1 = /*@__PURE__*/new Vector3();
  4671. const _vab = /*@__PURE__*/new Vector3();
  4672. const _vac = /*@__PURE__*/new Vector3();
  4673. const _vbc = /*@__PURE__*/new Vector3();
  4674. const _vap = /*@__PURE__*/new Vector3();
  4675. const _vbp = /*@__PURE__*/new Vector3();
  4676. const _vcp = /*@__PURE__*/new Vector3();
  4677. class Triangle {
  4678. constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) {
  4679. this.a = a;
  4680. this.b = b;
  4681. this.c = c;
  4682. }
  4683. static getNormal(a, b, c, target) {
  4684. target.subVectors(c, b);
  4685. _v0$1.subVectors(a, b);
  4686. target.cross(_v0$1);
  4687. const targetLengthSq = target.lengthSq();
  4688. if (targetLengthSq > 0) {
  4689. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  4690. }
  4691. return target.set(0, 0, 0);
  4692. } // static/instance method to calculate barycentric coordinates
  4693. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4694. static getBarycoord(point, a, b, c, target) {
  4695. _v0$1.subVectors(c, a);
  4696. _v1$3.subVectors(b, a);
  4697. _v2$2.subVectors(point, a);
  4698. const dot00 = _v0$1.dot(_v0$1);
  4699. const dot01 = _v0$1.dot(_v1$3);
  4700. const dot02 = _v0$1.dot(_v2$2);
  4701. const dot11 = _v1$3.dot(_v1$3);
  4702. const dot12 = _v1$3.dot(_v2$2);
  4703. const denom = dot00 * dot11 - dot01 * dot01; // collinear or singular triangle
  4704. if (denom === 0) {
  4705. // arbitrary location outside of triangle?
  4706. // not sure if this is the best idea, maybe should be returning undefined
  4707. return target.set(-2, -1, -1);
  4708. }
  4709. const invDenom = 1 / denom;
  4710. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  4711. const v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  4712. return target.set(1 - u - v, v, u);
  4713. }
  4714. static containsPoint(point, a, b, c) {
  4715. this.getBarycoord(point, a, b, c, _v3$1);
  4716. return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1;
  4717. }
  4718. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  4719. this.getBarycoord(point, p1, p2, p3, _v3$1);
  4720. target.set(0, 0);
  4721. target.addScaledVector(uv1, _v3$1.x);
  4722. target.addScaledVector(uv2, _v3$1.y);
  4723. target.addScaledVector(uv3, _v3$1.z);
  4724. return target;
  4725. }
  4726. static isFrontFacing(a, b, c, direction) {
  4727. _v0$1.subVectors(c, b);
  4728. _v1$3.subVectors(a, b); // strictly front facing
  4729. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  4730. }
  4731. set(a, b, c) {
  4732. this.a.copy(a);
  4733. this.b.copy(b);
  4734. this.c.copy(c);
  4735. return this;
  4736. }
  4737. setFromPointsAndIndices(points, i0, i1, i2) {
  4738. this.a.copy(points[i0]);
  4739. this.b.copy(points[i1]);
  4740. this.c.copy(points[i2]);
  4741. return this;
  4742. }
  4743. setFromAttributeAndIndices(attribute, i0, i1, i2) {
  4744. this.a.fromBufferAttribute(attribute, i0);
  4745. this.b.fromBufferAttribute(attribute, i1);
  4746. this.c.fromBufferAttribute(attribute, i2);
  4747. return this;
  4748. }
  4749. clone() {
  4750. return new this.constructor().copy(this);
  4751. }
  4752. copy(triangle) {
  4753. this.a.copy(triangle.a);
  4754. this.b.copy(triangle.b);
  4755. this.c.copy(triangle.c);
  4756. return this;
  4757. }
  4758. getArea() {
  4759. _v0$1.subVectors(this.c, this.b);
  4760. _v1$3.subVectors(this.a, this.b);
  4761. return _v0$1.cross(_v1$3).length() * 0.5;
  4762. }
  4763. getMidpoint(target) {
  4764. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  4765. }
  4766. getNormal(target) {
  4767. return Triangle.getNormal(this.a, this.b, this.c, target);
  4768. }
  4769. getPlane(target) {
  4770. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  4771. }
  4772. getBarycoord(point, target) {
  4773. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  4774. }
  4775. getUV(point, uv1, uv2, uv3, target) {
  4776. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  4777. }
  4778. containsPoint(point) {
  4779. return Triangle.containsPoint(point, this.a, this.b, this.c);
  4780. }
  4781. isFrontFacing(direction) {
  4782. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  4783. }
  4784. intersectsBox(box) {
  4785. return box.intersectsTriangle(this);
  4786. }
  4787. closestPointToPoint(p, target) {
  4788. const a = this.a,
  4789. b = this.b,
  4790. c = this.c;
  4791. let v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4792. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4793. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4794. // basically, we're distinguishing which of the voronoi regions of the triangle
  4795. // the point lies in with the minimum amount of redundant computation.
  4796. _vab.subVectors(b, a);
  4797. _vac.subVectors(c, a);
  4798. _vap.subVectors(p, a);
  4799. const d1 = _vab.dot(_vap);
  4800. const d2 = _vac.dot(_vap);
  4801. if (d1 <= 0 && d2 <= 0) {
  4802. // vertex region of A; barycentric coords (1, 0, 0)
  4803. return target.copy(a);
  4804. }
  4805. _vbp.subVectors(p, b);
  4806. const d3 = _vab.dot(_vbp);
  4807. const d4 = _vac.dot(_vbp);
  4808. if (d3 >= 0 && d4 <= d3) {
  4809. // vertex region of B; barycentric coords (0, 1, 0)
  4810. return target.copy(b);
  4811. }
  4812. const vc = d1 * d4 - d3 * d2;
  4813. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  4814. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  4815. return target.copy(a).addScaledVector(_vab, v);
  4816. }
  4817. _vcp.subVectors(p, c);
  4818. const d5 = _vab.dot(_vcp);
  4819. const d6 = _vac.dot(_vcp);
  4820. if (d6 >= 0 && d5 <= d6) {
  4821. // vertex region of C; barycentric coords (0, 0, 1)
  4822. return target.copy(c);
  4823. }
  4824. const vb = d5 * d2 - d1 * d6;
  4825. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  4826. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  4827. return target.copy(a).addScaledVector(_vac, w);
  4828. }
  4829. const va = d3 * d6 - d5 * d4;
  4830. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  4831. _vbc.subVectors(c, b);
  4832. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  4833. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  4834. } // face region
  4835. const denom = 1 / (va + vb + vc); // u = va * denom
  4836. v = vb * denom;
  4837. w = vc * denom;
  4838. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  4839. }
  4840. equals(triangle) {
  4841. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  4842. }
  4843. }
  4844. let materialId = 0;
  4845. class Material extends EventDispatcher {
  4846. constructor() {
  4847. super();
  4848. Object.defineProperty(this, 'id', {
  4849. value: materialId++
  4850. });
  4851. this.uuid = generateUUID();
  4852. this.name = '';
  4853. this.type = 'Material';
  4854. this.fog = true;
  4855. this.blending = NormalBlending;
  4856. this.side = FrontSide;
  4857. this.vertexColors = false;
  4858. this.opacity = 1;
  4859. this.format = RGBAFormat;
  4860. this.transparent = false;
  4861. this.blendSrc = SrcAlphaFactor;
  4862. this.blendDst = OneMinusSrcAlphaFactor;
  4863. this.blendEquation = AddEquation;
  4864. this.blendSrcAlpha = null;
  4865. this.blendDstAlpha = null;
  4866. this.blendEquationAlpha = null;
  4867. this.depthFunc = LessEqualDepth;
  4868. this.depthTest = true;
  4869. this.depthWrite = true;
  4870. this.stencilWriteMask = 0xff;
  4871. this.stencilFunc = AlwaysStencilFunc;
  4872. this.stencilRef = 0;
  4873. this.stencilFuncMask = 0xff;
  4874. this.stencilFail = KeepStencilOp;
  4875. this.stencilZFail = KeepStencilOp;
  4876. this.stencilZPass = KeepStencilOp;
  4877. this.stencilWrite = false;
  4878. this.clippingPlanes = null;
  4879. this.clipIntersection = false;
  4880. this.clipShadows = false;
  4881. this.shadowSide = null;
  4882. this.colorWrite = true;
  4883. this.precision = null; // override the renderer's default precision for this material
  4884. this.polygonOffset = false;
  4885. this.polygonOffsetFactor = 0;
  4886. this.polygonOffsetUnits = 0;
  4887. this.dithering = false;
  4888. this.alphaToCoverage = false;
  4889. this.premultipliedAlpha = false;
  4890. this.visible = true;
  4891. this.toneMapped = true;
  4892. this.userData = {};
  4893. this.version = 0;
  4894. this._alphaTest = 0;
  4895. }
  4896. get alphaTest() {
  4897. return this._alphaTest;
  4898. }
  4899. set alphaTest(value) {
  4900. if (this._alphaTest > 0 !== value > 0) {
  4901. this.version++;
  4902. }
  4903. this._alphaTest = value;
  4904. }
  4905. onBuild() {}
  4906. onBeforeRender() {}
  4907. onBeforeCompile() {}
  4908. customProgramCacheKey() {
  4909. return this.onBeforeCompile.toString();
  4910. }
  4911. setValues(values) {
  4912. if (values === undefined) return;
  4913. for (const key in values) {
  4914. const newValue = values[key];
  4915. if (newValue === undefined) {
  4916. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  4917. continue;
  4918. } // for backward compatability if shading is set in the constructor
  4919. if (key === 'shading') {
  4920. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  4921. this.flatShading = newValue === FlatShading ? true : false;
  4922. continue;
  4923. }
  4924. const currentValue = this[key];
  4925. if (currentValue === undefined) {
  4926. console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
  4927. continue;
  4928. }
  4929. if (currentValue && currentValue.isColor) {
  4930. currentValue.set(newValue);
  4931. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  4932. currentValue.copy(newValue);
  4933. } else {
  4934. this[key] = newValue;
  4935. }
  4936. }
  4937. }
  4938. toJSON(meta) {
  4939. const isRoot = meta === undefined || typeof meta === 'string';
  4940. if (isRoot) {
  4941. meta = {
  4942. textures: {},
  4943. images: {}
  4944. };
  4945. }
  4946. const data = {
  4947. metadata: {
  4948. version: 4.5,
  4949. type: 'Material',
  4950. generator: 'Material.toJSON'
  4951. }
  4952. }; // standard Material serialization
  4953. data.uuid = this.uuid;
  4954. data.type = this.type;
  4955. if (this.name !== '') data.name = this.name;
  4956. if (this.color && this.color.isColor) data.color = this.color.getHex();
  4957. if (this.roughness !== undefined) data.roughness = this.roughness;
  4958. if (this.metalness !== undefined) data.metalness = this.metalness;
  4959. if (this.sheen !== undefined) data.sheen = this.sheen;
  4960. if (this.sheenTint && this.sheenTint.isColor) data.sheenTint = this.sheenTint.getHex();
  4961. if (this.sheenRoughness !== undefined) data.sheenRoughness = this.sheenRoughness;
  4962. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  4963. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  4964. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  4965. if (this.specularIntensity !== undefined) data.specularIntensity = this.specularIntensity;
  4966. if (this.specularTint && this.specularTint.isColor) data.specularTint = this.specularTint.getHex();
  4967. if (this.shininess !== undefined) data.shininess = this.shininess;
  4968. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  4969. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  4970. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  4971. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  4972. }
  4973. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  4974. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  4975. }
  4976. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  4977. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  4978. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  4979. }
  4980. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  4981. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  4982. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  4983. if (this.lightMap && this.lightMap.isTexture) {
  4984. data.lightMap = this.lightMap.toJSON(meta).uuid;
  4985. data.lightMapIntensity = this.lightMapIntensity;
  4986. }
  4987. if (this.aoMap && this.aoMap.isTexture) {
  4988. data.aoMap = this.aoMap.toJSON(meta).uuid;
  4989. data.aoMapIntensity = this.aoMapIntensity;
  4990. }
  4991. if (this.bumpMap && this.bumpMap.isTexture) {
  4992. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  4993. data.bumpScale = this.bumpScale;
  4994. }
  4995. if (this.normalMap && this.normalMap.isTexture) {
  4996. data.normalMap = this.normalMap.toJSON(meta).uuid;
  4997. data.normalMapType = this.normalMapType;
  4998. data.normalScale = this.normalScale.toArray();
  4999. }
  5000. if (this.displacementMap && this.displacementMap.isTexture) {
  5001. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  5002. data.displacementScale = this.displacementScale;
  5003. data.displacementBias = this.displacementBias;
  5004. }
  5005. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  5006. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  5007. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  5008. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  5009. if (this.specularIntensityMap && this.specularIntensityMap.isTexture) data.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid;
  5010. if (this.specularTintMap && this.specularTintMap.isTexture) data.specularTintMap = this.specularTintMap.toJSON(meta).uuid;
  5011. if (this.envMap && this.envMap.isTexture) {
  5012. data.envMap = this.envMap.toJSON(meta).uuid;
  5013. if (this.combine !== undefined) data.combine = this.combine;
  5014. }
  5015. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  5016. if (this.reflectivity !== undefined) data.reflectivity = this.reflectivity;
  5017. if (this.refractionRatio !== undefined) data.refractionRatio = this.refractionRatio;
  5018. if (this.gradientMap && this.gradientMap.isTexture) {
  5019. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  5020. }
  5021. if (this.transmission !== undefined) data.transmission = this.transmission;
  5022. if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid;
  5023. if (this.thickness !== undefined) data.thickness = this.thickness;
  5024. if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid;
  5025. if (this.attenuationDistance !== undefined) data.attenuationDistance = this.attenuationDistance;
  5026. if (this.attenuationTint !== undefined) data.attenuationTint = this.attenuationTint.getHex();
  5027. if (this.size !== undefined) data.size = this.size;
  5028. if (this.shadowSide !== null) data.shadowSide = this.shadowSide;
  5029. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  5030. if (this.blending !== NormalBlending) data.blending = this.blending;
  5031. if (this.side !== FrontSide) data.side = this.side;
  5032. if (this.vertexColors) data.vertexColors = true;
  5033. if (this.opacity < 1) data.opacity = this.opacity;
  5034. if (this.format !== RGBAFormat) data.format = this.format;
  5035. if (this.transparent === true) data.transparent = this.transparent;
  5036. data.depthFunc = this.depthFunc;
  5037. data.depthTest = this.depthTest;
  5038. data.depthWrite = this.depthWrite;
  5039. data.colorWrite = this.colorWrite;
  5040. data.stencilWrite = this.stencilWrite;
  5041. data.stencilWriteMask = this.stencilWriteMask;
  5042. data.stencilFunc = this.stencilFunc;
  5043. data.stencilRef = this.stencilRef;
  5044. data.stencilFuncMask = this.stencilFuncMask;
  5045. data.stencilFail = this.stencilFail;
  5046. data.stencilZFail = this.stencilZFail;
  5047. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  5048. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  5049. if (this.polygonOffset === true) data.polygonOffset = true;
  5050. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5051. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5052. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  5053. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  5054. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  5055. if (this.scale !== undefined) data.scale = this.scale;
  5056. if (this.dithering === true) data.dithering = true;
  5057. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  5058. if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage;
  5059. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  5060. if (this.wireframe === true) data.wireframe = this.wireframe;
  5061. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  5062. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  5063. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  5064. if (this.flatShading === true) data.flatShading = this.flatShading;
  5065. if (this.visible === false) data.visible = false;
  5066. if (this.toneMapped === false) data.toneMapped = false;
  5067. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  5068. function extractFromCache(cache) {
  5069. const values = [];
  5070. for (const key in cache) {
  5071. const data = cache[key];
  5072. delete data.metadata;
  5073. values.push(data);
  5074. }
  5075. return values;
  5076. }
  5077. if (isRoot) {
  5078. const textures = extractFromCache(meta.textures);
  5079. const images = extractFromCache(meta.images);
  5080. if (textures.length > 0) data.textures = textures;
  5081. if (images.length > 0) data.images = images;
  5082. }
  5083. return data;
  5084. }
  5085. clone() {
  5086. return new this.constructor().copy(this);
  5087. }
  5088. copy(source) {
  5089. this.name = source.name;
  5090. this.fog = source.fog;
  5091. this.blending = source.blending;
  5092. this.side = source.side;
  5093. this.vertexColors = source.vertexColors;
  5094. this.opacity = source.opacity;
  5095. this.format = source.format;
  5096. this.transparent = source.transparent;
  5097. this.blendSrc = source.blendSrc;
  5098. this.blendDst = source.blendDst;
  5099. this.blendEquation = source.blendEquation;
  5100. this.blendSrcAlpha = source.blendSrcAlpha;
  5101. this.blendDstAlpha = source.blendDstAlpha;
  5102. this.blendEquationAlpha = source.blendEquationAlpha;
  5103. this.depthFunc = source.depthFunc;
  5104. this.depthTest = source.depthTest;
  5105. this.depthWrite = source.depthWrite;
  5106. this.stencilWriteMask = source.stencilWriteMask;
  5107. this.stencilFunc = source.stencilFunc;
  5108. this.stencilRef = source.stencilRef;
  5109. this.stencilFuncMask = source.stencilFuncMask;
  5110. this.stencilFail = source.stencilFail;
  5111. this.stencilZFail = source.stencilZFail;
  5112. this.stencilZPass = source.stencilZPass;
  5113. this.stencilWrite = source.stencilWrite;
  5114. const srcPlanes = source.clippingPlanes;
  5115. let dstPlanes = null;
  5116. if (srcPlanes !== null) {
  5117. const n = srcPlanes.length;
  5118. dstPlanes = new Array(n);
  5119. for (let i = 0; i !== n; ++i) {
  5120. dstPlanes[i] = srcPlanes[i].clone();
  5121. }
  5122. }
  5123. this.clippingPlanes = dstPlanes;
  5124. this.clipIntersection = source.clipIntersection;
  5125. this.clipShadows = source.clipShadows;
  5126. this.shadowSide = source.shadowSide;
  5127. this.colorWrite = source.colorWrite;
  5128. this.precision = source.precision;
  5129. this.polygonOffset = source.polygonOffset;
  5130. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5131. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5132. this.dithering = source.dithering;
  5133. this.alphaTest = source.alphaTest;
  5134. this.alphaToCoverage = source.alphaToCoverage;
  5135. this.premultipliedAlpha = source.premultipliedAlpha;
  5136. this.visible = source.visible;
  5137. this.toneMapped = source.toneMapped;
  5138. this.userData = JSON.parse(JSON.stringify(source.userData));
  5139. return this;
  5140. }
  5141. dispose() {
  5142. this.dispatchEvent({
  5143. type: 'dispose'
  5144. });
  5145. }
  5146. set needsUpdate(value) {
  5147. if (value === true) this.version++;
  5148. }
  5149. }
  5150. Material.prototype.isMaterial = true;
  5151. const _colorKeywords = {
  5152. 'aliceblue': 0xF0F8FF,
  5153. 'antiquewhite': 0xFAEBD7,
  5154. 'aqua': 0x00FFFF,
  5155. 'aquamarine': 0x7FFFD4,
  5156. 'azure': 0xF0FFFF,
  5157. 'beige': 0xF5F5DC,
  5158. 'bisque': 0xFFE4C4,
  5159. 'black': 0x000000,
  5160. 'blanchedalmond': 0xFFEBCD,
  5161. 'blue': 0x0000FF,
  5162. 'blueviolet': 0x8A2BE2,
  5163. 'brown': 0xA52A2A,
  5164. 'burlywood': 0xDEB887,
  5165. 'cadetblue': 0x5F9EA0,
  5166. 'chartreuse': 0x7FFF00,
  5167. 'chocolate': 0xD2691E,
  5168. 'coral': 0xFF7F50,
  5169. 'cornflowerblue': 0x6495ED,
  5170. 'cornsilk': 0xFFF8DC,
  5171. 'crimson': 0xDC143C,
  5172. 'cyan': 0x00FFFF,
  5173. 'darkblue': 0x00008B,
  5174. 'darkcyan': 0x008B8B,
  5175. 'darkgoldenrod': 0xB8860B,
  5176. 'darkgray': 0xA9A9A9,
  5177. 'darkgreen': 0x006400,
  5178. 'darkgrey': 0xA9A9A9,
  5179. 'darkkhaki': 0xBDB76B,
  5180. 'darkmagenta': 0x8B008B,
  5181. 'darkolivegreen': 0x556B2F,
  5182. 'darkorange': 0xFF8C00,
  5183. 'darkorchid': 0x9932CC,
  5184. 'darkred': 0x8B0000,
  5185. 'darksalmon': 0xE9967A,
  5186. 'darkseagreen': 0x8FBC8F,
  5187. 'darkslateblue': 0x483D8B,
  5188. 'darkslategray': 0x2F4F4F,
  5189. 'darkslategrey': 0x2F4F4F,
  5190. 'darkturquoise': 0x00CED1,
  5191. 'darkviolet': 0x9400D3,
  5192. 'deeppink': 0xFF1493,
  5193. 'deepskyblue': 0x00BFFF,
  5194. 'dimgray': 0x696969,
  5195. 'dimgrey': 0x696969,
  5196. 'dodgerblue': 0x1E90FF,
  5197. 'firebrick': 0xB22222,
  5198. 'floralwhite': 0xFFFAF0,
  5199. 'forestgreen': 0x228B22,
  5200. 'fuchsia': 0xFF00FF,
  5201. 'gainsboro': 0xDCDCDC,
  5202. 'ghostwhite': 0xF8F8FF,
  5203. 'gold': 0xFFD700,
  5204. 'goldenrod': 0xDAA520,
  5205. 'gray': 0x808080,
  5206. 'green': 0x008000,
  5207. 'greenyellow': 0xADFF2F,
  5208. 'grey': 0x808080,
  5209. 'honeydew': 0xF0FFF0,
  5210. 'hotpink': 0xFF69B4,
  5211. 'indianred': 0xCD5C5C,
  5212. 'indigo': 0x4B0082,
  5213. 'ivory': 0xFFFFF0,
  5214. 'khaki': 0xF0E68C,
  5215. 'lavender': 0xE6E6FA,
  5216. 'lavenderblush': 0xFFF0F5,
  5217. 'lawngreen': 0x7CFC00,
  5218. 'lemonchiffon': 0xFFFACD,
  5219. 'lightblue': 0xADD8E6,
  5220. 'lightcoral': 0xF08080,
  5221. 'lightcyan': 0xE0FFFF,
  5222. 'lightgoldenrodyellow': 0xFAFAD2,
  5223. 'lightgray': 0xD3D3D3,
  5224. 'lightgreen': 0x90EE90,
  5225. 'lightgrey': 0xD3D3D3,
  5226. 'lightpink': 0xFFB6C1,
  5227. 'lightsalmon': 0xFFA07A,
  5228. 'lightseagreen': 0x20B2AA,
  5229. 'lightskyblue': 0x87CEFA,
  5230. 'lightslategray': 0x778899,
  5231. 'lightslategrey': 0x778899,
  5232. 'lightsteelblue': 0xB0C4DE,
  5233. 'lightyellow': 0xFFFFE0,
  5234. 'lime': 0x00FF00,
  5235. 'limegreen': 0x32CD32,
  5236. 'linen': 0xFAF0E6,
  5237. 'magenta': 0xFF00FF,
  5238. 'maroon': 0x800000,
  5239. 'mediumaquamarine': 0x66CDAA,
  5240. 'mediumblue': 0x0000CD,
  5241. 'mediumorchid': 0xBA55D3,
  5242. 'mediumpurple': 0x9370DB,
  5243. 'mediumseagreen': 0x3CB371,
  5244. 'mediumslateblue': 0x7B68EE,
  5245. 'mediumspringgreen': 0x00FA9A,
  5246. 'mediumturquoise': 0x48D1CC,
  5247. 'mediumvioletred': 0xC71585,
  5248. 'midnightblue': 0x191970,
  5249. 'mintcream': 0xF5FFFA,
  5250. 'mistyrose': 0xFFE4E1,
  5251. 'moccasin': 0xFFE4B5,
  5252. 'navajowhite': 0xFFDEAD,
  5253. 'navy': 0x000080,
  5254. 'oldlace': 0xFDF5E6,
  5255. 'olive': 0x808000,
  5256. 'olivedrab': 0x6B8E23,
  5257. 'orange': 0xFFA500,
  5258. 'orangered': 0xFF4500,
  5259. 'orchid': 0xDA70D6,
  5260. 'palegoldenrod': 0xEEE8AA,
  5261. 'palegreen': 0x98FB98,
  5262. 'paleturquoise': 0xAFEEEE,
  5263. 'palevioletred': 0xDB7093,
  5264. 'papayawhip': 0xFFEFD5,
  5265. 'peachpuff': 0xFFDAB9,
  5266. 'peru': 0xCD853F,
  5267. 'pink': 0xFFC0CB,
  5268. 'plum': 0xDDA0DD,
  5269. 'powderblue': 0xB0E0E6,
  5270. 'purple': 0x800080,
  5271. 'rebeccapurple': 0x663399,
  5272. 'red': 0xFF0000,
  5273. 'rosybrown': 0xBC8F8F,
  5274. 'royalblue': 0x4169E1,
  5275. 'saddlebrown': 0x8B4513,
  5276. 'salmon': 0xFA8072,
  5277. 'sandybrown': 0xF4A460,
  5278. 'seagreen': 0x2E8B57,
  5279. 'seashell': 0xFFF5EE,
  5280. 'sienna': 0xA0522D,
  5281. 'silver': 0xC0C0C0,
  5282. 'skyblue': 0x87CEEB,
  5283. 'slateblue': 0x6A5ACD,
  5284. 'slategray': 0x708090,
  5285. 'slategrey': 0x708090,
  5286. 'snow': 0xFFFAFA,
  5287. 'springgreen': 0x00FF7F,
  5288. 'steelblue': 0x4682B4,
  5289. 'tan': 0xD2B48C,
  5290. 'teal': 0x008080,
  5291. 'thistle': 0xD8BFD8,
  5292. 'tomato': 0xFF6347,
  5293. 'turquoise': 0x40E0D0,
  5294. 'violet': 0xEE82EE,
  5295. 'wheat': 0xF5DEB3,
  5296. 'white': 0xFFFFFF,
  5297. 'whitesmoke': 0xF5F5F5,
  5298. 'yellow': 0xFFFF00,
  5299. 'yellowgreen': 0x9ACD32
  5300. };
  5301. const _hslA = {
  5302. h: 0,
  5303. s: 0,
  5304. l: 0
  5305. };
  5306. const _hslB = {
  5307. h: 0,
  5308. s: 0,
  5309. l: 0
  5310. };
  5311. function hue2rgb(p, q, t) {
  5312. if (t < 0) t += 1;
  5313. if (t > 1) t -= 1;
  5314. if (t < 1 / 6) return p + (q - p) * 6 * t;
  5315. if (t < 1 / 2) return q;
  5316. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  5317. return p;
  5318. }
  5319. function SRGBToLinear(c) {
  5320. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  5321. }
  5322. function LinearToSRGB(c) {
  5323. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  5324. }
  5325. class Color {
  5326. constructor(r, g, b) {
  5327. if (g === undefined && b === undefined) {
  5328. // r is THREE.Color, hex or string
  5329. return this.set(r);
  5330. }
  5331. return this.setRGB(r, g, b);
  5332. }
  5333. set(value) {
  5334. if (value && value.isColor) {
  5335. this.copy(value);
  5336. } else if (typeof value === 'number') {
  5337. this.setHex(value);
  5338. } else if (typeof value === 'string') {
  5339. this.setStyle(value);
  5340. }
  5341. return this;
  5342. }
  5343. setScalar(scalar) {
  5344. this.r = scalar;
  5345. this.g = scalar;
  5346. this.b = scalar;
  5347. return this;
  5348. }
  5349. setHex(hex) {
  5350. hex = Math.floor(hex);
  5351. this.r = (hex >> 16 & 255) / 255;
  5352. this.g = (hex >> 8 & 255) / 255;
  5353. this.b = (hex & 255) / 255;
  5354. return this;
  5355. }
  5356. setRGB(r, g, b) {
  5357. this.r = r;
  5358. this.g = g;
  5359. this.b = b;
  5360. return this;
  5361. }
  5362. setHSL(h, s, l) {
  5363. // h,s,l ranges are in 0.0 - 1.0
  5364. h = euclideanModulo(h, 1);
  5365. s = clamp(s, 0, 1);
  5366. l = clamp(l, 0, 1);
  5367. if (s === 0) {
  5368. this.r = this.g = this.b = l;
  5369. } else {
  5370. const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  5371. const q = 2 * l - p;
  5372. this.r = hue2rgb(q, p, h + 1 / 3);
  5373. this.g = hue2rgb(q, p, h);
  5374. this.b = hue2rgb(q, p, h - 1 / 3);
  5375. }
  5376. return this;
  5377. }
  5378. setStyle(style) {
  5379. function handleAlpha(string) {
  5380. if (string === undefined) return;
  5381. if (parseFloat(string) < 1) {
  5382. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  5383. }
  5384. }
  5385. let m;
  5386. if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
  5387. // rgb / hsl
  5388. let color;
  5389. const name = m[1];
  5390. const components = m[2];
  5391. switch (name) {
  5392. case 'rgb':
  5393. case 'rgba':
  5394. if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5395. // rgb(255,0,0) rgba(255,0,0,0.5)
  5396. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  5397. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  5398. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  5399. handleAlpha(color[4]);
  5400. return this;
  5401. }
  5402. if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5403. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5404. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  5405. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  5406. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  5407. handleAlpha(color[4]);
  5408. return this;
  5409. }
  5410. break;
  5411. case 'hsl':
  5412. case 'hsla':
  5413. if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5414. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5415. const h = parseFloat(color[1]) / 360;
  5416. const s = parseInt(color[2], 10) / 100;
  5417. const l = parseInt(color[3], 10) / 100;
  5418. handleAlpha(color[4]);
  5419. return this.setHSL(h, s, l);
  5420. }
  5421. break;
  5422. }
  5423. } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
  5424. // hex color
  5425. const hex = m[1];
  5426. const size = hex.length;
  5427. if (size === 3) {
  5428. // #ff0
  5429. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  5430. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  5431. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  5432. return this;
  5433. } else if (size === 6) {
  5434. // #ff0000
  5435. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  5436. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  5437. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  5438. return this;
  5439. }
  5440. }
  5441. if (style && style.length > 0) {
  5442. return this.setColorName(style);
  5443. }
  5444. return this;
  5445. }
  5446. setColorName(style) {
  5447. // color keywords
  5448. const hex = _colorKeywords[style.toLowerCase()];
  5449. if (hex !== undefined) {
  5450. // red
  5451. this.setHex(hex);
  5452. } else {
  5453. // unknown color
  5454. console.warn('THREE.Color: Unknown color ' + style);
  5455. }
  5456. return this;
  5457. }
  5458. clone() {
  5459. return new this.constructor(this.r, this.g, this.b);
  5460. }
  5461. copy(color) {
  5462. this.r = color.r;
  5463. this.g = color.g;
  5464. this.b = color.b;
  5465. return this;
  5466. }
  5467. copyGammaToLinear(color, gammaFactor = 2.0) {
  5468. this.r = Math.pow(color.r, gammaFactor);
  5469. this.g = Math.pow(color.g, gammaFactor);
  5470. this.b = Math.pow(color.b, gammaFactor);
  5471. return this;
  5472. }
  5473. copyLinearToGamma(color, gammaFactor = 2.0) {
  5474. const safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  5475. this.r = Math.pow(color.r, safeInverse);
  5476. this.g = Math.pow(color.g, safeInverse);
  5477. this.b = Math.pow(color.b, safeInverse);
  5478. return this;
  5479. }
  5480. convertGammaToLinear(gammaFactor) {
  5481. this.copyGammaToLinear(this, gammaFactor);
  5482. return this;
  5483. }
  5484. convertLinearToGamma(gammaFactor) {
  5485. this.copyLinearToGamma(this, gammaFactor);
  5486. return this;
  5487. }
  5488. copySRGBToLinear(color) {
  5489. this.r = SRGBToLinear(color.r);
  5490. this.g = SRGBToLinear(color.g);
  5491. this.b = SRGBToLinear(color.b);
  5492. return this;
  5493. }
  5494. copyLinearToSRGB(color) {
  5495. this.r = LinearToSRGB(color.r);
  5496. this.g = LinearToSRGB(color.g);
  5497. this.b = LinearToSRGB(color.b);
  5498. return this;
  5499. }
  5500. convertSRGBToLinear() {
  5501. this.copySRGBToLinear(this);
  5502. return this;
  5503. }
  5504. convertLinearToSRGB() {
  5505. this.copyLinearToSRGB(this);
  5506. return this;
  5507. }
  5508. getHex() {
  5509. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  5510. }
  5511. getHexString() {
  5512. return ('000000' + this.getHex().toString(16)).slice(-6);
  5513. }
  5514. getHSL(target) {
  5515. // h,s,l ranges are in 0.0 - 1.0
  5516. const r = this.r,
  5517. g = this.g,
  5518. b = this.b;
  5519. const max = Math.max(r, g, b);
  5520. const min = Math.min(r, g, b);
  5521. let hue, saturation;
  5522. const lightness = (min + max) / 2.0;
  5523. if (min === max) {
  5524. hue = 0;
  5525. saturation = 0;
  5526. } else {
  5527. const delta = max - min;
  5528. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  5529. switch (max) {
  5530. case r:
  5531. hue = (g - b) / delta + (g < b ? 6 : 0);
  5532. break;
  5533. case g:
  5534. hue = (b - r) / delta + 2;
  5535. break;
  5536. case b:
  5537. hue = (r - g) / delta + 4;
  5538. break;
  5539. }
  5540. hue /= 6;
  5541. }
  5542. target.h = hue;
  5543. target.s = saturation;
  5544. target.l = lightness;
  5545. return target;
  5546. }
  5547. getStyle() {
  5548. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  5549. }
  5550. offsetHSL(h, s, l) {
  5551. this.getHSL(_hslA);
  5552. _hslA.h += h;
  5553. _hslA.s += s;
  5554. _hslA.l += l;
  5555. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  5556. return this;
  5557. }
  5558. add(color) {
  5559. this.r += color.r;
  5560. this.g += color.g;
  5561. this.b += color.b;
  5562. return this;
  5563. }
  5564. addColors(color1, color2) {
  5565. this.r = color1.r + color2.r;
  5566. this.g = color1.g + color2.g;
  5567. this.b = color1.b + color2.b;
  5568. return this;
  5569. }
  5570. addScalar(s) {
  5571. this.r += s;
  5572. this.g += s;
  5573. this.b += s;
  5574. return this;
  5575. }
  5576. sub(color) {
  5577. this.r = Math.max(0, this.r - color.r);
  5578. this.g = Math.max(0, this.g - color.g);
  5579. this.b = Math.max(0, this.b - color.b);
  5580. return this;
  5581. }
  5582. multiply(color) {
  5583. this.r *= color.r;
  5584. this.g *= color.g;
  5585. this.b *= color.b;
  5586. return this;
  5587. }
  5588. multiplyScalar(s) {
  5589. this.r *= s;
  5590. this.g *= s;
  5591. this.b *= s;
  5592. return this;
  5593. }
  5594. lerp(color, alpha) {
  5595. this.r += (color.r - this.r) * alpha;
  5596. this.g += (color.g - this.g) * alpha;
  5597. this.b += (color.b - this.b) * alpha;
  5598. return this;
  5599. }
  5600. lerpColors(color1, color2, alpha) {
  5601. this.r = color1.r + (color2.r - color1.r) * alpha;
  5602. this.g = color1.g + (color2.g - color1.g) * alpha;
  5603. this.b = color1.b + (color2.b - color1.b) * alpha;
  5604. return this;
  5605. }
  5606. lerpHSL(color, alpha) {
  5607. this.getHSL(_hslA);
  5608. color.getHSL(_hslB);
  5609. const h = lerp(_hslA.h, _hslB.h, alpha);
  5610. const s = lerp(_hslA.s, _hslB.s, alpha);
  5611. const l = lerp(_hslA.l, _hslB.l, alpha);
  5612. this.setHSL(h, s, l);
  5613. return this;
  5614. }
  5615. equals(c) {
  5616. return c.r === this.r && c.g === this.g && c.b === this.b;
  5617. }
  5618. fromArray(array, offset = 0) {
  5619. this.r = array[offset];
  5620. this.g = array[offset + 1];
  5621. this.b = array[offset + 2];
  5622. return this;
  5623. }
  5624. toArray(array = [], offset = 0) {
  5625. array[offset] = this.r;
  5626. array[offset + 1] = this.g;
  5627. array[offset + 2] = this.b;
  5628. return array;
  5629. }
  5630. fromBufferAttribute(attribute, index) {
  5631. this.r = attribute.getX(index);
  5632. this.g = attribute.getY(index);
  5633. this.b = attribute.getZ(index);
  5634. if (attribute.normalized === true) {
  5635. // assuming Uint8Array
  5636. this.r /= 255;
  5637. this.g /= 255;
  5638. this.b /= 255;
  5639. }
  5640. return this;
  5641. }
  5642. toJSON() {
  5643. return this.getHex();
  5644. }
  5645. }
  5646. Color.NAMES = _colorKeywords;
  5647. Color.prototype.isColor = true;
  5648. Color.prototype.r = 1;
  5649. Color.prototype.g = 1;
  5650. Color.prototype.b = 1;
  5651. /**
  5652. * parameters = {
  5653. * color: <hex>,
  5654. * opacity: <float>,
  5655. * map: new THREE.Texture( <Image> ),
  5656. *
  5657. * lightMap: new THREE.Texture( <Image> ),
  5658. * lightMapIntensity: <float>
  5659. *
  5660. * aoMap: new THREE.Texture( <Image> ),
  5661. * aoMapIntensity: <float>
  5662. *
  5663. * specularMap: new THREE.Texture( <Image> ),
  5664. *
  5665. * alphaMap: new THREE.Texture( <Image> ),
  5666. *
  5667. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  5668. * combine: THREE.Multiply,
  5669. * reflectivity: <float>,
  5670. * refractionRatio: <float>,
  5671. *
  5672. * depthTest: <bool>,
  5673. * depthWrite: <bool>,
  5674. *
  5675. * wireframe: <boolean>,
  5676. * wireframeLinewidth: <float>,
  5677. * }
  5678. */
  5679. class MeshBasicMaterial extends Material {
  5680. constructor(parameters) {
  5681. super();
  5682. this.type = 'MeshBasicMaterial';
  5683. this.color = new Color(0xffffff); // emissive
  5684. this.map = null;
  5685. this.lightMap = null;
  5686. this.lightMapIntensity = 1.0;
  5687. this.aoMap = null;
  5688. this.aoMapIntensity = 1.0;
  5689. this.specularMap = null;
  5690. this.alphaMap = null;
  5691. this.envMap = null;
  5692. this.combine = MultiplyOperation;
  5693. this.reflectivity = 1;
  5694. this.refractionRatio = 0.98;
  5695. this.wireframe = false;
  5696. this.wireframeLinewidth = 1;
  5697. this.wireframeLinecap = 'round';
  5698. this.wireframeLinejoin = 'round';
  5699. this.setValues(parameters);
  5700. }
  5701. copy(source) {
  5702. super.copy(source);
  5703. this.color.copy(source.color);
  5704. this.map = source.map;
  5705. this.lightMap = source.lightMap;
  5706. this.lightMapIntensity = source.lightMapIntensity;
  5707. this.aoMap = source.aoMap;
  5708. this.aoMapIntensity = source.aoMapIntensity;
  5709. this.specularMap = source.specularMap;
  5710. this.alphaMap = source.alphaMap;
  5711. this.envMap = source.envMap;
  5712. this.combine = source.combine;
  5713. this.reflectivity = source.reflectivity;
  5714. this.refractionRatio = source.refractionRatio;
  5715. this.wireframe = source.wireframe;
  5716. this.wireframeLinewidth = source.wireframeLinewidth;
  5717. this.wireframeLinecap = source.wireframeLinecap;
  5718. this.wireframeLinejoin = source.wireframeLinejoin;
  5719. return this;
  5720. }
  5721. }
  5722. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  5723. const _vector$9 = /*@__PURE__*/new Vector3();
  5724. const _vector2$1 = /*@__PURE__*/new Vector2();
  5725. class BufferAttribute {
  5726. constructor(array, itemSize, normalized) {
  5727. if (Array.isArray(array)) {
  5728. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  5729. }
  5730. this.name = '';
  5731. this.array = array;
  5732. this.itemSize = itemSize;
  5733. this.count = array !== undefined ? array.length / itemSize : 0;
  5734. this.normalized = normalized === true;
  5735. this.usage = StaticDrawUsage;
  5736. this.updateRange = {
  5737. offset: 0,
  5738. count: -1
  5739. };
  5740. this.version = 0;
  5741. }
  5742. onUploadCallback() {}
  5743. set needsUpdate(value) {
  5744. if (value === true) this.version++;
  5745. }
  5746. setUsage(value) {
  5747. this.usage = value;
  5748. return this;
  5749. }
  5750. copy(source) {
  5751. this.name = source.name;
  5752. this.array = new source.array.constructor(source.array);
  5753. this.itemSize = source.itemSize;
  5754. this.count = source.count;
  5755. this.normalized = source.normalized;
  5756. this.usage = source.usage;
  5757. return this;
  5758. }
  5759. copyAt(index1, attribute, index2) {
  5760. index1 *= this.itemSize;
  5761. index2 *= attribute.itemSize;
  5762. for (let i = 0, l = this.itemSize; i < l; i++) {
  5763. this.array[index1 + i] = attribute.array[index2 + i];
  5764. }
  5765. return this;
  5766. }
  5767. copyArray(array) {
  5768. this.array.set(array);
  5769. return this;
  5770. }
  5771. copyColorsArray(colors) {
  5772. const array = this.array;
  5773. let offset = 0;
  5774. for (let i = 0, l = colors.length; i < l; i++) {
  5775. let color = colors[i];
  5776. if (color === undefined) {
  5777. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  5778. color = new Color();
  5779. }
  5780. array[offset++] = color.r;
  5781. array[offset++] = color.g;
  5782. array[offset++] = color.b;
  5783. }
  5784. return this;
  5785. }
  5786. copyVector2sArray(vectors) {
  5787. const array = this.array;
  5788. let offset = 0;
  5789. for (let i = 0, l = vectors.length; i < l; i++) {
  5790. let vector = vectors[i];
  5791. if (vector === undefined) {
  5792. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  5793. vector = new Vector2();
  5794. }
  5795. array[offset++] = vector.x;
  5796. array[offset++] = vector.y;
  5797. }
  5798. return this;
  5799. }
  5800. copyVector3sArray(vectors) {
  5801. const array = this.array;
  5802. let offset = 0;
  5803. for (let i = 0, l = vectors.length; i < l; i++) {
  5804. let vector = vectors[i];
  5805. if (vector === undefined) {
  5806. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  5807. vector = new Vector3();
  5808. }
  5809. array[offset++] = vector.x;
  5810. array[offset++] = vector.y;
  5811. array[offset++] = vector.z;
  5812. }
  5813. return this;
  5814. }
  5815. copyVector4sArray(vectors) {
  5816. const array = this.array;
  5817. let offset = 0;
  5818. for (let i = 0, l = vectors.length; i < l; i++) {
  5819. let vector = vectors[i];
  5820. if (vector === undefined) {
  5821. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  5822. vector = new Vector4();
  5823. }
  5824. array[offset++] = vector.x;
  5825. array[offset++] = vector.y;
  5826. array[offset++] = vector.z;
  5827. array[offset++] = vector.w;
  5828. }
  5829. return this;
  5830. }
  5831. applyMatrix3(m) {
  5832. if (this.itemSize === 2) {
  5833. for (let i = 0, l = this.count; i < l; i++) {
  5834. _vector2$1.fromBufferAttribute(this, i);
  5835. _vector2$1.applyMatrix3(m);
  5836. this.setXY(i, _vector2$1.x, _vector2$1.y);
  5837. }
  5838. } else if (this.itemSize === 3) {
  5839. for (let i = 0, l = this.count; i < l; i++) {
  5840. _vector$9.fromBufferAttribute(this, i);
  5841. _vector$9.applyMatrix3(m);
  5842. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5843. }
  5844. }
  5845. return this;
  5846. }
  5847. applyMatrix4(m) {
  5848. for (let i = 0, l = this.count; i < l; i++) {
  5849. _vector$9.x = this.getX(i);
  5850. _vector$9.y = this.getY(i);
  5851. _vector$9.z = this.getZ(i);
  5852. _vector$9.applyMatrix4(m);
  5853. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5854. }
  5855. return this;
  5856. }
  5857. applyNormalMatrix(m) {
  5858. for (let i = 0, l = this.count; i < l; i++) {
  5859. _vector$9.x = this.getX(i);
  5860. _vector$9.y = this.getY(i);
  5861. _vector$9.z = this.getZ(i);
  5862. _vector$9.applyNormalMatrix(m);
  5863. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5864. }
  5865. return this;
  5866. }
  5867. transformDirection(m) {
  5868. for (let i = 0, l = this.count; i < l; i++) {
  5869. _vector$9.x = this.getX(i);
  5870. _vector$9.y = this.getY(i);
  5871. _vector$9.z = this.getZ(i);
  5872. _vector$9.transformDirection(m);
  5873. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5874. }
  5875. return this;
  5876. }
  5877. set(value, offset = 0) {
  5878. this.array.set(value, offset);
  5879. return this;
  5880. }
  5881. getX(index) {
  5882. return this.array[index * this.itemSize];
  5883. }
  5884. setX(index, x) {
  5885. this.array[index * this.itemSize] = x;
  5886. return this;
  5887. }
  5888. getY(index) {
  5889. return this.array[index * this.itemSize + 1];
  5890. }
  5891. setY(index, y) {
  5892. this.array[index * this.itemSize + 1] = y;
  5893. return this;
  5894. }
  5895. getZ(index) {
  5896. return this.array[index * this.itemSize + 2];
  5897. }
  5898. setZ(index, z) {
  5899. this.array[index * this.itemSize + 2] = z;
  5900. return this;
  5901. }
  5902. getW(index) {
  5903. return this.array[index * this.itemSize + 3];
  5904. }
  5905. setW(index, w) {
  5906. this.array[index * this.itemSize + 3] = w;
  5907. return this;
  5908. }
  5909. setXY(index, x, y) {
  5910. index *= this.itemSize;
  5911. this.array[index + 0] = x;
  5912. this.array[index + 1] = y;
  5913. return this;
  5914. }
  5915. setXYZ(index, x, y, z) {
  5916. index *= this.itemSize;
  5917. this.array[index + 0] = x;
  5918. this.array[index + 1] = y;
  5919. this.array[index + 2] = z;
  5920. return this;
  5921. }
  5922. setXYZW(index, x, y, z, w) {
  5923. index *= this.itemSize;
  5924. this.array[index + 0] = x;
  5925. this.array[index + 1] = y;
  5926. this.array[index + 2] = z;
  5927. this.array[index + 3] = w;
  5928. return this;
  5929. }
  5930. onUpload(callback) {
  5931. this.onUploadCallback = callback;
  5932. return this;
  5933. }
  5934. clone() {
  5935. return new this.constructor(this.array, this.itemSize).copy(this);
  5936. }
  5937. toJSON() {
  5938. const data = {
  5939. itemSize: this.itemSize,
  5940. type: this.array.constructor.name,
  5941. array: Array.prototype.slice.call(this.array),
  5942. normalized: this.normalized
  5943. };
  5944. if (this.name !== '') data.name = this.name;
  5945. if (this.usage !== StaticDrawUsage) data.usage = this.usage;
  5946. if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange;
  5947. return data;
  5948. }
  5949. }
  5950. BufferAttribute.prototype.isBufferAttribute = true; //
  5951. class Int8BufferAttribute extends BufferAttribute {
  5952. constructor(array, itemSize, normalized) {
  5953. super(new Int8Array(array), itemSize, normalized);
  5954. }
  5955. }
  5956. class Uint8BufferAttribute extends BufferAttribute {
  5957. constructor(array, itemSize, normalized) {
  5958. super(new Uint8Array(array), itemSize, normalized);
  5959. }
  5960. }
  5961. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5962. constructor(array, itemSize, normalized) {
  5963. super(new Uint8ClampedArray(array), itemSize, normalized);
  5964. }
  5965. }
  5966. class Int16BufferAttribute extends BufferAttribute {
  5967. constructor(array, itemSize, normalized) {
  5968. super(new Int16Array(array), itemSize, normalized);
  5969. }
  5970. }
  5971. class Uint16BufferAttribute extends BufferAttribute {
  5972. constructor(array, itemSize, normalized) {
  5973. super(new Uint16Array(array), itemSize, normalized);
  5974. }
  5975. }
  5976. class Int32BufferAttribute extends BufferAttribute {
  5977. constructor(array, itemSize, normalized) {
  5978. super(new Int32Array(array), itemSize, normalized);
  5979. }
  5980. }
  5981. class Uint32BufferAttribute extends BufferAttribute {
  5982. constructor(array, itemSize, normalized) {
  5983. super(new Uint32Array(array), itemSize, normalized);
  5984. }
  5985. }
  5986. class Float16BufferAttribute extends BufferAttribute {
  5987. constructor(array, itemSize, normalized) {
  5988. super(new Uint16Array(array), itemSize, normalized);
  5989. }
  5990. }
  5991. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  5992. class Float32BufferAttribute extends BufferAttribute {
  5993. constructor(array, itemSize, normalized) {
  5994. super(new Float32Array(array), itemSize, normalized);
  5995. }
  5996. }
  5997. class Float64BufferAttribute extends BufferAttribute {
  5998. constructor(array, itemSize, normalized) {
  5999. super(new Float64Array(array), itemSize, normalized);
  6000. }
  6001. } //
  6002. let _id = 0;
  6003. const _m1 = /*@__PURE__*/new Matrix4();
  6004. const _obj = /*@__PURE__*/new Object3D();
  6005. const _offset = /*@__PURE__*/new Vector3();
  6006. const _box$1 = /*@__PURE__*/new Box3();
  6007. const _boxMorphTargets = /*@__PURE__*/new Box3();
  6008. const _vector$8 = /*@__PURE__*/new Vector3();
  6009. class BufferGeometry extends EventDispatcher {
  6010. constructor() {
  6011. super();
  6012. Object.defineProperty(this, 'id', {
  6013. value: _id++
  6014. });
  6015. this.uuid = generateUUID();
  6016. this.name = '';
  6017. this.type = 'BufferGeometry';
  6018. this.index = null;
  6019. this.attributes = {};
  6020. this.morphAttributes = {};
  6021. this.morphTargetsRelative = false;
  6022. this.groups = [];
  6023. this.boundingBox = null;
  6024. this.boundingSphere = null;
  6025. this.drawRange = {
  6026. start: 0,
  6027. count: Infinity
  6028. };
  6029. this.userData = {};
  6030. }
  6031. getIndex() {
  6032. return this.index;
  6033. }
  6034. setIndex(index) {
  6035. if (Array.isArray(index)) {
  6036. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  6037. } else {
  6038. this.index = index;
  6039. }
  6040. return this;
  6041. }
  6042. getAttribute(name) {
  6043. return this.attributes[name];
  6044. }
  6045. setAttribute(name, attribute) {
  6046. this.attributes[name] = attribute;
  6047. return this;
  6048. }
  6049. deleteAttribute(name) {
  6050. delete this.attributes[name];
  6051. return this;
  6052. }
  6053. hasAttribute(name) {
  6054. return this.attributes[name] !== undefined;
  6055. }
  6056. addGroup(start, count, materialIndex = 0) {
  6057. this.groups.push({
  6058. start: start,
  6059. count: count,
  6060. materialIndex: materialIndex
  6061. });
  6062. }
  6063. clearGroups() {
  6064. this.groups = [];
  6065. }
  6066. setDrawRange(start, count) {
  6067. this.drawRange.start = start;
  6068. this.drawRange.count = count;
  6069. }
  6070. applyMatrix4(matrix) {
  6071. const position = this.attributes.position;
  6072. if (position !== undefined) {
  6073. position.applyMatrix4(matrix);
  6074. position.needsUpdate = true;
  6075. }
  6076. const normal = this.attributes.normal;
  6077. if (normal !== undefined) {
  6078. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6079. normal.applyNormalMatrix(normalMatrix);
  6080. normal.needsUpdate = true;
  6081. }
  6082. const tangent = this.attributes.tangent;
  6083. if (tangent !== undefined) {
  6084. tangent.transformDirection(matrix);
  6085. tangent.needsUpdate = true;
  6086. }
  6087. if (this.boundingBox !== null) {
  6088. this.computeBoundingBox();
  6089. }
  6090. if (this.boundingSphere !== null) {
  6091. this.computeBoundingSphere();
  6092. }
  6093. return this;
  6094. }
  6095. applyQuaternion(q) {
  6096. _m1.makeRotationFromQuaternion(q);
  6097. this.applyMatrix4(_m1);
  6098. return this;
  6099. }
  6100. rotateX(angle) {
  6101. // rotate geometry around world x-axis
  6102. _m1.makeRotationX(angle);
  6103. this.applyMatrix4(_m1);
  6104. return this;
  6105. }
  6106. rotateY(angle) {
  6107. // rotate geometry around world y-axis
  6108. _m1.makeRotationY(angle);
  6109. this.applyMatrix4(_m1);
  6110. return this;
  6111. }
  6112. rotateZ(angle) {
  6113. // rotate geometry around world z-axis
  6114. _m1.makeRotationZ(angle);
  6115. this.applyMatrix4(_m1);
  6116. return this;
  6117. }
  6118. translate(x, y, z) {
  6119. // translate geometry
  6120. _m1.makeTranslation(x, y, z);
  6121. this.applyMatrix4(_m1);
  6122. return this;
  6123. }
  6124. scale(x, y, z) {
  6125. // scale geometry
  6126. _m1.makeScale(x, y, z);
  6127. this.applyMatrix4(_m1);
  6128. return this;
  6129. }
  6130. lookAt(vector) {
  6131. _obj.lookAt(vector);
  6132. _obj.updateMatrix();
  6133. this.applyMatrix4(_obj.matrix);
  6134. return this;
  6135. }
  6136. center() {
  6137. this.computeBoundingBox();
  6138. this.boundingBox.getCenter(_offset).negate();
  6139. this.translate(_offset.x, _offset.y, _offset.z);
  6140. return this;
  6141. }
  6142. setFromPoints(points) {
  6143. const position = [];
  6144. for (let i = 0, l = points.length; i < l; i++) {
  6145. const point = points[i];
  6146. position.push(point.x, point.y, point.z || 0);
  6147. }
  6148. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6149. return this;
  6150. }
  6151. computeBoundingBox() {
  6152. if (this.boundingBox === null) {
  6153. this.boundingBox = new Box3();
  6154. }
  6155. const position = this.attributes.position;
  6156. const morphAttributesPosition = this.morphAttributes.position;
  6157. if (position && position.isGLBufferAttribute) {
  6158. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  6159. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  6160. return;
  6161. }
  6162. if (position !== undefined) {
  6163. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  6164. if (morphAttributesPosition) {
  6165. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6166. const morphAttribute = morphAttributesPosition[i];
  6167. _box$1.setFromBufferAttribute(morphAttribute);
  6168. if (this.morphTargetsRelative) {
  6169. _vector$8.addVectors(this.boundingBox.min, _box$1.min);
  6170. this.boundingBox.expandByPoint(_vector$8);
  6171. _vector$8.addVectors(this.boundingBox.max, _box$1.max);
  6172. this.boundingBox.expandByPoint(_vector$8);
  6173. } else {
  6174. this.boundingBox.expandByPoint(_box$1.min);
  6175. this.boundingBox.expandByPoint(_box$1.max);
  6176. }
  6177. }
  6178. }
  6179. } else {
  6180. this.boundingBox.makeEmpty();
  6181. }
  6182. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  6183. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  6184. }
  6185. }
  6186. computeBoundingSphere() {
  6187. if (this.boundingSphere === null) {
  6188. this.boundingSphere = new Sphere();
  6189. }
  6190. const position = this.attributes.position;
  6191. const morphAttributesPosition = this.morphAttributes.position;
  6192. if (position && position.isGLBufferAttribute) {
  6193. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  6194. this.boundingSphere.set(new Vector3(), Infinity);
  6195. return;
  6196. }
  6197. if (position) {
  6198. // first, find the center of the bounding sphere
  6199. const center = this.boundingSphere.center;
  6200. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  6201. if (morphAttributesPosition) {
  6202. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6203. const morphAttribute = morphAttributesPosition[i];
  6204. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  6205. if (this.morphTargetsRelative) {
  6206. _vector$8.addVectors(_box$1.min, _boxMorphTargets.min);
  6207. _box$1.expandByPoint(_vector$8);
  6208. _vector$8.addVectors(_box$1.max, _boxMorphTargets.max);
  6209. _box$1.expandByPoint(_vector$8);
  6210. } else {
  6211. _box$1.expandByPoint(_boxMorphTargets.min);
  6212. _box$1.expandByPoint(_boxMorphTargets.max);
  6213. }
  6214. }
  6215. }
  6216. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  6217. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6218. let maxRadiusSq = 0;
  6219. for (let i = 0, il = position.count; i < il; i++) {
  6220. _vector$8.fromBufferAttribute(position, i);
  6221. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6222. } // process morph attributes if present
  6223. if (morphAttributesPosition) {
  6224. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6225. const morphAttribute = morphAttributesPosition[i];
  6226. const morphTargetsRelative = this.morphTargetsRelative;
  6227. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  6228. _vector$8.fromBufferAttribute(morphAttribute, j);
  6229. if (morphTargetsRelative) {
  6230. _offset.fromBufferAttribute(position, j);
  6231. _vector$8.add(_offset);
  6232. }
  6233. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6234. }
  6235. }
  6236. }
  6237. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  6238. if (isNaN(this.boundingSphere.radius)) {
  6239. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  6240. }
  6241. }
  6242. }
  6243. computeTangents() {
  6244. const index = this.index;
  6245. const attributes = this.attributes; // based on http://www.terathon.com/code/tangent.html
  6246. // (per vertex tangents)
  6247. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  6248. console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  6249. return;
  6250. }
  6251. const indices = index.array;
  6252. const positions = attributes.position.array;
  6253. const normals = attributes.normal.array;
  6254. const uvs = attributes.uv.array;
  6255. const nVertices = positions.length / 3;
  6256. if (attributes.tangent === undefined) {
  6257. this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
  6258. }
  6259. const tangents = attributes.tangent.array;
  6260. const tan1 = [],
  6261. tan2 = [];
  6262. for (let i = 0; i < nVertices; i++) {
  6263. tan1[i] = new Vector3();
  6264. tan2[i] = new Vector3();
  6265. }
  6266. const vA = new Vector3(),
  6267. vB = new Vector3(),
  6268. vC = new Vector3(),
  6269. uvA = new Vector2(),
  6270. uvB = new Vector2(),
  6271. uvC = new Vector2(),
  6272. sdir = new Vector3(),
  6273. tdir = new Vector3();
  6274. function handleTriangle(a, b, c) {
  6275. vA.fromArray(positions, a * 3);
  6276. vB.fromArray(positions, b * 3);
  6277. vC.fromArray(positions, c * 3);
  6278. uvA.fromArray(uvs, a * 2);
  6279. uvB.fromArray(uvs, b * 2);
  6280. uvC.fromArray(uvs, c * 2);
  6281. vB.sub(vA);
  6282. vC.sub(vA);
  6283. uvB.sub(uvA);
  6284. uvC.sub(uvA);
  6285. const r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  6286. if (!isFinite(r)) return;
  6287. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  6288. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  6289. tan1[a].add(sdir);
  6290. tan1[b].add(sdir);
  6291. tan1[c].add(sdir);
  6292. tan2[a].add(tdir);
  6293. tan2[b].add(tdir);
  6294. tan2[c].add(tdir);
  6295. }
  6296. let groups = this.groups;
  6297. if (groups.length === 0) {
  6298. groups = [{
  6299. start: 0,
  6300. count: indices.length
  6301. }];
  6302. }
  6303. for (let i = 0, il = groups.length; i < il; ++i) {
  6304. const group = groups[i];
  6305. const start = group.start;
  6306. const count = group.count;
  6307. for (let j = start, jl = start + count; j < jl; j += 3) {
  6308. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  6309. }
  6310. }
  6311. const tmp = new Vector3(),
  6312. tmp2 = new Vector3();
  6313. const n = new Vector3(),
  6314. n2 = new Vector3();
  6315. function handleVertex(v) {
  6316. n.fromArray(normals, v * 3);
  6317. n2.copy(n);
  6318. const t = tan1[v]; // Gram-Schmidt orthogonalize
  6319. tmp.copy(t);
  6320. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  6321. tmp2.crossVectors(n2, t);
  6322. const test = tmp2.dot(tan2[v]);
  6323. const w = test < 0.0 ? -1.0 : 1.0;
  6324. tangents[v * 4] = tmp.x;
  6325. tangents[v * 4 + 1] = tmp.y;
  6326. tangents[v * 4 + 2] = tmp.z;
  6327. tangents[v * 4 + 3] = w;
  6328. }
  6329. for (let i = 0, il = groups.length; i < il; ++i) {
  6330. const group = groups[i];
  6331. const start = group.start;
  6332. const count = group.count;
  6333. for (let j = start, jl = start + count; j < jl; j += 3) {
  6334. handleVertex(indices[j + 0]);
  6335. handleVertex(indices[j + 1]);
  6336. handleVertex(indices[j + 2]);
  6337. }
  6338. }
  6339. }
  6340. computeVertexNormals() {
  6341. const index = this.index;
  6342. const positionAttribute = this.getAttribute('position');
  6343. if (positionAttribute !== undefined) {
  6344. let normalAttribute = this.getAttribute('normal');
  6345. if (normalAttribute === undefined) {
  6346. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  6347. this.setAttribute('normal', normalAttribute);
  6348. } else {
  6349. // reset existing normals to zero
  6350. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  6351. normalAttribute.setXYZ(i, 0, 0, 0);
  6352. }
  6353. }
  6354. const pA = new Vector3(),
  6355. pB = new Vector3(),
  6356. pC = new Vector3();
  6357. const nA = new Vector3(),
  6358. nB = new Vector3(),
  6359. nC = new Vector3();
  6360. const cb = new Vector3(),
  6361. ab = new Vector3(); // indexed elements
  6362. if (index) {
  6363. for (let i = 0, il = index.count; i < il; i += 3) {
  6364. const vA = index.getX(i + 0);
  6365. const vB = index.getX(i + 1);
  6366. const vC = index.getX(i + 2);
  6367. pA.fromBufferAttribute(positionAttribute, vA);
  6368. pB.fromBufferAttribute(positionAttribute, vB);
  6369. pC.fromBufferAttribute(positionAttribute, vC);
  6370. cb.subVectors(pC, pB);
  6371. ab.subVectors(pA, pB);
  6372. cb.cross(ab);
  6373. nA.fromBufferAttribute(normalAttribute, vA);
  6374. nB.fromBufferAttribute(normalAttribute, vB);
  6375. nC.fromBufferAttribute(normalAttribute, vC);
  6376. nA.add(cb);
  6377. nB.add(cb);
  6378. nC.add(cb);
  6379. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  6380. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  6381. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  6382. }
  6383. } else {
  6384. // non-indexed elements (unconnected triangle soup)
  6385. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  6386. pA.fromBufferAttribute(positionAttribute, i + 0);
  6387. pB.fromBufferAttribute(positionAttribute, i + 1);
  6388. pC.fromBufferAttribute(positionAttribute, i + 2);
  6389. cb.subVectors(pC, pB);
  6390. ab.subVectors(pA, pB);
  6391. cb.cross(ab);
  6392. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  6393. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  6394. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  6395. }
  6396. }
  6397. this.normalizeNormals();
  6398. normalAttribute.needsUpdate = true;
  6399. }
  6400. }
  6401. merge(geometry, offset) {
  6402. if (!(geometry && geometry.isBufferGeometry)) {
  6403. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  6404. return;
  6405. }
  6406. if (offset === undefined) {
  6407. offset = 0;
  6408. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  6409. }
  6410. const attributes = this.attributes;
  6411. for (const key in attributes) {
  6412. if (geometry.attributes[key] === undefined) continue;
  6413. const attribute1 = attributes[key];
  6414. const attributeArray1 = attribute1.array;
  6415. const attribute2 = geometry.attributes[key];
  6416. const attributeArray2 = attribute2.array;
  6417. const attributeOffset = attribute2.itemSize * offset;
  6418. const length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  6419. for (let i = 0, j = attributeOffset; i < length; i++, j++) {
  6420. attributeArray1[j] = attributeArray2[i];
  6421. }
  6422. }
  6423. return this;
  6424. }
  6425. normalizeNormals() {
  6426. const normals = this.attributes.normal;
  6427. for (let i = 0, il = normals.count; i < il; i++) {
  6428. _vector$8.fromBufferAttribute(normals, i);
  6429. _vector$8.normalize();
  6430. normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z);
  6431. }
  6432. }
  6433. toNonIndexed() {
  6434. function convertBufferAttribute(attribute, indices) {
  6435. const array = attribute.array;
  6436. const itemSize = attribute.itemSize;
  6437. const normalized = attribute.normalized;
  6438. const array2 = new array.constructor(indices.length * itemSize);
  6439. let index = 0,
  6440. index2 = 0;
  6441. for (let i = 0, l = indices.length; i < l; i++) {
  6442. if (attribute.isInterleavedBufferAttribute) {
  6443. index = indices[i] * attribute.data.stride + attribute.offset;
  6444. } else {
  6445. index = indices[i] * itemSize;
  6446. }
  6447. for (let j = 0; j < itemSize; j++) {
  6448. array2[index2++] = array[index++];
  6449. }
  6450. }
  6451. return new BufferAttribute(array2, itemSize, normalized);
  6452. } //
  6453. if (this.index === null) {
  6454. console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
  6455. return this;
  6456. }
  6457. const geometry2 = new BufferGeometry();
  6458. const indices = this.index.array;
  6459. const attributes = this.attributes; // attributes
  6460. for (const name in attributes) {
  6461. const attribute = attributes[name];
  6462. const newAttribute = convertBufferAttribute(attribute, indices);
  6463. geometry2.setAttribute(name, newAttribute);
  6464. } // morph attributes
  6465. const morphAttributes = this.morphAttributes;
  6466. for (const name in morphAttributes) {
  6467. const morphArray = [];
  6468. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6469. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  6470. const attribute = morphAttribute[i];
  6471. const newAttribute = convertBufferAttribute(attribute, indices);
  6472. morphArray.push(newAttribute);
  6473. }
  6474. geometry2.morphAttributes[name] = morphArray;
  6475. }
  6476. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  6477. const groups = this.groups;
  6478. for (let i = 0, l = groups.length; i < l; i++) {
  6479. const group = groups[i];
  6480. geometry2.addGroup(group.start, group.count, group.materialIndex);
  6481. }
  6482. return geometry2;
  6483. }
  6484. toJSON() {
  6485. const data = {
  6486. metadata: {
  6487. version: 4.5,
  6488. type: 'BufferGeometry',
  6489. generator: 'BufferGeometry.toJSON'
  6490. }
  6491. }; // standard BufferGeometry serialization
  6492. data.uuid = this.uuid;
  6493. data.type = this.type;
  6494. if (this.name !== '') data.name = this.name;
  6495. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  6496. if (this.parameters !== undefined) {
  6497. const parameters = this.parameters;
  6498. for (const key in parameters) {
  6499. if (parameters[key] !== undefined) data[key] = parameters[key];
  6500. }
  6501. return data;
  6502. } // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6503. data.data = {
  6504. attributes: {}
  6505. };
  6506. const index = this.index;
  6507. if (index !== null) {
  6508. data.data.index = {
  6509. type: index.array.constructor.name,
  6510. array: Array.prototype.slice.call(index.array)
  6511. };
  6512. }
  6513. const attributes = this.attributes;
  6514. for (const key in attributes) {
  6515. const attribute = attributes[key];
  6516. data.data.attributes[key] = attribute.toJSON(data.data);
  6517. }
  6518. const morphAttributes = {};
  6519. let hasMorphAttributes = false;
  6520. for (const key in this.morphAttributes) {
  6521. const attributeArray = this.morphAttributes[key];
  6522. const array = [];
  6523. for (let i = 0, il = attributeArray.length; i < il; i++) {
  6524. const attribute = attributeArray[i];
  6525. array.push(attribute.toJSON(data.data));
  6526. }
  6527. if (array.length > 0) {
  6528. morphAttributes[key] = array;
  6529. hasMorphAttributes = true;
  6530. }
  6531. }
  6532. if (hasMorphAttributes) {
  6533. data.data.morphAttributes = morphAttributes;
  6534. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6535. }
  6536. const groups = this.groups;
  6537. if (groups.length > 0) {
  6538. data.data.groups = JSON.parse(JSON.stringify(groups));
  6539. }
  6540. const boundingSphere = this.boundingSphere;
  6541. if (boundingSphere !== null) {
  6542. data.data.boundingSphere = {
  6543. center: boundingSphere.center.toArray(),
  6544. radius: boundingSphere.radius
  6545. };
  6546. }
  6547. return data;
  6548. }
  6549. clone() {
  6550. return new this.constructor().copy(this);
  6551. }
  6552. copy(source) {
  6553. // reset
  6554. this.index = null;
  6555. this.attributes = {};
  6556. this.morphAttributes = {};
  6557. this.groups = [];
  6558. this.boundingBox = null;
  6559. this.boundingSphere = null; // used for storing cloned, shared data
  6560. const data = {}; // name
  6561. this.name = source.name; // index
  6562. const index = source.index;
  6563. if (index !== null) {
  6564. this.setIndex(index.clone(data));
  6565. } // attributes
  6566. const attributes = source.attributes;
  6567. for (const name in attributes) {
  6568. const attribute = attributes[name];
  6569. this.setAttribute(name, attribute.clone(data));
  6570. } // morph attributes
  6571. const morphAttributes = source.morphAttributes;
  6572. for (const name in morphAttributes) {
  6573. const array = [];
  6574. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6575. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  6576. array.push(morphAttribute[i].clone(data));
  6577. }
  6578. this.morphAttributes[name] = array;
  6579. }
  6580. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  6581. const groups = source.groups;
  6582. for (let i = 0, l = groups.length; i < l; i++) {
  6583. const group = groups[i];
  6584. this.addGroup(group.start, group.count, group.materialIndex);
  6585. } // bounding box
  6586. const boundingBox = source.boundingBox;
  6587. if (boundingBox !== null) {
  6588. this.boundingBox = boundingBox.clone();
  6589. } // bounding sphere
  6590. const boundingSphere = source.boundingSphere;
  6591. if (boundingSphere !== null) {
  6592. this.boundingSphere = boundingSphere.clone();
  6593. } // draw range
  6594. this.drawRange.start = source.drawRange.start;
  6595. this.drawRange.count = source.drawRange.count; // user data
  6596. this.userData = source.userData; // geometry generator parameters
  6597. if (source.parameters !== undefined) this.parameters = Object.assign({}, source.parameters);
  6598. return this;
  6599. }
  6600. dispose() {
  6601. this.dispatchEvent({
  6602. type: 'dispose'
  6603. });
  6604. }
  6605. }
  6606. BufferGeometry.prototype.isBufferGeometry = true;
  6607. const _inverseMatrix$2 = /*@__PURE__*/new Matrix4();
  6608. const _ray$2 = /*@__PURE__*/new Ray();
  6609. const _sphere$3 = /*@__PURE__*/new Sphere();
  6610. const _vA$1 = /*@__PURE__*/new Vector3();
  6611. const _vB$1 = /*@__PURE__*/new Vector3();
  6612. const _vC$1 = /*@__PURE__*/new Vector3();
  6613. const _tempA = /*@__PURE__*/new Vector3();
  6614. const _tempB = /*@__PURE__*/new Vector3();
  6615. const _tempC = /*@__PURE__*/new Vector3();
  6616. const _morphA = /*@__PURE__*/new Vector3();
  6617. const _morphB = /*@__PURE__*/new Vector3();
  6618. const _morphC = /*@__PURE__*/new Vector3();
  6619. const _uvA$1 = /*@__PURE__*/new Vector2();
  6620. const _uvB$1 = /*@__PURE__*/new Vector2();
  6621. const _uvC$1 = /*@__PURE__*/new Vector2();
  6622. const _intersectionPoint = /*@__PURE__*/new Vector3();
  6623. const _intersectionPointWorld = /*@__PURE__*/new Vector3();
  6624. class Mesh extends Object3D {
  6625. constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) {
  6626. super();
  6627. this.type = 'Mesh';
  6628. this.geometry = geometry;
  6629. this.material = material;
  6630. this.updateMorphTargets();
  6631. }
  6632. copy(source) {
  6633. super.copy(source);
  6634. if (source.morphTargetInfluences !== undefined) {
  6635. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6636. }
  6637. if (source.morphTargetDictionary !== undefined) {
  6638. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  6639. }
  6640. this.material = source.material;
  6641. this.geometry = source.geometry;
  6642. return this;
  6643. }
  6644. updateMorphTargets() {
  6645. const geometry = this.geometry;
  6646. if (geometry.isBufferGeometry) {
  6647. const morphAttributes = geometry.morphAttributes;
  6648. const keys = Object.keys(morphAttributes);
  6649. if (keys.length > 0) {
  6650. const morphAttribute = morphAttributes[keys[0]];
  6651. if (morphAttribute !== undefined) {
  6652. this.morphTargetInfluences = [];
  6653. this.morphTargetDictionary = {};
  6654. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  6655. const name = morphAttribute[m].name || String(m);
  6656. this.morphTargetInfluences.push(0);
  6657. this.morphTargetDictionary[name] = m;
  6658. }
  6659. }
  6660. }
  6661. } else {
  6662. const morphTargets = geometry.morphTargets;
  6663. if (morphTargets !== undefined && morphTargets.length > 0) {
  6664. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6665. }
  6666. }
  6667. }
  6668. raycast(raycaster, intersects) {
  6669. const geometry = this.geometry;
  6670. const material = this.material;
  6671. const matrixWorld = this.matrixWorld;
  6672. if (material === undefined) return; // Checking boundingSphere distance to ray
  6673. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  6674. _sphere$3.copy(geometry.boundingSphere);
  6675. _sphere$3.applyMatrix4(matrixWorld);
  6676. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  6677. _inverseMatrix$2.copy(matrixWorld).invert();
  6678. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); // Check boundingBox before continuing
  6679. if (geometry.boundingBox !== null) {
  6680. if (_ray$2.intersectsBox(geometry.boundingBox) === false) return;
  6681. }
  6682. let intersection;
  6683. if (geometry.isBufferGeometry) {
  6684. const index = geometry.index;
  6685. const position = geometry.attributes.position;
  6686. const morphPosition = geometry.morphAttributes.position;
  6687. const morphTargetsRelative = geometry.morphTargetsRelative;
  6688. const uv = geometry.attributes.uv;
  6689. const uv2 = geometry.attributes.uv2;
  6690. const groups = geometry.groups;
  6691. const drawRange = geometry.drawRange;
  6692. if (index !== null) {
  6693. // indexed buffer geometry
  6694. if (Array.isArray(material)) {
  6695. for (let i = 0, il = groups.length; i < il; i++) {
  6696. const group = groups[i];
  6697. const groupMaterial = material[group.materialIndex];
  6698. const start = Math.max(group.start, drawRange.start);
  6699. const end = Math.min(index.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  6700. for (let j = start, jl = end; j < jl; j += 3) {
  6701. const a = index.getX(j);
  6702. const b = index.getX(j + 1);
  6703. const c = index.getX(j + 2);
  6704. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6705. if (intersection) {
  6706. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  6707. intersection.face.materialIndex = group.materialIndex;
  6708. intersects.push(intersection);
  6709. }
  6710. }
  6711. }
  6712. } else {
  6713. const start = Math.max(0, drawRange.start);
  6714. const end = Math.min(index.count, drawRange.start + drawRange.count);
  6715. for (let i = start, il = end; i < il; i += 3) {
  6716. const a = index.getX(i);
  6717. const b = index.getX(i + 1);
  6718. const c = index.getX(i + 2);
  6719. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6720. if (intersection) {
  6721. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  6722. intersects.push(intersection);
  6723. }
  6724. }
  6725. }
  6726. } else if (position !== undefined) {
  6727. // non-indexed buffer geometry
  6728. if (Array.isArray(material)) {
  6729. for (let i = 0, il = groups.length; i < il; i++) {
  6730. const group = groups[i];
  6731. const groupMaterial = material[group.materialIndex];
  6732. const start = Math.max(group.start, drawRange.start);
  6733. const end = Math.min(position.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  6734. for (let j = start, jl = end; j < jl; j += 3) {
  6735. const a = j;
  6736. const b = j + 1;
  6737. const c = j + 2;
  6738. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6739. if (intersection) {
  6740. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  6741. intersection.face.materialIndex = group.materialIndex;
  6742. intersects.push(intersection);
  6743. }
  6744. }
  6745. }
  6746. } else {
  6747. const start = Math.max(0, drawRange.start);
  6748. const end = Math.min(position.count, drawRange.start + drawRange.count);
  6749. for (let i = start, il = end; i < il; i += 3) {
  6750. const a = i;
  6751. const b = i + 1;
  6752. const c = i + 2;
  6753. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6754. if (intersection) {
  6755. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  6756. intersects.push(intersection);
  6757. }
  6758. }
  6759. }
  6760. }
  6761. } else if (geometry.isGeometry) {
  6762. console.error('THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6763. }
  6764. }
  6765. }
  6766. Mesh.prototype.isMesh = true;
  6767. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  6768. let intersect;
  6769. if (material.side === BackSide) {
  6770. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  6771. } else {
  6772. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  6773. }
  6774. if (intersect === null) return null;
  6775. _intersectionPointWorld.copy(point);
  6776. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  6777. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  6778. if (distance < raycaster.near || distance > raycaster.far) return null;
  6779. return {
  6780. distance: distance,
  6781. point: _intersectionPointWorld.clone(),
  6782. object: object
  6783. };
  6784. }
  6785. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  6786. _vA$1.fromBufferAttribute(position, a);
  6787. _vB$1.fromBufferAttribute(position, b);
  6788. _vC$1.fromBufferAttribute(position, c);
  6789. const morphInfluences = object.morphTargetInfluences;
  6790. if (morphPosition && morphInfluences) {
  6791. _morphA.set(0, 0, 0);
  6792. _morphB.set(0, 0, 0);
  6793. _morphC.set(0, 0, 0);
  6794. for (let i = 0, il = morphPosition.length; i < il; i++) {
  6795. const influence = morphInfluences[i];
  6796. const morphAttribute = morphPosition[i];
  6797. if (influence === 0) continue;
  6798. _tempA.fromBufferAttribute(morphAttribute, a);
  6799. _tempB.fromBufferAttribute(morphAttribute, b);
  6800. _tempC.fromBufferAttribute(morphAttribute, c);
  6801. if (morphTargetsRelative) {
  6802. _morphA.addScaledVector(_tempA, influence);
  6803. _morphB.addScaledVector(_tempB, influence);
  6804. _morphC.addScaledVector(_tempC, influence);
  6805. } else {
  6806. _morphA.addScaledVector(_tempA.sub(_vA$1), influence);
  6807. _morphB.addScaledVector(_tempB.sub(_vB$1), influence);
  6808. _morphC.addScaledVector(_tempC.sub(_vC$1), influence);
  6809. }
  6810. }
  6811. _vA$1.add(_morphA);
  6812. _vB$1.add(_morphB);
  6813. _vC$1.add(_morphC);
  6814. }
  6815. if (object.isSkinnedMesh) {
  6816. object.boneTransform(a, _vA$1);
  6817. object.boneTransform(b, _vB$1);
  6818. object.boneTransform(c, _vC$1);
  6819. }
  6820. const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
  6821. if (intersection) {
  6822. if (uv) {
  6823. _uvA$1.fromBufferAttribute(uv, a);
  6824. _uvB$1.fromBufferAttribute(uv, b);
  6825. _uvC$1.fromBufferAttribute(uv, c);
  6826. intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6827. }
  6828. if (uv2) {
  6829. _uvA$1.fromBufferAttribute(uv2, a);
  6830. _uvB$1.fromBufferAttribute(uv2, b);
  6831. _uvC$1.fromBufferAttribute(uv2, c);
  6832. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6833. }
  6834. const face = {
  6835. a: a,
  6836. b: b,
  6837. c: c,
  6838. normal: new Vector3(),
  6839. materialIndex: 0
  6840. };
  6841. Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
  6842. intersection.face = face;
  6843. }
  6844. return intersection;
  6845. }
  6846. class BoxGeometry extends BufferGeometry {
  6847. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  6848. super();
  6849. this.type = 'BoxGeometry';
  6850. this.parameters = {
  6851. width: width,
  6852. height: height,
  6853. depth: depth,
  6854. widthSegments: widthSegments,
  6855. heightSegments: heightSegments,
  6856. depthSegments: depthSegments
  6857. };
  6858. const scope = this; // segments
  6859. widthSegments = Math.floor(widthSegments);
  6860. heightSegments = Math.floor(heightSegments);
  6861. depthSegments = Math.floor(depthSegments); // buffers
  6862. const indices = [];
  6863. const vertices = [];
  6864. const normals = [];
  6865. const uvs = []; // helper variables
  6866. let numberOfVertices = 0;
  6867. let groupStart = 0; // build each side of the box geometry
  6868. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  6869. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  6870. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  6871. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  6872. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  6873. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  6874. // build geometry
  6875. this.setIndex(indices);
  6876. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  6877. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  6878. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  6879. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  6880. const segmentWidth = width / gridX;
  6881. const segmentHeight = height / gridY;
  6882. const widthHalf = width / 2;
  6883. const heightHalf = height / 2;
  6884. const depthHalf = depth / 2;
  6885. const gridX1 = gridX + 1;
  6886. const gridY1 = gridY + 1;
  6887. let vertexCounter = 0;
  6888. let groupCount = 0;
  6889. const vector = new Vector3(); // generate vertices, normals and uvs
  6890. for (let iy = 0; iy < gridY1; iy++) {
  6891. const y = iy * segmentHeight - heightHalf;
  6892. for (let ix = 0; ix < gridX1; ix++) {
  6893. const x = ix * segmentWidth - widthHalf; // set values to correct vector component
  6894. vector[u] = x * udir;
  6895. vector[v] = y * vdir;
  6896. vector[w] = depthHalf; // now apply vector to vertex buffer
  6897. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  6898. vector[u] = 0;
  6899. vector[v] = 0;
  6900. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  6901. normals.push(vector.x, vector.y, vector.z); // uvs
  6902. uvs.push(ix / gridX);
  6903. uvs.push(1 - iy / gridY); // counters
  6904. vertexCounter += 1;
  6905. }
  6906. } // indices
  6907. // 1. you need three indices to draw a single face
  6908. // 2. a single segment consists of two faces
  6909. // 3. so we need to generate six (2*3) indices per segment
  6910. for (let iy = 0; iy < gridY; iy++) {
  6911. for (let ix = 0; ix < gridX; ix++) {
  6912. const a = numberOfVertices + ix + gridX1 * iy;
  6913. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  6914. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  6915. const d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  6916. indices.push(a, b, d);
  6917. indices.push(b, c, d); // increase counter
  6918. groupCount += 6;
  6919. }
  6920. } // add a group to the geometry. this will ensure multi material support
  6921. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  6922. groupStart += groupCount; // update total number of vertices
  6923. numberOfVertices += vertexCounter;
  6924. }
  6925. }
  6926. static fromJSON(data) {
  6927. return new BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  6928. }
  6929. }
  6930. /**
  6931. * Uniform Utilities
  6932. */
  6933. function cloneUniforms(src) {
  6934. const dst = {};
  6935. for (const u in src) {
  6936. dst[u] = {};
  6937. for (const p in src[u]) {
  6938. const property = src[u][p];
  6939. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
  6940. dst[u][p] = property.clone();
  6941. } else if (Array.isArray(property)) {
  6942. dst[u][p] = property.slice();
  6943. } else {
  6944. dst[u][p] = property;
  6945. }
  6946. }
  6947. }
  6948. return dst;
  6949. }
  6950. function mergeUniforms(uniforms) {
  6951. const merged = {};
  6952. for (let u = 0; u < uniforms.length; u++) {
  6953. const tmp = cloneUniforms(uniforms[u]);
  6954. for (const p in tmp) {
  6955. merged[p] = tmp[p];
  6956. }
  6957. }
  6958. return merged;
  6959. } // Legacy
  6960. const UniformsUtils = {
  6961. clone: cloneUniforms,
  6962. merge: mergeUniforms
  6963. };
  6964. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6965. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6966. /**
  6967. * parameters = {
  6968. * defines: { "label" : "value" },
  6969. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  6970. *
  6971. * fragmentShader: <string>,
  6972. * vertexShader: <string>,
  6973. *
  6974. * wireframe: <boolean>,
  6975. * wireframeLinewidth: <float>,
  6976. *
  6977. * lights: <bool>
  6978. * }
  6979. */
  6980. class ShaderMaterial extends Material {
  6981. constructor(parameters) {
  6982. super();
  6983. this.type = 'ShaderMaterial';
  6984. this.defines = {};
  6985. this.uniforms = {};
  6986. this.vertexShader = default_vertex;
  6987. this.fragmentShader = default_fragment;
  6988. this.linewidth = 1;
  6989. this.wireframe = false;
  6990. this.wireframeLinewidth = 1;
  6991. this.fog = false; // set to use scene fog
  6992. this.lights = false; // set to use scene lights
  6993. this.clipping = false; // set to use user-defined clipping planes
  6994. this.extensions = {
  6995. derivatives: false,
  6996. // set to use derivatives
  6997. fragDepth: false,
  6998. // set to use fragment depth values
  6999. drawBuffers: false,
  7000. // set to use draw buffers
  7001. shaderTextureLOD: false // set to use shader texture LOD
  7002. }; // When rendered geometry doesn't include these attributes but the material does,
  7003. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7004. this.defaultAttributeValues = {
  7005. 'color': [1, 1, 1],
  7006. 'uv': [0, 0],
  7007. 'uv2': [0, 0]
  7008. };
  7009. this.index0AttributeName = undefined;
  7010. this.uniformsNeedUpdate = false;
  7011. this.glslVersion = null;
  7012. if (parameters !== undefined) {
  7013. if (parameters.attributes !== undefined) {
  7014. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  7015. }
  7016. this.setValues(parameters);
  7017. }
  7018. }
  7019. copy(source) {
  7020. super.copy(source);
  7021. this.fragmentShader = source.fragmentShader;
  7022. this.vertexShader = source.vertexShader;
  7023. this.uniforms = cloneUniforms(source.uniforms);
  7024. this.defines = Object.assign({}, source.defines);
  7025. this.wireframe = source.wireframe;
  7026. this.wireframeLinewidth = source.wireframeLinewidth;
  7027. this.lights = source.lights;
  7028. this.clipping = source.clipping;
  7029. this.extensions = Object.assign({}, source.extensions);
  7030. this.glslVersion = source.glslVersion;
  7031. return this;
  7032. }
  7033. toJSON(meta) {
  7034. const data = super.toJSON(meta);
  7035. data.glslVersion = this.glslVersion;
  7036. data.uniforms = {};
  7037. for (const name in this.uniforms) {
  7038. const uniform = this.uniforms[name];
  7039. const value = uniform.value;
  7040. if (value && value.isTexture) {
  7041. data.uniforms[name] = {
  7042. type: 't',
  7043. value: value.toJSON(meta).uuid
  7044. };
  7045. } else if (value && value.isColor) {
  7046. data.uniforms[name] = {
  7047. type: 'c',
  7048. value: value.getHex()
  7049. };
  7050. } else if (value && value.isVector2) {
  7051. data.uniforms[name] = {
  7052. type: 'v2',
  7053. value: value.toArray()
  7054. };
  7055. } else if (value && value.isVector3) {
  7056. data.uniforms[name] = {
  7057. type: 'v3',
  7058. value: value.toArray()
  7059. };
  7060. } else if (value && value.isVector4) {
  7061. data.uniforms[name] = {
  7062. type: 'v4',
  7063. value: value.toArray()
  7064. };
  7065. } else if (value && value.isMatrix3) {
  7066. data.uniforms[name] = {
  7067. type: 'm3',
  7068. value: value.toArray()
  7069. };
  7070. } else if (value && value.isMatrix4) {
  7071. data.uniforms[name] = {
  7072. type: 'm4',
  7073. value: value.toArray()
  7074. };
  7075. } else {
  7076. data.uniforms[name] = {
  7077. value: value
  7078. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7079. }
  7080. }
  7081. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  7082. data.vertexShader = this.vertexShader;
  7083. data.fragmentShader = this.fragmentShader;
  7084. const extensions = {};
  7085. for (const key in this.extensions) {
  7086. if (this.extensions[key] === true) extensions[key] = true;
  7087. }
  7088. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  7089. return data;
  7090. }
  7091. }
  7092. ShaderMaterial.prototype.isShaderMaterial = true;
  7093. class Camera extends Object3D {
  7094. constructor() {
  7095. super();
  7096. this.type = 'Camera';
  7097. this.matrixWorldInverse = new Matrix4();
  7098. this.projectionMatrix = new Matrix4();
  7099. this.projectionMatrixInverse = new Matrix4();
  7100. }
  7101. copy(source, recursive) {
  7102. super.copy(source, recursive);
  7103. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  7104. this.projectionMatrix.copy(source.projectionMatrix);
  7105. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  7106. return this;
  7107. }
  7108. getWorldDirection(target) {
  7109. this.updateWorldMatrix(true, false);
  7110. const e = this.matrixWorld.elements;
  7111. return target.set(-e[8], -e[9], -e[10]).normalize();
  7112. }
  7113. updateMatrixWorld(force) {
  7114. super.updateMatrixWorld(force);
  7115. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7116. }
  7117. updateWorldMatrix(updateParents, updateChildren) {
  7118. super.updateWorldMatrix(updateParents, updateChildren);
  7119. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7120. }
  7121. clone() {
  7122. return new this.constructor().copy(this);
  7123. }
  7124. }
  7125. Camera.prototype.isCamera = true;
  7126. class PerspectiveCamera extends Camera {
  7127. constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  7128. super();
  7129. this.type = 'PerspectiveCamera';
  7130. this.fov = fov;
  7131. this.zoom = 1;
  7132. this.near = near;
  7133. this.far = far;
  7134. this.focus = 10;
  7135. this.aspect = aspect;
  7136. this.view = null;
  7137. this.filmGauge = 35; // width of the film (default in millimeters)
  7138. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7139. this.updateProjectionMatrix();
  7140. }
  7141. copy(source, recursive) {
  7142. super.copy(source, recursive);
  7143. this.fov = source.fov;
  7144. this.zoom = source.zoom;
  7145. this.near = source.near;
  7146. this.far = source.far;
  7147. this.focus = source.focus;
  7148. this.aspect = source.aspect;
  7149. this.view = source.view === null ? null : Object.assign({}, source.view);
  7150. this.filmGauge = source.filmGauge;
  7151. this.filmOffset = source.filmOffset;
  7152. return this;
  7153. }
  7154. /**
  7155. * Sets the FOV by focal length in respect to the current .filmGauge.
  7156. *
  7157. * The default film gauge is 35, so that the focal length can be specified for
  7158. * a 35mm (full frame) camera.
  7159. *
  7160. * Values for focal length and film gauge must have the same unit.
  7161. */
  7162. setFocalLength(focalLength) {
  7163. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7164. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7165. this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope);
  7166. this.updateProjectionMatrix();
  7167. }
  7168. /**
  7169. * Calculates the focal length from the current .fov and .filmGauge.
  7170. */
  7171. getFocalLength() {
  7172. const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov);
  7173. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7174. }
  7175. getEffectiveFOV() {
  7176. return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom);
  7177. }
  7178. getFilmWidth() {
  7179. // film not completely covered in portrait format (aspect < 1)
  7180. return this.filmGauge * Math.min(this.aspect, 1);
  7181. }
  7182. getFilmHeight() {
  7183. // film not completely covered in landscape format (aspect > 1)
  7184. return this.filmGauge / Math.max(this.aspect, 1);
  7185. }
  7186. /**
  7187. * Sets an offset in a larger frustum. This is useful for multi-window or
  7188. * multi-monitor/multi-machine setups.
  7189. *
  7190. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7191. * the monitors are in grid like this
  7192. *
  7193. * +---+---+---+
  7194. * | A | B | C |
  7195. * +---+---+---+
  7196. * | D | E | F |
  7197. * +---+---+---+
  7198. *
  7199. * then for each monitor you would call it like this
  7200. *
  7201. * const w = 1920;
  7202. * const h = 1080;
  7203. * const fullWidth = w * 3;
  7204. * const fullHeight = h * 2;
  7205. *
  7206. * --A--
  7207. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7208. * --B--
  7209. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7210. * --C--
  7211. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7212. * --D--
  7213. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7214. * --E--
  7215. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7216. * --F--
  7217. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7218. *
  7219. * Note there is no reason monitors have to be the same size or in a grid.
  7220. */
  7221. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  7222. this.aspect = fullWidth / fullHeight;
  7223. if (this.view === null) {
  7224. this.view = {
  7225. enabled: true,
  7226. fullWidth: 1,
  7227. fullHeight: 1,
  7228. offsetX: 0,
  7229. offsetY: 0,
  7230. width: 1,
  7231. height: 1
  7232. };
  7233. }
  7234. this.view.enabled = true;
  7235. this.view.fullWidth = fullWidth;
  7236. this.view.fullHeight = fullHeight;
  7237. this.view.offsetX = x;
  7238. this.view.offsetY = y;
  7239. this.view.width = width;
  7240. this.view.height = height;
  7241. this.updateProjectionMatrix();
  7242. }
  7243. clearViewOffset() {
  7244. if (this.view !== null) {
  7245. this.view.enabled = false;
  7246. }
  7247. this.updateProjectionMatrix();
  7248. }
  7249. updateProjectionMatrix() {
  7250. const near = this.near;
  7251. let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom;
  7252. let height = 2 * top;
  7253. let width = this.aspect * height;
  7254. let left = -0.5 * width;
  7255. const view = this.view;
  7256. if (this.view !== null && this.view.enabled) {
  7257. const fullWidth = view.fullWidth,
  7258. fullHeight = view.fullHeight;
  7259. left += view.offsetX * width / fullWidth;
  7260. top -= view.offsetY * height / fullHeight;
  7261. width *= view.width / fullWidth;
  7262. height *= view.height / fullHeight;
  7263. }
  7264. const skew = this.filmOffset;
  7265. if (skew !== 0) left += near * skew / this.getFilmWidth();
  7266. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  7267. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  7268. }
  7269. toJSON(meta) {
  7270. const data = super.toJSON(meta);
  7271. data.object.fov = this.fov;
  7272. data.object.zoom = this.zoom;
  7273. data.object.near = this.near;
  7274. data.object.far = this.far;
  7275. data.object.focus = this.focus;
  7276. data.object.aspect = this.aspect;
  7277. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  7278. data.object.filmGauge = this.filmGauge;
  7279. data.object.filmOffset = this.filmOffset;
  7280. return data;
  7281. }
  7282. }
  7283. PerspectiveCamera.prototype.isPerspectiveCamera = true;
  7284. const fov = 90,
  7285. aspect = 1;
  7286. class CubeCamera extends Object3D {
  7287. constructor(near, far, renderTarget) {
  7288. super();
  7289. this.type = 'CubeCamera';
  7290. if (renderTarget.isWebGLCubeRenderTarget !== true) {
  7291. console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
  7292. return;
  7293. }
  7294. this.renderTarget = renderTarget;
  7295. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  7296. cameraPX.layers = this.layers;
  7297. cameraPX.up.set(0, -1, 0);
  7298. cameraPX.lookAt(new Vector3(1, 0, 0));
  7299. this.add(cameraPX);
  7300. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  7301. cameraNX.layers = this.layers;
  7302. cameraNX.up.set(0, -1, 0);
  7303. cameraNX.lookAt(new Vector3(-1, 0, 0));
  7304. this.add(cameraNX);
  7305. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  7306. cameraPY.layers = this.layers;
  7307. cameraPY.up.set(0, 0, 1);
  7308. cameraPY.lookAt(new Vector3(0, 1, 0));
  7309. this.add(cameraPY);
  7310. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  7311. cameraNY.layers = this.layers;
  7312. cameraNY.up.set(0, 0, -1);
  7313. cameraNY.lookAt(new Vector3(0, -1, 0));
  7314. this.add(cameraNY);
  7315. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  7316. cameraPZ.layers = this.layers;
  7317. cameraPZ.up.set(0, -1, 0);
  7318. cameraPZ.lookAt(new Vector3(0, 0, 1));
  7319. this.add(cameraPZ);
  7320. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  7321. cameraNZ.layers = this.layers;
  7322. cameraNZ.up.set(0, -1, 0);
  7323. cameraNZ.lookAt(new Vector3(0, 0, -1));
  7324. this.add(cameraNZ);
  7325. }
  7326. update(renderer, scene) {
  7327. if (this.parent === null) this.updateMatrixWorld();
  7328. const renderTarget = this.renderTarget;
  7329. const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children;
  7330. const currentXrEnabled = renderer.xr.enabled;
  7331. const currentRenderTarget = renderer.getRenderTarget();
  7332. renderer.xr.enabled = false;
  7333. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7334. renderTarget.texture.generateMipmaps = false;
  7335. renderer.setRenderTarget(renderTarget, 0);
  7336. renderer.render(scene, cameraPX);
  7337. renderer.setRenderTarget(renderTarget, 1);
  7338. renderer.render(scene, cameraNX);
  7339. renderer.setRenderTarget(renderTarget, 2);
  7340. renderer.render(scene, cameraPY);
  7341. renderer.setRenderTarget(renderTarget, 3);
  7342. renderer.render(scene, cameraNY);
  7343. renderer.setRenderTarget(renderTarget, 4);
  7344. renderer.render(scene, cameraPZ);
  7345. renderTarget.texture.generateMipmaps = generateMipmaps;
  7346. renderer.setRenderTarget(renderTarget, 5);
  7347. renderer.render(scene, cameraNZ);
  7348. renderer.setRenderTarget(currentRenderTarget);
  7349. renderer.xr.enabled = currentXrEnabled;
  7350. }
  7351. }
  7352. class CubeTexture extends Texture {
  7353. constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  7354. images = images !== undefined ? images : [];
  7355. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7356. super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  7357. this.flipY = false;
  7358. }
  7359. get images() {
  7360. return this.image;
  7361. }
  7362. set images(value) {
  7363. this.image = value;
  7364. }
  7365. }
  7366. CubeTexture.prototype.isCubeTexture = true;
  7367. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7368. constructor(size, options, dummy) {
  7369. if (Number.isInteger(options)) {
  7370. console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
  7371. options = dummy;
  7372. }
  7373. super(size, size, options);
  7374. options = options || {}; // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7375. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7376. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7377. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7378. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7379. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7380. this.texture = new CubeTexture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  7381. this.texture.isRenderTargetTexture = true;
  7382. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7383. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7384. this.texture._needsFlipEnvMap = false;
  7385. }
  7386. fromEquirectangularTexture(renderer, texture) {
  7387. this.texture.type = texture.type;
  7388. this.texture.format = RGBAFormat; // see #18859
  7389. this.texture.encoding = texture.encoding;
  7390. this.texture.generateMipmaps = texture.generateMipmaps;
  7391. this.texture.minFilter = texture.minFilter;
  7392. this.texture.magFilter = texture.magFilter;
  7393. const shader = {
  7394. uniforms: {
  7395. tEquirect: {
  7396. value: null
  7397. }
  7398. },
  7399. vertexShader:
  7400. /* glsl */
  7401. `
  7402. varying vec3 vWorldDirection;
  7403. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7404. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7405. }
  7406. void main() {
  7407. vWorldDirection = transformDirection( position, modelMatrix );
  7408. #include <begin_vertex>
  7409. #include <project_vertex>
  7410. }
  7411. `,
  7412. fragmentShader:
  7413. /* glsl */
  7414. `
  7415. uniform sampler2D tEquirect;
  7416. varying vec3 vWorldDirection;
  7417. #include <common>
  7418. void main() {
  7419. vec3 direction = normalize( vWorldDirection );
  7420. vec2 sampleUV = equirectUv( direction );
  7421. gl_FragColor = texture2D( tEquirect, sampleUV );
  7422. }
  7423. `
  7424. };
  7425. const geometry = new BoxGeometry(5, 5, 5);
  7426. const material = new ShaderMaterial({
  7427. name: 'CubemapFromEquirect',
  7428. uniforms: cloneUniforms(shader.uniforms),
  7429. vertexShader: shader.vertexShader,
  7430. fragmentShader: shader.fragmentShader,
  7431. side: BackSide,
  7432. blending: NoBlending
  7433. });
  7434. material.uniforms.tEquirect.value = texture;
  7435. const mesh = new Mesh(geometry, material);
  7436. const currentMinFilter = texture.minFilter; // Avoid blurred poles
  7437. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  7438. const camera = new CubeCamera(1, 10, this);
  7439. camera.update(renderer, mesh);
  7440. texture.minFilter = currentMinFilter;
  7441. mesh.geometry.dispose();
  7442. mesh.material.dispose();
  7443. return this;
  7444. }
  7445. clear(renderer, color, depth, stencil) {
  7446. const currentRenderTarget = renderer.getRenderTarget();
  7447. for (let i = 0; i < 6; i++) {
  7448. renderer.setRenderTarget(this, i);
  7449. renderer.clear(color, depth, stencil);
  7450. }
  7451. renderer.setRenderTarget(currentRenderTarget);
  7452. }
  7453. }
  7454. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  7455. const _vector1 = /*@__PURE__*/new Vector3();
  7456. const _vector2 = /*@__PURE__*/new Vector3();
  7457. const _normalMatrix = /*@__PURE__*/new Matrix3();
  7458. class Plane {
  7459. constructor(normal = new Vector3(1, 0, 0), constant = 0) {
  7460. // normal is assumed to be normalized
  7461. this.normal = normal;
  7462. this.constant = constant;
  7463. }
  7464. set(normal, constant) {
  7465. this.normal.copy(normal);
  7466. this.constant = constant;
  7467. return this;
  7468. }
  7469. setComponents(x, y, z, w) {
  7470. this.normal.set(x, y, z);
  7471. this.constant = w;
  7472. return this;
  7473. }
  7474. setFromNormalAndCoplanarPoint(normal, point) {
  7475. this.normal.copy(normal);
  7476. this.constant = -point.dot(this.normal);
  7477. return this;
  7478. }
  7479. setFromCoplanarPoints(a, b, c) {
  7480. 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)?
  7481. this.setFromNormalAndCoplanarPoint(normal, a);
  7482. return this;
  7483. }
  7484. copy(plane) {
  7485. this.normal.copy(plane.normal);
  7486. this.constant = plane.constant;
  7487. return this;
  7488. }
  7489. normalize() {
  7490. // Note: will lead to a divide by zero if the plane is invalid.
  7491. const inverseNormalLength = 1.0 / this.normal.length();
  7492. this.normal.multiplyScalar(inverseNormalLength);
  7493. this.constant *= inverseNormalLength;
  7494. return this;
  7495. }
  7496. negate() {
  7497. this.constant *= -1;
  7498. this.normal.negate();
  7499. return this;
  7500. }
  7501. distanceToPoint(point) {
  7502. return this.normal.dot(point) + this.constant;
  7503. }
  7504. distanceToSphere(sphere) {
  7505. return this.distanceToPoint(sphere.center) - sphere.radius;
  7506. }
  7507. projectPoint(point, target) {
  7508. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  7509. }
  7510. intersectLine(line, target) {
  7511. const direction = line.delta(_vector1);
  7512. const denominator = this.normal.dot(direction);
  7513. if (denominator === 0) {
  7514. // line is coplanar, return origin
  7515. if (this.distanceToPoint(line.start) === 0) {
  7516. return target.copy(line.start);
  7517. } // Unsure if this is the correct method to handle this case.
  7518. return null;
  7519. }
  7520. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  7521. if (t < 0 || t > 1) {
  7522. return null;
  7523. }
  7524. return target.copy(direction).multiplyScalar(t).add(line.start);
  7525. }
  7526. intersectsLine(line) {
  7527. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7528. const startSign = this.distanceToPoint(line.start);
  7529. const endSign = this.distanceToPoint(line.end);
  7530. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  7531. }
  7532. intersectsBox(box) {
  7533. return box.intersectsPlane(this);
  7534. }
  7535. intersectsSphere(sphere) {
  7536. return sphere.intersectsPlane(this);
  7537. }
  7538. coplanarPoint(target) {
  7539. return target.copy(this.normal).multiplyScalar(-this.constant);
  7540. }
  7541. applyMatrix4(matrix, optionalNormalMatrix) {
  7542. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  7543. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  7544. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  7545. this.constant = -referencePoint.dot(normal);
  7546. return this;
  7547. }
  7548. translate(offset) {
  7549. this.constant -= offset.dot(this.normal);
  7550. return this;
  7551. }
  7552. equals(plane) {
  7553. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  7554. }
  7555. clone() {
  7556. return new this.constructor().copy(this);
  7557. }
  7558. }
  7559. Plane.prototype.isPlane = true;
  7560. const _sphere$2 = /*@__PURE__*/new Sphere();
  7561. const _vector$7 = /*@__PURE__*/new Vector3();
  7562. class Frustum {
  7563. constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) {
  7564. this.planes = [p0, p1, p2, p3, p4, p5];
  7565. }
  7566. set(p0, p1, p2, p3, p4, p5) {
  7567. const planes = this.planes;
  7568. planes[0].copy(p0);
  7569. planes[1].copy(p1);
  7570. planes[2].copy(p2);
  7571. planes[3].copy(p3);
  7572. planes[4].copy(p4);
  7573. planes[5].copy(p5);
  7574. return this;
  7575. }
  7576. copy(frustum) {
  7577. const planes = this.planes;
  7578. for (let i = 0; i < 6; i++) {
  7579. planes[i].copy(frustum.planes[i]);
  7580. }
  7581. return this;
  7582. }
  7583. setFromProjectionMatrix(m) {
  7584. const planes = this.planes;
  7585. const me = m.elements;
  7586. const me0 = me[0],
  7587. me1 = me[1],
  7588. me2 = me[2],
  7589. me3 = me[3];
  7590. const me4 = me[4],
  7591. me5 = me[5],
  7592. me6 = me[6],
  7593. me7 = me[7];
  7594. const me8 = me[8],
  7595. me9 = me[9],
  7596. me10 = me[10],
  7597. me11 = me[11];
  7598. const me12 = me[12],
  7599. me13 = me[13],
  7600. me14 = me[14],
  7601. me15 = me[15];
  7602. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  7603. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  7604. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  7605. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  7606. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  7607. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  7608. return this;
  7609. }
  7610. intersectsObject(object) {
  7611. const geometry = object.geometry;
  7612. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7613. _sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  7614. return this.intersectsSphere(_sphere$2);
  7615. }
  7616. intersectsSprite(sprite) {
  7617. _sphere$2.center.set(0, 0, 0);
  7618. _sphere$2.radius = 0.7071067811865476;
  7619. _sphere$2.applyMatrix4(sprite.matrixWorld);
  7620. return this.intersectsSphere(_sphere$2);
  7621. }
  7622. intersectsSphere(sphere) {
  7623. const planes = this.planes;
  7624. const center = sphere.center;
  7625. const negRadius = -sphere.radius;
  7626. for (let i = 0; i < 6; i++) {
  7627. const distance = planes[i].distanceToPoint(center);
  7628. if (distance < negRadius) {
  7629. return false;
  7630. }
  7631. }
  7632. return true;
  7633. }
  7634. intersectsBox(box) {
  7635. const planes = this.planes;
  7636. for (let i = 0; i < 6; i++) {
  7637. const plane = planes[i]; // corner at max distance
  7638. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7639. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7640. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7641. if (plane.distanceToPoint(_vector$7) < 0) {
  7642. return false;
  7643. }
  7644. }
  7645. return true;
  7646. }
  7647. containsPoint(point) {
  7648. const planes = this.planes;
  7649. for (let i = 0; i < 6; i++) {
  7650. if (planes[i].distanceToPoint(point) < 0) {
  7651. return false;
  7652. }
  7653. }
  7654. return true;
  7655. }
  7656. clone() {
  7657. return new this.constructor().copy(this);
  7658. }
  7659. }
  7660. function WebGLAnimation() {
  7661. let context = null;
  7662. let isAnimating = false;
  7663. let animationLoop = null;
  7664. let requestId = null;
  7665. function onAnimationFrame(time, frame) {
  7666. animationLoop(time, frame);
  7667. requestId = context.requestAnimationFrame(onAnimationFrame);
  7668. }
  7669. return {
  7670. start: function () {
  7671. if (isAnimating === true) return;
  7672. if (animationLoop === null) return;
  7673. requestId = context.requestAnimationFrame(onAnimationFrame);
  7674. isAnimating = true;
  7675. },
  7676. stop: function () {
  7677. context.cancelAnimationFrame(requestId);
  7678. isAnimating = false;
  7679. },
  7680. setAnimationLoop: function (callback) {
  7681. animationLoop = callback;
  7682. },
  7683. setContext: function (value) {
  7684. context = value;
  7685. }
  7686. };
  7687. }
  7688. function WebGLAttributes(gl, capabilities) {
  7689. const isWebGL2 = capabilities.isWebGL2;
  7690. const buffers = new WeakMap();
  7691. function createBuffer(attribute, bufferType) {
  7692. const array = attribute.array;
  7693. const usage = attribute.usage;
  7694. const buffer = gl.createBuffer();
  7695. gl.bindBuffer(bufferType, buffer);
  7696. gl.bufferData(bufferType, array, usage);
  7697. attribute.onUploadCallback();
  7698. let type = gl.FLOAT;
  7699. if (array instanceof Float32Array) {
  7700. type = gl.FLOAT;
  7701. } else if (array instanceof Float64Array) {
  7702. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  7703. } else if (array instanceof Uint16Array) {
  7704. if (attribute.isFloat16BufferAttribute) {
  7705. if (isWebGL2) {
  7706. type = gl.HALF_FLOAT;
  7707. } else {
  7708. console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  7709. }
  7710. } else {
  7711. type = gl.UNSIGNED_SHORT;
  7712. }
  7713. } else if (array instanceof Int16Array) {
  7714. type = gl.SHORT;
  7715. } else if (array instanceof Uint32Array) {
  7716. type = gl.UNSIGNED_INT;
  7717. } else if (array instanceof Int32Array) {
  7718. type = gl.INT;
  7719. } else if (array instanceof Int8Array) {
  7720. type = gl.BYTE;
  7721. } else if (array instanceof Uint8Array) {
  7722. type = gl.UNSIGNED_BYTE;
  7723. } else if (array instanceof Uint8ClampedArray) {
  7724. type = gl.UNSIGNED_BYTE;
  7725. }
  7726. return {
  7727. buffer: buffer,
  7728. type: type,
  7729. bytesPerElement: array.BYTES_PER_ELEMENT,
  7730. version: attribute.version
  7731. };
  7732. }
  7733. function updateBuffer(buffer, attribute, bufferType) {
  7734. const array = attribute.array;
  7735. const updateRange = attribute.updateRange;
  7736. gl.bindBuffer(bufferType, buffer);
  7737. if (updateRange.count === -1) {
  7738. // Not using update ranges
  7739. gl.bufferSubData(bufferType, 0, array);
  7740. } else {
  7741. if (isWebGL2) {
  7742. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  7743. } else {
  7744. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  7745. }
  7746. updateRange.count = -1; // reset range
  7747. }
  7748. } //
  7749. function get(attribute) {
  7750. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7751. return buffers.get(attribute);
  7752. }
  7753. function remove(attribute) {
  7754. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7755. const data = buffers.get(attribute);
  7756. if (data) {
  7757. gl.deleteBuffer(data.buffer);
  7758. buffers.delete(attribute);
  7759. }
  7760. }
  7761. function update(attribute, bufferType) {
  7762. if (attribute.isGLBufferAttribute) {
  7763. const cached = buffers.get(attribute);
  7764. if (!cached || cached.version < attribute.version) {
  7765. buffers.set(attribute, {
  7766. buffer: attribute.buffer,
  7767. type: attribute.type,
  7768. bytesPerElement: attribute.elementSize,
  7769. version: attribute.version
  7770. });
  7771. }
  7772. return;
  7773. }
  7774. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7775. const data = buffers.get(attribute);
  7776. if (data === undefined) {
  7777. buffers.set(attribute, createBuffer(attribute, bufferType));
  7778. } else if (data.version < attribute.version) {
  7779. updateBuffer(data.buffer, attribute, bufferType);
  7780. data.version = attribute.version;
  7781. }
  7782. }
  7783. return {
  7784. get: get,
  7785. remove: remove,
  7786. update: update
  7787. };
  7788. }
  7789. class PlaneGeometry extends BufferGeometry {
  7790. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  7791. super();
  7792. this.type = 'PlaneGeometry';
  7793. this.parameters = {
  7794. width: width,
  7795. height: height,
  7796. widthSegments: widthSegments,
  7797. heightSegments: heightSegments
  7798. };
  7799. const width_half = width / 2;
  7800. const height_half = height / 2;
  7801. const gridX = Math.floor(widthSegments);
  7802. const gridY = Math.floor(heightSegments);
  7803. const gridX1 = gridX + 1;
  7804. const gridY1 = gridY + 1;
  7805. const segment_width = width / gridX;
  7806. const segment_height = height / gridY; //
  7807. const indices = [];
  7808. const vertices = [];
  7809. const normals = [];
  7810. const uvs = [];
  7811. for (let iy = 0; iy < gridY1; iy++) {
  7812. const y = iy * segment_height - height_half;
  7813. for (let ix = 0; ix < gridX1; ix++) {
  7814. const x = ix * segment_width - width_half;
  7815. vertices.push(x, -y, 0);
  7816. normals.push(0, 0, 1);
  7817. uvs.push(ix / gridX);
  7818. uvs.push(1 - iy / gridY);
  7819. }
  7820. }
  7821. for (let iy = 0; iy < gridY; iy++) {
  7822. for (let ix = 0; ix < gridX; ix++) {
  7823. const a = ix + gridX1 * iy;
  7824. const b = ix + gridX1 * (iy + 1);
  7825. const c = ix + 1 + gridX1 * (iy + 1);
  7826. const d = ix + 1 + gridX1 * iy;
  7827. indices.push(a, b, d);
  7828. indices.push(b, c, d);
  7829. }
  7830. }
  7831. this.setIndex(indices);
  7832. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7833. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7834. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7835. }
  7836. static fromJSON(data) {
  7837. return new PlaneGeometry(data.width, data.height, data.widthSegments, data.heightSegments);
  7838. }
  7839. }
  7840. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7841. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7842. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7843. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7844. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif";
  7845. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7846. var begin_vertex = "vec3 transformed = vec3( position );";
  7847. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7848. var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenTint, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenTint * ( D * V );\n}\n#endif";
  7849. 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";
  7850. 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";
  7851. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7852. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7853. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7854. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7855. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7856. 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";
  7857. 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";
  7858. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
  7859. 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";
  7860. 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";
  7861. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7862. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7863. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7864. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7865. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7866. 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}";
  7867. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  7868. 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";
  7869. 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";
  7870. 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";
  7871. 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";
  7872. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7873. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7874. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  7875. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  7876. 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}";
  7877. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tlightMapIrradiance *= PI;\n\t#endif\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7878. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7879. 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.normal );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry.normal );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointLightInfo( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotLightInfo( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalLightInfo( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry.normal );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
  7880. 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 vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif";
  7881. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec;\n\t\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\t\treflectVec = reflect( - viewDir, normal );\n\t\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\t#else\n\t\t\t\treflectVec = refract( - viewDir, normal, refractionRatio );\n\t\t\t#endif\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif";
  7882. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7883. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
  7884. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7885. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
  7886. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularTintFactor = specularTint;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARTINTMAP\n\t\t\tspecularTintFactor *= specularTintMapTexelToLinear( texture2D( specularTintMap, vUv ) ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularTintFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularTintFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenTint = sheenTint;\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n#endif";
  7887. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenTint;\n\t\tfloat sheenRoughness;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\tvec3 FssEss = specularColor * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenTint, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  7888. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\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.normal );\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";
  7889. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  7890. 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";
  7891. 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";
  7892. 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";
  7893. 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";
  7894. 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";
  7895. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  7896. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7897. 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";
  7898. 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";
  7899. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7900. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7901. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1, 2 ) * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif";
  7902. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform vec2 morphTargetsTextureSize;\n\t\tvec3 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset, const in int stride ) {\n\t\t\tfloat texelIndex = float( vertexIndex * stride + offset );\n\t\t\tfloat y = floor( texelIndex / morphTargetsTextureSize.x );\n\t\t\tfloat x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tvec3 morphUV = vec3( ( x + 0.5 ) / morphTargetsTextureSize.x, y / morphTargetsTextureSize.y, morphTargetIndex );\n\t\t\treturn texture( morphTargetsTexture, morphUV ).xyz;\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif";
  7903. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\t#ifndef USE_MORPHNORMALS\n\t\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 1 ) * morphTargetInfluences[ i ];\n\t\t\t#else\n\t\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 2 ) * morphTargetInfluences[ i ];\n\t\t\t#endif\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif";
  7904. 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;";
  7905. 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";
  7906. var normal_pars_fragment = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
  7907. var normal_pars_vertex = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
  7908. var normal_vertex = "#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif";
  7909. 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";
  7910. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7911. 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";
  7912. 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";
  7913. var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  7914. 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}";
  7915. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7916. 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;";
  7917. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7918. 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";
  7919. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7920. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7921. 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";
  7922. 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";
  7923. 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";
  7924. 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}";
  7925. 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";
  7926. 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";
  7927. 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";
  7928. 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";
  7929. 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";
  7930. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7931. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7932. 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; }";
  7933. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tfloat transmissionAlpha = 1.0;\n\tfloat transmissionFactor = transmission;\n\tfloat thicknessFactor = thickness;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\ttransmissionFactor *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tthicknessFactor *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, roughnessFactor, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationTint, attenuationDistance );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, transmissionFactor );\n\ttransmissionAlpha = mix( transmissionAlpha, transmission.a, transmissionFactor );\n#endif";
  7934. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationTint;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( vec3 n, vec3 v, float thickness, float ior, mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( float roughness, float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( vec2 fragCoord, float roughness, float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( vec3 radiance, float transmissionDistance, vec3 attenuationColor, float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( vec3 n, vec3 v, float roughness, vec3 diffuseColor, vec3 specularColor, float specularF90,\n\t\tvec3 position, mat4 modelMatrix, mat4 viewMatrix, mat4 projMatrix, float ior, float thickness,\n\t\tvec3 attenuationColor, float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif";
  7935. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7936. 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";
  7937. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7938. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7939. 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";
  7940. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7941. 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";
  7942. const vertex$g = "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}";
  7943. const fragment$g = "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}";
  7944. const vertex$f = "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}";
  7945. const fragment$f = "#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}";
  7946. const vertex$e = "#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}";
  7947. const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  7948. const vertex$d = "#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}";
  7949. const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  7950. const vertex$c = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  7951. const fragment$c = "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}";
  7952. const vertex$b = "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}";
  7953. const fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7954. const vertex$a = "#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}";
  7955. const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7956. const vertex$9 = "#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}";
  7957. const fragment$9 = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7958. const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  7959. const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7960. const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  7961. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";
  7962. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7963. const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7964. const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}";
  7965. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularTint;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARTINTMAP\n\t\tuniform sampler2D specularTintMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenTint;\n\tuniform float sheenRoughness;\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - clearcoat * Fcc ) + clearcoatSpecular * clearcoat;\n\t#endif\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7966. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7967. const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7968. const vertex$3 = "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}";
  7969. const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7970. const vertex$2 = "#include <common>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\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 <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7971. const fragment$2 = "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}";
  7972. const vertex$1 = "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}";
  7973. const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  7974. const ShaderChunk = {
  7975. alphamap_fragment: alphamap_fragment,
  7976. alphamap_pars_fragment: alphamap_pars_fragment,
  7977. alphatest_fragment: alphatest_fragment,
  7978. alphatest_pars_fragment: alphatest_pars_fragment,
  7979. aomap_fragment: aomap_fragment,
  7980. aomap_pars_fragment: aomap_pars_fragment,
  7981. begin_vertex: begin_vertex,
  7982. beginnormal_vertex: beginnormal_vertex,
  7983. bsdfs: bsdfs,
  7984. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7985. clipping_planes_fragment: clipping_planes_fragment,
  7986. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7987. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7988. clipping_planes_vertex: clipping_planes_vertex,
  7989. color_fragment: color_fragment,
  7990. color_pars_fragment: color_pars_fragment,
  7991. color_pars_vertex: color_pars_vertex,
  7992. color_vertex: color_vertex,
  7993. common: common,
  7994. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7995. defaultnormal_vertex: defaultnormal_vertex,
  7996. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7997. displacementmap_vertex: displacementmap_vertex,
  7998. emissivemap_fragment: emissivemap_fragment,
  7999. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8000. encodings_fragment: encodings_fragment,
  8001. encodings_pars_fragment: encodings_pars_fragment,
  8002. envmap_fragment: envmap_fragment,
  8003. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8004. envmap_pars_fragment: envmap_pars_fragment,
  8005. envmap_pars_vertex: envmap_pars_vertex,
  8006. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8007. envmap_vertex: envmap_vertex,
  8008. fog_vertex: fog_vertex,
  8009. fog_pars_vertex: fog_pars_vertex,
  8010. fog_fragment: fog_fragment,
  8011. fog_pars_fragment: fog_pars_fragment,
  8012. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8013. lightmap_fragment: lightmap_fragment,
  8014. lightmap_pars_fragment: lightmap_pars_fragment,
  8015. lights_lambert_vertex: lights_lambert_vertex,
  8016. lights_pars_begin: lights_pars_begin,
  8017. lights_toon_fragment: lights_toon_fragment,
  8018. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8019. lights_phong_fragment: lights_phong_fragment,
  8020. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8021. lights_physical_fragment: lights_physical_fragment,
  8022. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8023. lights_fragment_begin: lights_fragment_begin,
  8024. lights_fragment_maps: lights_fragment_maps,
  8025. lights_fragment_end: lights_fragment_end,
  8026. logdepthbuf_fragment: logdepthbuf_fragment,
  8027. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8028. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8029. logdepthbuf_vertex: logdepthbuf_vertex,
  8030. map_fragment: map_fragment,
  8031. map_pars_fragment: map_pars_fragment,
  8032. map_particle_fragment: map_particle_fragment,
  8033. map_particle_pars_fragment: map_particle_pars_fragment,
  8034. metalnessmap_fragment: metalnessmap_fragment,
  8035. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8036. morphnormal_vertex: morphnormal_vertex,
  8037. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8038. morphtarget_vertex: morphtarget_vertex,
  8039. normal_fragment_begin: normal_fragment_begin,
  8040. normal_fragment_maps: normal_fragment_maps,
  8041. normal_pars_fragment: normal_pars_fragment,
  8042. normal_pars_vertex: normal_pars_vertex,
  8043. normal_vertex: normal_vertex,
  8044. normalmap_pars_fragment: normalmap_pars_fragment,
  8045. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8046. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8047. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8048. output_fragment: output_fragment,
  8049. packing: packing,
  8050. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8051. project_vertex: project_vertex,
  8052. dithering_fragment: dithering_fragment,
  8053. dithering_pars_fragment: dithering_pars_fragment,
  8054. roughnessmap_fragment: roughnessmap_fragment,
  8055. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8056. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8057. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8058. shadowmap_vertex: shadowmap_vertex,
  8059. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8060. skinbase_vertex: skinbase_vertex,
  8061. skinning_pars_vertex: skinning_pars_vertex,
  8062. skinning_vertex: skinning_vertex,
  8063. skinnormal_vertex: skinnormal_vertex,
  8064. specularmap_fragment: specularmap_fragment,
  8065. specularmap_pars_fragment: specularmap_pars_fragment,
  8066. tonemapping_fragment: tonemapping_fragment,
  8067. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8068. transmission_fragment: transmission_fragment,
  8069. transmission_pars_fragment: transmission_pars_fragment,
  8070. uv_pars_fragment: uv_pars_fragment,
  8071. uv_pars_vertex: uv_pars_vertex,
  8072. uv_vertex: uv_vertex,
  8073. uv2_pars_fragment: uv2_pars_fragment,
  8074. uv2_pars_vertex: uv2_pars_vertex,
  8075. uv2_vertex: uv2_vertex,
  8076. worldpos_vertex: worldpos_vertex,
  8077. background_vert: vertex$g,
  8078. background_frag: fragment$g,
  8079. cube_vert: vertex$f,
  8080. cube_frag: fragment$f,
  8081. depth_vert: vertex$e,
  8082. depth_frag: fragment$e,
  8083. distanceRGBA_vert: vertex$d,
  8084. distanceRGBA_frag: fragment$d,
  8085. equirect_vert: vertex$c,
  8086. equirect_frag: fragment$c,
  8087. linedashed_vert: vertex$b,
  8088. linedashed_frag: fragment$b,
  8089. meshbasic_vert: vertex$a,
  8090. meshbasic_frag: fragment$a,
  8091. meshlambert_vert: vertex$9,
  8092. meshlambert_frag: fragment$9,
  8093. meshmatcap_vert: vertex$8,
  8094. meshmatcap_frag: fragment$8,
  8095. meshnormal_vert: vertex$7,
  8096. meshnormal_frag: fragment$7,
  8097. meshphong_vert: vertex$6,
  8098. meshphong_frag: fragment$6,
  8099. meshphysical_vert: vertex$5,
  8100. meshphysical_frag: fragment$5,
  8101. meshtoon_vert: vertex$4,
  8102. meshtoon_frag: fragment$4,
  8103. points_vert: vertex$3,
  8104. points_frag: fragment$3,
  8105. shadow_vert: vertex$2,
  8106. shadow_frag: fragment$2,
  8107. sprite_vert: vertex$1,
  8108. sprite_frag: fragment$1
  8109. };
  8110. /**
  8111. * Uniforms library for shared webgl shaders
  8112. */
  8113. const UniformsLib = {
  8114. common: {
  8115. diffuse: {
  8116. value: new Color(0xffffff)
  8117. },
  8118. opacity: {
  8119. value: 1.0
  8120. },
  8121. map: {
  8122. value: null
  8123. },
  8124. uvTransform: {
  8125. value: new Matrix3()
  8126. },
  8127. uv2Transform: {
  8128. value: new Matrix3()
  8129. },
  8130. alphaMap: {
  8131. value: null
  8132. },
  8133. alphaTest: {
  8134. value: 0
  8135. }
  8136. },
  8137. specularmap: {
  8138. specularMap: {
  8139. value: null
  8140. }
  8141. },
  8142. envmap: {
  8143. envMap: {
  8144. value: null
  8145. },
  8146. flipEnvMap: {
  8147. value: -1
  8148. },
  8149. reflectivity: {
  8150. value: 1.0
  8151. },
  8152. // basic, lambert, phong
  8153. ior: {
  8154. value: 1.5
  8155. },
  8156. // standard, physical
  8157. refractionRatio: {
  8158. value: 0.98
  8159. },
  8160. maxMipLevel: {
  8161. value: 0
  8162. }
  8163. },
  8164. aomap: {
  8165. aoMap: {
  8166. value: null
  8167. },
  8168. aoMapIntensity: {
  8169. value: 1
  8170. }
  8171. },
  8172. lightmap: {
  8173. lightMap: {
  8174. value: null
  8175. },
  8176. lightMapIntensity: {
  8177. value: 1
  8178. }
  8179. },
  8180. emissivemap: {
  8181. emissiveMap: {
  8182. value: null
  8183. }
  8184. },
  8185. bumpmap: {
  8186. bumpMap: {
  8187. value: null
  8188. },
  8189. bumpScale: {
  8190. value: 1
  8191. }
  8192. },
  8193. normalmap: {
  8194. normalMap: {
  8195. value: null
  8196. },
  8197. normalScale: {
  8198. value: new Vector2(1, 1)
  8199. }
  8200. },
  8201. displacementmap: {
  8202. displacementMap: {
  8203. value: null
  8204. },
  8205. displacementScale: {
  8206. value: 1
  8207. },
  8208. displacementBias: {
  8209. value: 0
  8210. }
  8211. },
  8212. roughnessmap: {
  8213. roughnessMap: {
  8214. value: null
  8215. }
  8216. },
  8217. metalnessmap: {
  8218. metalnessMap: {
  8219. value: null
  8220. }
  8221. },
  8222. gradientmap: {
  8223. gradientMap: {
  8224. value: null
  8225. }
  8226. },
  8227. fog: {
  8228. fogDensity: {
  8229. value: 0.00025
  8230. },
  8231. fogNear: {
  8232. value: 1
  8233. },
  8234. fogFar: {
  8235. value: 2000
  8236. },
  8237. fogColor: {
  8238. value: new Color(0xffffff)
  8239. }
  8240. },
  8241. lights: {
  8242. ambientLightColor: {
  8243. value: []
  8244. },
  8245. lightProbe: {
  8246. value: []
  8247. },
  8248. directionalLights: {
  8249. value: [],
  8250. properties: {
  8251. direction: {},
  8252. color: {}
  8253. }
  8254. },
  8255. directionalLightShadows: {
  8256. value: [],
  8257. properties: {
  8258. shadowBias: {},
  8259. shadowNormalBias: {},
  8260. shadowRadius: {},
  8261. shadowMapSize: {}
  8262. }
  8263. },
  8264. directionalShadowMap: {
  8265. value: []
  8266. },
  8267. directionalShadowMatrix: {
  8268. value: []
  8269. },
  8270. spotLights: {
  8271. value: [],
  8272. properties: {
  8273. color: {},
  8274. position: {},
  8275. direction: {},
  8276. distance: {},
  8277. coneCos: {},
  8278. penumbraCos: {},
  8279. decay: {}
  8280. }
  8281. },
  8282. spotLightShadows: {
  8283. value: [],
  8284. properties: {
  8285. shadowBias: {},
  8286. shadowNormalBias: {},
  8287. shadowRadius: {},
  8288. shadowMapSize: {}
  8289. }
  8290. },
  8291. spotShadowMap: {
  8292. value: []
  8293. },
  8294. spotShadowMatrix: {
  8295. value: []
  8296. },
  8297. pointLights: {
  8298. value: [],
  8299. properties: {
  8300. color: {},
  8301. position: {},
  8302. decay: {},
  8303. distance: {}
  8304. }
  8305. },
  8306. pointLightShadows: {
  8307. value: [],
  8308. properties: {
  8309. shadowBias: {},
  8310. shadowNormalBias: {},
  8311. shadowRadius: {},
  8312. shadowMapSize: {},
  8313. shadowCameraNear: {},
  8314. shadowCameraFar: {}
  8315. }
  8316. },
  8317. pointShadowMap: {
  8318. value: []
  8319. },
  8320. pointShadowMatrix: {
  8321. value: []
  8322. },
  8323. hemisphereLights: {
  8324. value: [],
  8325. properties: {
  8326. direction: {},
  8327. skyColor: {},
  8328. groundColor: {}
  8329. }
  8330. },
  8331. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8332. rectAreaLights: {
  8333. value: [],
  8334. properties: {
  8335. color: {},
  8336. position: {},
  8337. width: {},
  8338. height: {}
  8339. }
  8340. },
  8341. ltc_1: {
  8342. value: null
  8343. },
  8344. ltc_2: {
  8345. value: null
  8346. }
  8347. },
  8348. points: {
  8349. diffuse: {
  8350. value: new Color(0xffffff)
  8351. },
  8352. opacity: {
  8353. value: 1.0
  8354. },
  8355. size: {
  8356. value: 1.0
  8357. },
  8358. scale: {
  8359. value: 1.0
  8360. },
  8361. map: {
  8362. value: null
  8363. },
  8364. alphaMap: {
  8365. value: null
  8366. },
  8367. alphaTest: {
  8368. value: 0
  8369. },
  8370. uvTransform: {
  8371. value: new Matrix3()
  8372. }
  8373. },
  8374. sprite: {
  8375. diffuse: {
  8376. value: new Color(0xffffff)
  8377. },
  8378. opacity: {
  8379. value: 1.0
  8380. },
  8381. center: {
  8382. value: new Vector2(0.5, 0.5)
  8383. },
  8384. rotation: {
  8385. value: 0.0
  8386. },
  8387. map: {
  8388. value: null
  8389. },
  8390. alphaMap: {
  8391. value: null
  8392. },
  8393. alphaTest: {
  8394. value: 0
  8395. },
  8396. uvTransform: {
  8397. value: new Matrix3()
  8398. }
  8399. }
  8400. };
  8401. const ShaderLib = {
  8402. basic: {
  8403. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  8404. vertexShader: ShaderChunk.meshbasic_vert,
  8405. fragmentShader: ShaderChunk.meshbasic_frag
  8406. },
  8407. lambert: {
  8408. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  8409. emissive: {
  8410. value: new Color(0x000000)
  8411. }
  8412. }]),
  8413. vertexShader: ShaderChunk.meshlambert_vert,
  8414. fragmentShader: ShaderChunk.meshlambert_frag
  8415. },
  8416. phong: {
  8417. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  8418. emissive: {
  8419. value: new Color(0x000000)
  8420. },
  8421. specular: {
  8422. value: new Color(0x111111)
  8423. },
  8424. shininess: {
  8425. value: 30
  8426. }
  8427. }]),
  8428. vertexShader: ShaderChunk.meshphong_vert,
  8429. fragmentShader: ShaderChunk.meshphong_frag
  8430. },
  8431. standard: {
  8432. 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, {
  8433. emissive: {
  8434. value: new Color(0x000000)
  8435. },
  8436. roughness: {
  8437. value: 1.0
  8438. },
  8439. metalness: {
  8440. value: 0.0
  8441. },
  8442. envMapIntensity: {
  8443. value: 1
  8444. } // temporary
  8445. }]),
  8446. vertexShader: ShaderChunk.meshphysical_vert,
  8447. fragmentShader: ShaderChunk.meshphysical_frag
  8448. },
  8449. toon: {
  8450. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  8451. emissive: {
  8452. value: new Color(0x000000)
  8453. }
  8454. }]),
  8455. vertexShader: ShaderChunk.meshtoon_vert,
  8456. fragmentShader: ShaderChunk.meshtoon_frag
  8457. },
  8458. matcap: {
  8459. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  8460. matcap: {
  8461. value: null
  8462. }
  8463. }]),
  8464. vertexShader: ShaderChunk.meshmatcap_vert,
  8465. fragmentShader: ShaderChunk.meshmatcap_frag
  8466. },
  8467. points: {
  8468. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  8469. vertexShader: ShaderChunk.points_vert,
  8470. fragmentShader: ShaderChunk.points_frag
  8471. },
  8472. dashed: {
  8473. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  8474. scale: {
  8475. value: 1
  8476. },
  8477. dashSize: {
  8478. value: 1
  8479. },
  8480. totalSize: {
  8481. value: 2
  8482. }
  8483. }]),
  8484. vertexShader: ShaderChunk.linedashed_vert,
  8485. fragmentShader: ShaderChunk.linedashed_frag
  8486. },
  8487. depth: {
  8488. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  8489. vertexShader: ShaderChunk.depth_vert,
  8490. fragmentShader: ShaderChunk.depth_frag
  8491. },
  8492. normal: {
  8493. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  8494. opacity: {
  8495. value: 1.0
  8496. }
  8497. }]),
  8498. vertexShader: ShaderChunk.meshnormal_vert,
  8499. fragmentShader: ShaderChunk.meshnormal_frag
  8500. },
  8501. sprite: {
  8502. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  8503. vertexShader: ShaderChunk.sprite_vert,
  8504. fragmentShader: ShaderChunk.sprite_frag
  8505. },
  8506. background: {
  8507. uniforms: {
  8508. uvTransform: {
  8509. value: new Matrix3()
  8510. },
  8511. t2D: {
  8512. value: null
  8513. }
  8514. },
  8515. vertexShader: ShaderChunk.background_vert,
  8516. fragmentShader: ShaderChunk.background_frag
  8517. },
  8518. /* -------------------------------------------------------------------------
  8519. // Cube map shader
  8520. ------------------------------------------------------------------------- */
  8521. cube: {
  8522. uniforms: mergeUniforms([UniformsLib.envmap, {
  8523. opacity: {
  8524. value: 1.0
  8525. }
  8526. }]),
  8527. vertexShader: ShaderChunk.cube_vert,
  8528. fragmentShader: ShaderChunk.cube_frag
  8529. },
  8530. equirect: {
  8531. uniforms: {
  8532. tEquirect: {
  8533. value: null
  8534. }
  8535. },
  8536. vertexShader: ShaderChunk.equirect_vert,
  8537. fragmentShader: ShaderChunk.equirect_frag
  8538. },
  8539. distanceRGBA: {
  8540. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  8541. referencePosition: {
  8542. value: new Vector3()
  8543. },
  8544. nearDistance: {
  8545. value: 1
  8546. },
  8547. farDistance: {
  8548. value: 1000
  8549. }
  8550. }]),
  8551. vertexShader: ShaderChunk.distanceRGBA_vert,
  8552. fragmentShader: ShaderChunk.distanceRGBA_frag
  8553. },
  8554. shadow: {
  8555. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  8556. color: {
  8557. value: new Color(0x00000)
  8558. },
  8559. opacity: {
  8560. value: 1.0
  8561. }
  8562. }]),
  8563. vertexShader: ShaderChunk.shadow_vert,
  8564. fragmentShader: ShaderChunk.shadow_frag
  8565. }
  8566. };
  8567. ShaderLib.physical = {
  8568. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  8569. clearcoat: {
  8570. value: 0
  8571. },
  8572. clearcoatMap: {
  8573. value: null
  8574. },
  8575. clearcoatRoughness: {
  8576. value: 0
  8577. },
  8578. clearcoatRoughnessMap: {
  8579. value: null
  8580. },
  8581. clearcoatNormalScale: {
  8582. value: new Vector2(1, 1)
  8583. },
  8584. clearcoatNormalMap: {
  8585. value: null
  8586. },
  8587. sheen: {
  8588. value: 0
  8589. },
  8590. sheenTint: {
  8591. value: new Color(0x000000)
  8592. },
  8593. sheenRoughness: {
  8594. value: 0
  8595. },
  8596. transmission: {
  8597. value: 0
  8598. },
  8599. transmissionMap: {
  8600. value: null
  8601. },
  8602. transmissionSamplerSize: {
  8603. value: new Vector2()
  8604. },
  8605. transmissionSamplerMap: {
  8606. value: null
  8607. },
  8608. thickness: {
  8609. value: 0
  8610. },
  8611. thicknessMap: {
  8612. value: null
  8613. },
  8614. attenuationDistance: {
  8615. value: 0
  8616. },
  8617. attenuationTint: {
  8618. value: new Color(0x000000)
  8619. },
  8620. specularIntensity: {
  8621. value: 0
  8622. },
  8623. specularIntensityMap: {
  8624. value: null
  8625. },
  8626. specularTint: {
  8627. value: new Color(1, 1, 1)
  8628. },
  8629. specularTintMap: {
  8630. value: null
  8631. }
  8632. }]),
  8633. vertexShader: ShaderChunk.meshphysical_vert,
  8634. fragmentShader: ShaderChunk.meshphysical_frag
  8635. };
  8636. function WebGLBackground(renderer, cubemaps, state, objects, premultipliedAlpha) {
  8637. const clearColor = new Color(0x000000);
  8638. let clearAlpha = 0;
  8639. let planeMesh;
  8640. let boxMesh;
  8641. let currentBackground = null;
  8642. let currentBackgroundVersion = 0;
  8643. let currentTonemapping = null;
  8644. function render(renderList, scene) {
  8645. let forceClear = false;
  8646. let background = scene.isScene === true ? scene.background : null;
  8647. if (background && background.isTexture) {
  8648. background = cubemaps.get(background);
  8649. } // Ignore background in AR
  8650. // TODO: Reconsider this.
  8651. const xr = renderer.xr;
  8652. const session = xr.getSession && xr.getSession();
  8653. if (session && session.environmentBlendMode === 'additive') {
  8654. background = null;
  8655. }
  8656. if (background === null) {
  8657. setClear(clearColor, clearAlpha);
  8658. } else if (background && background.isColor) {
  8659. setClear(background, 1);
  8660. forceClear = true;
  8661. }
  8662. if (renderer.autoClear || forceClear) {
  8663. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  8664. }
  8665. if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
  8666. if (boxMesh === undefined) {
  8667. boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
  8668. name: 'BackgroundCubeMaterial',
  8669. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  8670. vertexShader: ShaderLib.cube.vertexShader,
  8671. fragmentShader: ShaderLib.cube.fragmentShader,
  8672. side: BackSide,
  8673. depthTest: false,
  8674. depthWrite: false,
  8675. fog: false
  8676. }));
  8677. boxMesh.geometry.deleteAttribute('normal');
  8678. boxMesh.geometry.deleteAttribute('uv');
  8679. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  8680. this.matrixWorld.copyPosition(camera.matrixWorld);
  8681. }; // enable code injection for non-built-in material
  8682. Object.defineProperty(boxMesh.material, 'envMap', {
  8683. get: function () {
  8684. return this.uniforms.envMap.value;
  8685. }
  8686. });
  8687. objects.update(boxMesh);
  8688. }
  8689. boxMesh.material.uniforms.envMap.value = background;
  8690. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1;
  8691. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8692. boxMesh.material.needsUpdate = true;
  8693. currentBackground = background;
  8694. currentBackgroundVersion = background.version;
  8695. currentTonemapping = renderer.toneMapping;
  8696. } // push to the pre-sorted opaque render list
  8697. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  8698. } else if (background && background.isTexture) {
  8699. if (planeMesh === undefined) {
  8700. planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
  8701. name: 'BackgroundMaterial',
  8702. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  8703. vertexShader: ShaderLib.background.vertexShader,
  8704. fragmentShader: ShaderLib.background.fragmentShader,
  8705. side: FrontSide,
  8706. depthTest: false,
  8707. depthWrite: false,
  8708. fog: false
  8709. }));
  8710. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  8711. Object.defineProperty(planeMesh.material, 'map', {
  8712. get: function () {
  8713. return this.uniforms.t2D.value;
  8714. }
  8715. });
  8716. objects.update(planeMesh);
  8717. }
  8718. planeMesh.material.uniforms.t2D.value = background;
  8719. if (background.matrixAutoUpdate === true) {
  8720. background.updateMatrix();
  8721. }
  8722. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  8723. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8724. planeMesh.material.needsUpdate = true;
  8725. currentBackground = background;
  8726. currentBackgroundVersion = background.version;
  8727. currentTonemapping = renderer.toneMapping;
  8728. } // push to the pre-sorted opaque render list
  8729. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  8730. }
  8731. }
  8732. function setClear(color, alpha) {
  8733. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  8734. }
  8735. return {
  8736. getClearColor: function () {
  8737. return clearColor;
  8738. },
  8739. setClearColor: function (color, alpha = 1) {
  8740. clearColor.set(color);
  8741. clearAlpha = alpha;
  8742. setClear(clearColor, clearAlpha);
  8743. },
  8744. getClearAlpha: function () {
  8745. return clearAlpha;
  8746. },
  8747. setClearAlpha: function (alpha) {
  8748. clearAlpha = alpha;
  8749. setClear(clearColor, clearAlpha);
  8750. },
  8751. render: render
  8752. };
  8753. }
  8754. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  8755. const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  8756. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  8757. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8758. const bindingStates = {};
  8759. const defaultState = createBindingState(null);
  8760. let currentState = defaultState;
  8761. function setup(object, material, program, geometry, index) {
  8762. let updateBuffers = false;
  8763. if (vaoAvailable) {
  8764. const state = getBindingState(geometry, program, material);
  8765. if (currentState !== state) {
  8766. currentState = state;
  8767. bindVertexArrayObject(currentState.object);
  8768. }
  8769. updateBuffers = needsUpdate(geometry, index);
  8770. if (updateBuffers) saveCache(geometry, index);
  8771. } else {
  8772. const wireframe = material.wireframe === true;
  8773. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  8774. currentState.geometry = geometry.id;
  8775. currentState.program = program.id;
  8776. currentState.wireframe = wireframe;
  8777. updateBuffers = true;
  8778. }
  8779. }
  8780. if (object.isInstancedMesh === true) {
  8781. updateBuffers = true;
  8782. }
  8783. if (index !== null) {
  8784. attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
  8785. }
  8786. if (updateBuffers) {
  8787. setupVertexAttributes(object, material, program, geometry);
  8788. if (index !== null) {
  8789. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
  8790. }
  8791. }
  8792. }
  8793. function createVertexArrayObject() {
  8794. if (capabilities.isWebGL2) return gl.createVertexArray();
  8795. return extension.createVertexArrayOES();
  8796. }
  8797. function bindVertexArrayObject(vao) {
  8798. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  8799. return extension.bindVertexArrayOES(vao);
  8800. }
  8801. function deleteVertexArrayObject(vao) {
  8802. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  8803. return extension.deleteVertexArrayOES(vao);
  8804. }
  8805. function getBindingState(geometry, program, material) {
  8806. const wireframe = material.wireframe === true;
  8807. let programMap = bindingStates[geometry.id];
  8808. if (programMap === undefined) {
  8809. programMap = {};
  8810. bindingStates[geometry.id] = programMap;
  8811. }
  8812. let stateMap = programMap[program.id];
  8813. if (stateMap === undefined) {
  8814. stateMap = {};
  8815. programMap[program.id] = stateMap;
  8816. }
  8817. let state = stateMap[wireframe];
  8818. if (state === undefined) {
  8819. state = createBindingState(createVertexArrayObject());
  8820. stateMap[wireframe] = state;
  8821. }
  8822. return state;
  8823. }
  8824. function createBindingState(vao) {
  8825. const newAttributes = [];
  8826. const enabledAttributes = [];
  8827. const attributeDivisors = [];
  8828. for (let i = 0; i < maxVertexAttributes; i++) {
  8829. newAttributes[i] = 0;
  8830. enabledAttributes[i] = 0;
  8831. attributeDivisors[i] = 0;
  8832. }
  8833. return {
  8834. // for backward compatibility on non-VAO support browser
  8835. geometry: null,
  8836. program: null,
  8837. wireframe: false,
  8838. newAttributes: newAttributes,
  8839. enabledAttributes: enabledAttributes,
  8840. attributeDivisors: attributeDivisors,
  8841. object: vao,
  8842. attributes: {},
  8843. index: null
  8844. };
  8845. }
  8846. function needsUpdate(geometry, index) {
  8847. const cachedAttributes = currentState.attributes;
  8848. const geometryAttributes = geometry.attributes;
  8849. let attributesNum = 0;
  8850. for (const key in geometryAttributes) {
  8851. const cachedAttribute = cachedAttributes[key];
  8852. const geometryAttribute = geometryAttributes[key];
  8853. if (cachedAttribute === undefined) return true;
  8854. if (cachedAttribute.attribute !== geometryAttribute) return true;
  8855. if (cachedAttribute.data !== geometryAttribute.data) return true;
  8856. attributesNum++;
  8857. }
  8858. if (currentState.attributesNum !== attributesNum) return true;
  8859. if (currentState.index !== index) return true;
  8860. return false;
  8861. }
  8862. function saveCache(geometry, index) {
  8863. const cache = {};
  8864. const attributes = geometry.attributes;
  8865. let attributesNum = 0;
  8866. for (const key in attributes) {
  8867. const attribute = attributes[key];
  8868. const data = {};
  8869. data.attribute = attribute;
  8870. if (attribute.data) {
  8871. data.data = attribute.data;
  8872. }
  8873. cache[key] = data;
  8874. attributesNum++;
  8875. }
  8876. currentState.attributes = cache;
  8877. currentState.attributesNum = attributesNum;
  8878. currentState.index = index;
  8879. }
  8880. function initAttributes() {
  8881. const newAttributes = currentState.newAttributes;
  8882. for (let i = 0, il = newAttributes.length; i < il; i++) {
  8883. newAttributes[i] = 0;
  8884. }
  8885. }
  8886. function enableAttribute(attribute) {
  8887. enableAttributeAndDivisor(attribute, 0);
  8888. }
  8889. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  8890. const newAttributes = currentState.newAttributes;
  8891. const enabledAttributes = currentState.enabledAttributes;
  8892. const attributeDivisors = currentState.attributeDivisors;
  8893. newAttributes[attribute] = 1;
  8894. if (enabledAttributes[attribute] === 0) {
  8895. gl.enableVertexAttribArray(attribute);
  8896. enabledAttributes[attribute] = 1;
  8897. }
  8898. if (attributeDivisors[attribute] !== meshPerAttribute) {
  8899. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  8900. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  8901. attributeDivisors[attribute] = meshPerAttribute;
  8902. }
  8903. }
  8904. function disableUnusedAttributes() {
  8905. const newAttributes = currentState.newAttributes;
  8906. const enabledAttributes = currentState.enabledAttributes;
  8907. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  8908. if (enabledAttributes[i] !== newAttributes[i]) {
  8909. gl.disableVertexAttribArray(i);
  8910. enabledAttributes[i] = 0;
  8911. }
  8912. }
  8913. }
  8914. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  8915. if (capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT)) {
  8916. gl.vertexAttribIPointer(index, size, type, stride, offset);
  8917. } else {
  8918. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  8919. }
  8920. }
  8921. function setupVertexAttributes(object, material, program, geometry) {
  8922. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  8923. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  8924. }
  8925. initAttributes();
  8926. const geometryAttributes = geometry.attributes;
  8927. const programAttributes = program.getAttributes();
  8928. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8929. for (const name in programAttributes) {
  8930. const programAttribute = programAttributes[name];
  8931. if (programAttribute.location >= 0) {
  8932. let geometryAttribute = geometryAttributes[name];
  8933. if (geometryAttribute === undefined) {
  8934. if (name === 'instanceMatrix' && object.instanceMatrix) geometryAttribute = object.instanceMatrix;
  8935. if (name === 'instanceColor' && object.instanceColor) geometryAttribute = object.instanceColor;
  8936. }
  8937. if (geometryAttribute !== undefined) {
  8938. const normalized = geometryAttribute.normalized;
  8939. const size = geometryAttribute.itemSize;
  8940. const attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  8941. if (attribute === undefined) continue;
  8942. const buffer = attribute.buffer;
  8943. const type = attribute.type;
  8944. const bytesPerElement = attribute.bytesPerElement;
  8945. if (geometryAttribute.isInterleavedBufferAttribute) {
  8946. const data = geometryAttribute.data;
  8947. const stride = data.stride;
  8948. const offset = geometryAttribute.offset;
  8949. if (data && data.isInstancedInterleavedBuffer) {
  8950. for (let i = 0; i < programAttribute.locationSize; i++) {
  8951. enableAttributeAndDivisor(programAttribute.location + i, data.meshPerAttribute);
  8952. }
  8953. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  8954. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8955. }
  8956. } else {
  8957. for (let i = 0; i < programAttribute.locationSize; i++) {
  8958. enableAttribute(programAttribute.location + i);
  8959. }
  8960. }
  8961. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8962. for (let i = 0; i < programAttribute.locationSize; i++) {
  8963. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, stride * bytesPerElement, (offset + size / programAttribute.locationSize * i) * bytesPerElement);
  8964. }
  8965. } else {
  8966. if (geometryAttribute.isInstancedBufferAttribute) {
  8967. for (let i = 0; i < programAttribute.locationSize; i++) {
  8968. enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute);
  8969. }
  8970. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  8971. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8972. }
  8973. } else {
  8974. for (let i = 0; i < programAttribute.locationSize; i++) {
  8975. enableAttribute(programAttribute.location + i);
  8976. }
  8977. }
  8978. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8979. for (let i = 0; i < programAttribute.locationSize; i++) {
  8980. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, size * bytesPerElement, size / programAttribute.locationSize * i * bytesPerElement);
  8981. }
  8982. }
  8983. } else if (materialDefaultAttributeValues !== undefined) {
  8984. const value = materialDefaultAttributeValues[name];
  8985. if (value !== undefined) {
  8986. switch (value.length) {
  8987. case 2:
  8988. gl.vertexAttrib2fv(programAttribute.location, value);
  8989. break;
  8990. case 3:
  8991. gl.vertexAttrib3fv(programAttribute.location, value);
  8992. break;
  8993. case 4:
  8994. gl.vertexAttrib4fv(programAttribute.location, value);
  8995. break;
  8996. default:
  8997. gl.vertexAttrib1fv(programAttribute.location, value);
  8998. }
  8999. }
  9000. }
  9001. }
  9002. }
  9003. disableUnusedAttributes();
  9004. }
  9005. function dispose() {
  9006. reset();
  9007. for (const geometryId in bindingStates) {
  9008. const programMap = bindingStates[geometryId];
  9009. for (const programId in programMap) {
  9010. const stateMap = programMap[programId];
  9011. for (const wireframe in stateMap) {
  9012. deleteVertexArrayObject(stateMap[wireframe].object);
  9013. delete stateMap[wireframe];
  9014. }
  9015. delete programMap[programId];
  9016. }
  9017. delete bindingStates[geometryId];
  9018. }
  9019. }
  9020. function releaseStatesOfGeometry(geometry) {
  9021. if (bindingStates[geometry.id] === undefined) return;
  9022. const programMap = bindingStates[geometry.id];
  9023. for (const programId in programMap) {
  9024. const stateMap = programMap[programId];
  9025. for (const wireframe in stateMap) {
  9026. deleteVertexArrayObject(stateMap[wireframe].object);
  9027. delete stateMap[wireframe];
  9028. }
  9029. delete programMap[programId];
  9030. }
  9031. delete bindingStates[geometry.id];
  9032. }
  9033. function releaseStatesOfProgram(program) {
  9034. for (const geometryId in bindingStates) {
  9035. const programMap = bindingStates[geometryId];
  9036. if (programMap[program.id] === undefined) continue;
  9037. const stateMap = programMap[program.id];
  9038. for (const wireframe in stateMap) {
  9039. deleteVertexArrayObject(stateMap[wireframe].object);
  9040. delete stateMap[wireframe];
  9041. }
  9042. delete programMap[program.id];
  9043. }
  9044. }
  9045. function reset() {
  9046. resetDefaultState();
  9047. if (currentState === defaultState) return;
  9048. currentState = defaultState;
  9049. bindVertexArrayObject(currentState.object);
  9050. } // for backward-compatilibity
  9051. function resetDefaultState() {
  9052. defaultState.geometry = null;
  9053. defaultState.program = null;
  9054. defaultState.wireframe = false;
  9055. }
  9056. return {
  9057. setup: setup,
  9058. reset: reset,
  9059. resetDefaultState: resetDefaultState,
  9060. dispose: dispose,
  9061. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9062. releaseStatesOfProgram: releaseStatesOfProgram,
  9063. initAttributes: initAttributes,
  9064. enableAttribute: enableAttribute,
  9065. disableUnusedAttributes: disableUnusedAttributes
  9066. };
  9067. }
  9068. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  9069. const isWebGL2 = capabilities.isWebGL2;
  9070. let mode;
  9071. function setMode(value) {
  9072. mode = value;
  9073. }
  9074. function render(start, count) {
  9075. gl.drawArrays(mode, start, count);
  9076. info.update(count, mode, 1);
  9077. }
  9078. function renderInstances(start, count, primcount) {
  9079. if (primcount === 0) return;
  9080. let extension, methodName;
  9081. if (isWebGL2) {
  9082. extension = gl;
  9083. methodName = 'drawArraysInstanced';
  9084. } else {
  9085. extension = extensions.get('ANGLE_instanced_arrays');
  9086. methodName = 'drawArraysInstancedANGLE';
  9087. if (extension === null) {
  9088. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9089. return;
  9090. }
  9091. }
  9092. extension[methodName](mode, start, count, primcount);
  9093. info.update(count, mode, primcount);
  9094. } //
  9095. this.setMode = setMode;
  9096. this.render = render;
  9097. this.renderInstances = renderInstances;
  9098. }
  9099. function WebGLCapabilities(gl, extensions, parameters) {
  9100. let maxAnisotropy;
  9101. function getMaxAnisotropy() {
  9102. if (maxAnisotropy !== undefined) return maxAnisotropy;
  9103. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  9104. const extension = extensions.get('EXT_texture_filter_anisotropic');
  9105. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  9106. } else {
  9107. maxAnisotropy = 0;
  9108. }
  9109. return maxAnisotropy;
  9110. }
  9111. function getMaxPrecision(precision) {
  9112. if (precision === 'highp') {
  9113. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
  9114. return 'highp';
  9115. }
  9116. precision = 'mediump';
  9117. }
  9118. if (precision === 'mediump') {
  9119. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
  9120. return 'mediump';
  9121. }
  9122. }
  9123. return 'lowp';
  9124. }
  9125. /* eslint-disable no-undef */
  9126. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  9127. /* eslint-enable no-undef */
  9128. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9129. const maxPrecision = getMaxPrecision(precision);
  9130. if (maxPrecision !== precision) {
  9131. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  9132. precision = maxPrecision;
  9133. }
  9134. const drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers');
  9135. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9136. const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  9137. const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9138. const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  9139. const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9140. const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  9141. const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
  9142. const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
  9143. const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9144. const vertexTextures = maxVertexTextures > 0;
  9145. const floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float');
  9146. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9147. const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
  9148. return {
  9149. isWebGL2: isWebGL2,
  9150. drawBuffers: drawBuffers,
  9151. getMaxAnisotropy: getMaxAnisotropy,
  9152. getMaxPrecision: getMaxPrecision,
  9153. precision: precision,
  9154. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9155. maxTextures: maxTextures,
  9156. maxVertexTextures: maxVertexTextures,
  9157. maxTextureSize: maxTextureSize,
  9158. maxCubemapSize: maxCubemapSize,
  9159. maxAttributes: maxAttributes,
  9160. maxVertexUniforms: maxVertexUniforms,
  9161. maxVaryings: maxVaryings,
  9162. maxFragmentUniforms: maxFragmentUniforms,
  9163. vertexTextures: vertexTextures,
  9164. floatFragmentTextures: floatFragmentTextures,
  9165. floatVertexTextures: floatVertexTextures,
  9166. maxSamples: maxSamples
  9167. };
  9168. }
  9169. function WebGLClipping(properties) {
  9170. const scope = this;
  9171. let globalState = null,
  9172. numGlobalPlanes = 0,
  9173. localClippingEnabled = false,
  9174. renderingShadows = false;
  9175. const plane = new Plane(),
  9176. viewNormalMatrix = new Matrix3(),
  9177. uniform = {
  9178. value: null,
  9179. needsUpdate: false
  9180. };
  9181. this.uniform = uniform;
  9182. this.numPlanes = 0;
  9183. this.numIntersection = 0;
  9184. this.init = function (planes, enableLocalClipping, camera) {
  9185. const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  9186. // run another frame in order to reset the state:
  9187. numGlobalPlanes !== 0 || localClippingEnabled;
  9188. localClippingEnabled = enableLocalClipping;
  9189. globalState = projectPlanes(planes, camera, 0);
  9190. numGlobalPlanes = planes.length;
  9191. return enabled;
  9192. };
  9193. this.beginShadows = function () {
  9194. renderingShadows = true;
  9195. projectPlanes(null);
  9196. };
  9197. this.endShadows = function () {
  9198. renderingShadows = false;
  9199. resetGlobalState();
  9200. };
  9201. this.setState = function (material, camera, useCache) {
  9202. const planes = material.clippingPlanes,
  9203. clipIntersection = material.clipIntersection,
  9204. clipShadows = material.clipShadows;
  9205. const materialProperties = properties.get(material);
  9206. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  9207. // there's no local clipping
  9208. if (renderingShadows) {
  9209. // there's no global clipping
  9210. projectPlanes(null);
  9211. } else {
  9212. resetGlobalState();
  9213. }
  9214. } else {
  9215. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9216. lGlobal = nGlobal * 4;
  9217. let dstArray = materialProperties.clippingState || null;
  9218. uniform.value = dstArray; // ensure unique state
  9219. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  9220. for (let i = 0; i !== lGlobal; ++i) {
  9221. dstArray[i] = globalState[i];
  9222. }
  9223. materialProperties.clippingState = dstArray;
  9224. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9225. this.numPlanes += nGlobal;
  9226. }
  9227. };
  9228. function resetGlobalState() {
  9229. if (uniform.value !== globalState) {
  9230. uniform.value = globalState;
  9231. uniform.needsUpdate = numGlobalPlanes > 0;
  9232. }
  9233. scope.numPlanes = numGlobalPlanes;
  9234. scope.numIntersection = 0;
  9235. }
  9236. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  9237. const nPlanes = planes !== null ? planes.length : 0;
  9238. let dstArray = null;
  9239. if (nPlanes !== 0) {
  9240. dstArray = uniform.value;
  9241. if (skipTransform !== true || dstArray === null) {
  9242. const flatSize = dstOffset + nPlanes * 4,
  9243. viewMatrix = camera.matrixWorldInverse;
  9244. viewNormalMatrix.getNormalMatrix(viewMatrix);
  9245. if (dstArray === null || dstArray.length < flatSize) {
  9246. dstArray = new Float32Array(flatSize);
  9247. }
  9248. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  9249. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  9250. plane.normal.toArray(dstArray, i4);
  9251. dstArray[i4 + 3] = plane.constant;
  9252. }
  9253. }
  9254. uniform.value = dstArray;
  9255. uniform.needsUpdate = true;
  9256. }
  9257. scope.numPlanes = nPlanes;
  9258. scope.numIntersection = 0;
  9259. return dstArray;
  9260. }
  9261. }
  9262. function WebGLCubeMaps(renderer) {
  9263. let cubemaps = new WeakMap();
  9264. function mapTextureMapping(texture, mapping) {
  9265. if (mapping === EquirectangularReflectionMapping) {
  9266. texture.mapping = CubeReflectionMapping;
  9267. } else if (mapping === EquirectangularRefractionMapping) {
  9268. texture.mapping = CubeRefractionMapping;
  9269. }
  9270. return texture;
  9271. }
  9272. function get(texture) {
  9273. if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
  9274. const mapping = texture.mapping;
  9275. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  9276. if (cubemaps.has(texture)) {
  9277. const cubemap = cubemaps.get(texture).texture;
  9278. return mapTextureMapping(cubemap, texture.mapping);
  9279. } else {
  9280. const image = texture.image;
  9281. if (image && image.height > 0) {
  9282. const currentRenderTarget = renderer.getRenderTarget();
  9283. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  9284. renderTarget.fromEquirectangularTexture(renderer, texture);
  9285. cubemaps.set(texture, renderTarget);
  9286. renderer.setRenderTarget(currentRenderTarget);
  9287. texture.addEventListener('dispose', onTextureDispose);
  9288. return mapTextureMapping(renderTarget.texture, texture.mapping);
  9289. } else {
  9290. // image not yet ready. try the conversion next frame
  9291. return null;
  9292. }
  9293. }
  9294. }
  9295. }
  9296. return texture;
  9297. }
  9298. function onTextureDispose(event) {
  9299. const texture = event.target;
  9300. texture.removeEventListener('dispose', onTextureDispose);
  9301. const cubemap = cubemaps.get(texture);
  9302. if (cubemap !== undefined) {
  9303. cubemaps.delete(texture);
  9304. cubemap.dispose();
  9305. }
  9306. }
  9307. function dispose() {
  9308. cubemaps = new WeakMap();
  9309. }
  9310. return {
  9311. get: get,
  9312. dispose: dispose
  9313. };
  9314. }
  9315. class OrthographicCamera extends Camera {
  9316. constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) {
  9317. super();
  9318. this.type = 'OrthographicCamera';
  9319. this.zoom = 1;
  9320. this.view = null;
  9321. this.left = left;
  9322. this.right = right;
  9323. this.top = top;
  9324. this.bottom = bottom;
  9325. this.near = near;
  9326. this.far = far;
  9327. this.updateProjectionMatrix();
  9328. }
  9329. copy(source, recursive) {
  9330. super.copy(source, recursive);
  9331. this.left = source.left;
  9332. this.right = source.right;
  9333. this.top = source.top;
  9334. this.bottom = source.bottom;
  9335. this.near = source.near;
  9336. this.far = source.far;
  9337. this.zoom = source.zoom;
  9338. this.view = source.view === null ? null : Object.assign({}, source.view);
  9339. return this;
  9340. }
  9341. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  9342. if (this.view === null) {
  9343. this.view = {
  9344. enabled: true,
  9345. fullWidth: 1,
  9346. fullHeight: 1,
  9347. offsetX: 0,
  9348. offsetY: 0,
  9349. width: 1,
  9350. height: 1
  9351. };
  9352. }
  9353. this.view.enabled = true;
  9354. this.view.fullWidth = fullWidth;
  9355. this.view.fullHeight = fullHeight;
  9356. this.view.offsetX = x;
  9357. this.view.offsetY = y;
  9358. this.view.width = width;
  9359. this.view.height = height;
  9360. this.updateProjectionMatrix();
  9361. }
  9362. clearViewOffset() {
  9363. if (this.view !== null) {
  9364. this.view.enabled = false;
  9365. }
  9366. this.updateProjectionMatrix();
  9367. }
  9368. updateProjectionMatrix() {
  9369. const dx = (this.right - this.left) / (2 * this.zoom);
  9370. const dy = (this.top - this.bottom) / (2 * this.zoom);
  9371. const cx = (this.right + this.left) / 2;
  9372. const cy = (this.top + this.bottom) / 2;
  9373. let left = cx - dx;
  9374. let right = cx + dx;
  9375. let top = cy + dy;
  9376. let bottom = cy - dy;
  9377. if (this.view !== null && this.view.enabled) {
  9378. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  9379. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  9380. left += scaleW * this.view.offsetX;
  9381. right = left + scaleW * this.view.width;
  9382. top -= scaleH * this.view.offsetY;
  9383. bottom = top - scaleH * this.view.height;
  9384. }
  9385. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  9386. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  9387. }
  9388. toJSON(meta) {
  9389. const data = super.toJSON(meta);
  9390. data.object.zoom = this.zoom;
  9391. data.object.left = this.left;
  9392. data.object.right = this.right;
  9393. data.object.top = this.top;
  9394. data.object.bottom = this.bottom;
  9395. data.object.near = this.near;
  9396. data.object.far = this.far;
  9397. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  9398. return data;
  9399. }
  9400. }
  9401. OrthographicCamera.prototype.isOrthographicCamera = true;
  9402. class RawShaderMaterial extends ShaderMaterial {
  9403. constructor(parameters) {
  9404. super(parameters);
  9405. this.type = 'RawShaderMaterial';
  9406. }
  9407. }
  9408. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  9409. const LOD_MIN = 4;
  9410. const LOD_MAX = 8;
  9411. const SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
  9412. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9413. // geometric shadowing function. These sigma values squared must match the
  9414. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9415. const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  9416. 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
  9417. // samples and exit early, but not recompile the shader.
  9418. const MAX_SAMPLES = 20;
  9419. const ENCODINGS = {
  9420. [LinearEncoding]: 0,
  9421. [sRGBEncoding]: 1,
  9422. [RGBEEncoding]: 2,
  9423. [RGBM7Encoding]: 3,
  9424. [RGBM16Encoding]: 4,
  9425. [RGBDEncoding]: 5,
  9426. [GammaEncoding]: 6
  9427. };
  9428. const _flatCamera = /*@__PURE__*/new OrthographicCamera();
  9429. const {
  9430. _lodPlanes,
  9431. _sizeLods,
  9432. _sigmas
  9433. } = /*@__PURE__*/_createPlanes();
  9434. const _clearColor = /*@__PURE__*/new Color();
  9435. let _oldTarget = null; // Golden Ratio
  9436. const PHI = (1 + Math.sqrt(5)) / 2;
  9437. const INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  9438. // same axis), used as axis directions evenly spread on a sphere.
  9439. 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)];
  9440. /**
  9441. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9442. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9443. * blur to be quickly accessed based on material roughness. It is packed into a
  9444. * special CubeUV format that allows us to perform custom interpolation so that
  9445. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9446. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9447. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9448. * higher roughness levels. In this way we maintain resolution to smoothly
  9449. * interpolate diffuse lighting while limiting sampling computation.
  9450. *
  9451. * Paper: Fast, Accurate Image-Based Lighting
  9452. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9453. */
  9454. class PMREMGenerator {
  9455. constructor(renderer) {
  9456. this._renderer = renderer;
  9457. this._pingPongRenderTarget = null;
  9458. this._blurMaterial = _getBlurShader(MAX_SAMPLES);
  9459. this._equirectShader = null;
  9460. this._cubemapShader = null;
  9461. this._compileMaterial(this._blurMaterial);
  9462. }
  9463. /**
  9464. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9465. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9466. * in radians to be applied to the scene before PMREM generation. Optional near
  9467. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9468. * is placed at the origin).
  9469. */
  9470. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  9471. _oldTarget = this._renderer.getRenderTarget();
  9472. const cubeUVRenderTarget = this._allocateTargets();
  9473. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  9474. if (sigma > 0) {
  9475. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  9476. }
  9477. this._applyPMREM(cubeUVRenderTarget);
  9478. this._cleanup(cubeUVRenderTarget);
  9479. return cubeUVRenderTarget;
  9480. }
  9481. /**
  9482. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9483. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  9484. * as this matches best with the 256 x 256 cubemap output.
  9485. */
  9486. fromEquirectangular(equirectangular) {
  9487. return this._fromTexture(equirectangular);
  9488. }
  9489. /**
  9490. * Generates a PMREM from an cubemap texture, which can be either LDR
  9491. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  9492. * as this matches best with the 256 x 256 cubemap output.
  9493. */
  9494. fromCubemap(cubemap) {
  9495. return this._fromTexture(cubemap);
  9496. }
  9497. /**
  9498. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9499. * your texture's network fetch for increased concurrency.
  9500. */
  9501. compileCubemapShader() {
  9502. if (this._cubemapShader === null) {
  9503. this._cubemapShader = _getCubemapShader();
  9504. this._compileMaterial(this._cubemapShader);
  9505. }
  9506. }
  9507. /**
  9508. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9509. * your texture's network fetch for increased concurrency.
  9510. */
  9511. compileEquirectangularShader() {
  9512. if (this._equirectShader === null) {
  9513. this._equirectShader = _getEquirectShader();
  9514. this._compileMaterial(this._equirectShader);
  9515. }
  9516. }
  9517. /**
  9518. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9519. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9520. * one of them will cause any others to also become unusable.
  9521. */
  9522. dispose() {
  9523. this._blurMaterial.dispose();
  9524. if (this._cubemapShader !== null) this._cubemapShader.dispose();
  9525. if (this._equirectShader !== null) this._equirectShader.dispose();
  9526. for (let i = 0; i < _lodPlanes.length; i++) {
  9527. _lodPlanes[i].dispose();
  9528. }
  9529. } // private interface
  9530. _cleanup(outputTarget) {
  9531. this._pingPongRenderTarget.dispose();
  9532. this._renderer.setRenderTarget(_oldTarget);
  9533. outputTarget.scissorTest = false;
  9534. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  9535. }
  9536. _fromTexture(texture) {
  9537. _oldTarget = this._renderer.getRenderTarget();
  9538. const cubeUVRenderTarget = this._allocateTargets(texture);
  9539. this._textureToCubeUV(texture, cubeUVRenderTarget);
  9540. this._applyPMREM(cubeUVRenderTarget);
  9541. this._cleanup(cubeUVRenderTarget);
  9542. return cubeUVRenderTarget;
  9543. }
  9544. _allocateTargets(texture) {
  9545. // warning: null texture is valid
  9546. const params = {
  9547. magFilter: NearestFilter,
  9548. minFilter: NearestFilter,
  9549. generateMipmaps: false,
  9550. type: UnsignedByteType,
  9551. format: RGBEFormat,
  9552. encoding: _isLDR(texture) ? texture.encoding : RGBEEncoding,
  9553. depthBuffer: false
  9554. };
  9555. const cubeUVRenderTarget = _createRenderTarget(params);
  9556. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  9557. this._pingPongRenderTarget = _createRenderTarget(params);
  9558. return cubeUVRenderTarget;
  9559. }
  9560. _compileMaterial(material) {
  9561. const tmpMesh = new Mesh(_lodPlanes[0], material);
  9562. this._renderer.compile(tmpMesh, _flatCamera);
  9563. }
  9564. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  9565. const fov = 90;
  9566. const aspect = 1;
  9567. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  9568. const upSign = [1, -1, 1, 1, 1, 1];
  9569. const forwardSign = [1, 1, 1, -1, -1, -1];
  9570. const renderer = this._renderer;
  9571. const originalAutoClear = renderer.autoClear;
  9572. const outputEncoding = renderer.outputEncoding;
  9573. const toneMapping = renderer.toneMapping;
  9574. renderer.getClearColor(_clearColor);
  9575. renderer.toneMapping = NoToneMapping;
  9576. renderer.outputEncoding = LinearEncoding;
  9577. renderer.autoClear = false;
  9578. const backgroundMaterial = new MeshBasicMaterial({
  9579. name: 'PMREM.Background',
  9580. side: BackSide,
  9581. depthWrite: false,
  9582. depthTest: false
  9583. });
  9584. const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
  9585. let useSolidColor = false;
  9586. const background = scene.background;
  9587. if (background) {
  9588. if (background.isColor) {
  9589. backgroundMaterial.color.copy(background);
  9590. scene.background = null;
  9591. useSolidColor = true;
  9592. }
  9593. } else {
  9594. backgroundMaterial.color.copy(_clearColor);
  9595. useSolidColor = true;
  9596. }
  9597. for (let i = 0; i < 6; i++) {
  9598. const col = i % 3;
  9599. if (col == 0) {
  9600. cubeCamera.up.set(0, upSign[i], 0);
  9601. cubeCamera.lookAt(forwardSign[i], 0, 0);
  9602. } else if (col == 1) {
  9603. cubeCamera.up.set(0, 0, upSign[i]);
  9604. cubeCamera.lookAt(0, forwardSign[i], 0);
  9605. } else {
  9606. cubeCamera.up.set(0, upSign[i], 0);
  9607. cubeCamera.lookAt(0, 0, forwardSign[i]);
  9608. }
  9609. _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
  9610. renderer.setRenderTarget(cubeUVRenderTarget);
  9611. if (useSolidColor) {
  9612. renderer.render(backgroundBox, cubeCamera);
  9613. }
  9614. renderer.render(scene, cubeCamera);
  9615. }
  9616. backgroundBox.geometry.dispose();
  9617. backgroundBox.material.dispose();
  9618. renderer.toneMapping = toneMapping;
  9619. renderer.outputEncoding = outputEncoding;
  9620. renderer.autoClear = originalAutoClear;
  9621. scene.background = background;
  9622. }
  9623. _setEncoding(uniform, texture) {
  9624. if (this._renderer.capabilities.isWebGL2 === true && texture.format === RGBAFormat && texture.type === UnsignedByteType && texture.encoding === sRGBEncoding) {
  9625. uniform.value = ENCODINGS[LinearEncoding];
  9626. } else {
  9627. uniform.value = ENCODINGS[texture.encoding];
  9628. }
  9629. }
  9630. _textureToCubeUV(texture, cubeUVRenderTarget) {
  9631. const renderer = this._renderer;
  9632. if (texture.isCubeTexture) {
  9633. if (this._cubemapShader == null) {
  9634. this._cubemapShader = _getCubemapShader();
  9635. }
  9636. } else {
  9637. if (this._equirectShader == null) {
  9638. this._equirectShader = _getEquirectShader();
  9639. }
  9640. }
  9641. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  9642. const mesh = new Mesh(_lodPlanes[0], material);
  9643. const uniforms = material.uniforms;
  9644. uniforms['envMap'].value = texture;
  9645. if (!texture.isCubeTexture) {
  9646. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  9647. }
  9648. this._setEncoding(uniforms['inputEncoding'], texture);
  9649. this._setEncoding(uniforms['outputEncoding'], cubeUVRenderTarget.texture);
  9650. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  9651. renderer.setRenderTarget(cubeUVRenderTarget);
  9652. renderer.render(mesh, _flatCamera);
  9653. }
  9654. _applyPMREM(cubeUVRenderTarget) {
  9655. const renderer = this._renderer;
  9656. const autoClear = renderer.autoClear;
  9657. renderer.autoClear = false;
  9658. for (let i = 1; i < TOTAL_LODS; i++) {
  9659. const sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  9660. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  9661. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  9662. }
  9663. renderer.autoClear = autoClear;
  9664. }
  9665. /**
  9666. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9667. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9668. * the blur latitudinally (around the poles), and then longitudinally (towards
  9669. * the poles) to approximate the orthogonally-separable blur. It is least
  9670. * accurate at the poles, but still does a decent job.
  9671. */
  9672. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  9673. const pingPongRenderTarget = this._pingPongRenderTarget;
  9674. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  9675. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  9676. }
  9677. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  9678. const renderer = this._renderer;
  9679. const blurMaterial = this._blurMaterial;
  9680. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  9681. console.error('blur direction must be either latitudinal or longitudinal!');
  9682. } // Number of standard deviations at which to cut off the discrete approximation.
  9683. const STANDARD_DEVIATIONS = 3;
  9684. const blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
  9685. const blurUniforms = blurMaterial.uniforms;
  9686. const pixels = _sizeLods[lodIn] - 1;
  9687. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  9688. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9689. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  9690. if (samples > MAX_SAMPLES) {
  9691. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  9692. }
  9693. const weights = [];
  9694. let sum = 0;
  9695. for (let i = 0; i < MAX_SAMPLES; ++i) {
  9696. const x = i / sigmaPixels;
  9697. const weight = Math.exp(-x * x / 2);
  9698. weights.push(weight);
  9699. if (i == 0) {
  9700. sum += weight;
  9701. } else if (i < samples) {
  9702. sum += 2 * weight;
  9703. }
  9704. }
  9705. for (let i = 0; i < weights.length; i++) {
  9706. weights[i] = weights[i] / sum;
  9707. }
  9708. blurUniforms['envMap'].value = targetIn.texture;
  9709. blurUniforms['samples'].value = samples;
  9710. blurUniforms['weights'].value = weights;
  9711. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  9712. if (poleAxis) {
  9713. blurUniforms['poleAxis'].value = poleAxis;
  9714. }
  9715. blurUniforms['dTheta'].value = radiansPerPixel;
  9716. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  9717. this._setEncoding(blurUniforms['inputEncoding'], targetIn.texture);
  9718. this._setEncoding(blurUniforms['outputEncoding'], targetIn.texture);
  9719. const outputSize = _sizeLods[lodOut];
  9720. const x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  9721. const y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  9722. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  9723. renderer.setRenderTarget(targetOut);
  9724. renderer.render(blurMesh, _flatCamera);
  9725. }
  9726. }
  9727. function _isLDR(texture) {
  9728. if (texture === undefined || texture.type !== UnsignedByteType) return false;
  9729. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  9730. }
  9731. function _createPlanes() {
  9732. const _lodPlanes = [];
  9733. const _sizeLods = [];
  9734. const _sigmas = [];
  9735. let lod = LOD_MAX;
  9736. for (let i = 0; i < TOTAL_LODS; i++) {
  9737. const sizeLod = Math.pow(2, lod);
  9738. _sizeLods.push(sizeLod);
  9739. let sigma = 1.0 / sizeLod;
  9740. if (i > LOD_MAX - LOD_MIN) {
  9741. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  9742. } else if (i == 0) {
  9743. sigma = 0;
  9744. }
  9745. _sigmas.push(sigma);
  9746. const texelSize = 1.0 / (sizeLod - 1);
  9747. const min = -texelSize / 2;
  9748. const max = 1 + texelSize / 2;
  9749. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  9750. const cubeFaces = 6;
  9751. const vertices = 6;
  9752. const positionSize = 3;
  9753. const uvSize = 2;
  9754. const faceIndexSize = 1;
  9755. const position = new Float32Array(positionSize * vertices * cubeFaces);
  9756. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  9757. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  9758. for (let face = 0; face < cubeFaces; face++) {
  9759. const x = face % 3 * 2 / 3 - 1;
  9760. const y = face > 2 ? 0 : -1;
  9761. 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];
  9762. position.set(coordinates, positionSize * vertices * face);
  9763. uv.set(uv1, uvSize * vertices * face);
  9764. const fill = [face, face, face, face, face, face];
  9765. faceIndex.set(fill, faceIndexSize * vertices * face);
  9766. }
  9767. const planes = new BufferGeometry();
  9768. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  9769. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  9770. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  9771. _lodPlanes.push(planes);
  9772. if (lod > LOD_MIN) {
  9773. lod--;
  9774. }
  9775. }
  9776. return {
  9777. _lodPlanes,
  9778. _sizeLods,
  9779. _sigmas
  9780. };
  9781. }
  9782. function _createRenderTarget(params) {
  9783. const cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  9784. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9785. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9786. cubeUVRenderTarget.scissorTest = true;
  9787. return cubeUVRenderTarget;
  9788. }
  9789. function _setViewport(target, x, y, width, height) {
  9790. target.viewport.set(x, y, width, height);
  9791. target.scissor.set(x, y, width, height);
  9792. }
  9793. function _getBlurShader(maxSamples) {
  9794. const weights = new Float32Array(maxSamples);
  9795. const poleAxis = new Vector3(0, 1, 0);
  9796. const shaderMaterial = new RawShaderMaterial({
  9797. name: 'SphericalGaussianBlur',
  9798. defines: {
  9799. 'n': maxSamples
  9800. },
  9801. uniforms: {
  9802. 'envMap': {
  9803. value: null
  9804. },
  9805. 'samples': {
  9806. value: 1
  9807. },
  9808. 'weights': {
  9809. value: weights
  9810. },
  9811. 'latitudinal': {
  9812. value: false
  9813. },
  9814. 'dTheta': {
  9815. value: 0
  9816. },
  9817. 'mipInt': {
  9818. value: 0
  9819. },
  9820. 'poleAxis': {
  9821. value: poleAxis
  9822. },
  9823. 'inputEncoding': {
  9824. value: ENCODINGS[LinearEncoding]
  9825. },
  9826. 'outputEncoding': {
  9827. value: ENCODINGS[LinearEncoding]
  9828. }
  9829. },
  9830. vertexShader: _getCommonVertexShader(),
  9831. fragmentShader:
  9832. /* glsl */
  9833. `
  9834. precision mediump float;
  9835. precision mediump int;
  9836. varying vec3 vOutputDirection;
  9837. uniform sampler2D envMap;
  9838. uniform int samples;
  9839. uniform float weights[ n ];
  9840. uniform bool latitudinal;
  9841. uniform float dTheta;
  9842. uniform float mipInt;
  9843. uniform vec3 poleAxis;
  9844. ${_getEncodings()}
  9845. #define ENVMAP_TYPE_CUBE_UV
  9846. #include <cube_uv_reflection_fragment>
  9847. vec3 getSample( float theta, vec3 axis ) {
  9848. float cosTheta = cos( theta );
  9849. // Rodrigues' axis-angle rotation
  9850. vec3 sampleDirection = vOutputDirection * cosTheta
  9851. + cross( axis, vOutputDirection ) * sin( theta )
  9852. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9853. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9854. }
  9855. void main() {
  9856. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9857. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9858. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9859. }
  9860. axis = normalize( axis );
  9861. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9862. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9863. for ( int i = 1; i < n; i++ ) {
  9864. if ( i >= samples ) {
  9865. break;
  9866. }
  9867. float theta = dTheta * float( i );
  9868. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9869. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9870. }
  9871. gl_FragColor = linearToOutputTexel( gl_FragColor );
  9872. }
  9873. `,
  9874. blending: NoBlending,
  9875. depthTest: false,
  9876. depthWrite: false
  9877. });
  9878. return shaderMaterial;
  9879. }
  9880. function _getEquirectShader() {
  9881. const texelSize = new Vector2(1, 1);
  9882. const shaderMaterial = new RawShaderMaterial({
  9883. name: 'EquirectangularToCubeUV',
  9884. uniforms: {
  9885. 'envMap': {
  9886. value: null
  9887. },
  9888. 'texelSize': {
  9889. value: texelSize
  9890. },
  9891. 'inputEncoding': {
  9892. value: ENCODINGS[LinearEncoding]
  9893. },
  9894. 'outputEncoding': {
  9895. value: ENCODINGS[LinearEncoding]
  9896. }
  9897. },
  9898. vertexShader: _getCommonVertexShader(),
  9899. fragmentShader:
  9900. /* glsl */
  9901. `
  9902. precision mediump float;
  9903. precision mediump int;
  9904. varying vec3 vOutputDirection;
  9905. uniform sampler2D envMap;
  9906. uniform vec2 texelSize;
  9907. ${_getEncodings()}
  9908. #include <common>
  9909. void main() {
  9910. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9911. vec3 outputDirection = normalize( vOutputDirection );
  9912. vec2 uv = equirectUv( outputDirection );
  9913. vec2 f = fract( uv / texelSize - 0.5 );
  9914. uv -= f * texelSize;
  9915. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9916. uv.x += texelSize.x;
  9917. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9918. uv.y += texelSize.y;
  9919. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9920. uv.x -= texelSize.x;
  9921. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9922. vec3 tm = mix( tl, tr, f.x );
  9923. vec3 bm = mix( bl, br, f.x );
  9924. gl_FragColor.rgb = mix( tm, bm, f.y );
  9925. gl_FragColor = linearToOutputTexel( gl_FragColor );
  9926. }
  9927. `,
  9928. blending: NoBlending,
  9929. depthTest: false,
  9930. depthWrite: false
  9931. });
  9932. return shaderMaterial;
  9933. }
  9934. function _getCubemapShader() {
  9935. const shaderMaterial = new RawShaderMaterial({
  9936. name: 'CubemapToCubeUV',
  9937. uniforms: {
  9938. 'envMap': {
  9939. value: null
  9940. },
  9941. 'inputEncoding': {
  9942. value: ENCODINGS[LinearEncoding]
  9943. },
  9944. 'outputEncoding': {
  9945. value: ENCODINGS[LinearEncoding]
  9946. }
  9947. },
  9948. vertexShader: _getCommonVertexShader(),
  9949. fragmentShader:
  9950. /* glsl */
  9951. `
  9952. precision mediump float;
  9953. precision mediump int;
  9954. varying vec3 vOutputDirection;
  9955. uniform samplerCube envMap;
  9956. ${_getEncodings()}
  9957. void main() {
  9958. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9959. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  9960. gl_FragColor = linearToOutputTexel( gl_FragColor );
  9961. }
  9962. `,
  9963. blending: NoBlending,
  9964. depthTest: false,
  9965. depthWrite: false
  9966. });
  9967. return shaderMaterial;
  9968. }
  9969. function _getCommonVertexShader() {
  9970. return (
  9971. /* glsl */
  9972. `
  9973. precision mediump float;
  9974. precision mediump int;
  9975. attribute vec3 position;
  9976. attribute vec2 uv;
  9977. attribute float faceIndex;
  9978. varying vec3 vOutputDirection;
  9979. // RH coordinate system; PMREM face-indexing convention
  9980. vec3 getDirection( vec2 uv, float face ) {
  9981. uv = 2.0 * uv - 1.0;
  9982. vec3 direction = vec3( uv, 1.0 );
  9983. if ( face == 0.0 ) {
  9984. direction = direction.zyx; // ( 1, v, u ) pos x
  9985. } else if ( face == 1.0 ) {
  9986. direction = direction.xzy;
  9987. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  9988. } else if ( face == 2.0 ) {
  9989. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  9990. } else if ( face == 3.0 ) {
  9991. direction = direction.zyx;
  9992. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  9993. } else if ( face == 4.0 ) {
  9994. direction = direction.xzy;
  9995. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  9996. } else if ( face == 5.0 ) {
  9997. direction.z *= -1.0; // ( u, v, -1 ) neg z
  9998. }
  9999. return direction;
  10000. }
  10001. void main() {
  10002. vOutputDirection = getDirection( uv, faceIndex );
  10003. gl_Position = vec4( position, 1.0 );
  10004. }
  10005. `
  10006. );
  10007. }
  10008. function _getEncodings() {
  10009. return (
  10010. /* glsl */
  10011. `
  10012. uniform int inputEncoding;
  10013. uniform int outputEncoding;
  10014. #include <encodings_pars_fragment>
  10015. vec4 inputTexelToLinear( vec4 value ) {
  10016. if ( inputEncoding == 0 ) {
  10017. return value;
  10018. } else if ( inputEncoding == 1 ) {
  10019. return sRGBToLinear( value );
  10020. } else if ( inputEncoding == 2 ) {
  10021. return RGBEToLinear( value );
  10022. } else if ( inputEncoding == 3 ) {
  10023. return RGBMToLinear( value, 7.0 );
  10024. } else if ( inputEncoding == 4 ) {
  10025. return RGBMToLinear( value, 16.0 );
  10026. } else if ( inputEncoding == 5 ) {
  10027. return RGBDToLinear( value, 256.0 );
  10028. } else {
  10029. return GammaToLinear( value, 2.2 );
  10030. }
  10031. }
  10032. vec4 linearToOutputTexel( vec4 value ) {
  10033. if ( outputEncoding == 0 ) {
  10034. return value;
  10035. } else if ( outputEncoding == 1 ) {
  10036. return LinearTosRGB( value );
  10037. } else if ( outputEncoding == 2 ) {
  10038. return LinearToRGBE( value );
  10039. } else if ( outputEncoding == 3 ) {
  10040. return LinearToRGBM( value, 7.0 );
  10041. } else if ( outputEncoding == 4 ) {
  10042. return LinearToRGBM( value, 16.0 );
  10043. } else if ( outputEncoding == 5 ) {
  10044. return LinearToRGBD( value, 256.0 );
  10045. } else {
  10046. return LinearToGamma( value, 2.2 );
  10047. }
  10048. }
  10049. vec4 envMapTexelToLinear( vec4 color ) {
  10050. return inputTexelToLinear( color );
  10051. }
  10052. `
  10053. );
  10054. }
  10055. function WebGLCubeUVMaps(renderer) {
  10056. let cubeUVmaps = new WeakMap();
  10057. let pmremGenerator = null;
  10058. function get(texture) {
  10059. if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
  10060. const mapping = texture.mapping;
  10061. const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping;
  10062. const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping;
  10063. if (isEquirectMap || isCubeMap) {
  10064. // equirect/cube map to cubeUV conversion
  10065. if (cubeUVmaps.has(texture)) {
  10066. return cubeUVmaps.get(texture).texture;
  10067. } else {
  10068. const image = texture.image;
  10069. if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) {
  10070. const currentRenderTarget = renderer.getRenderTarget();
  10071. if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
  10072. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture);
  10073. cubeUVmaps.set(texture, renderTarget);
  10074. renderer.setRenderTarget(currentRenderTarget);
  10075. texture.addEventListener('dispose', onTextureDispose);
  10076. return renderTarget.texture;
  10077. } else {
  10078. // image not yet ready. try the conversion next frame
  10079. return null;
  10080. }
  10081. }
  10082. }
  10083. }
  10084. return texture;
  10085. }
  10086. function isCubeTextureComplete(image) {
  10087. let count = 0;
  10088. const length = 6;
  10089. for (let i = 0; i < length; i++) {
  10090. if (image[i] !== undefined) count++;
  10091. }
  10092. return count === length;
  10093. }
  10094. function onTextureDispose(event) {
  10095. const texture = event.target;
  10096. texture.removeEventListener('dispose', onTextureDispose);
  10097. const cubemapUV = cubeUVmaps.get(texture);
  10098. if (cubemapUV !== undefined) {
  10099. cubeUVmaps.delete(texture);
  10100. cubemapUV.dispose();
  10101. }
  10102. }
  10103. function dispose() {
  10104. cubeUVmaps = new WeakMap();
  10105. if (pmremGenerator !== null) {
  10106. pmremGenerator.dispose();
  10107. pmremGenerator = null;
  10108. }
  10109. }
  10110. return {
  10111. get: get,
  10112. dispose: dispose
  10113. };
  10114. }
  10115. function WebGLExtensions(gl) {
  10116. const extensions = {};
  10117. function getExtension(name) {
  10118. if (extensions[name] !== undefined) {
  10119. return extensions[name];
  10120. }
  10121. let extension;
  10122. switch (name) {
  10123. case 'WEBGL_depth_texture':
  10124. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  10125. break;
  10126. case 'EXT_texture_filter_anisotropic':
  10127. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  10128. break;
  10129. case 'WEBGL_compressed_texture_s3tc':
  10130. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10131. break;
  10132. case 'WEBGL_compressed_texture_pvrtc':
  10133. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10134. break;
  10135. default:
  10136. extension = gl.getExtension(name);
  10137. }
  10138. extensions[name] = extension;
  10139. return extension;
  10140. }
  10141. return {
  10142. has: function (name) {
  10143. return getExtension(name) !== null;
  10144. },
  10145. init: function (capabilities) {
  10146. if (capabilities.isWebGL2) {
  10147. getExtension('EXT_color_buffer_float');
  10148. } else {
  10149. getExtension('WEBGL_depth_texture');
  10150. getExtension('OES_texture_float');
  10151. getExtension('OES_texture_half_float');
  10152. getExtension('OES_texture_half_float_linear');
  10153. getExtension('OES_standard_derivatives');
  10154. getExtension('OES_element_index_uint');
  10155. getExtension('OES_vertex_array_object');
  10156. getExtension('ANGLE_instanced_arrays');
  10157. }
  10158. getExtension('OES_texture_float_linear');
  10159. getExtension('EXT_color_buffer_half_float');
  10160. getExtension('EXT_multisampled_render_to_texture');
  10161. },
  10162. get: function (name) {
  10163. const extension = getExtension(name);
  10164. if (extension === null) {
  10165. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  10166. }
  10167. return extension;
  10168. }
  10169. };
  10170. }
  10171. function WebGLGeometries(gl, attributes, info, bindingStates) {
  10172. const geometries = {};
  10173. const wireframeAttributes = new WeakMap();
  10174. function onGeometryDispose(event) {
  10175. const geometry = event.target;
  10176. if (geometry.index !== null) {
  10177. attributes.remove(geometry.index);
  10178. }
  10179. for (const name in geometry.attributes) {
  10180. attributes.remove(geometry.attributes[name]);
  10181. }
  10182. geometry.removeEventListener('dispose', onGeometryDispose);
  10183. delete geometries[geometry.id];
  10184. const attribute = wireframeAttributes.get(geometry);
  10185. if (attribute) {
  10186. attributes.remove(attribute);
  10187. wireframeAttributes.delete(geometry);
  10188. }
  10189. bindingStates.releaseStatesOfGeometry(geometry);
  10190. if (geometry.isInstancedBufferGeometry === true) {
  10191. delete geometry._maxInstanceCount;
  10192. } //
  10193. info.memory.geometries--;
  10194. }
  10195. function get(object, geometry) {
  10196. if (geometries[geometry.id] === true) return geometry;
  10197. geometry.addEventListener('dispose', onGeometryDispose);
  10198. geometries[geometry.id] = true;
  10199. info.memory.geometries++;
  10200. return geometry;
  10201. }
  10202. function update(geometry) {
  10203. const geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  10204. for (const name in geometryAttributes) {
  10205. attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
  10206. } // morph targets
  10207. const morphAttributes = geometry.morphAttributes;
  10208. for (const name in morphAttributes) {
  10209. const array = morphAttributes[name];
  10210. for (let i = 0, l = array.length; i < l; i++) {
  10211. attributes.update(array[i], gl.ARRAY_BUFFER);
  10212. }
  10213. }
  10214. }
  10215. function updateWireframeAttribute(geometry) {
  10216. const indices = [];
  10217. const geometryIndex = geometry.index;
  10218. const geometryPosition = geometry.attributes.position;
  10219. let version = 0;
  10220. if (geometryIndex !== null) {
  10221. const array = geometryIndex.array;
  10222. version = geometryIndex.version;
  10223. for (let i = 0, l = array.length; i < l; i += 3) {
  10224. const a = array[i + 0];
  10225. const b = array[i + 1];
  10226. const c = array[i + 2];
  10227. indices.push(a, b, b, c, c, a);
  10228. }
  10229. } else {
  10230. const array = geometryPosition.array;
  10231. version = geometryPosition.version;
  10232. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  10233. const a = i + 0;
  10234. const b = i + 1;
  10235. const c = i + 2;
  10236. indices.push(a, b, b, c, c, a);
  10237. }
  10238. }
  10239. const attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  10240. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  10241. //
  10242. const previousAttribute = wireframeAttributes.get(geometry);
  10243. if (previousAttribute) attributes.remove(previousAttribute); //
  10244. wireframeAttributes.set(geometry, attribute);
  10245. }
  10246. function getWireframeAttribute(geometry) {
  10247. const currentAttribute = wireframeAttributes.get(geometry);
  10248. if (currentAttribute) {
  10249. const geometryIndex = geometry.index;
  10250. if (geometryIndex !== null) {
  10251. // if the attribute is obsolete, create a new one
  10252. if (currentAttribute.version < geometryIndex.version) {
  10253. updateWireframeAttribute(geometry);
  10254. }
  10255. }
  10256. } else {
  10257. updateWireframeAttribute(geometry);
  10258. }
  10259. return wireframeAttributes.get(geometry);
  10260. }
  10261. return {
  10262. get: get,
  10263. update: update,
  10264. getWireframeAttribute: getWireframeAttribute
  10265. };
  10266. }
  10267. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  10268. const isWebGL2 = capabilities.isWebGL2;
  10269. let mode;
  10270. function setMode(value) {
  10271. mode = value;
  10272. }
  10273. let type, bytesPerElement;
  10274. function setIndex(value) {
  10275. type = value.type;
  10276. bytesPerElement = value.bytesPerElement;
  10277. }
  10278. function render(start, count) {
  10279. gl.drawElements(mode, count, type, start * bytesPerElement);
  10280. info.update(count, mode, 1);
  10281. }
  10282. function renderInstances(start, count, primcount) {
  10283. if (primcount === 0) return;
  10284. let extension, methodName;
  10285. if (isWebGL2) {
  10286. extension = gl;
  10287. methodName = 'drawElementsInstanced';
  10288. } else {
  10289. extension = extensions.get('ANGLE_instanced_arrays');
  10290. methodName = 'drawElementsInstancedANGLE';
  10291. if (extension === null) {
  10292. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10293. return;
  10294. }
  10295. }
  10296. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  10297. info.update(count, mode, primcount);
  10298. } //
  10299. this.setMode = setMode;
  10300. this.setIndex = setIndex;
  10301. this.render = render;
  10302. this.renderInstances = renderInstances;
  10303. }
  10304. function WebGLInfo(gl) {
  10305. const memory = {
  10306. geometries: 0,
  10307. textures: 0
  10308. };
  10309. const render = {
  10310. frame: 0,
  10311. calls: 0,
  10312. triangles: 0,
  10313. points: 0,
  10314. lines: 0
  10315. };
  10316. function update(count, mode, instanceCount) {
  10317. render.calls++;
  10318. switch (mode) {
  10319. case gl.TRIANGLES:
  10320. render.triangles += instanceCount * (count / 3);
  10321. break;
  10322. case gl.LINES:
  10323. render.lines += instanceCount * (count / 2);
  10324. break;
  10325. case gl.LINE_STRIP:
  10326. render.lines += instanceCount * (count - 1);
  10327. break;
  10328. case gl.LINE_LOOP:
  10329. render.lines += instanceCount * count;
  10330. break;
  10331. case gl.POINTS:
  10332. render.points += instanceCount * count;
  10333. break;
  10334. default:
  10335. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  10336. break;
  10337. }
  10338. }
  10339. function reset() {
  10340. render.frame++;
  10341. render.calls = 0;
  10342. render.triangles = 0;
  10343. render.points = 0;
  10344. render.lines = 0;
  10345. }
  10346. return {
  10347. memory: memory,
  10348. render: render,
  10349. programs: null,
  10350. autoReset: true,
  10351. reset: reset,
  10352. update: update
  10353. };
  10354. }
  10355. class DataTexture2DArray extends Texture {
  10356. constructor(data = null, width = 1, height = 1, depth = 1) {
  10357. super(null);
  10358. this.image = {
  10359. data,
  10360. width,
  10361. height,
  10362. depth
  10363. };
  10364. this.magFilter = NearestFilter;
  10365. this.minFilter = NearestFilter;
  10366. this.wrapR = ClampToEdgeWrapping;
  10367. this.generateMipmaps = false;
  10368. this.flipY = false;
  10369. this.unpackAlignment = 1;
  10370. this.needsUpdate = true;
  10371. }
  10372. }
  10373. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  10374. function numericalSort(a, b) {
  10375. return a[0] - b[0];
  10376. }
  10377. function absNumericalSort(a, b) {
  10378. return Math.abs(b[1]) - Math.abs(a[1]);
  10379. }
  10380. function denormalize(morph, attribute) {
  10381. let denominator = 1;
  10382. const array = attribute.isInterleavedBufferAttribute ? attribute.data.array : attribute.array;
  10383. if (array instanceof Int8Array) denominator = 127;else if (array instanceof Int16Array) denominator = 32767;else if (array instanceof Int32Array) denominator = 2147483647;else console.error('THREE.WebGLMorphtargets: Unsupported morph attribute data type: ', array);
  10384. morph.divideScalar(denominator);
  10385. }
  10386. function WebGLMorphtargets(gl, capabilities, textures) {
  10387. const influencesList = {};
  10388. const morphInfluences = new Float32Array(8);
  10389. const morphTextures = new WeakMap();
  10390. const morph = new Vector3();
  10391. const workInfluences = [];
  10392. for (let i = 0; i < 8; i++) {
  10393. workInfluences[i] = [i, 0];
  10394. }
  10395. function update(object, geometry, material, program) {
  10396. const objectInfluences = object.morphTargetInfluences;
  10397. if (capabilities.isWebGL2 === true) {
  10398. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10399. // into an array of data textures. Each layer represents a single morph target.
  10400. const numberOfMorphTargets = geometry.morphAttributes.position.length;
  10401. let entry = morphTextures.get(geometry);
  10402. if (entry === undefined || entry.count !== numberOfMorphTargets) {
  10403. if (entry !== undefined) entry.texture.dispose();
  10404. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10405. const morphTargets = geometry.morphAttributes.position;
  10406. const morphNormals = geometry.morphAttributes.normal || [];
  10407. const numberOfVertices = geometry.attributes.position.count;
  10408. const numberOfVertexData = hasMorphNormals === true ? 2 : 1; // (v,n) vs. (v)
  10409. let width = numberOfVertices * numberOfVertexData;
  10410. let height = 1;
  10411. if (width > capabilities.maxTextureSize) {
  10412. height = Math.ceil(width / capabilities.maxTextureSize);
  10413. width = capabilities.maxTextureSize;
  10414. }
  10415. const buffer = new Float32Array(width * height * 4 * numberOfMorphTargets);
  10416. const texture = new DataTexture2DArray(buffer, width, height, numberOfMorphTargets);
  10417. texture.format = RGBAFormat; // using RGBA since RGB might be emulated (and is thus slower)
  10418. texture.type = FloatType; // fill buffer
  10419. const vertexDataStride = numberOfVertexData * 4;
  10420. for (let i = 0; i < numberOfMorphTargets; i++) {
  10421. const morphTarget = morphTargets[i];
  10422. const morphNormal = morphNormals[i];
  10423. const offset = width * height * 4 * i;
  10424. for (let j = 0; j < morphTarget.count; j++) {
  10425. morph.fromBufferAttribute(morphTarget, j);
  10426. if (morphTarget.normalized === true) denormalize(morph, morphTarget);
  10427. const stride = j * vertexDataStride;
  10428. buffer[offset + stride + 0] = morph.x;
  10429. buffer[offset + stride + 1] = morph.y;
  10430. buffer[offset + stride + 2] = morph.z;
  10431. buffer[offset + stride + 3] = 0;
  10432. if (hasMorphNormals === true) {
  10433. morph.fromBufferAttribute(morphNormal, j);
  10434. if (morphNormal.normalized === true) denormalize(morph, morphNormal);
  10435. buffer[offset + stride + 4] = morph.x;
  10436. buffer[offset + stride + 5] = morph.y;
  10437. buffer[offset + stride + 6] = morph.z;
  10438. buffer[offset + stride + 7] = 0;
  10439. }
  10440. }
  10441. }
  10442. entry = {
  10443. count: numberOfMorphTargets,
  10444. texture: texture,
  10445. size: new Vector2(width, height)
  10446. };
  10447. morphTextures.set(geometry, entry);
  10448. } //
  10449. let morphInfluencesSum = 0;
  10450. for (let i = 0; i < objectInfluences.length; i++) {
  10451. morphInfluencesSum += objectInfluences[i];
  10452. }
  10453. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10454. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10455. program.getUniforms().setValue(gl, 'morphTargetInfluences', objectInfluences);
  10456. program.getUniforms().setValue(gl, 'morphTargetsTexture', entry.texture, textures);
  10457. program.getUniforms().setValue(gl, 'morphTargetsTextureSize', entry.size);
  10458. } else {
  10459. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10460. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10461. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10462. let influences = influencesList[geometry.id];
  10463. if (influences === undefined || influences.length !== length) {
  10464. // initialise list
  10465. influences = [];
  10466. for (let i = 0; i < length; i++) {
  10467. influences[i] = [i, 0];
  10468. }
  10469. influencesList[geometry.id] = influences;
  10470. } // Collect influences
  10471. for (let i = 0; i < length; i++) {
  10472. const influence = influences[i];
  10473. influence[0] = i;
  10474. influence[1] = objectInfluences[i];
  10475. }
  10476. influences.sort(absNumericalSort);
  10477. for (let i = 0; i < 8; i++) {
  10478. if (i < length && influences[i][1]) {
  10479. workInfluences[i][0] = influences[i][0];
  10480. workInfluences[i][1] = influences[i][1];
  10481. } else {
  10482. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  10483. workInfluences[i][1] = 0;
  10484. }
  10485. }
  10486. workInfluences.sort(numericalSort);
  10487. const morphTargets = geometry.morphAttributes.position;
  10488. const morphNormals = geometry.morphAttributes.normal;
  10489. let morphInfluencesSum = 0;
  10490. for (let i = 0; i < 8; i++) {
  10491. const influence = workInfluences[i];
  10492. const index = influence[0];
  10493. const value = influence[1];
  10494. if (index !== Number.MAX_SAFE_INTEGER && value) {
  10495. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  10496. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  10497. }
  10498. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  10499. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  10500. }
  10501. morphInfluences[i] = value;
  10502. morphInfluencesSum += value;
  10503. } else {
  10504. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  10505. geometry.deleteAttribute('morphTarget' + i);
  10506. }
  10507. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  10508. geometry.deleteAttribute('morphNormal' + i);
  10509. }
  10510. morphInfluences[i] = 0;
  10511. }
  10512. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10513. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10514. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10515. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10516. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10517. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  10518. }
  10519. }
  10520. return {
  10521. update: update
  10522. };
  10523. }
  10524. function WebGLObjects(gl, geometries, attributes, info) {
  10525. let updateMap = new WeakMap();
  10526. function update(object) {
  10527. const frame = info.render.frame;
  10528. const geometry = object.geometry;
  10529. const buffergeometry = geometries.get(object, geometry); // Update once per frame
  10530. if (updateMap.get(buffergeometry) !== frame) {
  10531. geometries.update(buffergeometry);
  10532. updateMap.set(buffergeometry, frame);
  10533. }
  10534. if (object.isInstancedMesh) {
  10535. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  10536. object.addEventListener('dispose', onInstancedMeshDispose);
  10537. }
  10538. attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
  10539. if (object.instanceColor !== null) {
  10540. attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
  10541. }
  10542. }
  10543. return buffergeometry;
  10544. }
  10545. function dispose() {
  10546. updateMap = new WeakMap();
  10547. }
  10548. function onInstancedMeshDispose(event) {
  10549. const instancedMesh = event.target;
  10550. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  10551. attributes.remove(instancedMesh.instanceMatrix);
  10552. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  10553. }
  10554. return {
  10555. update: update,
  10556. dispose: dispose
  10557. };
  10558. }
  10559. class DataTexture3D extends Texture {
  10560. constructor(data = null, width = 1, height = 1, depth = 1) {
  10561. // We're going to add .setXXX() methods for setting properties later.
  10562. // Users can still set in DataTexture3D directly.
  10563. //
  10564. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  10565. // texture.anisotropy = 16;
  10566. //
  10567. // See #14839
  10568. super(null);
  10569. this.image = {
  10570. data,
  10571. width,
  10572. height,
  10573. depth
  10574. };
  10575. this.magFilter = NearestFilter;
  10576. this.minFilter = NearestFilter;
  10577. this.wrapR = ClampToEdgeWrapping;
  10578. this.generateMipmaps = false;
  10579. this.flipY = false;
  10580. this.unpackAlignment = 1;
  10581. this.needsUpdate = true;
  10582. }
  10583. }
  10584. DataTexture3D.prototype.isDataTexture3D = true;
  10585. /**
  10586. * Uniforms of a program.
  10587. * Those form a tree structure with a special top-level container for the root,
  10588. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10589. *
  10590. *
  10591. * Properties of inner nodes including the top-level container:
  10592. *
  10593. * .seq - array of nested uniforms
  10594. * .map - nested uniforms by name
  10595. *
  10596. *
  10597. * Methods of all nodes except the top-level container:
  10598. *
  10599. * .setValue( gl, value, [textures] )
  10600. *
  10601. * uploads a uniform value(s)
  10602. * the 'textures' parameter is needed for sampler uniforms
  10603. *
  10604. *
  10605. * Static methods of the top-level container (textures factorizations):
  10606. *
  10607. * .upload( gl, seq, values, textures )
  10608. *
  10609. * sets uniforms in 'seq' to 'values[id].value'
  10610. *
  10611. * .seqWithValue( seq, values ) : filteredSeq
  10612. *
  10613. * filters 'seq' entries with corresponding entry in values
  10614. *
  10615. *
  10616. * Methods of the top-level container (textures factorizations):
  10617. *
  10618. * .setValue( gl, name, value, textures )
  10619. *
  10620. * sets uniform with name 'name' to 'value'
  10621. *
  10622. * .setOptional( gl, obj, prop )
  10623. *
  10624. * like .set for an optional property of the object
  10625. *
  10626. */
  10627. const emptyTexture = new Texture();
  10628. const emptyTexture2dArray = new DataTexture2DArray();
  10629. const emptyTexture3d = new DataTexture3D();
  10630. const emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  10631. // Array Caches (provide typed arrays for temporary by size)
  10632. const arrayCacheF32 = [];
  10633. const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  10634. const mat4array = new Float32Array(16);
  10635. const mat3array = new Float32Array(9);
  10636. const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  10637. function flatten(array, nBlocks, blockSize) {
  10638. const firstElem = array[0];
  10639. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  10640. // see http://jacksondunstan.com/articles/983
  10641. const n = nBlocks * blockSize;
  10642. let r = arrayCacheF32[n];
  10643. if (r === undefined) {
  10644. r = new Float32Array(n);
  10645. arrayCacheF32[n] = r;
  10646. }
  10647. if (nBlocks !== 0) {
  10648. firstElem.toArray(r, 0);
  10649. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  10650. offset += blockSize;
  10651. array[i].toArray(r, offset);
  10652. }
  10653. }
  10654. return r;
  10655. }
  10656. function arraysEqual(a, b) {
  10657. if (a.length !== b.length) return false;
  10658. for (let i = 0, l = a.length; i < l; i++) {
  10659. if (a[i] !== b[i]) return false;
  10660. }
  10661. return true;
  10662. }
  10663. function copyArray(a, b) {
  10664. for (let i = 0, l = b.length; i < l; i++) {
  10665. a[i] = b[i];
  10666. }
  10667. } // Texture unit allocation
  10668. function allocTexUnits(textures, n) {
  10669. let r = arrayCacheI32[n];
  10670. if (r === undefined) {
  10671. r = new Int32Array(n);
  10672. arrayCacheI32[n] = r;
  10673. }
  10674. for (let i = 0; i !== n; ++i) {
  10675. r[i] = textures.allocateTextureUnit();
  10676. }
  10677. return r;
  10678. } // --- Setters ---
  10679. // Note: Defining these methods externally, because they come in a bunch
  10680. // and this way their names minify.
  10681. // Single scalar
  10682. function setValueV1f(gl, v) {
  10683. const cache = this.cache;
  10684. if (cache[0] === v) return;
  10685. gl.uniform1f(this.addr, v);
  10686. cache[0] = v;
  10687. } // Single float vector (from flat array or THREE.VectorN)
  10688. function setValueV2f(gl, v) {
  10689. const cache = this.cache;
  10690. if (v.x !== undefined) {
  10691. if (cache[0] !== v.x || cache[1] !== v.y) {
  10692. gl.uniform2f(this.addr, v.x, v.y);
  10693. cache[0] = v.x;
  10694. cache[1] = v.y;
  10695. }
  10696. } else {
  10697. if (arraysEqual(cache, v)) return;
  10698. gl.uniform2fv(this.addr, v);
  10699. copyArray(cache, v);
  10700. }
  10701. }
  10702. function setValueV3f(gl, v) {
  10703. const cache = this.cache;
  10704. if (v.x !== undefined) {
  10705. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10706. gl.uniform3f(this.addr, v.x, v.y, v.z);
  10707. cache[0] = v.x;
  10708. cache[1] = v.y;
  10709. cache[2] = v.z;
  10710. }
  10711. } else if (v.r !== undefined) {
  10712. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  10713. gl.uniform3f(this.addr, v.r, v.g, v.b);
  10714. cache[0] = v.r;
  10715. cache[1] = v.g;
  10716. cache[2] = v.b;
  10717. }
  10718. } else {
  10719. if (arraysEqual(cache, v)) return;
  10720. gl.uniform3fv(this.addr, v);
  10721. copyArray(cache, v);
  10722. }
  10723. }
  10724. function setValueV4f(gl, v) {
  10725. const cache = this.cache;
  10726. if (v.x !== undefined) {
  10727. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  10728. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  10729. cache[0] = v.x;
  10730. cache[1] = v.y;
  10731. cache[2] = v.z;
  10732. cache[3] = v.w;
  10733. }
  10734. } else {
  10735. if (arraysEqual(cache, v)) return;
  10736. gl.uniform4fv(this.addr, v);
  10737. copyArray(cache, v);
  10738. }
  10739. } // Single matrix (from flat array or THREE.MatrixN)
  10740. function setValueM2(gl, v) {
  10741. const cache = this.cache;
  10742. const elements = v.elements;
  10743. if (elements === undefined) {
  10744. if (arraysEqual(cache, v)) return;
  10745. gl.uniformMatrix2fv(this.addr, false, v);
  10746. copyArray(cache, v);
  10747. } else {
  10748. if (arraysEqual(cache, elements)) return;
  10749. mat2array.set(elements);
  10750. gl.uniformMatrix2fv(this.addr, false, mat2array);
  10751. copyArray(cache, elements);
  10752. }
  10753. }
  10754. function setValueM3(gl, v) {
  10755. const cache = this.cache;
  10756. const elements = v.elements;
  10757. if (elements === undefined) {
  10758. if (arraysEqual(cache, v)) return;
  10759. gl.uniformMatrix3fv(this.addr, false, v);
  10760. copyArray(cache, v);
  10761. } else {
  10762. if (arraysEqual(cache, elements)) return;
  10763. mat3array.set(elements);
  10764. gl.uniformMatrix3fv(this.addr, false, mat3array);
  10765. copyArray(cache, elements);
  10766. }
  10767. }
  10768. function setValueM4(gl, v) {
  10769. const cache = this.cache;
  10770. const elements = v.elements;
  10771. if (elements === undefined) {
  10772. if (arraysEqual(cache, v)) return;
  10773. gl.uniformMatrix4fv(this.addr, false, v);
  10774. copyArray(cache, v);
  10775. } else {
  10776. if (arraysEqual(cache, elements)) return;
  10777. mat4array.set(elements);
  10778. gl.uniformMatrix4fv(this.addr, false, mat4array);
  10779. copyArray(cache, elements);
  10780. }
  10781. } // Single integer / boolean
  10782. function setValueV1i(gl, v) {
  10783. const cache = this.cache;
  10784. if (cache[0] === v) return;
  10785. gl.uniform1i(this.addr, v);
  10786. cache[0] = v;
  10787. } // Single integer / boolean vector (from flat array)
  10788. function setValueV2i(gl, v) {
  10789. const cache = this.cache;
  10790. if (arraysEqual(cache, v)) return;
  10791. gl.uniform2iv(this.addr, v);
  10792. copyArray(cache, v);
  10793. }
  10794. function setValueV3i(gl, v) {
  10795. const cache = this.cache;
  10796. if (arraysEqual(cache, v)) return;
  10797. gl.uniform3iv(this.addr, v);
  10798. copyArray(cache, v);
  10799. }
  10800. function setValueV4i(gl, v) {
  10801. const cache = this.cache;
  10802. if (arraysEqual(cache, v)) return;
  10803. gl.uniform4iv(this.addr, v);
  10804. copyArray(cache, v);
  10805. } // Single unsigned integer
  10806. function setValueV1ui(gl, v) {
  10807. const cache = this.cache;
  10808. if (cache[0] === v) return;
  10809. gl.uniform1ui(this.addr, v);
  10810. cache[0] = v;
  10811. } // Single unsigned integer vector (from flat array)
  10812. function setValueV2ui(gl, v) {
  10813. const cache = this.cache;
  10814. if (arraysEqual(cache, v)) return;
  10815. gl.uniform2uiv(this.addr, v);
  10816. copyArray(cache, v);
  10817. }
  10818. function setValueV3ui(gl, v) {
  10819. const cache = this.cache;
  10820. if (arraysEqual(cache, v)) return;
  10821. gl.uniform3uiv(this.addr, v);
  10822. copyArray(cache, v);
  10823. }
  10824. function setValueV4ui(gl, v) {
  10825. const cache = this.cache;
  10826. if (arraysEqual(cache, v)) return;
  10827. gl.uniform4uiv(this.addr, v);
  10828. copyArray(cache, v);
  10829. } // Single texture (2D / Cube)
  10830. function setValueT1(gl, v, textures) {
  10831. const cache = this.cache;
  10832. const unit = textures.allocateTextureUnit();
  10833. if (cache[0] !== unit) {
  10834. gl.uniform1i(this.addr, unit);
  10835. cache[0] = unit;
  10836. }
  10837. textures.safeSetTexture2D(v || emptyTexture, unit);
  10838. }
  10839. function setValueT3D1(gl, v, textures) {
  10840. const cache = this.cache;
  10841. const unit = textures.allocateTextureUnit();
  10842. if (cache[0] !== unit) {
  10843. gl.uniform1i(this.addr, unit);
  10844. cache[0] = unit;
  10845. }
  10846. textures.setTexture3D(v || emptyTexture3d, unit);
  10847. }
  10848. function setValueT6(gl, v, textures) {
  10849. const cache = this.cache;
  10850. const unit = textures.allocateTextureUnit();
  10851. if (cache[0] !== unit) {
  10852. gl.uniform1i(this.addr, unit);
  10853. cache[0] = unit;
  10854. }
  10855. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  10856. }
  10857. function setValueT2DArray1(gl, v, textures) {
  10858. const cache = this.cache;
  10859. const unit = textures.allocateTextureUnit();
  10860. if (cache[0] !== unit) {
  10861. gl.uniform1i(this.addr, unit);
  10862. cache[0] = unit;
  10863. }
  10864. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  10865. } // Helper to pick the right setter for the singular case
  10866. function getSingularSetter(type) {
  10867. switch (type) {
  10868. case 0x1406:
  10869. return setValueV1f;
  10870. // FLOAT
  10871. case 0x8b50:
  10872. return setValueV2f;
  10873. // _VEC2
  10874. case 0x8b51:
  10875. return setValueV3f;
  10876. // _VEC3
  10877. case 0x8b52:
  10878. return setValueV4f;
  10879. // _VEC4
  10880. case 0x8b5a:
  10881. return setValueM2;
  10882. // _MAT2
  10883. case 0x8b5b:
  10884. return setValueM3;
  10885. // _MAT3
  10886. case 0x8b5c:
  10887. return setValueM4;
  10888. // _MAT4
  10889. case 0x1404:
  10890. case 0x8b56:
  10891. return setValueV1i;
  10892. // INT, BOOL
  10893. case 0x8b53:
  10894. case 0x8b57:
  10895. return setValueV2i;
  10896. // _VEC2
  10897. case 0x8b54:
  10898. case 0x8b58:
  10899. return setValueV3i;
  10900. // _VEC3
  10901. case 0x8b55:
  10902. case 0x8b59:
  10903. return setValueV4i;
  10904. // _VEC4
  10905. case 0x1405:
  10906. return setValueV1ui;
  10907. // UINT
  10908. case 0x8dc6:
  10909. return setValueV2ui;
  10910. // _VEC2
  10911. case 0x8dc7:
  10912. return setValueV3ui;
  10913. // _VEC3
  10914. case 0x8dc8:
  10915. return setValueV4ui;
  10916. // _VEC4
  10917. case 0x8b5e: // SAMPLER_2D
  10918. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10919. case 0x8dca: // INT_SAMPLER_2D
  10920. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10921. case 0x8b62:
  10922. // SAMPLER_2D_SHADOW
  10923. return setValueT1;
  10924. case 0x8b5f: // SAMPLER_3D
  10925. case 0x8dcb: // INT_SAMPLER_3D
  10926. case 0x8dd3:
  10927. // UNSIGNED_INT_SAMPLER_3D
  10928. return setValueT3D1;
  10929. case 0x8b60: // SAMPLER_CUBE
  10930. case 0x8dcc: // INT_SAMPLER_CUBE
  10931. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10932. case 0x8dc5:
  10933. // SAMPLER_CUBE_SHADOW
  10934. return setValueT6;
  10935. case 0x8dc1: // SAMPLER_2D_ARRAY
  10936. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10937. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10938. case 0x8dc4:
  10939. // SAMPLER_2D_ARRAY_SHADOW
  10940. return setValueT2DArray1;
  10941. }
  10942. } // Array of scalars
  10943. function setValueV1fArray(gl, v) {
  10944. gl.uniform1fv(this.addr, v);
  10945. } // Array of vectors (from flat array or array of THREE.VectorN)
  10946. function setValueV2fArray(gl, v) {
  10947. const data = flatten(v, this.size, 2);
  10948. gl.uniform2fv(this.addr, data);
  10949. }
  10950. function setValueV3fArray(gl, v) {
  10951. const data = flatten(v, this.size, 3);
  10952. gl.uniform3fv(this.addr, data);
  10953. }
  10954. function setValueV4fArray(gl, v) {
  10955. const data = flatten(v, this.size, 4);
  10956. gl.uniform4fv(this.addr, data);
  10957. } // Array of matrices (from flat array or array of THREE.MatrixN)
  10958. function setValueM2Array(gl, v) {
  10959. const data = flatten(v, this.size, 4);
  10960. gl.uniformMatrix2fv(this.addr, false, data);
  10961. }
  10962. function setValueM3Array(gl, v) {
  10963. const data = flatten(v, this.size, 9);
  10964. gl.uniformMatrix3fv(this.addr, false, data);
  10965. }
  10966. function setValueM4Array(gl, v) {
  10967. const data = flatten(v, this.size, 16);
  10968. gl.uniformMatrix4fv(this.addr, false, data);
  10969. } // Array of integer / boolean
  10970. function setValueV1iArray(gl, v) {
  10971. gl.uniform1iv(this.addr, v);
  10972. } // Array of integer / boolean vectors (from flat array)
  10973. function setValueV2iArray(gl, v) {
  10974. gl.uniform2iv(this.addr, v);
  10975. }
  10976. function setValueV3iArray(gl, v) {
  10977. gl.uniform3iv(this.addr, v);
  10978. }
  10979. function setValueV4iArray(gl, v) {
  10980. gl.uniform4iv(this.addr, v);
  10981. } // Array of unsigned integer
  10982. function setValueV1uiArray(gl, v) {
  10983. gl.uniform1uiv(this.addr, v);
  10984. } // Array of unsigned integer vectors (from flat array)
  10985. function setValueV2uiArray(gl, v) {
  10986. gl.uniform2uiv(this.addr, v);
  10987. }
  10988. function setValueV3uiArray(gl, v) {
  10989. gl.uniform3uiv(this.addr, v);
  10990. }
  10991. function setValueV4uiArray(gl, v) {
  10992. gl.uniform4uiv(this.addr, v);
  10993. } // Array of textures (2D / Cube)
  10994. function setValueT1Array(gl, v, textures) {
  10995. const n = v.length;
  10996. const units = allocTexUnits(textures, n);
  10997. gl.uniform1iv(this.addr, units);
  10998. for (let i = 0; i !== n; ++i) {
  10999. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  11000. }
  11001. }
  11002. function setValueT6Array(gl, v, textures) {
  11003. const n = v.length;
  11004. const units = allocTexUnits(textures, n);
  11005. gl.uniform1iv(this.addr, units);
  11006. for (let i = 0; i !== n; ++i) {
  11007. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  11008. }
  11009. } // Helper to pick the right setter for a pure (bottom-level) array
  11010. function getPureArraySetter(type) {
  11011. switch (type) {
  11012. case 0x1406:
  11013. return setValueV1fArray;
  11014. // FLOAT
  11015. case 0x8b50:
  11016. return setValueV2fArray;
  11017. // _VEC2
  11018. case 0x8b51:
  11019. return setValueV3fArray;
  11020. // _VEC3
  11021. case 0x8b52:
  11022. return setValueV4fArray;
  11023. // _VEC4
  11024. case 0x8b5a:
  11025. return setValueM2Array;
  11026. // _MAT2
  11027. case 0x8b5b:
  11028. return setValueM3Array;
  11029. // _MAT3
  11030. case 0x8b5c:
  11031. return setValueM4Array;
  11032. // _MAT4
  11033. case 0x1404:
  11034. case 0x8b56:
  11035. return setValueV1iArray;
  11036. // INT, BOOL
  11037. case 0x8b53:
  11038. case 0x8b57:
  11039. return setValueV2iArray;
  11040. // _VEC2
  11041. case 0x8b54:
  11042. case 0x8b58:
  11043. return setValueV3iArray;
  11044. // _VEC3
  11045. case 0x8b55:
  11046. case 0x8b59:
  11047. return setValueV4iArray;
  11048. // _VEC4
  11049. case 0x1405:
  11050. return setValueV1uiArray;
  11051. // UINT
  11052. case 0x8dc6:
  11053. return setValueV2uiArray;
  11054. // _VEC2
  11055. case 0x8dc7:
  11056. return setValueV3uiArray;
  11057. // _VEC3
  11058. case 0x8dc8:
  11059. return setValueV4uiArray;
  11060. // _VEC4
  11061. case 0x8b5e: // SAMPLER_2D
  11062. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11063. case 0x8dca: // INT_SAMPLER_2D
  11064. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11065. case 0x8b62:
  11066. // SAMPLER_2D_SHADOW
  11067. return setValueT1Array;
  11068. case 0x8b60: // SAMPLER_CUBE
  11069. case 0x8dcc: // INT_SAMPLER_CUBE
  11070. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11071. case 0x8dc5:
  11072. // SAMPLER_CUBE_SHADOW
  11073. return setValueT6Array;
  11074. }
  11075. } // --- Uniform Classes ---
  11076. function SingleUniform(id, activeInfo, addr) {
  11077. this.id = id;
  11078. this.addr = addr;
  11079. this.cache = [];
  11080. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11081. }
  11082. function PureArrayUniform(id, activeInfo, addr) {
  11083. this.id = id;
  11084. this.addr = addr;
  11085. this.cache = [];
  11086. this.size = activeInfo.size;
  11087. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11088. }
  11089. PureArrayUniform.prototype.updateCache = function (data) {
  11090. const cache = this.cache;
  11091. if (data instanceof Float32Array && cache.length !== data.length) {
  11092. this.cache = new Float32Array(data.length);
  11093. }
  11094. copyArray(cache, data);
  11095. };
  11096. function StructuredUniform(id) {
  11097. this.id = id;
  11098. this.seq = [];
  11099. this.map = {};
  11100. }
  11101. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  11102. const seq = this.seq;
  11103. for (let i = 0, n = seq.length; i !== n; ++i) {
  11104. const u = seq[i];
  11105. u.setValue(gl, value[u.id], textures);
  11106. }
  11107. }; // --- Top-level ---
  11108. // Parser - builds up the property tree from the path strings
  11109. const RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
  11110. // - the identifier (member name or array index)
  11111. // - followed by an optional right bracket (found when array index)
  11112. // - followed by an optional left bracket or dot (type of subscript)
  11113. //
  11114. // Note: These portions can be read in a non-overlapping fashion and
  11115. // allow straightforward parsing of the hierarchy that WebGL encodes
  11116. // in the uniform names.
  11117. function addUniform(container, uniformObject) {
  11118. container.seq.push(uniformObject);
  11119. container.map[uniformObject.id] = uniformObject;
  11120. }
  11121. function parseUniform(activeInfo, addr, container) {
  11122. const path = activeInfo.name,
  11123. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  11124. RePathPart.lastIndex = 0;
  11125. while (true) {
  11126. const match = RePathPart.exec(path),
  11127. matchEnd = RePathPart.lastIndex;
  11128. let id = match[1];
  11129. const idIsIndex = match[2] === ']',
  11130. subscript = match[3];
  11131. if (idIsIndex) id = id | 0; // convert to integer
  11132. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  11133. // bare name or "pure" bottom-level array "[0]" suffix
  11134. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  11135. break;
  11136. } else {
  11137. // step into inner node / create it in case it doesn't exist
  11138. const map = container.map;
  11139. let next = map[id];
  11140. if (next === undefined) {
  11141. next = new StructuredUniform(id);
  11142. addUniform(container, next);
  11143. }
  11144. container = next;
  11145. }
  11146. }
  11147. } // Root Container
  11148. function WebGLUniforms(gl, program) {
  11149. this.seq = [];
  11150. this.map = {};
  11151. const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  11152. for (let i = 0; i < n; ++i) {
  11153. const info = gl.getActiveUniform(program, i),
  11154. addr = gl.getUniformLocation(program, info.name);
  11155. parseUniform(info, addr, this);
  11156. }
  11157. }
  11158. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  11159. const u = this.map[name];
  11160. if (u !== undefined) u.setValue(gl, value, textures);
  11161. };
  11162. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  11163. const v = object[name];
  11164. if (v !== undefined) this.setValue(gl, name, v);
  11165. }; // Static interface
  11166. WebGLUniforms.upload = function (gl, seq, values, textures) {
  11167. for (let i = 0, n = seq.length; i !== n; ++i) {
  11168. const u = seq[i],
  11169. v = values[u.id];
  11170. if (v.needsUpdate !== false) {
  11171. // note: always updating when .needsUpdate is undefined
  11172. u.setValue(gl, v.value, textures);
  11173. }
  11174. }
  11175. };
  11176. WebGLUniforms.seqWithValue = function (seq, values) {
  11177. const r = [];
  11178. for (let i = 0, n = seq.length; i !== n; ++i) {
  11179. const u = seq[i];
  11180. if (u.id in values) r.push(u);
  11181. }
  11182. return r;
  11183. };
  11184. function WebGLShader(gl, type, string) {
  11185. const shader = gl.createShader(type);
  11186. gl.shaderSource(shader, string);
  11187. gl.compileShader(shader);
  11188. return shader;
  11189. }
  11190. let programIdCount = 0;
  11191. function addLineNumbers(string) {
  11192. const lines = string.split('\n');
  11193. for (let i = 0; i < lines.length; i++) {
  11194. lines[i] = i + 1 + ': ' + lines[i];
  11195. }
  11196. return lines.join('\n');
  11197. }
  11198. function getEncodingComponents(encoding) {
  11199. switch (encoding) {
  11200. case LinearEncoding:
  11201. return ['Linear', '( value )'];
  11202. case sRGBEncoding:
  11203. return ['sRGB', '( value )'];
  11204. case RGBEEncoding:
  11205. return ['RGBE', '( value )'];
  11206. case RGBM7Encoding:
  11207. return ['RGBM', '( value, 7.0 )'];
  11208. case RGBM16Encoding:
  11209. return ['RGBM', '( value, 16.0 )'];
  11210. case RGBDEncoding:
  11211. return ['RGBD', '( value, 256.0 )'];
  11212. case GammaEncoding:
  11213. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  11214. case LogLuvEncoding:
  11215. return ['LogLuv', '( value )'];
  11216. default:
  11217. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  11218. return ['Linear', '( value )'];
  11219. }
  11220. }
  11221. function getShaderErrors(gl, shader, type) {
  11222. const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  11223. const errors = gl.getShaderInfoLog(shader).trim();
  11224. if (status && errors === '') return ''; // --enable-privileged-webgl-extension
  11225. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11226. return type.toUpperCase() + '\n\n' + errors + '\n\n' + addLineNumbers(gl.getShaderSource(shader));
  11227. }
  11228. function getTexelDecodingFunction(functionName, encoding) {
  11229. const components = getEncodingComponents(encoding);
  11230. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  11231. }
  11232. function getTexelEncodingFunction(functionName, encoding) {
  11233. const components = getEncodingComponents(encoding);
  11234. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  11235. }
  11236. function getToneMappingFunction(functionName, toneMapping) {
  11237. let toneMappingName;
  11238. switch (toneMapping) {
  11239. case LinearToneMapping:
  11240. toneMappingName = 'Linear';
  11241. break;
  11242. case ReinhardToneMapping:
  11243. toneMappingName = 'Reinhard';
  11244. break;
  11245. case CineonToneMapping:
  11246. toneMappingName = 'OptimizedCineon';
  11247. break;
  11248. case ACESFilmicToneMapping:
  11249. toneMappingName = 'ACESFilmic';
  11250. break;
  11251. case CustomToneMapping:
  11252. toneMappingName = 'Custom';
  11253. break;
  11254. default:
  11255. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  11256. toneMappingName = 'Linear';
  11257. }
  11258. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11259. }
  11260. function generateExtensions(parameters) {
  11261. const chunks = [parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ? '#extension GL_OES_standard_derivatives : enable' : '', (parameters.extensionFragDepth || parameters.logarithmicDepthBuffer) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ? '#extension GL_EXT_draw_buffers : require' : '', (parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  11262. return chunks.filter(filterEmptyLine).join('\n');
  11263. }
  11264. function generateDefines(defines) {
  11265. const chunks = [];
  11266. for (const name in defines) {
  11267. const value = defines[name];
  11268. if (value === false) continue;
  11269. chunks.push('#define ' + name + ' ' + value);
  11270. }
  11271. return chunks.join('\n');
  11272. }
  11273. function fetchAttributeLocations(gl, program) {
  11274. const attributes = {};
  11275. const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  11276. for (let i = 0; i < n; i++) {
  11277. const info = gl.getActiveAttrib(program, i);
  11278. const name = info.name;
  11279. let locationSize = 1;
  11280. if (info.type === gl.FLOAT_MAT2) locationSize = 2;
  11281. if (info.type === gl.FLOAT_MAT3) locationSize = 3;
  11282. if (info.type === gl.FLOAT_MAT4) locationSize = 4; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11283. attributes[name] = {
  11284. type: info.type,
  11285. location: gl.getAttribLocation(program, name),
  11286. locationSize: locationSize
  11287. };
  11288. }
  11289. return attributes;
  11290. }
  11291. function filterEmptyLine(string) {
  11292. return string !== '';
  11293. }
  11294. function replaceLightNums(string, parameters) {
  11295. 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);
  11296. }
  11297. function replaceClippingPlaneNums(string, parameters) {
  11298. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  11299. } // Resolve Includes
  11300. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11301. function resolveIncludes(string) {
  11302. return string.replace(includePattern, includeReplacer);
  11303. }
  11304. function includeReplacer(match, include) {
  11305. const string = ShaderChunk[include];
  11306. if (string === undefined) {
  11307. throw new Error('Can not resolve #include <' + include + '>');
  11308. }
  11309. return resolveIncludes(string);
  11310. } // Unroll Loops
  11311. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  11312. 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;
  11313. function unrollLoops(string) {
  11314. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  11315. }
  11316. function deprecatedLoopReplacer(match, start, end, snippet) {
  11317. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  11318. return loopReplacer(match, start, end, snippet);
  11319. }
  11320. function loopReplacer(match, start, end, snippet) {
  11321. let string = '';
  11322. for (let i = parseInt(start); i < parseInt(end); i++) {
  11323. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  11324. }
  11325. return string;
  11326. } //
  11327. function generatePrecision(parameters) {
  11328. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11329. if (parameters.precision === 'highp') {
  11330. precisionstring += '\n#define HIGH_PRECISION';
  11331. } else if (parameters.precision === 'mediump') {
  11332. precisionstring += '\n#define MEDIUM_PRECISION';
  11333. } else if (parameters.precision === 'lowp') {
  11334. precisionstring += '\n#define LOW_PRECISION';
  11335. }
  11336. return precisionstring;
  11337. }
  11338. function generateShadowMapTypeDefine(parameters) {
  11339. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11340. if (parameters.shadowMapType === PCFShadowMap) {
  11341. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11342. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  11343. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11344. } else if (parameters.shadowMapType === VSMShadowMap) {
  11345. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11346. }
  11347. return shadowMapTypeDefine;
  11348. }
  11349. function generateEnvMapTypeDefine(parameters) {
  11350. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11351. if (parameters.envMap) {
  11352. switch (parameters.envMapMode) {
  11353. case CubeReflectionMapping:
  11354. case CubeRefractionMapping:
  11355. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11356. break;
  11357. case CubeUVReflectionMapping:
  11358. case CubeUVRefractionMapping:
  11359. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11360. break;
  11361. }
  11362. }
  11363. return envMapTypeDefine;
  11364. }
  11365. function generateEnvMapModeDefine(parameters) {
  11366. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11367. if (parameters.envMap) {
  11368. switch (parameters.envMapMode) {
  11369. case CubeRefractionMapping:
  11370. case CubeUVRefractionMapping:
  11371. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11372. break;
  11373. }
  11374. }
  11375. return envMapModeDefine;
  11376. }
  11377. function generateEnvMapBlendingDefine(parameters) {
  11378. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11379. if (parameters.envMap) {
  11380. switch (parameters.combine) {
  11381. case MultiplyOperation:
  11382. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11383. break;
  11384. case MixOperation:
  11385. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11386. break;
  11387. case AddOperation:
  11388. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11389. break;
  11390. }
  11391. }
  11392. return envMapBlendingDefine;
  11393. }
  11394. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  11395. // TODO Send this event to Three.js DevTools
  11396. // console.log( 'WebGLProgram', cacheKey );
  11397. const gl = renderer.getContext();
  11398. const defines = parameters.defines;
  11399. let vertexShader = parameters.vertexShader;
  11400. let fragmentShader = parameters.fragmentShader;
  11401. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  11402. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  11403. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  11404. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  11405. const gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  11406. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  11407. const customDefines = generateDefines(defines);
  11408. const program = gl.createProgram();
  11409. let prefixVertex, prefixFragment;
  11410. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11411. if (parameters.isRawShaderMaterial) {
  11412. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  11413. if (prefixVertex.length > 0) {
  11414. prefixVertex += '\n';
  11415. }
  11416. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  11417. if (prefixFragment.length > 0) {
  11418. prefixFragment += '\n';
  11419. }
  11420. } else {
  11421. prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', '#define GAMMA_FACTOR ' + gammaFactorDefine, '#define MAX_BONES ' + parameters.maxBones, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularTintMap ? '#define USE_SPECULARTINTMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', parameters.morphTargets && parameters.isWebGL2 ? '#define MORPHTARGETS_TEXTURE' : '', parameters.morphTargets && parameters.isWebGL2 ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '', 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', '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )', ' 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');
  11422. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, '#define GAMMA_FACTOR ' + gammaFactorDefine, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapTypeDefine : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.envMap ? '#define ' + envMapBlendingDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoat ? '#define USE_CLEARCOAT' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularTintMap ? '#define USE_SPECULARTINTMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.alphaTest ? '#define USE_ALPHATEST' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', (parameters.extensionShaderTextureLOD || parameters.envMap) && parameters.rendererExtensionShaderTextureLod ? '#define TEXTURE_LOD_EXT' : '', 'uniform mat4 viewMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', parameters.toneMapping !== NoToneMapping ? '#define TONE_MAPPING' : '', parameters.toneMapping !== NoToneMapping ? ShaderChunk['tonemapping_pars_fragment'] : '', // this code is required here because it is used by the toneMapping() function defined below
  11423. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', parameters.format === RGBFormat ? '#define OPAQUE' : '', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
  11424. parameters.map ? getTexelDecodingFunction('mapTexelToLinear', parameters.mapEncoding) : '', parameters.matcap ? getTexelDecodingFunction('matcapTexelToLinear', parameters.matcapEncoding) : '', parameters.envMap ? getTexelDecodingFunction('envMapTexelToLinear', parameters.envMapEncoding) : '', parameters.emissiveMap ? getTexelDecodingFunction('emissiveMapTexelToLinear', parameters.emissiveMapEncoding) : '', parameters.specularTintMap ? getTexelDecodingFunction('specularTintMapTexelToLinear', parameters.specularTintMapEncoding) : '', parameters.lightMap ? getTexelDecodingFunction('lightMapTexelToLinear', parameters.lightMapEncoding) : '', getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  11425. }
  11426. vertexShader = resolveIncludes(vertexShader);
  11427. vertexShader = replaceLightNums(vertexShader, parameters);
  11428. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  11429. fragmentShader = resolveIncludes(fragmentShader);
  11430. fragmentShader = replaceLightNums(fragmentShader, parameters);
  11431. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  11432. vertexShader = unrollLoops(vertexShader);
  11433. fragmentShader = unrollLoops(fragmentShader);
  11434. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  11435. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11436. versionString = '#version 300 es\n';
  11437. prefixVertex = ['precision mediump sampler2DArray;', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  11438. 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;
  11439. }
  11440. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11441. const fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  11442. // console.log( '*FRAGMENT*', fragmentGlsl );
  11443. const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl);
  11444. const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl);
  11445. gl.attachShader(program, glVertexShader);
  11446. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  11447. if (parameters.index0AttributeName !== undefined) {
  11448. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  11449. } else if (parameters.morphTargets === true) {
  11450. // programs with morphTargets displace position out of attribute 0
  11451. gl.bindAttribLocation(program, 0, 'position');
  11452. }
  11453. gl.linkProgram(program); // check for link errors
  11454. if (renderer.debug.checkShaderErrors) {
  11455. const programLog = gl.getProgramInfoLog(program).trim();
  11456. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  11457. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  11458. let runnable = true;
  11459. let haveDiagnostics = true;
  11460. if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
  11461. runnable = false;
  11462. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  11463. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  11464. console.error('THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' + 'VALIDATE_STATUS ' + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + '\n\n' + 'Program Info Log: ' + programLog + '\n' + vertexErrors + '\n' + fragmentErrors);
  11465. } else if (programLog !== '') {
  11466. console.warn('THREE.WebGLProgram: Program Info Log:', programLog);
  11467. } else if (vertexLog === '' || fragmentLog === '') {
  11468. haveDiagnostics = false;
  11469. }
  11470. if (haveDiagnostics) {
  11471. this.diagnostics = {
  11472. runnable: runnable,
  11473. programLog: programLog,
  11474. vertexShader: {
  11475. log: vertexLog,
  11476. prefix: prefixVertex
  11477. },
  11478. fragmentShader: {
  11479. log: fragmentLog,
  11480. prefix: prefixFragment
  11481. }
  11482. };
  11483. }
  11484. } // Clean up
  11485. // Crashes in iOS9 and iOS10. #18402
  11486. // gl.detachShader( program, glVertexShader );
  11487. // gl.detachShader( program, glFragmentShader );
  11488. gl.deleteShader(glVertexShader);
  11489. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  11490. let cachedUniforms;
  11491. this.getUniforms = function () {
  11492. if (cachedUniforms === undefined) {
  11493. cachedUniforms = new WebGLUniforms(gl, program);
  11494. }
  11495. return cachedUniforms;
  11496. }; // set up caching for attribute locations
  11497. let cachedAttributes;
  11498. this.getAttributes = function () {
  11499. if (cachedAttributes === undefined) {
  11500. cachedAttributes = fetchAttributeLocations(gl, program);
  11501. }
  11502. return cachedAttributes;
  11503. }; // free resource
  11504. this.destroy = function () {
  11505. bindingStates.releaseStatesOfProgram(this);
  11506. gl.deleteProgram(program);
  11507. this.program = undefined;
  11508. }; //
  11509. this.name = parameters.shaderName;
  11510. this.id = programIdCount++;
  11511. this.cacheKey = cacheKey;
  11512. this.usedTimes = 1;
  11513. this.program = program;
  11514. this.vertexShader = glVertexShader;
  11515. this.fragmentShader = glFragmentShader;
  11516. return this;
  11517. }
  11518. function WebGLPrograms(renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) {
  11519. const programs = [];
  11520. const isWebGL2 = capabilities.isWebGL2;
  11521. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11522. const floatVertexTextures = capabilities.floatVertexTextures;
  11523. const maxVertexUniforms = capabilities.maxVertexUniforms;
  11524. const vertexTextures = capabilities.vertexTextures;
  11525. let precision = capabilities.precision;
  11526. const shaderIDs = {
  11527. MeshDepthMaterial: 'depth',
  11528. MeshDistanceMaterial: 'distanceRGBA',
  11529. MeshNormalMaterial: 'normal',
  11530. MeshBasicMaterial: 'basic',
  11531. MeshLambertMaterial: 'lambert',
  11532. MeshPhongMaterial: 'phong',
  11533. MeshToonMaterial: 'toon',
  11534. MeshStandardMaterial: 'physical',
  11535. MeshPhysicalMaterial: 'physical',
  11536. MeshMatcapMaterial: 'matcap',
  11537. LineBasicMaterial: 'basic',
  11538. LineDashedMaterial: 'dashed',
  11539. PointsMaterial: 'points',
  11540. ShadowMaterial: 'shadow',
  11541. SpriteMaterial: 'sprite'
  11542. };
  11543. const parameterNames = ['precision', 'isWebGL2', 'supportsVertexTextures', 'outputEncoding', 'instancing', 'instancingColor', 'map', 'mapEncoding', 'matcap', 'matcapEncoding', 'envMap', 'envMapMode', 'envMapEncoding', 'envMapCubeUV', 'lightMap', 'lightMapEncoding', 'aoMap', 'emissiveMap', 'emissiveMapEncoding', 'bumpMap', 'normalMap', 'objectSpaceNormalMap', 'tangentSpaceNormalMap', 'clearcoat', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap', 'displacementMap', 'specularMap', 'specularIntensityMap', 'specularTintMap', 'specularTintMapEncoding', 'roughnessMap', 'metalnessMap', 'gradientMap', 'alphaMap', 'alphaTest', 'combine', 'vertexColors', 'vertexAlphas', 'vertexTangents', 'vertexUvs', 'uvsVertexOnly', 'fog', 'useFog', 'fogExp2', 'flatShading', 'sizeAttenuation', 'logarithmicDepthBuffer', 'skinning', 'maxBones', 'useVertexTexture', 'morphTargets', 'morphNormals', 'morphTargetsCount', 'premultipliedAlpha', 'numDirLights', 'numPointLights', 'numSpotLights', 'numHemiLights', 'numRectAreaLights', 'numDirLightShadows', 'numPointLightShadows', 'numSpotLightShadows', 'shadowMapEnabled', 'shadowMapType', 'toneMapping', 'physicallyCorrectLights', 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering', 'format', 'sheen', 'transmission', 'transmissionMap', 'thicknessMap'];
  11544. function getMaxBones(object) {
  11545. const skeleton = object.skeleton;
  11546. const bones = skeleton.bones;
  11547. if (floatVertexTextures) {
  11548. return 1024;
  11549. } else {
  11550. // default for when object is not specified
  11551. // ( for example when prebuilding shader to be used with multiple objects )
  11552. //
  11553. // - leave some extra space for other uniforms
  11554. // - limit here is ANGLE's 254 max uniform vectors
  11555. // (up to 54 should be safe)
  11556. const nVertexUniforms = maxVertexUniforms;
  11557. const nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  11558. const maxBones = Math.min(nVertexMatrices, bones.length);
  11559. if (maxBones < bones.length) {
  11560. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  11561. return 0;
  11562. }
  11563. return maxBones;
  11564. }
  11565. }
  11566. function getTextureEncodingFromMap(map) {
  11567. let encoding;
  11568. if (map && map.isTexture) {
  11569. encoding = map.encoding;
  11570. } else if (map && map.isWebGLRenderTarget) {
  11571. console.warn('THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.');
  11572. encoding = map.texture.encoding;
  11573. } else {
  11574. encoding = LinearEncoding;
  11575. }
  11576. if (isWebGL2 && map && map.isTexture && map.format === RGBAFormat && map.type === UnsignedByteType && map.encoding === sRGBEncoding) {
  11577. encoding = LinearEncoding; // disable inline decode for sRGB textures in WebGL 2
  11578. }
  11579. return encoding;
  11580. }
  11581. function getParameters(material, lights, shadows, scene, object) {
  11582. const fog = scene.fog;
  11583. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11584. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  11585. const shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  11586. // (not to blow over maxLights budget)
  11587. const maxBones = object.isSkinnedMesh ? getMaxBones(object) : 0;
  11588. if (material.precision !== null) {
  11589. precision = capabilities.getMaxPrecision(material.precision);
  11590. if (precision !== material.precision) {
  11591. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  11592. }
  11593. }
  11594. let vertexShader, fragmentShader;
  11595. if (shaderID) {
  11596. const shader = ShaderLib[shaderID];
  11597. vertexShader = shader.vertexShader;
  11598. fragmentShader = shader.fragmentShader;
  11599. } else {
  11600. vertexShader = material.vertexShader;
  11601. fragmentShader = material.fragmentShader;
  11602. }
  11603. const currentRenderTarget = renderer.getRenderTarget();
  11604. const useAlphaTest = material.alphaTest > 0;
  11605. const useClearcoat = material.clearcoat > 0;
  11606. const parameters = {
  11607. isWebGL2: isWebGL2,
  11608. shaderID: shaderID,
  11609. shaderName: material.type,
  11610. vertexShader: vertexShader,
  11611. fragmentShader: fragmentShader,
  11612. defines: material.defines,
  11613. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11614. glslVersion: material.glslVersion,
  11615. precision: precision,
  11616. instancing: object.isInstancedMesh === true,
  11617. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11618. supportsVertexTextures: vertexTextures,
  11619. outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
  11620. map: !!material.map,
  11621. mapEncoding: getTextureEncodingFromMap(material.map),
  11622. matcap: !!material.matcap,
  11623. matcapEncoding: getTextureEncodingFromMap(material.matcap),
  11624. envMap: !!envMap,
  11625. envMapMode: envMap && envMap.mapping,
  11626. envMapEncoding: getTextureEncodingFromMap(envMap),
  11627. envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
  11628. lightMap: !!material.lightMap,
  11629. lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
  11630. aoMap: !!material.aoMap,
  11631. emissiveMap: !!material.emissiveMap,
  11632. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
  11633. bumpMap: !!material.bumpMap,
  11634. normalMap: !!material.normalMap,
  11635. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11636. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11637. clearcoat: useClearcoat,
  11638. clearcoatMap: useClearcoat && !!material.clearcoatMap,
  11639. clearcoatRoughnessMap: useClearcoat && !!material.clearcoatRoughnessMap,
  11640. clearcoatNormalMap: useClearcoat && !!material.clearcoatNormalMap,
  11641. displacementMap: !!material.displacementMap,
  11642. roughnessMap: !!material.roughnessMap,
  11643. metalnessMap: !!material.metalnessMap,
  11644. specularMap: !!material.specularMap,
  11645. specularIntensityMap: !!material.specularIntensityMap,
  11646. specularTintMap: !!material.specularTintMap,
  11647. specularTintMapEncoding: getTextureEncodingFromMap(material.specularTintMap),
  11648. alphaMap: !!material.alphaMap,
  11649. alphaTest: useAlphaTest,
  11650. gradientMap: !!material.gradientMap,
  11651. sheen: material.sheen > 0,
  11652. transmission: material.transmission > 0,
  11653. transmissionMap: !!material.transmissionMap,
  11654. thicknessMap: !!material.thicknessMap,
  11655. combine: material.combine,
  11656. vertexTangents: !!material.normalMap && !!object.geometry && !!object.geometry.attributes.tangent,
  11657. vertexColors: material.vertexColors,
  11658. vertexAlphas: material.vertexColors === true && !!object.geometry && !!object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4,
  11659. vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatMap || !!material.clearcoatRoughnessMap || !!material.clearcoatNormalMap || !!material.displacementMap || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularTintMap,
  11660. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || material.transmission > 0 || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularTintMap) && !!material.displacementMap,
  11661. fog: !!fog,
  11662. useFog: material.fog,
  11663. fogExp2: fog && fog.isFogExp2,
  11664. flatShading: !!material.flatShading,
  11665. sizeAttenuation: material.sizeAttenuation,
  11666. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11667. skinning: object.isSkinnedMesh === true && maxBones > 0,
  11668. maxBones: maxBones,
  11669. useVertexTexture: floatVertexTextures,
  11670. morphTargets: !!object.geometry && !!object.geometry.morphAttributes.position,
  11671. morphNormals: !!object.geometry && !!object.geometry.morphAttributes.normal,
  11672. morphTargetsCount: !!object.geometry && !!object.geometry.morphAttributes.position ? object.geometry.morphAttributes.position.length : 0,
  11673. numDirLights: lights.directional.length,
  11674. numPointLights: lights.point.length,
  11675. numSpotLights: lights.spot.length,
  11676. numRectAreaLights: lights.rectArea.length,
  11677. numHemiLights: lights.hemi.length,
  11678. numDirLightShadows: lights.directionalShadowMap.length,
  11679. numPointLightShadows: lights.pointShadowMap.length,
  11680. numSpotLightShadows: lights.spotShadowMap.length,
  11681. numClippingPlanes: clipping.numPlanes,
  11682. numClipIntersection: clipping.numIntersection,
  11683. format: material.format,
  11684. dithering: material.dithering,
  11685. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11686. shadowMapType: renderer.shadowMap.type,
  11687. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11688. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11689. premultipliedAlpha: material.premultipliedAlpha,
  11690. doubleSided: material.side === DoubleSide,
  11691. flipSided: material.side === BackSide,
  11692. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
  11693. index0AttributeName: material.index0AttributeName,
  11694. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11695. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11696. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11697. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11698. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  11699. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  11700. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  11701. customProgramCacheKey: material.customProgramCacheKey()
  11702. };
  11703. return parameters;
  11704. }
  11705. function getProgramCacheKey(parameters) {
  11706. const array = [];
  11707. if (parameters.shaderID) {
  11708. array.push(parameters.shaderID);
  11709. } else {
  11710. array.push(parameters.fragmentShader);
  11711. array.push(parameters.vertexShader);
  11712. }
  11713. if (parameters.defines !== undefined) {
  11714. for (const name in parameters.defines) {
  11715. array.push(name);
  11716. array.push(parameters.defines[name]);
  11717. }
  11718. }
  11719. if (parameters.isRawShaderMaterial === false) {
  11720. for (let i = 0; i < parameterNames.length; i++) {
  11721. array.push(parameters[parameterNames[i]]);
  11722. }
  11723. array.push(renderer.outputEncoding);
  11724. array.push(renderer.gammaFactor);
  11725. }
  11726. array.push(parameters.customProgramCacheKey);
  11727. return array.join();
  11728. }
  11729. function getUniforms(material) {
  11730. const shaderID = shaderIDs[material.type];
  11731. let uniforms;
  11732. if (shaderID) {
  11733. const shader = ShaderLib[shaderID];
  11734. uniforms = UniformsUtils.clone(shader.uniforms);
  11735. } else {
  11736. uniforms = material.uniforms;
  11737. }
  11738. return uniforms;
  11739. }
  11740. function acquireProgram(parameters, cacheKey) {
  11741. let program; // Check if code has been already compiled
  11742. for (let p = 0, pl = programs.length; p < pl; p++) {
  11743. const preexistingProgram = programs[p];
  11744. if (preexistingProgram.cacheKey === cacheKey) {
  11745. program = preexistingProgram;
  11746. ++program.usedTimes;
  11747. break;
  11748. }
  11749. }
  11750. if (program === undefined) {
  11751. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  11752. programs.push(program);
  11753. }
  11754. return program;
  11755. }
  11756. function releaseProgram(program) {
  11757. if (--program.usedTimes === 0) {
  11758. // Remove from unordered set
  11759. const i = programs.indexOf(program);
  11760. programs[i] = programs[programs.length - 1];
  11761. programs.pop(); // Free WebGL resources
  11762. program.destroy();
  11763. }
  11764. }
  11765. return {
  11766. getParameters: getParameters,
  11767. getProgramCacheKey: getProgramCacheKey,
  11768. getUniforms: getUniforms,
  11769. acquireProgram: acquireProgram,
  11770. releaseProgram: releaseProgram,
  11771. // Exposed for resource monitoring & error feedback via renderer.info:
  11772. programs: programs
  11773. };
  11774. }
  11775. function WebGLProperties() {
  11776. let properties = new WeakMap();
  11777. function get(object) {
  11778. let map = properties.get(object);
  11779. if (map === undefined) {
  11780. map = {};
  11781. properties.set(object, map);
  11782. }
  11783. return map;
  11784. }
  11785. function remove(object) {
  11786. properties.delete(object);
  11787. }
  11788. function update(object, key, value) {
  11789. properties.get(object)[key] = value;
  11790. }
  11791. function dispose() {
  11792. properties = new WeakMap();
  11793. }
  11794. return {
  11795. get: get,
  11796. remove: remove,
  11797. update: update,
  11798. dispose: dispose
  11799. };
  11800. }
  11801. function painterSortStable(a, b) {
  11802. if (a.groupOrder !== b.groupOrder) {
  11803. return a.groupOrder - b.groupOrder;
  11804. } else if (a.renderOrder !== b.renderOrder) {
  11805. return a.renderOrder - b.renderOrder;
  11806. } else if (a.program !== b.program) {
  11807. return a.program.id - b.program.id;
  11808. } else if (a.material.id !== b.material.id) {
  11809. return a.material.id - b.material.id;
  11810. } else if (a.z !== b.z) {
  11811. return a.z - b.z;
  11812. } else {
  11813. return a.id - b.id;
  11814. }
  11815. }
  11816. function reversePainterSortStable(a, b) {
  11817. if (a.groupOrder !== b.groupOrder) {
  11818. return a.groupOrder - b.groupOrder;
  11819. } else if (a.renderOrder !== b.renderOrder) {
  11820. return a.renderOrder - b.renderOrder;
  11821. } else if (a.z !== b.z) {
  11822. return b.z - a.z;
  11823. } else {
  11824. return a.id - b.id;
  11825. }
  11826. }
  11827. function WebGLRenderList(properties) {
  11828. const renderItems = [];
  11829. let renderItemsIndex = 0;
  11830. const opaque = [];
  11831. const transmissive = [];
  11832. const transparent = [];
  11833. const defaultProgram = {
  11834. id: -1
  11835. };
  11836. function init() {
  11837. renderItemsIndex = 0;
  11838. opaque.length = 0;
  11839. transmissive.length = 0;
  11840. transparent.length = 0;
  11841. }
  11842. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  11843. let renderItem = renderItems[renderItemsIndex];
  11844. const materialProperties = properties.get(material);
  11845. if (renderItem === undefined) {
  11846. renderItem = {
  11847. id: object.id,
  11848. object: object,
  11849. geometry: geometry,
  11850. material: material,
  11851. program: materialProperties.program || defaultProgram,
  11852. groupOrder: groupOrder,
  11853. renderOrder: object.renderOrder,
  11854. z: z,
  11855. group: group
  11856. };
  11857. renderItems[renderItemsIndex] = renderItem;
  11858. } else {
  11859. renderItem.id = object.id;
  11860. renderItem.object = object;
  11861. renderItem.geometry = geometry;
  11862. renderItem.material = material;
  11863. renderItem.program = materialProperties.program || defaultProgram;
  11864. renderItem.groupOrder = groupOrder;
  11865. renderItem.renderOrder = object.renderOrder;
  11866. renderItem.z = z;
  11867. renderItem.group = group;
  11868. }
  11869. renderItemsIndex++;
  11870. return renderItem;
  11871. }
  11872. function push(object, geometry, material, groupOrder, z, group) {
  11873. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  11874. if (material.transmission > 0.0) {
  11875. transmissive.push(renderItem);
  11876. } else if (material.transparent === true) {
  11877. transparent.push(renderItem);
  11878. } else {
  11879. opaque.push(renderItem);
  11880. }
  11881. }
  11882. function unshift(object, geometry, material, groupOrder, z, group) {
  11883. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  11884. if (material.transmission > 0.0) {
  11885. transmissive.unshift(renderItem);
  11886. } else if (material.transparent === true) {
  11887. transparent.unshift(renderItem);
  11888. } else {
  11889. opaque.unshift(renderItem);
  11890. }
  11891. }
  11892. function sort(customOpaqueSort, customTransparentSort) {
  11893. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  11894. if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable);
  11895. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  11896. }
  11897. function finish() {
  11898. // Clear references from inactive renderItems in the list
  11899. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  11900. const renderItem = renderItems[i];
  11901. if (renderItem.id === null) break;
  11902. renderItem.id = null;
  11903. renderItem.object = null;
  11904. renderItem.geometry = null;
  11905. renderItem.material = null;
  11906. renderItem.program = null;
  11907. renderItem.group = null;
  11908. }
  11909. }
  11910. return {
  11911. opaque: opaque,
  11912. transmissive: transmissive,
  11913. transparent: transparent,
  11914. init: init,
  11915. push: push,
  11916. unshift: unshift,
  11917. finish: finish,
  11918. sort: sort
  11919. };
  11920. }
  11921. function WebGLRenderLists(properties) {
  11922. let lists = new WeakMap();
  11923. function get(scene, renderCallDepth) {
  11924. let list;
  11925. if (lists.has(scene) === false) {
  11926. list = new WebGLRenderList(properties);
  11927. lists.set(scene, [list]);
  11928. } else {
  11929. if (renderCallDepth >= lists.get(scene).length) {
  11930. list = new WebGLRenderList(properties);
  11931. lists.get(scene).push(list);
  11932. } else {
  11933. list = lists.get(scene)[renderCallDepth];
  11934. }
  11935. }
  11936. return list;
  11937. }
  11938. function dispose() {
  11939. lists = new WeakMap();
  11940. }
  11941. return {
  11942. get: get,
  11943. dispose: dispose
  11944. };
  11945. }
  11946. function UniformsCache() {
  11947. const lights = {};
  11948. return {
  11949. get: function (light) {
  11950. if (lights[light.id] !== undefined) {
  11951. return lights[light.id];
  11952. }
  11953. let uniforms;
  11954. switch (light.type) {
  11955. case 'DirectionalLight':
  11956. uniforms = {
  11957. direction: new Vector3(),
  11958. color: new Color()
  11959. };
  11960. break;
  11961. case 'SpotLight':
  11962. uniforms = {
  11963. position: new Vector3(),
  11964. direction: new Vector3(),
  11965. color: new Color(),
  11966. distance: 0,
  11967. coneCos: 0,
  11968. penumbraCos: 0,
  11969. decay: 0
  11970. };
  11971. break;
  11972. case 'PointLight':
  11973. uniforms = {
  11974. position: new Vector3(),
  11975. color: new Color(),
  11976. distance: 0,
  11977. decay: 0
  11978. };
  11979. break;
  11980. case 'HemisphereLight':
  11981. uniforms = {
  11982. direction: new Vector3(),
  11983. skyColor: new Color(),
  11984. groundColor: new Color()
  11985. };
  11986. break;
  11987. case 'RectAreaLight':
  11988. uniforms = {
  11989. color: new Color(),
  11990. position: new Vector3(),
  11991. halfWidth: new Vector3(),
  11992. halfHeight: new Vector3()
  11993. };
  11994. break;
  11995. }
  11996. lights[light.id] = uniforms;
  11997. return uniforms;
  11998. }
  11999. };
  12000. }
  12001. function ShadowUniformsCache() {
  12002. const lights = {};
  12003. return {
  12004. get: function (light) {
  12005. if (lights[light.id] !== undefined) {
  12006. return lights[light.id];
  12007. }
  12008. let uniforms;
  12009. switch (light.type) {
  12010. case 'DirectionalLight':
  12011. uniforms = {
  12012. shadowBias: 0,
  12013. shadowNormalBias: 0,
  12014. shadowRadius: 1,
  12015. shadowMapSize: new Vector2()
  12016. };
  12017. break;
  12018. case 'SpotLight':
  12019. uniforms = {
  12020. shadowBias: 0,
  12021. shadowNormalBias: 0,
  12022. shadowRadius: 1,
  12023. shadowMapSize: new Vector2()
  12024. };
  12025. break;
  12026. case 'PointLight':
  12027. uniforms = {
  12028. shadowBias: 0,
  12029. shadowNormalBias: 0,
  12030. shadowRadius: 1,
  12031. shadowMapSize: new Vector2(),
  12032. shadowCameraNear: 1,
  12033. shadowCameraFar: 1000
  12034. };
  12035. break;
  12036. // TODO (abelnation): set RectAreaLight shadow uniforms
  12037. }
  12038. lights[light.id] = uniforms;
  12039. return uniforms;
  12040. }
  12041. };
  12042. }
  12043. let nextVersion = 0;
  12044. function shadowCastingLightsFirst(lightA, lightB) {
  12045. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  12046. }
  12047. function WebGLLights(extensions, capabilities) {
  12048. const cache = new UniformsCache();
  12049. const shadowCache = ShadowUniformsCache();
  12050. const state = {
  12051. version: 0,
  12052. hash: {
  12053. directionalLength: -1,
  12054. pointLength: -1,
  12055. spotLength: -1,
  12056. rectAreaLength: -1,
  12057. hemiLength: -1,
  12058. numDirectionalShadows: -1,
  12059. numPointShadows: -1,
  12060. numSpotShadows: -1
  12061. },
  12062. ambient: [0, 0, 0],
  12063. probe: [],
  12064. directional: [],
  12065. directionalShadow: [],
  12066. directionalShadowMap: [],
  12067. directionalShadowMatrix: [],
  12068. spot: [],
  12069. spotShadow: [],
  12070. spotShadowMap: [],
  12071. spotShadowMatrix: [],
  12072. rectArea: [],
  12073. rectAreaLTC1: null,
  12074. rectAreaLTC2: null,
  12075. point: [],
  12076. pointShadow: [],
  12077. pointShadowMap: [],
  12078. pointShadowMatrix: [],
  12079. hemi: []
  12080. };
  12081. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  12082. const vector3 = new Vector3();
  12083. const matrix4 = new Matrix4();
  12084. const matrix42 = new Matrix4();
  12085. function setup(lights, physicallyCorrectLights) {
  12086. let r = 0,
  12087. g = 0,
  12088. b = 0;
  12089. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  12090. let directionalLength = 0;
  12091. let pointLength = 0;
  12092. let spotLength = 0;
  12093. let rectAreaLength = 0;
  12094. let hemiLength = 0;
  12095. let numDirectionalShadows = 0;
  12096. let numPointShadows = 0;
  12097. let numSpotShadows = 0;
  12098. lights.sort(shadowCastingLightsFirst); // artist-friendly light intensity scaling factor
  12099. const scaleFactor = physicallyCorrectLights !== true ? Math.PI : 1;
  12100. for (let i = 0, l = lights.length; i < l; i++) {
  12101. const light = lights[i];
  12102. const color = light.color;
  12103. const intensity = light.intensity;
  12104. const distance = light.distance;
  12105. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  12106. if (light.isAmbientLight) {
  12107. r += color.r * intensity * scaleFactor;
  12108. g += color.g * intensity * scaleFactor;
  12109. b += color.b * intensity * scaleFactor;
  12110. } else if (light.isLightProbe) {
  12111. for (let j = 0; j < 9; j++) {
  12112. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  12113. }
  12114. } else if (light.isDirectionalLight) {
  12115. const uniforms = cache.get(light);
  12116. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  12117. if (light.castShadow) {
  12118. const shadow = light.shadow;
  12119. const shadowUniforms = shadowCache.get(light);
  12120. shadowUniforms.shadowBias = shadow.bias;
  12121. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12122. shadowUniforms.shadowRadius = shadow.radius;
  12123. shadowUniforms.shadowMapSize = shadow.mapSize;
  12124. state.directionalShadow[directionalLength] = shadowUniforms;
  12125. state.directionalShadowMap[directionalLength] = shadowMap;
  12126. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  12127. numDirectionalShadows++;
  12128. }
  12129. state.directional[directionalLength] = uniforms;
  12130. directionalLength++;
  12131. } else if (light.isSpotLight) {
  12132. const uniforms = cache.get(light);
  12133. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12134. uniforms.color.copy(color).multiplyScalar(intensity * scaleFactor);
  12135. uniforms.distance = distance;
  12136. uniforms.coneCos = Math.cos(light.angle);
  12137. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  12138. uniforms.decay = light.decay;
  12139. if (light.castShadow) {
  12140. const shadow = light.shadow;
  12141. const shadowUniforms = shadowCache.get(light);
  12142. shadowUniforms.shadowBias = shadow.bias;
  12143. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12144. shadowUniforms.shadowRadius = shadow.radius;
  12145. shadowUniforms.shadowMapSize = shadow.mapSize;
  12146. state.spotShadow[spotLength] = shadowUniforms;
  12147. state.spotShadowMap[spotLength] = shadowMap;
  12148. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  12149. numSpotShadows++;
  12150. }
  12151. state.spot[spotLength] = uniforms;
  12152. spotLength++;
  12153. } else if (light.isRectAreaLight) {
  12154. const uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  12155. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  12156. // (b) intensity is the brightness of the light
  12157. uniforms.color.copy(color).multiplyScalar(intensity);
  12158. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12159. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12160. state.rectArea[rectAreaLength] = uniforms;
  12161. rectAreaLength++;
  12162. } else if (light.isPointLight) {
  12163. const uniforms = cache.get(light);
  12164. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  12165. uniforms.distance = light.distance;
  12166. uniforms.decay = light.decay;
  12167. if (light.castShadow) {
  12168. const shadow = light.shadow;
  12169. const shadowUniforms = shadowCache.get(light);
  12170. shadowUniforms.shadowBias = shadow.bias;
  12171. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12172. shadowUniforms.shadowRadius = shadow.radius;
  12173. shadowUniforms.shadowMapSize = shadow.mapSize;
  12174. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12175. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12176. state.pointShadow[pointLength] = shadowUniforms;
  12177. state.pointShadowMap[pointLength] = shadowMap;
  12178. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  12179. numPointShadows++;
  12180. }
  12181. state.point[pointLength] = uniforms;
  12182. pointLength++;
  12183. } else if (light.isHemisphereLight) {
  12184. const uniforms = cache.get(light);
  12185. uniforms.skyColor.copy(light.color).multiplyScalar(intensity * scaleFactor);
  12186. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity * scaleFactor);
  12187. state.hemi[hemiLength] = uniforms;
  12188. hemiLength++;
  12189. }
  12190. }
  12191. if (rectAreaLength > 0) {
  12192. if (capabilities.isWebGL2) {
  12193. // WebGL 2
  12194. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12195. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12196. } else {
  12197. // WebGL 1
  12198. if (extensions.has('OES_texture_float_linear') === true) {
  12199. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12200. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12201. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  12202. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12203. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12204. } else {
  12205. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  12206. }
  12207. }
  12208. }
  12209. state.ambient[0] = r;
  12210. state.ambient[1] = g;
  12211. state.ambient[2] = b;
  12212. const hash = state.hash;
  12213. 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) {
  12214. state.directional.length = directionalLength;
  12215. state.spot.length = spotLength;
  12216. state.rectArea.length = rectAreaLength;
  12217. state.point.length = pointLength;
  12218. state.hemi.length = hemiLength;
  12219. state.directionalShadow.length = numDirectionalShadows;
  12220. state.directionalShadowMap.length = numDirectionalShadows;
  12221. state.pointShadow.length = numPointShadows;
  12222. state.pointShadowMap.length = numPointShadows;
  12223. state.spotShadow.length = numSpotShadows;
  12224. state.spotShadowMap.length = numSpotShadows;
  12225. state.directionalShadowMatrix.length = numDirectionalShadows;
  12226. state.pointShadowMatrix.length = numPointShadows;
  12227. state.spotShadowMatrix.length = numSpotShadows;
  12228. hash.directionalLength = directionalLength;
  12229. hash.pointLength = pointLength;
  12230. hash.spotLength = spotLength;
  12231. hash.rectAreaLength = rectAreaLength;
  12232. hash.hemiLength = hemiLength;
  12233. hash.numDirectionalShadows = numDirectionalShadows;
  12234. hash.numPointShadows = numPointShadows;
  12235. hash.numSpotShadows = numSpotShadows;
  12236. state.version = nextVersion++;
  12237. }
  12238. }
  12239. function setupView(lights, camera) {
  12240. let directionalLength = 0;
  12241. let pointLength = 0;
  12242. let spotLength = 0;
  12243. let rectAreaLength = 0;
  12244. let hemiLength = 0;
  12245. const viewMatrix = camera.matrixWorldInverse;
  12246. for (let i = 0, l = lights.length; i < l; i++) {
  12247. const light = lights[i];
  12248. if (light.isDirectionalLight) {
  12249. const uniforms = state.directional[directionalLength];
  12250. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12251. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12252. uniforms.direction.sub(vector3);
  12253. uniforms.direction.transformDirection(viewMatrix);
  12254. directionalLength++;
  12255. } else if (light.isSpotLight) {
  12256. const uniforms = state.spot[spotLength];
  12257. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12258. uniforms.position.applyMatrix4(viewMatrix);
  12259. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12260. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12261. uniforms.direction.sub(vector3);
  12262. uniforms.direction.transformDirection(viewMatrix);
  12263. spotLength++;
  12264. } else if (light.isRectAreaLight) {
  12265. const uniforms = state.rectArea[rectAreaLength];
  12266. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12267. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  12268. matrix42.identity();
  12269. matrix4.copy(light.matrixWorld);
  12270. matrix4.premultiply(viewMatrix);
  12271. matrix42.extractRotation(matrix4);
  12272. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12273. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12274. uniforms.halfWidth.applyMatrix4(matrix42);
  12275. uniforms.halfHeight.applyMatrix4(matrix42);
  12276. rectAreaLength++;
  12277. } else if (light.isPointLight) {
  12278. const uniforms = state.point[pointLength];
  12279. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12280. uniforms.position.applyMatrix4(viewMatrix);
  12281. pointLength++;
  12282. } else if (light.isHemisphereLight) {
  12283. const uniforms = state.hemi[hemiLength];
  12284. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12285. uniforms.direction.transformDirection(viewMatrix);
  12286. uniforms.direction.normalize();
  12287. hemiLength++;
  12288. }
  12289. }
  12290. }
  12291. return {
  12292. setup: setup,
  12293. setupView: setupView,
  12294. state: state
  12295. };
  12296. }
  12297. function WebGLRenderState(extensions, capabilities) {
  12298. const lights = new WebGLLights(extensions, capabilities);
  12299. const lightsArray = [];
  12300. const shadowsArray = [];
  12301. function init() {
  12302. lightsArray.length = 0;
  12303. shadowsArray.length = 0;
  12304. }
  12305. function pushLight(light) {
  12306. lightsArray.push(light);
  12307. }
  12308. function pushShadow(shadowLight) {
  12309. shadowsArray.push(shadowLight);
  12310. }
  12311. function setupLights(physicallyCorrectLights) {
  12312. lights.setup(lightsArray, physicallyCorrectLights);
  12313. }
  12314. function setupLightsView(camera) {
  12315. lights.setupView(lightsArray, camera);
  12316. }
  12317. const state = {
  12318. lightsArray: lightsArray,
  12319. shadowsArray: shadowsArray,
  12320. lights: lights
  12321. };
  12322. return {
  12323. init: init,
  12324. state: state,
  12325. setupLights: setupLights,
  12326. setupLightsView: setupLightsView,
  12327. pushLight: pushLight,
  12328. pushShadow: pushShadow
  12329. };
  12330. }
  12331. function WebGLRenderStates(extensions, capabilities) {
  12332. let renderStates = new WeakMap();
  12333. function get(scene, renderCallDepth = 0) {
  12334. let renderState;
  12335. if (renderStates.has(scene) === false) {
  12336. renderState = new WebGLRenderState(extensions, capabilities);
  12337. renderStates.set(scene, [renderState]);
  12338. } else {
  12339. if (renderCallDepth >= renderStates.get(scene).length) {
  12340. renderState = new WebGLRenderState(extensions, capabilities);
  12341. renderStates.get(scene).push(renderState);
  12342. } else {
  12343. renderState = renderStates.get(scene)[renderCallDepth];
  12344. }
  12345. }
  12346. return renderState;
  12347. }
  12348. function dispose() {
  12349. renderStates = new WeakMap();
  12350. }
  12351. return {
  12352. get: get,
  12353. dispose: dispose
  12354. };
  12355. }
  12356. /**
  12357. * parameters = {
  12358. *
  12359. * opacity: <float>,
  12360. *
  12361. * map: new THREE.Texture( <Image> ),
  12362. *
  12363. * alphaMap: new THREE.Texture( <Image> ),
  12364. *
  12365. * displacementMap: new THREE.Texture( <Image> ),
  12366. * displacementScale: <float>,
  12367. * displacementBias: <float>,
  12368. *
  12369. * wireframe: <boolean>,
  12370. * wireframeLinewidth: <float>
  12371. * }
  12372. */
  12373. class MeshDepthMaterial extends Material {
  12374. constructor(parameters) {
  12375. super();
  12376. this.type = 'MeshDepthMaterial';
  12377. this.depthPacking = BasicDepthPacking;
  12378. this.map = null;
  12379. this.alphaMap = null;
  12380. this.displacementMap = null;
  12381. this.displacementScale = 1;
  12382. this.displacementBias = 0;
  12383. this.wireframe = false;
  12384. this.wireframeLinewidth = 1;
  12385. this.fog = false;
  12386. this.setValues(parameters);
  12387. }
  12388. copy(source) {
  12389. super.copy(source);
  12390. this.depthPacking = source.depthPacking;
  12391. this.map = source.map;
  12392. this.alphaMap = source.alphaMap;
  12393. this.displacementMap = source.displacementMap;
  12394. this.displacementScale = source.displacementScale;
  12395. this.displacementBias = source.displacementBias;
  12396. this.wireframe = source.wireframe;
  12397. this.wireframeLinewidth = source.wireframeLinewidth;
  12398. return this;
  12399. }
  12400. }
  12401. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  12402. /**
  12403. * parameters = {
  12404. *
  12405. * referencePosition: <float>,
  12406. * nearDistance: <float>,
  12407. * farDistance: <float>,
  12408. *
  12409. * map: new THREE.Texture( <Image> ),
  12410. *
  12411. * alphaMap: new THREE.Texture( <Image> ),
  12412. *
  12413. * displacementMap: new THREE.Texture( <Image> ),
  12414. * displacementScale: <float>,
  12415. * displacementBias: <float>
  12416. *
  12417. * }
  12418. */
  12419. class MeshDistanceMaterial extends Material {
  12420. constructor(parameters) {
  12421. super();
  12422. this.type = 'MeshDistanceMaterial';
  12423. this.referencePosition = new Vector3();
  12424. this.nearDistance = 1;
  12425. this.farDistance = 1000;
  12426. this.map = null;
  12427. this.alphaMap = null;
  12428. this.displacementMap = null;
  12429. this.displacementScale = 1;
  12430. this.displacementBias = 0;
  12431. this.fog = false;
  12432. this.setValues(parameters);
  12433. }
  12434. copy(source) {
  12435. super.copy(source);
  12436. this.referencePosition.copy(source.referencePosition);
  12437. this.nearDistance = source.nearDistance;
  12438. this.farDistance = source.farDistance;
  12439. this.map = source.map;
  12440. this.alphaMap = source.alphaMap;
  12441. this.displacementMap = source.displacementMap;
  12442. this.displacementScale = source.displacementScale;
  12443. this.displacementBias = source.displacementBias;
  12444. return this;
  12445. }
  12446. }
  12447. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  12448. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12449. const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\nuniform float samples;\n#include <packing>\nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  12450. function WebGLShadowMap(_renderer, _objects, _capabilities) {
  12451. let _frustum = new Frustum();
  12452. const _shadowMapSize = new Vector2(),
  12453. _viewportSize = new Vector2(),
  12454. _viewport = new Vector4(),
  12455. _depthMaterial = new MeshDepthMaterial({
  12456. depthPacking: RGBADepthPacking
  12457. }),
  12458. _distanceMaterial = new MeshDistanceMaterial(),
  12459. _materialCache = {},
  12460. _maxTextureSize = _capabilities.maxTextureSize;
  12461. const shadowSide = {
  12462. 0: BackSide,
  12463. 1: FrontSide,
  12464. 2: DoubleSide
  12465. };
  12466. const shadowMaterialVertical = new ShaderMaterial({
  12467. uniforms: {
  12468. shadow_pass: {
  12469. value: null
  12470. },
  12471. resolution: {
  12472. value: new Vector2()
  12473. },
  12474. radius: {
  12475. value: 4.0
  12476. },
  12477. samples: {
  12478. value: 8.0
  12479. }
  12480. },
  12481. vertexShader: vertex,
  12482. fragmentShader: fragment
  12483. });
  12484. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12485. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12486. const fullScreenTri = new BufferGeometry();
  12487. fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  12488. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  12489. const scope = this;
  12490. this.enabled = false;
  12491. this.autoUpdate = true;
  12492. this.needsUpdate = false;
  12493. this.type = PCFShadowMap;
  12494. this.render = function (lights, scene, camera) {
  12495. if (scope.enabled === false) return;
  12496. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  12497. if (lights.length === 0) return;
  12498. const currentRenderTarget = _renderer.getRenderTarget();
  12499. const activeCubeFace = _renderer.getActiveCubeFace();
  12500. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12501. const _state = _renderer.state; // Set GL state for depth map.
  12502. _state.setBlending(NoBlending);
  12503. _state.buffers.color.setClear(1, 1, 1, 1);
  12504. _state.buffers.depth.setTest(true);
  12505. _state.setScissorTest(false); // render depth map
  12506. for (let i = 0, il = lights.length; i < il; i++) {
  12507. const light = lights[i];
  12508. const shadow = light.shadow;
  12509. if (shadow === undefined) {
  12510. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  12511. continue;
  12512. }
  12513. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  12514. _shadowMapSize.copy(shadow.mapSize);
  12515. const shadowFrameExtents = shadow.getFrameExtents();
  12516. _shadowMapSize.multiply(shadowFrameExtents);
  12517. _viewportSize.copy(shadow.mapSize);
  12518. if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) {
  12519. if (_shadowMapSize.x > _maxTextureSize) {
  12520. _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x);
  12521. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12522. shadow.mapSize.x = _viewportSize.x;
  12523. }
  12524. if (_shadowMapSize.y > _maxTextureSize) {
  12525. _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y);
  12526. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12527. shadow.mapSize.y = _viewportSize.y;
  12528. }
  12529. }
  12530. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12531. const pars = {
  12532. minFilter: LinearFilter,
  12533. magFilter: LinearFilter,
  12534. format: RGBAFormat
  12535. };
  12536. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12537. shadow.map.texture.name = light.name + '.shadowMap';
  12538. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12539. shadow.camera.updateProjectionMatrix();
  12540. }
  12541. if (shadow.map === null) {
  12542. const pars = {
  12543. minFilter: NearestFilter,
  12544. magFilter: NearestFilter,
  12545. format: RGBAFormat
  12546. };
  12547. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12548. shadow.map.texture.name = light.name + '.shadowMap';
  12549. shadow.camera.updateProjectionMatrix();
  12550. }
  12551. _renderer.setRenderTarget(shadow.map);
  12552. _renderer.clear();
  12553. const viewportCount = shadow.getViewportCount();
  12554. for (let vp = 0; vp < viewportCount; vp++) {
  12555. const viewport = shadow.getViewport(vp);
  12556. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  12557. _state.viewport(_viewport);
  12558. shadow.updateMatrices(light, vp);
  12559. _frustum = shadow.getFrustum();
  12560. renderObject(scene, camera, shadow.camera, light, this.type);
  12561. } // do blur pass for VSM
  12562. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12563. VSMPass(shadow, camera);
  12564. }
  12565. shadow.needsUpdate = false;
  12566. }
  12567. scope.needsUpdate = false;
  12568. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  12569. };
  12570. function VSMPass(shadow, camera) {
  12571. const geometry = _objects.update(fullScreenMesh); // vertical pass
  12572. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12573. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12574. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12575. shadowMaterialVertical.uniforms.samples.value = shadow.blurSamples;
  12576. _renderer.setRenderTarget(shadow.mapPass);
  12577. _renderer.clear();
  12578. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizontal pass
  12579. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12580. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12581. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12582. shadowMaterialHorizontal.uniforms.samples.value = shadow.blurSamples;
  12583. _renderer.setRenderTarget(shadow.map);
  12584. _renderer.clear();
  12585. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  12586. }
  12587. function getDepthMaterial(object, geometry, material, light, shadowCameraNear, shadowCameraFar, type) {
  12588. let result = null;
  12589. const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial;
  12590. if (customMaterial !== undefined) {
  12591. result = customMaterial;
  12592. } else {
  12593. result = light.isPointLight === true ? _distanceMaterial : _depthMaterial;
  12594. }
  12595. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0) {
  12596. // in this case we need a unique material instance reflecting the
  12597. // appropriate state
  12598. const keyA = result.uuid,
  12599. keyB = material.uuid;
  12600. let materialsForVariant = _materialCache[keyA];
  12601. if (materialsForVariant === undefined) {
  12602. materialsForVariant = {};
  12603. _materialCache[keyA] = materialsForVariant;
  12604. }
  12605. let cachedMaterial = materialsForVariant[keyB];
  12606. if (cachedMaterial === undefined) {
  12607. cachedMaterial = result.clone();
  12608. materialsForVariant[keyB] = cachedMaterial;
  12609. }
  12610. result = cachedMaterial;
  12611. }
  12612. result.visible = material.visible;
  12613. result.wireframe = material.wireframe;
  12614. if (type === VSMShadowMap) {
  12615. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  12616. } else {
  12617. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  12618. }
  12619. result.alphaMap = material.alphaMap;
  12620. result.alphaTest = material.alphaTest;
  12621. result.clipShadows = material.clipShadows;
  12622. result.clippingPlanes = material.clippingPlanes;
  12623. result.clipIntersection = material.clipIntersection;
  12624. result.displacementMap = material.displacementMap;
  12625. result.displacementScale = material.displacementScale;
  12626. result.displacementBias = material.displacementBias;
  12627. result.wireframeLinewidth = material.wireframeLinewidth;
  12628. result.linewidth = material.linewidth;
  12629. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  12630. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  12631. result.nearDistance = shadowCameraNear;
  12632. result.farDistance = shadowCameraFar;
  12633. }
  12634. return result;
  12635. }
  12636. function renderObject(object, camera, shadowCamera, light, type) {
  12637. if (object.visible === false) return;
  12638. const visible = object.layers.test(camera.layers);
  12639. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  12640. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  12641. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  12642. const geometry = _objects.update(object);
  12643. const material = object.material;
  12644. if (Array.isArray(material)) {
  12645. const groups = geometry.groups;
  12646. for (let k = 0, kl = groups.length; k < kl; k++) {
  12647. const group = groups[k];
  12648. const groupMaterial = material[group.materialIndex];
  12649. if (groupMaterial && groupMaterial.visible) {
  12650. const depthMaterial = getDepthMaterial(object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  12651. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  12652. }
  12653. }
  12654. } else if (material.visible) {
  12655. const depthMaterial = getDepthMaterial(object, geometry, material, light, shadowCamera.near, shadowCamera.far, type);
  12656. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  12657. }
  12658. }
  12659. }
  12660. const children = object.children;
  12661. for (let i = 0, l = children.length; i < l; i++) {
  12662. renderObject(children[i], camera, shadowCamera, light, type);
  12663. }
  12664. }
  12665. }
  12666. function WebGLState(gl, extensions, capabilities) {
  12667. const isWebGL2 = capabilities.isWebGL2;
  12668. function ColorBuffer() {
  12669. let locked = false;
  12670. const color = new Vector4();
  12671. let currentColorMask = null;
  12672. const currentColorClear = new Vector4(0, 0, 0, 0);
  12673. return {
  12674. setMask: function (colorMask) {
  12675. if (currentColorMask !== colorMask && !locked) {
  12676. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  12677. currentColorMask = colorMask;
  12678. }
  12679. },
  12680. setLocked: function (lock) {
  12681. locked = lock;
  12682. },
  12683. setClear: function (r, g, b, a, premultipliedAlpha) {
  12684. if (premultipliedAlpha === true) {
  12685. r *= a;
  12686. g *= a;
  12687. b *= a;
  12688. }
  12689. color.set(r, g, b, a);
  12690. if (currentColorClear.equals(color) === false) {
  12691. gl.clearColor(r, g, b, a);
  12692. currentColorClear.copy(color);
  12693. }
  12694. },
  12695. reset: function () {
  12696. locked = false;
  12697. currentColorMask = null;
  12698. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  12699. }
  12700. };
  12701. }
  12702. function DepthBuffer() {
  12703. let locked = false;
  12704. let currentDepthMask = null;
  12705. let currentDepthFunc = null;
  12706. let currentDepthClear = null;
  12707. return {
  12708. setTest: function (depthTest) {
  12709. if (depthTest) {
  12710. enable(gl.DEPTH_TEST);
  12711. } else {
  12712. disable(gl.DEPTH_TEST);
  12713. }
  12714. },
  12715. setMask: function (depthMask) {
  12716. if (currentDepthMask !== depthMask && !locked) {
  12717. gl.depthMask(depthMask);
  12718. currentDepthMask = depthMask;
  12719. }
  12720. },
  12721. setFunc: function (depthFunc) {
  12722. if (currentDepthFunc !== depthFunc) {
  12723. if (depthFunc) {
  12724. switch (depthFunc) {
  12725. case NeverDepth:
  12726. gl.depthFunc(gl.NEVER);
  12727. break;
  12728. case AlwaysDepth:
  12729. gl.depthFunc(gl.ALWAYS);
  12730. break;
  12731. case LessDepth:
  12732. gl.depthFunc(gl.LESS);
  12733. break;
  12734. case LessEqualDepth:
  12735. gl.depthFunc(gl.LEQUAL);
  12736. break;
  12737. case EqualDepth:
  12738. gl.depthFunc(gl.EQUAL);
  12739. break;
  12740. case GreaterEqualDepth:
  12741. gl.depthFunc(gl.GEQUAL);
  12742. break;
  12743. case GreaterDepth:
  12744. gl.depthFunc(gl.GREATER);
  12745. break;
  12746. case NotEqualDepth:
  12747. gl.depthFunc(gl.NOTEQUAL);
  12748. break;
  12749. default:
  12750. gl.depthFunc(gl.LEQUAL);
  12751. }
  12752. } else {
  12753. gl.depthFunc(gl.LEQUAL);
  12754. }
  12755. currentDepthFunc = depthFunc;
  12756. }
  12757. },
  12758. setLocked: function (lock) {
  12759. locked = lock;
  12760. },
  12761. setClear: function (depth) {
  12762. if (currentDepthClear !== depth) {
  12763. gl.clearDepth(depth);
  12764. currentDepthClear = depth;
  12765. }
  12766. },
  12767. reset: function () {
  12768. locked = false;
  12769. currentDepthMask = null;
  12770. currentDepthFunc = null;
  12771. currentDepthClear = null;
  12772. }
  12773. };
  12774. }
  12775. function StencilBuffer() {
  12776. let locked = false;
  12777. let currentStencilMask = null;
  12778. let currentStencilFunc = null;
  12779. let currentStencilRef = null;
  12780. let currentStencilFuncMask = null;
  12781. let currentStencilFail = null;
  12782. let currentStencilZFail = null;
  12783. let currentStencilZPass = null;
  12784. let currentStencilClear = null;
  12785. return {
  12786. setTest: function (stencilTest) {
  12787. if (!locked) {
  12788. if (stencilTest) {
  12789. enable(gl.STENCIL_TEST);
  12790. } else {
  12791. disable(gl.STENCIL_TEST);
  12792. }
  12793. }
  12794. },
  12795. setMask: function (stencilMask) {
  12796. if (currentStencilMask !== stencilMask && !locked) {
  12797. gl.stencilMask(stencilMask);
  12798. currentStencilMask = stencilMask;
  12799. }
  12800. },
  12801. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  12802. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  12803. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  12804. currentStencilFunc = stencilFunc;
  12805. currentStencilRef = stencilRef;
  12806. currentStencilFuncMask = stencilMask;
  12807. }
  12808. },
  12809. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  12810. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  12811. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  12812. currentStencilFail = stencilFail;
  12813. currentStencilZFail = stencilZFail;
  12814. currentStencilZPass = stencilZPass;
  12815. }
  12816. },
  12817. setLocked: function (lock) {
  12818. locked = lock;
  12819. },
  12820. setClear: function (stencil) {
  12821. if (currentStencilClear !== stencil) {
  12822. gl.clearStencil(stencil);
  12823. currentStencilClear = stencil;
  12824. }
  12825. },
  12826. reset: function () {
  12827. locked = false;
  12828. currentStencilMask = null;
  12829. currentStencilFunc = null;
  12830. currentStencilRef = null;
  12831. currentStencilFuncMask = null;
  12832. currentStencilFail = null;
  12833. currentStencilZFail = null;
  12834. currentStencilZPass = null;
  12835. currentStencilClear = null;
  12836. }
  12837. };
  12838. } //
  12839. const colorBuffer = new ColorBuffer();
  12840. const depthBuffer = new DepthBuffer();
  12841. const stencilBuffer = new StencilBuffer();
  12842. let enabledCapabilities = {};
  12843. let xrFramebuffer = null;
  12844. let currentBoundFramebuffers = {};
  12845. let currentProgram = null;
  12846. let currentBlendingEnabled = false;
  12847. let currentBlending = null;
  12848. let currentBlendEquation = null;
  12849. let currentBlendSrc = null;
  12850. let currentBlendDst = null;
  12851. let currentBlendEquationAlpha = null;
  12852. let currentBlendSrcAlpha = null;
  12853. let currentBlendDstAlpha = null;
  12854. let currentPremultipledAlpha = false;
  12855. let currentFlipSided = null;
  12856. let currentCullFace = null;
  12857. let currentLineWidth = null;
  12858. let currentPolygonOffsetFactor = null;
  12859. let currentPolygonOffsetUnits = null;
  12860. const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12861. let lineWidthAvailable = false;
  12862. let version = 0;
  12863. const glVersion = gl.getParameter(gl.VERSION);
  12864. if (glVersion.indexOf('WebGL') !== -1) {
  12865. version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
  12866. lineWidthAvailable = version >= 1.0;
  12867. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  12868. version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
  12869. lineWidthAvailable = version >= 2.0;
  12870. }
  12871. let currentTextureSlot = null;
  12872. let currentBoundTextures = {};
  12873. const scissorParam = gl.getParameter(gl.SCISSOR_BOX);
  12874. const viewportParam = gl.getParameter(gl.VIEWPORT);
  12875. const currentScissor = new Vector4().fromArray(scissorParam);
  12876. const currentViewport = new Vector4().fromArray(viewportParam);
  12877. function createTexture(type, target, count) {
  12878. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  12879. const texture = gl.createTexture();
  12880. gl.bindTexture(type, texture);
  12881. gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12882. gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12883. for (let i = 0; i < count; i++) {
  12884. gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
  12885. }
  12886. return texture;
  12887. }
  12888. const emptyTextures = {};
  12889. emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1);
  12890. emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); // init
  12891. colorBuffer.setClear(0, 0, 0, 1);
  12892. depthBuffer.setClear(1);
  12893. stencilBuffer.setClear(0);
  12894. enable(gl.DEPTH_TEST);
  12895. depthBuffer.setFunc(LessEqualDepth);
  12896. setFlipSided(false);
  12897. setCullFace(CullFaceBack);
  12898. enable(gl.CULL_FACE);
  12899. setBlending(NoBlending); //
  12900. function enable(id) {
  12901. if (enabledCapabilities[id] !== true) {
  12902. gl.enable(id);
  12903. enabledCapabilities[id] = true;
  12904. }
  12905. }
  12906. function disable(id) {
  12907. if (enabledCapabilities[id] !== false) {
  12908. gl.disable(id);
  12909. enabledCapabilities[id] = false;
  12910. }
  12911. }
  12912. function bindXRFramebuffer(framebuffer) {
  12913. if (framebuffer !== xrFramebuffer) {
  12914. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  12915. xrFramebuffer = framebuffer;
  12916. }
  12917. }
  12918. function bindFramebuffer(target, framebuffer) {
  12919. if (framebuffer === null && xrFramebuffer !== null) framebuffer = xrFramebuffer; // use active XR framebuffer if available
  12920. if (currentBoundFramebuffers[target] !== framebuffer) {
  12921. gl.bindFramebuffer(target, framebuffer);
  12922. currentBoundFramebuffers[target] = framebuffer;
  12923. if (isWebGL2) {
  12924. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  12925. if (target === gl.DRAW_FRAMEBUFFER) {
  12926. currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer;
  12927. }
  12928. if (target === gl.FRAMEBUFFER) {
  12929. currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer;
  12930. }
  12931. }
  12932. return true;
  12933. }
  12934. return false;
  12935. }
  12936. function useProgram(program) {
  12937. if (currentProgram !== program) {
  12938. gl.useProgram(program);
  12939. currentProgram = program;
  12940. return true;
  12941. }
  12942. return false;
  12943. }
  12944. const equationToGL = {
  12945. [AddEquation]: gl.FUNC_ADD,
  12946. [SubtractEquation]: gl.FUNC_SUBTRACT,
  12947. [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT
  12948. };
  12949. if (isWebGL2) {
  12950. equationToGL[MinEquation] = gl.MIN;
  12951. equationToGL[MaxEquation] = gl.MAX;
  12952. } else {
  12953. const extension = extensions.get('EXT_blend_minmax');
  12954. if (extension !== null) {
  12955. equationToGL[MinEquation] = extension.MIN_EXT;
  12956. equationToGL[MaxEquation] = extension.MAX_EXT;
  12957. }
  12958. }
  12959. const factorToGL = {
  12960. [ZeroFactor]: gl.ZERO,
  12961. [OneFactor]: gl.ONE,
  12962. [SrcColorFactor]: gl.SRC_COLOR,
  12963. [SrcAlphaFactor]: gl.SRC_ALPHA,
  12964. [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE,
  12965. [DstColorFactor]: gl.DST_COLOR,
  12966. [DstAlphaFactor]: gl.DST_ALPHA,
  12967. [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR,
  12968. [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA,
  12969. [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR,
  12970. [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA
  12971. };
  12972. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  12973. if (blending === NoBlending) {
  12974. if (currentBlendingEnabled === true) {
  12975. disable(gl.BLEND);
  12976. currentBlendingEnabled = false;
  12977. }
  12978. return;
  12979. }
  12980. if (currentBlendingEnabled === false) {
  12981. enable(gl.BLEND);
  12982. currentBlendingEnabled = true;
  12983. }
  12984. if (blending !== CustomBlending) {
  12985. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  12986. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  12987. gl.blendEquation(gl.FUNC_ADD);
  12988. currentBlendEquation = AddEquation;
  12989. currentBlendEquationAlpha = AddEquation;
  12990. }
  12991. if (premultipliedAlpha) {
  12992. switch (blending) {
  12993. case NormalBlending:
  12994. gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  12995. break;
  12996. case AdditiveBlending:
  12997. gl.blendFunc(gl.ONE, gl.ONE);
  12998. break;
  12999. case SubtractiveBlending:
  13000. gl.blendFuncSeparate(gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA);
  13001. break;
  13002. case MultiplyBlending:
  13003. gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA);
  13004. break;
  13005. default:
  13006. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13007. break;
  13008. }
  13009. } else {
  13010. switch (blending) {
  13011. case NormalBlending:
  13012. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  13013. break;
  13014. case AdditiveBlending:
  13015. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  13016. break;
  13017. case SubtractiveBlending:
  13018. gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_COLOR);
  13019. break;
  13020. case MultiplyBlending:
  13021. gl.blendFunc(gl.ZERO, gl.SRC_COLOR);
  13022. break;
  13023. default:
  13024. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13025. break;
  13026. }
  13027. }
  13028. currentBlendSrc = null;
  13029. currentBlendDst = null;
  13030. currentBlendSrcAlpha = null;
  13031. currentBlendDstAlpha = null;
  13032. currentBlending = blending;
  13033. currentPremultipledAlpha = premultipliedAlpha;
  13034. }
  13035. return;
  13036. } // custom blending
  13037. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13038. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13039. blendDstAlpha = blendDstAlpha || blendDst;
  13040. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  13041. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  13042. currentBlendEquation = blendEquation;
  13043. currentBlendEquationAlpha = blendEquationAlpha;
  13044. }
  13045. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  13046. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  13047. currentBlendSrc = blendSrc;
  13048. currentBlendDst = blendDst;
  13049. currentBlendSrcAlpha = blendSrcAlpha;
  13050. currentBlendDstAlpha = blendDstAlpha;
  13051. }
  13052. currentBlending = blending;
  13053. currentPremultipledAlpha = null;
  13054. }
  13055. function setMaterial(material, frontFaceCW) {
  13056. material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE);
  13057. let flipSided = material.side === BackSide;
  13058. if (frontFaceCW) flipSided = !flipSided;
  13059. setFlipSided(flipSided);
  13060. 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);
  13061. depthBuffer.setFunc(material.depthFunc);
  13062. depthBuffer.setTest(material.depthTest);
  13063. depthBuffer.setMask(material.depthWrite);
  13064. colorBuffer.setMask(material.colorWrite);
  13065. const stencilWrite = material.stencilWrite;
  13066. stencilBuffer.setTest(stencilWrite);
  13067. if (stencilWrite) {
  13068. stencilBuffer.setMask(material.stencilWriteMask);
  13069. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  13070. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  13071. }
  13072. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  13073. material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13074. } //
  13075. function setFlipSided(flipSided) {
  13076. if (currentFlipSided !== flipSided) {
  13077. if (flipSided) {
  13078. gl.frontFace(gl.CW);
  13079. } else {
  13080. gl.frontFace(gl.CCW);
  13081. }
  13082. currentFlipSided = flipSided;
  13083. }
  13084. }
  13085. function setCullFace(cullFace) {
  13086. if (cullFace !== CullFaceNone) {
  13087. enable(gl.CULL_FACE);
  13088. if (cullFace !== currentCullFace) {
  13089. if (cullFace === CullFaceBack) {
  13090. gl.cullFace(gl.BACK);
  13091. } else if (cullFace === CullFaceFront) {
  13092. gl.cullFace(gl.FRONT);
  13093. } else {
  13094. gl.cullFace(gl.FRONT_AND_BACK);
  13095. }
  13096. }
  13097. } else {
  13098. disable(gl.CULL_FACE);
  13099. }
  13100. currentCullFace = cullFace;
  13101. }
  13102. function setLineWidth(width) {
  13103. if (width !== currentLineWidth) {
  13104. if (lineWidthAvailable) gl.lineWidth(width);
  13105. currentLineWidth = width;
  13106. }
  13107. }
  13108. function setPolygonOffset(polygonOffset, factor, units) {
  13109. if (polygonOffset) {
  13110. enable(gl.POLYGON_OFFSET_FILL);
  13111. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  13112. gl.polygonOffset(factor, units);
  13113. currentPolygonOffsetFactor = factor;
  13114. currentPolygonOffsetUnits = units;
  13115. }
  13116. } else {
  13117. disable(gl.POLYGON_OFFSET_FILL);
  13118. }
  13119. }
  13120. function setScissorTest(scissorTest) {
  13121. if (scissorTest) {
  13122. enable(gl.SCISSOR_TEST);
  13123. } else {
  13124. disable(gl.SCISSOR_TEST);
  13125. }
  13126. } // texture
  13127. function activeTexture(webglSlot) {
  13128. if (webglSlot === undefined) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13129. if (currentTextureSlot !== webglSlot) {
  13130. gl.activeTexture(webglSlot);
  13131. currentTextureSlot = webglSlot;
  13132. }
  13133. }
  13134. function bindTexture(webglType, webglTexture) {
  13135. if (currentTextureSlot === null) {
  13136. activeTexture();
  13137. }
  13138. let boundTexture = currentBoundTextures[currentTextureSlot];
  13139. if (boundTexture === undefined) {
  13140. boundTexture = {
  13141. type: undefined,
  13142. texture: undefined
  13143. };
  13144. currentBoundTextures[currentTextureSlot] = boundTexture;
  13145. }
  13146. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  13147. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  13148. boundTexture.type = webglType;
  13149. boundTexture.texture = webglTexture;
  13150. }
  13151. }
  13152. function unbindTexture() {
  13153. const boundTexture = currentBoundTextures[currentTextureSlot];
  13154. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  13155. gl.bindTexture(boundTexture.type, null);
  13156. boundTexture.type = undefined;
  13157. boundTexture.texture = undefined;
  13158. }
  13159. }
  13160. function compressedTexImage2D() {
  13161. try {
  13162. gl.compressedTexImage2D.apply(gl, arguments);
  13163. } catch (error) {
  13164. console.error('THREE.WebGLState:', error);
  13165. }
  13166. }
  13167. function texImage2D() {
  13168. try {
  13169. gl.texImage2D.apply(gl, arguments);
  13170. } catch (error) {
  13171. console.error('THREE.WebGLState:', error);
  13172. }
  13173. }
  13174. function texImage3D() {
  13175. try {
  13176. gl.texImage3D.apply(gl, arguments);
  13177. } catch (error) {
  13178. console.error('THREE.WebGLState:', error);
  13179. }
  13180. } //
  13181. function scissor(scissor) {
  13182. if (currentScissor.equals(scissor) === false) {
  13183. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  13184. currentScissor.copy(scissor);
  13185. }
  13186. }
  13187. function viewport(viewport) {
  13188. if (currentViewport.equals(viewport) === false) {
  13189. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  13190. currentViewport.copy(viewport);
  13191. }
  13192. } //
  13193. function reset() {
  13194. // reset state
  13195. gl.disable(gl.BLEND);
  13196. gl.disable(gl.CULL_FACE);
  13197. gl.disable(gl.DEPTH_TEST);
  13198. gl.disable(gl.POLYGON_OFFSET_FILL);
  13199. gl.disable(gl.SCISSOR_TEST);
  13200. gl.disable(gl.STENCIL_TEST);
  13201. gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13202. gl.blendEquation(gl.FUNC_ADD);
  13203. gl.blendFunc(gl.ONE, gl.ZERO);
  13204. gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
  13205. gl.colorMask(true, true, true, true);
  13206. gl.clearColor(0, 0, 0, 0);
  13207. gl.depthMask(true);
  13208. gl.depthFunc(gl.LESS);
  13209. gl.clearDepth(1);
  13210. gl.stencilMask(0xffffffff);
  13211. gl.stencilFunc(gl.ALWAYS, 0, 0xffffffff);
  13212. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  13213. gl.clearStencil(0);
  13214. gl.cullFace(gl.BACK);
  13215. gl.frontFace(gl.CCW);
  13216. gl.polygonOffset(0, 0);
  13217. gl.activeTexture(gl.TEXTURE0);
  13218. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13219. if (isWebGL2 === true) {
  13220. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  13221. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  13222. }
  13223. gl.useProgram(null);
  13224. gl.lineWidth(1);
  13225. gl.scissor(0, 0, gl.canvas.width, gl.canvas.height);
  13226. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); // reset internals
  13227. enabledCapabilities = {};
  13228. currentTextureSlot = null;
  13229. currentBoundTextures = {};
  13230. xrFramebuffer = null;
  13231. currentBoundFramebuffers = {};
  13232. currentProgram = null;
  13233. currentBlendingEnabled = false;
  13234. currentBlending = null;
  13235. currentBlendEquation = null;
  13236. currentBlendSrc = null;
  13237. currentBlendDst = null;
  13238. currentBlendEquationAlpha = null;
  13239. currentBlendSrcAlpha = null;
  13240. currentBlendDstAlpha = null;
  13241. currentPremultipledAlpha = false;
  13242. currentFlipSided = null;
  13243. currentCullFace = null;
  13244. currentLineWidth = null;
  13245. currentPolygonOffsetFactor = null;
  13246. currentPolygonOffsetUnits = null;
  13247. currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height);
  13248. currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height);
  13249. colorBuffer.reset();
  13250. depthBuffer.reset();
  13251. stencilBuffer.reset();
  13252. }
  13253. return {
  13254. buffers: {
  13255. color: colorBuffer,
  13256. depth: depthBuffer,
  13257. stencil: stencilBuffer
  13258. },
  13259. enable: enable,
  13260. disable: disable,
  13261. bindFramebuffer: bindFramebuffer,
  13262. bindXRFramebuffer: bindXRFramebuffer,
  13263. useProgram: useProgram,
  13264. setBlending: setBlending,
  13265. setMaterial: setMaterial,
  13266. setFlipSided: setFlipSided,
  13267. setCullFace: setCullFace,
  13268. setLineWidth: setLineWidth,
  13269. setPolygonOffset: setPolygonOffset,
  13270. setScissorTest: setScissorTest,
  13271. activeTexture: activeTexture,
  13272. bindTexture: bindTexture,
  13273. unbindTexture: unbindTexture,
  13274. compressedTexImage2D: compressedTexImage2D,
  13275. texImage2D: texImage2D,
  13276. texImage3D: texImage3D,
  13277. scissor: scissor,
  13278. viewport: viewport,
  13279. reset: reset
  13280. };
  13281. }
  13282. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  13283. const isWebGL2 = capabilities.isWebGL2;
  13284. const maxTextures = capabilities.maxTextures;
  13285. const maxCubemapSize = capabilities.maxCubemapSize;
  13286. const maxTextureSize = capabilities.maxTextureSize;
  13287. const maxSamples = capabilities.maxSamples;
  13288. const _videoTextures = new WeakMap();
  13289. let _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13290. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13291. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13292. let useOffscreenCanvas = false;
  13293. try {
  13294. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext('2d') !== null;
  13295. } catch (err) {// Ignore any errors
  13296. }
  13297. function createCanvas(width, height) {
  13298. // Use OffscreenCanvas when available. Specially needed in web workers
  13299. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : createElementNS('canvas');
  13300. }
  13301. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  13302. let scale = 1; // handle case if texture exceeds max size
  13303. if (image.width > maxSize || image.height > maxSize) {
  13304. scale = maxSize / Math.max(image.width, image.height);
  13305. } // only perform resize if necessary
  13306. if (scale < 1 || needsPowerOfTwo === true) {
  13307. // only perform resize for certain image types
  13308. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  13309. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13310. const width = floor(scale * image.width);
  13311. const height = floor(scale * image.height);
  13312. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  13313. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  13314. canvas.width = width;
  13315. canvas.height = height;
  13316. const context = canvas.getContext('2d');
  13317. context.drawImage(image, 0, 0, width, height);
  13318. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  13319. return canvas;
  13320. } else {
  13321. if ('data' in image) {
  13322. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  13323. }
  13324. return image;
  13325. }
  13326. }
  13327. return image;
  13328. }
  13329. function isPowerOfTwo$1(image) {
  13330. return isPowerOfTwo(image.width) && isPowerOfTwo(image.height);
  13331. }
  13332. function textureNeedsPowerOfTwo(texture) {
  13333. if (isWebGL2) return false;
  13334. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13335. }
  13336. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  13337. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13338. }
  13339. function generateMipmap(target, texture, width, height, depth = 1) {
  13340. _gl.generateMipmap(target);
  13341. const textureProperties = properties.get(texture);
  13342. textureProperties.__maxMipLevel = Math.log2(Math.max(width, height, depth));
  13343. }
  13344. function getInternalFormat(internalFormatName, glFormat, glType, encoding) {
  13345. if (isWebGL2 === false) return glFormat;
  13346. if (internalFormatName !== null) {
  13347. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  13348. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  13349. }
  13350. let internalFormat = glFormat;
  13351. if (glFormat === _gl.RED) {
  13352. if (glType === _gl.FLOAT) internalFormat = _gl.R32F;
  13353. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F;
  13354. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8;
  13355. }
  13356. if (glFormat === _gl.RGB) {
  13357. if (glType === _gl.FLOAT) internalFormat = _gl.RGB32F;
  13358. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGB16F;
  13359. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGB8;
  13360. }
  13361. if (glFormat === _gl.RGBA) {
  13362. if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
  13363. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
  13364. if (glType === _gl.UNSIGNED_BYTE) internalFormat = encoding === sRGBEncoding ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  13365. }
  13366. if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) {
  13367. extensions.get('EXT_color_buffer_float');
  13368. }
  13369. return internalFormat;
  13370. } // Fallback filters for non-power-of-2 textures
  13371. function filterFallback(f) {
  13372. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  13373. return _gl.NEAREST;
  13374. }
  13375. return _gl.LINEAR;
  13376. } //
  13377. function onTextureDispose(event) {
  13378. const texture = event.target;
  13379. texture.removeEventListener('dispose', onTextureDispose);
  13380. deallocateTexture(texture);
  13381. if (texture.isVideoTexture) {
  13382. _videoTextures.delete(texture);
  13383. }
  13384. info.memory.textures--;
  13385. }
  13386. function onRenderTargetDispose(event) {
  13387. const renderTarget = event.target;
  13388. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  13389. deallocateRenderTarget(renderTarget);
  13390. } //
  13391. function deallocateTexture(texture) {
  13392. const textureProperties = properties.get(texture);
  13393. if (textureProperties.__webglInit === undefined) return;
  13394. _gl.deleteTexture(textureProperties.__webglTexture);
  13395. properties.remove(texture);
  13396. }
  13397. function deallocateRenderTarget(renderTarget) {
  13398. const texture = renderTarget.texture;
  13399. const renderTargetProperties = properties.get(renderTarget);
  13400. const textureProperties = properties.get(texture);
  13401. if (!renderTarget) return;
  13402. if (textureProperties.__webglTexture !== undefined) {
  13403. _gl.deleteTexture(textureProperties.__webglTexture);
  13404. info.memory.textures--;
  13405. }
  13406. if (renderTarget.depthTexture) {
  13407. renderTarget.depthTexture.dispose();
  13408. }
  13409. if (renderTarget.isWebGLCubeRenderTarget) {
  13410. for (let i = 0; i < 6; i++) {
  13411. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  13412. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  13413. }
  13414. } else {
  13415. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  13416. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  13417. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  13418. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  13419. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  13420. }
  13421. if (renderTarget.isWebGLMultipleRenderTargets) {
  13422. for (let i = 0, il = texture.length; i < il; i++) {
  13423. const attachmentProperties = properties.get(texture[i]);
  13424. if (attachmentProperties.__webglTexture) {
  13425. _gl.deleteTexture(attachmentProperties.__webglTexture);
  13426. info.memory.textures--;
  13427. }
  13428. properties.remove(texture[i]);
  13429. }
  13430. }
  13431. properties.remove(texture);
  13432. properties.remove(renderTarget);
  13433. } //
  13434. let textureUnits = 0;
  13435. function resetTextureUnits() {
  13436. textureUnits = 0;
  13437. }
  13438. function allocateTextureUnit() {
  13439. const textureUnit = textureUnits;
  13440. if (textureUnit >= maxTextures) {
  13441. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  13442. }
  13443. textureUnits += 1;
  13444. return textureUnit;
  13445. } //
  13446. function setTexture2D(texture, slot) {
  13447. const textureProperties = properties.get(texture);
  13448. if (texture.isVideoTexture) updateVideoTexture(texture);
  13449. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13450. const image = texture.image;
  13451. if (image === undefined) {
  13452. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  13453. } else if (image.complete === false) {
  13454. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  13455. } else {
  13456. uploadTexture(textureProperties, texture, slot);
  13457. return;
  13458. }
  13459. }
  13460. state.activeTexture(_gl.TEXTURE0 + slot);
  13461. state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture);
  13462. }
  13463. function setTexture2DArray(texture, slot) {
  13464. const textureProperties = properties.get(texture);
  13465. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13466. uploadTexture(textureProperties, texture, slot);
  13467. return;
  13468. }
  13469. state.activeTexture(_gl.TEXTURE0 + slot);
  13470. state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture);
  13471. }
  13472. function setTexture3D(texture, slot) {
  13473. const textureProperties = properties.get(texture);
  13474. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13475. uploadTexture(textureProperties, texture, slot);
  13476. return;
  13477. }
  13478. state.activeTexture(_gl.TEXTURE0 + slot);
  13479. state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture);
  13480. }
  13481. function setTextureCube(texture, slot) {
  13482. const textureProperties = properties.get(texture);
  13483. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13484. uploadCubeTexture(textureProperties, texture, slot);
  13485. return;
  13486. }
  13487. state.activeTexture(_gl.TEXTURE0 + slot);
  13488. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13489. }
  13490. const wrappingToGL = {
  13491. [RepeatWrapping]: _gl.REPEAT,
  13492. [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE,
  13493. [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT
  13494. };
  13495. const filterToGL = {
  13496. [NearestFilter]: _gl.NEAREST,
  13497. [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST,
  13498. [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR,
  13499. [LinearFilter]: _gl.LINEAR,
  13500. [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST,
  13501. [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR
  13502. };
  13503. function setTextureParameters(textureType, texture, supportsMips) {
  13504. if (supportsMips) {
  13505. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]);
  13506. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]);
  13507. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  13508. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]);
  13509. }
  13510. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]);
  13511. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]);
  13512. } else {
  13513. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE);
  13514. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE);
  13515. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  13516. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE);
  13517. }
  13518. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  13519. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  13520. }
  13521. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter));
  13522. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter));
  13523. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13524. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  13525. }
  13526. }
  13527. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  13528. const extension = extensions.get('EXT_texture_filter_anisotropic');
  13529. if (texture.type === FloatType && extensions.has('OES_texture_float_linear') === false) return; // verify extension for WebGL 1 and WebGL 2
  13530. if (isWebGL2 === false && texture.type === HalfFloatType && extensions.has('OES_texture_half_float_linear') === false) return; // verify extension for WebGL 1 only
  13531. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  13532. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  13533. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  13534. }
  13535. }
  13536. }
  13537. function initTexture(textureProperties, texture) {
  13538. if (textureProperties.__webglInit === undefined) {
  13539. textureProperties.__webglInit = true;
  13540. texture.addEventListener('dispose', onTextureDispose);
  13541. textureProperties.__webglTexture = _gl.createTexture();
  13542. info.memory.textures++;
  13543. }
  13544. }
  13545. function uploadTexture(textureProperties, texture, slot) {
  13546. let textureType = _gl.TEXTURE_2D;
  13547. if (texture.isDataTexture2DArray) textureType = _gl.TEXTURE_2D_ARRAY;
  13548. if (texture.isDataTexture3D) textureType = _gl.TEXTURE_3D;
  13549. initTexture(textureProperties, texture);
  13550. state.activeTexture(_gl.TEXTURE0 + slot);
  13551. state.bindTexture(textureType, textureProperties.__webglTexture);
  13552. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  13553. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  13554. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  13555. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  13556. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false;
  13557. const image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  13558. const supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  13559. glFormat = utils.convert(texture.format);
  13560. let glType = utils.convert(texture.type),
  13561. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  13562. setTextureParameters(textureType, texture, supportsMips);
  13563. let mipmap;
  13564. const mipmaps = texture.mipmaps;
  13565. if (texture.isDepthTexture) {
  13566. // populate depth texture with dummy data
  13567. glInternalFormat = _gl.DEPTH_COMPONENT;
  13568. if (isWebGL2) {
  13569. if (texture.type === FloatType) {
  13570. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  13571. } else if (texture.type === UnsignedIntType) {
  13572. glInternalFormat = _gl.DEPTH_COMPONENT24;
  13573. } else if (texture.type === UnsignedInt248Type) {
  13574. glInternalFormat = _gl.DEPTH24_STENCIL8;
  13575. } else {
  13576. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  13577. }
  13578. } else {
  13579. if (texture.type === FloatType) {
  13580. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  13581. }
  13582. } // validation checks for WebGL 1
  13583. if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  13584. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13585. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13586. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13587. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  13588. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  13589. texture.type = UnsignedShortType;
  13590. glType = utils.convert(texture.type);
  13591. }
  13592. }
  13593. if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  13594. // Depth stencil textures need the DEPTH_STENCIL internal format
  13595. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13596. glInternalFormat = _gl.DEPTH_STENCIL; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13597. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13598. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13599. if (texture.type !== UnsignedInt248Type) {
  13600. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  13601. texture.type = UnsignedInt248Type;
  13602. glType = utils.convert(texture.type);
  13603. }
  13604. } //
  13605. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  13606. } else if (texture.isDataTexture) {
  13607. // use manually created mipmaps if available
  13608. // if there are no manual mipmaps
  13609. // set 0 level mipmap and then use GL to generate other mipmap levels
  13610. if (mipmaps.length > 0 && supportsMips) {
  13611. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13612. mipmap = mipmaps[i];
  13613. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13614. }
  13615. texture.generateMipmaps = false;
  13616. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13617. } else {
  13618. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  13619. textureProperties.__maxMipLevel = 0;
  13620. }
  13621. } else if (texture.isCompressedTexture) {
  13622. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13623. mipmap = mipmaps[i];
  13624. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13625. if (glFormat !== null) {
  13626. state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13627. } else {
  13628. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  13629. }
  13630. } else {
  13631. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13632. }
  13633. }
  13634. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13635. } else if (texture.isDataTexture2DArray) {
  13636. state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13637. textureProperties.__maxMipLevel = 0;
  13638. } else if (texture.isDataTexture3D) {
  13639. state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13640. textureProperties.__maxMipLevel = 0;
  13641. } else {
  13642. // regular Texture (image, video, canvas)
  13643. // use manually created mipmaps if available
  13644. // if there are no manual mipmaps
  13645. // set 0 level mipmap and then use GL to generate other mipmap levels
  13646. if (mipmaps.length > 0 && supportsMips) {
  13647. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13648. mipmap = mipmaps[i];
  13649. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap);
  13650. }
  13651. texture.generateMipmaps = false;
  13652. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13653. } else {
  13654. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image);
  13655. textureProperties.__maxMipLevel = 0;
  13656. }
  13657. }
  13658. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13659. generateMipmap(textureType, texture, image.width, image.height);
  13660. }
  13661. textureProperties.__version = texture.version;
  13662. if (texture.onUpdate) texture.onUpdate(texture);
  13663. }
  13664. function uploadCubeTexture(textureProperties, texture, slot) {
  13665. if (texture.image.length !== 6) return;
  13666. initTexture(textureProperties, texture);
  13667. state.activeTexture(_gl.TEXTURE0 + slot);
  13668. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13669. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  13670. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  13671. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  13672. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  13673. const isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
  13674. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  13675. const cubeImage = [];
  13676. for (let i = 0; i < 6; i++) {
  13677. if (!isCompressed && !isDataTexture) {
  13678. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  13679. } else {
  13680. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  13681. }
  13682. }
  13683. const image = cubeImage[0],
  13684. supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  13685. glFormat = utils.convert(texture.format),
  13686. glType = utils.convert(texture.type),
  13687. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  13688. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  13689. let mipmaps;
  13690. if (isCompressed) {
  13691. for (let i = 0; i < 6; i++) {
  13692. mipmaps = cubeImage[i].mipmaps;
  13693. for (let j = 0; j < mipmaps.length; j++) {
  13694. const mipmap = mipmaps[j];
  13695. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13696. if (glFormat !== null) {
  13697. state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13698. } else {
  13699. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  13700. }
  13701. } else {
  13702. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13703. }
  13704. }
  13705. }
  13706. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13707. } else {
  13708. mipmaps = texture.mipmaps;
  13709. for (let i = 0; i < 6; i++) {
  13710. if (isDataTexture) {
  13711. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  13712. for (let j = 0; j < mipmaps.length; j++) {
  13713. const mipmap = mipmaps[j];
  13714. const mipmapImage = mipmap.image[i].image;
  13715. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  13716. }
  13717. } else {
  13718. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  13719. for (let j = 0; j < mipmaps.length; j++) {
  13720. const mipmap = mipmaps[j];
  13721. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  13722. }
  13723. }
  13724. }
  13725. textureProperties.__maxMipLevel = mipmaps.length;
  13726. }
  13727. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13728. // We assume images for cube map have the same size.
  13729. generateMipmap(_gl.TEXTURE_CUBE_MAP, texture, image.width, image.height);
  13730. }
  13731. textureProperties.__version = texture.version;
  13732. if (texture.onUpdate) texture.onUpdate(texture);
  13733. } // Render targets
  13734. // Setup storage for target texture and bind it to correct framebuffer
  13735. function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) {
  13736. const glFormat = utils.convert(texture.format);
  13737. const glType = utils.convert(texture.type);
  13738. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  13739. if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) {
  13740. state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null);
  13741. } else {
  13742. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  13743. }
  13744. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  13745. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0);
  13746. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  13747. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  13748. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  13749. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
  13750. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  13751. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  13752. if (isMultisample) {
  13753. const depthTexture = renderTarget.depthTexture;
  13754. if (depthTexture && depthTexture.isDepthTexture) {
  13755. if (depthTexture.type === FloatType) {
  13756. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  13757. } else if (depthTexture.type === UnsignedIntType) {
  13758. glInternalFormat = _gl.DEPTH_COMPONENT24;
  13759. }
  13760. }
  13761. const samples = getRenderTargetSamples(renderTarget);
  13762. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13763. } else {
  13764. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  13765. }
  13766. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  13767. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  13768. if (isMultisample) {
  13769. const samples = getRenderTargetSamples(renderTarget);
  13770. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  13771. } else {
  13772. _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height);
  13773. }
  13774. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  13775. } else {
  13776. // Use the first texture for MRT so far
  13777. const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[0] : renderTarget.texture;
  13778. const glFormat = utils.convert(texture.format);
  13779. const glType = utils.convert(texture.type);
  13780. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  13781. if (isMultisample) {
  13782. const samples = getRenderTargetSamples(renderTarget);
  13783. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13784. } else {
  13785. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  13786. }
  13787. }
  13788. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  13789. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  13790. function setupDepthTexture(framebuffer, renderTarget) {
  13791. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  13792. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  13793. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  13794. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  13795. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  13796. } // upload an empty depth texture with framebuffer size
  13797. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  13798. renderTarget.depthTexture.image.width = renderTarget.width;
  13799. renderTarget.depthTexture.image.height = renderTarget.height;
  13800. renderTarget.depthTexture.needsUpdate = true;
  13801. }
  13802. setTexture2D(renderTarget.depthTexture, 0);
  13803. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  13804. if (renderTarget.depthTexture.format === DepthFormat) {
  13805. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  13806. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  13807. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  13808. } else {
  13809. throw new Error('Unknown depthTexture format');
  13810. }
  13811. } // Setup GL resources for a non-texture depth buffer
  13812. function setupDepthRenderbuffer(renderTarget) {
  13813. const renderTargetProperties = properties.get(renderTarget);
  13814. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  13815. if (renderTarget.depthTexture) {
  13816. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  13817. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  13818. } else {
  13819. if (isCube) {
  13820. renderTargetProperties.__webglDepthbuffer = [];
  13821. for (let i = 0; i < 6; i++) {
  13822. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]);
  13823. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  13824. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  13825. }
  13826. } else {
  13827. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  13828. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  13829. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  13830. }
  13831. }
  13832. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  13833. } // Set up GL resources for the render target
  13834. function setupRenderTarget(renderTarget) {
  13835. const texture = renderTarget.texture;
  13836. const renderTargetProperties = properties.get(renderTarget);
  13837. const textureProperties = properties.get(texture);
  13838. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  13839. if (renderTarget.isWebGLMultipleRenderTargets !== true) {
  13840. textureProperties.__webglTexture = _gl.createTexture();
  13841. textureProperties.__version = texture.version;
  13842. info.memory.textures++;
  13843. }
  13844. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  13845. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
  13846. const isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  13847. const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
  13848. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
  13849. if (isWebGL2 && texture.format === RGBFormat && (texture.type === FloatType || texture.type === HalfFloatType)) {
  13850. texture.format = RGBAFormat;
  13851. console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
  13852. } // Setup framebuffer
  13853. if (isCube) {
  13854. renderTargetProperties.__webglFramebuffer = [];
  13855. for (let i = 0; i < 6; i++) {
  13856. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  13857. }
  13858. } else {
  13859. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  13860. if (isMultipleRenderTargets) {
  13861. if (capabilities.drawBuffers) {
  13862. const textures = renderTarget.texture;
  13863. for (let i = 0, il = textures.length; i < il; i++) {
  13864. const attachmentProperties = properties.get(textures[i]);
  13865. if (attachmentProperties.__webglTexture === undefined) {
  13866. attachmentProperties.__webglTexture = _gl.createTexture();
  13867. info.memory.textures++;
  13868. }
  13869. }
  13870. } else {
  13871. console.warn('THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.');
  13872. }
  13873. } else if (isMultisample) {
  13874. if (isWebGL2) {
  13875. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  13876. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  13877. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  13878. const glFormat = utils.convert(texture.format);
  13879. const glType = utils.convert(texture.type);
  13880. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  13881. const samples = getRenderTargetSamples(renderTarget);
  13882. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13883. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13884. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  13885. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  13886. if (renderTarget.depthBuffer) {
  13887. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  13888. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  13889. }
  13890. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  13891. } else {
  13892. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13893. }
  13894. }
  13895. } // Setup color buffer
  13896. if (isCube) {
  13897. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13898. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  13899. for (let i = 0; i < 6; i++) {
  13900. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i);
  13901. }
  13902. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13903. generateMipmap(_gl.TEXTURE_CUBE_MAP, texture, renderTarget.width, renderTarget.height);
  13904. }
  13905. state.unbindTexture();
  13906. } else if (isMultipleRenderTargets) {
  13907. const textures = renderTarget.texture;
  13908. for (let i = 0, il = textures.length; i < il; i++) {
  13909. const attachment = textures[i];
  13910. const attachmentProperties = properties.get(attachment);
  13911. state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture);
  13912. setTextureParameters(_gl.TEXTURE_2D, attachment, supportsMips);
  13913. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D);
  13914. if (textureNeedsGenerateMipmaps(attachment, supportsMips)) {
  13915. generateMipmap(_gl.TEXTURE_2D, attachment, renderTarget.width, renderTarget.height);
  13916. }
  13917. }
  13918. state.unbindTexture();
  13919. } else {
  13920. let glTextureType = _gl.TEXTURE_2D;
  13921. if (isRenderTarget3D) {
  13922. // Render targets containing layers, i.e: Texture 3D and 2d arrays
  13923. if (isWebGL2) {
  13924. const isTexture3D = texture.isDataTexture3D;
  13925. glTextureType = isTexture3D ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  13926. } else {
  13927. console.warn('THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.');
  13928. }
  13929. }
  13930. state.bindTexture(glTextureType, textureProperties.__webglTexture);
  13931. setTextureParameters(glTextureType, texture, supportsMips);
  13932. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType);
  13933. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13934. generateMipmap(glTextureType, texture, renderTarget.width, renderTarget.height, renderTarget.depth);
  13935. }
  13936. state.unbindTexture();
  13937. } // Setup depth and stencil buffers
  13938. if (renderTarget.depthBuffer) {
  13939. setupDepthRenderbuffer(renderTarget);
  13940. }
  13941. }
  13942. function updateRenderTargetMipmap(renderTarget) {
  13943. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
  13944. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  13945. for (let i = 0, il = textures.length; i < il; i++) {
  13946. const texture = textures[i];
  13947. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13948. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  13949. const webglTexture = properties.get(texture).__webglTexture;
  13950. state.bindTexture(target, webglTexture);
  13951. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  13952. state.unbindTexture();
  13953. }
  13954. }
  13955. }
  13956. function updateMultisampleRenderTarget(renderTarget) {
  13957. if (renderTarget.isWebGLMultisampleRenderTarget) {
  13958. if (isWebGL2) {
  13959. const width = renderTarget.width;
  13960. const height = renderTarget.height;
  13961. let mask = _gl.COLOR_BUFFER_BIT;
  13962. if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT;
  13963. if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT;
  13964. const renderTargetProperties = properties.get(renderTarget);
  13965. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13966. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  13967. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST);
  13968. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
  13969. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13970. } else {
  13971. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13972. }
  13973. }
  13974. }
  13975. function getRenderTargetSamples(renderTarget) {
  13976. return isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(maxSamples, renderTarget.samples) : 0;
  13977. }
  13978. function updateVideoTexture(texture) {
  13979. const frame = info.render.frame; // Check the last frame we updated the VideoTexture
  13980. if (_videoTextures.get(texture) !== frame) {
  13981. _videoTextures.set(texture, frame);
  13982. texture.update();
  13983. }
  13984. } // backwards compatibility
  13985. let warnedTexture2D = false;
  13986. let warnedTextureCube = false;
  13987. function safeSetTexture2D(texture, slot) {
  13988. if (texture && texture.isWebGLRenderTarget) {
  13989. if (warnedTexture2D === false) {
  13990. console.warn('THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.');
  13991. warnedTexture2D = true;
  13992. }
  13993. texture = texture.texture;
  13994. }
  13995. setTexture2D(texture, slot);
  13996. }
  13997. function safeSetTextureCube(texture, slot) {
  13998. if (texture && texture.isWebGLCubeRenderTarget) {
  13999. if (warnedTextureCube === false) {
  14000. console.warn('THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.');
  14001. warnedTextureCube = true;
  14002. }
  14003. texture = texture.texture;
  14004. }
  14005. setTextureCube(texture, slot);
  14006. } //
  14007. this.allocateTextureUnit = allocateTextureUnit;
  14008. this.resetTextureUnits = resetTextureUnits;
  14009. this.setTexture2D = setTexture2D;
  14010. this.setTexture2DArray = setTexture2DArray;
  14011. this.setTexture3D = setTexture3D;
  14012. this.setTextureCube = setTextureCube;
  14013. this.setupRenderTarget = setupRenderTarget;
  14014. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14015. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14016. this.safeSetTexture2D = safeSetTexture2D;
  14017. this.safeSetTextureCube = safeSetTextureCube;
  14018. }
  14019. function WebGLUtils(gl, extensions, capabilities) {
  14020. const isWebGL2 = capabilities.isWebGL2;
  14021. function convert(p) {
  14022. let extension;
  14023. if (p === UnsignedByteType) return gl.UNSIGNED_BYTE;
  14024. if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4;
  14025. if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1;
  14026. if (p === UnsignedShort565Type) return gl.UNSIGNED_SHORT_5_6_5;
  14027. if (p === ByteType) return gl.BYTE;
  14028. if (p === ShortType) return gl.SHORT;
  14029. if (p === UnsignedShortType) return gl.UNSIGNED_SHORT;
  14030. if (p === IntType) return gl.INT;
  14031. if (p === UnsignedIntType) return gl.UNSIGNED_INT;
  14032. if (p === FloatType) return gl.FLOAT;
  14033. if (p === HalfFloatType) {
  14034. if (isWebGL2) return gl.HALF_FLOAT;
  14035. extension = extensions.get('OES_texture_half_float');
  14036. if (extension !== null) {
  14037. return extension.HALF_FLOAT_OES;
  14038. } else {
  14039. return null;
  14040. }
  14041. }
  14042. if (p === AlphaFormat) return gl.ALPHA;
  14043. if (p === RGBFormat) return gl.RGB;
  14044. if (p === RGBAFormat) return gl.RGBA;
  14045. if (p === LuminanceFormat) return gl.LUMINANCE;
  14046. if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
  14047. if (p === DepthFormat) return gl.DEPTH_COMPONENT;
  14048. if (p === DepthStencilFormat) return gl.DEPTH_STENCIL;
  14049. if (p === RedFormat) return gl.RED; // WebGL2 formats.
  14050. if (p === RedIntegerFormat) return gl.RED_INTEGER;
  14051. if (p === RGFormat) return gl.RG;
  14052. if (p === RGIntegerFormat) return gl.RG_INTEGER;
  14053. if (p === RGBIntegerFormat) return gl.RGB_INTEGER;
  14054. if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER;
  14055. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  14056. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  14057. if (extension !== null) {
  14058. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14059. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14060. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14061. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14062. } else {
  14063. return null;
  14064. }
  14065. }
  14066. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  14067. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  14068. if (extension !== null) {
  14069. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14070. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14071. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14072. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14073. } else {
  14074. return null;
  14075. }
  14076. }
  14077. if (p === RGB_ETC1_Format) {
  14078. extension = extensions.get('WEBGL_compressed_texture_etc1');
  14079. if (extension !== null) {
  14080. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14081. } else {
  14082. return null;
  14083. }
  14084. }
  14085. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  14086. extension = extensions.get('WEBGL_compressed_texture_etc');
  14087. if (extension !== null) {
  14088. if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
  14089. if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  14090. }
  14091. }
  14092. 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) {
  14093. extension = extensions.get('WEBGL_compressed_texture_astc');
  14094. if (extension !== null) {
  14095. // TODO Complete?
  14096. return p;
  14097. } else {
  14098. return null;
  14099. }
  14100. }
  14101. if (p === RGBA_BPTC_Format) {
  14102. extension = extensions.get('EXT_texture_compression_bptc');
  14103. if (extension !== null) {
  14104. // TODO Complete?
  14105. return p;
  14106. } else {
  14107. return null;
  14108. }
  14109. }
  14110. if (p === UnsignedInt248Type) {
  14111. if (isWebGL2) return gl.UNSIGNED_INT_24_8;
  14112. extension = extensions.get('WEBGL_depth_texture');
  14113. if (extension !== null) {
  14114. return extension.UNSIGNED_INT_24_8_WEBGL;
  14115. } else {
  14116. return null;
  14117. }
  14118. }
  14119. }
  14120. return {
  14121. convert: convert
  14122. };
  14123. }
  14124. class ArrayCamera extends PerspectiveCamera {
  14125. constructor(array = []) {
  14126. super();
  14127. this.cameras = array;
  14128. }
  14129. }
  14130. ArrayCamera.prototype.isArrayCamera = true;
  14131. class Group extends Object3D {
  14132. constructor() {
  14133. super();
  14134. this.type = 'Group';
  14135. }
  14136. }
  14137. Group.prototype.isGroup = true;
  14138. const _moveEvent = {
  14139. type: 'move'
  14140. };
  14141. class WebXRController {
  14142. constructor() {
  14143. this._targetRay = null;
  14144. this._grip = null;
  14145. this._hand = null;
  14146. }
  14147. getHandSpace() {
  14148. if (this._hand === null) {
  14149. this._hand = new Group();
  14150. this._hand.matrixAutoUpdate = false;
  14151. this._hand.visible = false;
  14152. this._hand.joints = {};
  14153. this._hand.inputState = {
  14154. pinching: false
  14155. };
  14156. }
  14157. return this._hand;
  14158. }
  14159. getTargetRaySpace() {
  14160. if (this._targetRay === null) {
  14161. this._targetRay = new Group();
  14162. this._targetRay.matrixAutoUpdate = false;
  14163. this._targetRay.visible = false;
  14164. this._targetRay.hasLinearVelocity = false;
  14165. this._targetRay.linearVelocity = new Vector3();
  14166. this._targetRay.hasAngularVelocity = false;
  14167. this._targetRay.angularVelocity = new Vector3();
  14168. }
  14169. return this._targetRay;
  14170. }
  14171. getGripSpace() {
  14172. if (this._grip === null) {
  14173. this._grip = new Group();
  14174. this._grip.matrixAutoUpdate = false;
  14175. this._grip.visible = false;
  14176. this._grip.hasLinearVelocity = false;
  14177. this._grip.linearVelocity = new Vector3();
  14178. this._grip.hasAngularVelocity = false;
  14179. this._grip.angularVelocity = new Vector3();
  14180. }
  14181. return this._grip;
  14182. }
  14183. dispatchEvent(event) {
  14184. if (this._targetRay !== null) {
  14185. this._targetRay.dispatchEvent(event);
  14186. }
  14187. if (this._grip !== null) {
  14188. this._grip.dispatchEvent(event);
  14189. }
  14190. if (this._hand !== null) {
  14191. this._hand.dispatchEvent(event);
  14192. }
  14193. return this;
  14194. }
  14195. disconnect(inputSource) {
  14196. this.dispatchEvent({
  14197. type: 'disconnected',
  14198. data: inputSource
  14199. });
  14200. if (this._targetRay !== null) {
  14201. this._targetRay.visible = false;
  14202. }
  14203. if (this._grip !== null) {
  14204. this._grip.visible = false;
  14205. }
  14206. if (this._hand !== null) {
  14207. this._hand.visible = false;
  14208. }
  14209. return this;
  14210. }
  14211. update(inputSource, frame, referenceSpace) {
  14212. let inputPose = null;
  14213. let gripPose = null;
  14214. let handPose = null;
  14215. const targetRay = this._targetRay;
  14216. const grip = this._grip;
  14217. const hand = this._hand;
  14218. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  14219. if (targetRay !== null) {
  14220. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  14221. if (inputPose !== null) {
  14222. targetRay.matrix.fromArray(inputPose.transform.matrix);
  14223. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  14224. if (inputPose.linearVelocity) {
  14225. targetRay.hasLinearVelocity = true;
  14226. targetRay.linearVelocity.copy(inputPose.linearVelocity);
  14227. } else {
  14228. targetRay.hasLinearVelocity = false;
  14229. }
  14230. if (inputPose.angularVelocity) {
  14231. targetRay.hasAngularVelocity = true;
  14232. targetRay.angularVelocity.copy(inputPose.angularVelocity);
  14233. } else {
  14234. targetRay.hasAngularVelocity = false;
  14235. }
  14236. this.dispatchEvent(_moveEvent);
  14237. }
  14238. }
  14239. if (hand && inputSource.hand) {
  14240. handPose = true;
  14241. for (const inputjoint of inputSource.hand.values()) {
  14242. // Update the joints groups with the XRJoint poses
  14243. const jointPose = frame.getJointPose(inputjoint, referenceSpace);
  14244. if (hand.joints[inputjoint.jointName] === undefined) {
  14245. // The transform of this joint will be updated with the joint pose on each frame
  14246. const joint = new Group();
  14247. joint.matrixAutoUpdate = false;
  14248. joint.visible = false;
  14249. hand.joints[inputjoint.jointName] = joint; // ??
  14250. hand.add(joint);
  14251. }
  14252. const joint = hand.joints[inputjoint.jointName];
  14253. if (jointPose !== null) {
  14254. joint.matrix.fromArray(jointPose.transform.matrix);
  14255. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  14256. joint.jointRadius = jointPose.radius;
  14257. }
  14258. joint.visible = jointPose !== null;
  14259. } // Custom events
  14260. // Check pinchz
  14261. const indexTip = hand.joints['index-finger-tip'];
  14262. const thumbTip = hand.joints['thumb-tip'];
  14263. const distance = indexTip.position.distanceTo(thumbTip.position);
  14264. const distanceToPinch = 0.02;
  14265. const threshold = 0.005;
  14266. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  14267. hand.inputState.pinching = false;
  14268. this.dispatchEvent({
  14269. type: 'pinchend',
  14270. handedness: inputSource.handedness,
  14271. target: this
  14272. });
  14273. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  14274. hand.inputState.pinching = true;
  14275. this.dispatchEvent({
  14276. type: 'pinchstart',
  14277. handedness: inputSource.handedness,
  14278. target: this
  14279. });
  14280. }
  14281. } else {
  14282. if (grip !== null && inputSource.gripSpace) {
  14283. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  14284. if (gripPose !== null) {
  14285. grip.matrix.fromArray(gripPose.transform.matrix);
  14286. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  14287. if (gripPose.linearVelocity) {
  14288. grip.hasLinearVelocity = true;
  14289. grip.linearVelocity.copy(gripPose.linearVelocity);
  14290. } else {
  14291. grip.hasLinearVelocity = false;
  14292. }
  14293. if (gripPose.angularVelocity) {
  14294. grip.hasAngularVelocity = true;
  14295. grip.angularVelocity.copy(gripPose.angularVelocity);
  14296. } else {
  14297. grip.hasAngularVelocity = false;
  14298. }
  14299. }
  14300. }
  14301. }
  14302. }
  14303. if (targetRay !== null) {
  14304. targetRay.visible = inputPose !== null;
  14305. }
  14306. if (grip !== null) {
  14307. grip.visible = gripPose !== null;
  14308. }
  14309. if (hand !== null) {
  14310. hand.visible = handPose !== null;
  14311. }
  14312. return this;
  14313. }
  14314. }
  14315. class WebXRManager extends EventDispatcher {
  14316. constructor(renderer, gl) {
  14317. super();
  14318. const scope = this;
  14319. const state = renderer.state;
  14320. let session = null;
  14321. let framebufferScaleFactor = 1.0;
  14322. let referenceSpace = null;
  14323. let referenceSpaceType = 'local-floor';
  14324. let pose = null;
  14325. let glBinding = null;
  14326. let glFramebuffer = null;
  14327. let glProjLayer = null;
  14328. let glBaseLayer = null;
  14329. let isMultisample = false;
  14330. let glMultisampledFramebuffer = null;
  14331. let glColorRenderbuffer = null;
  14332. let glDepthRenderbuffer = null;
  14333. let xrFrame = null;
  14334. let depthStyle = null;
  14335. let clearStyle = null;
  14336. const msaartcSupported = renderer.extensions.has('EXT_multisampled_render_to_texture');
  14337. let msaaExt = null;
  14338. const controllers = [];
  14339. const inputSourcesMap = new Map(); //
  14340. const cameraL = new PerspectiveCamera();
  14341. cameraL.layers.enable(1);
  14342. cameraL.viewport = new Vector4();
  14343. const cameraR = new PerspectiveCamera();
  14344. cameraR.layers.enable(2);
  14345. cameraR.viewport = new Vector4();
  14346. const cameras = [cameraL, cameraR];
  14347. const cameraVR = new ArrayCamera();
  14348. cameraVR.layers.enable(1);
  14349. cameraVR.layers.enable(2);
  14350. let _currentDepthNear = null;
  14351. let _currentDepthFar = null; //
  14352. this.cameraAutoUpdate = true;
  14353. this.enabled = false;
  14354. this.isPresenting = false;
  14355. this.getController = function (index) {
  14356. let controller = controllers[index];
  14357. if (controller === undefined) {
  14358. controller = new WebXRController();
  14359. controllers[index] = controller;
  14360. }
  14361. return controller.getTargetRaySpace();
  14362. };
  14363. this.getControllerGrip = function (index) {
  14364. let controller = controllers[index];
  14365. if (controller === undefined) {
  14366. controller = new WebXRController();
  14367. controllers[index] = controller;
  14368. }
  14369. return controller.getGripSpace();
  14370. };
  14371. this.getHand = function (index) {
  14372. let controller = controllers[index];
  14373. if (controller === undefined) {
  14374. controller = new WebXRController();
  14375. controllers[index] = controller;
  14376. }
  14377. return controller.getHandSpace();
  14378. }; //
  14379. function onSessionEvent(event) {
  14380. const controller = inputSourcesMap.get(event.inputSource);
  14381. if (controller) {
  14382. controller.dispatchEvent({
  14383. type: event.type,
  14384. data: event.inputSource
  14385. });
  14386. }
  14387. }
  14388. function onSessionEnd() {
  14389. inputSourcesMap.forEach(function (controller, inputSource) {
  14390. controller.disconnect(inputSource);
  14391. });
  14392. inputSourcesMap.clear();
  14393. _currentDepthNear = null;
  14394. _currentDepthFar = null; // restore framebuffer/rendering state
  14395. state.bindXRFramebuffer(null);
  14396. renderer.setRenderTarget(renderer.getRenderTarget());
  14397. if (glFramebuffer) gl.deleteFramebuffer(glFramebuffer);
  14398. if (glMultisampledFramebuffer) gl.deleteFramebuffer(glMultisampledFramebuffer);
  14399. if (glColorRenderbuffer) gl.deleteRenderbuffer(glColorRenderbuffer);
  14400. if (glDepthRenderbuffer) gl.deleteRenderbuffer(glDepthRenderbuffer);
  14401. glFramebuffer = null;
  14402. glMultisampledFramebuffer = null;
  14403. glColorRenderbuffer = null;
  14404. glDepthRenderbuffer = null;
  14405. glBaseLayer = null;
  14406. glProjLayer = null;
  14407. glBinding = null;
  14408. session = null; //
  14409. animation.stop();
  14410. scope.isPresenting = false;
  14411. scope.dispatchEvent({
  14412. type: 'sessionend'
  14413. });
  14414. }
  14415. this.setFramebufferScaleFactor = function (value) {
  14416. framebufferScaleFactor = value;
  14417. if (scope.isPresenting === true) {
  14418. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  14419. }
  14420. };
  14421. this.setReferenceSpaceType = function (value) {
  14422. referenceSpaceType = value;
  14423. if (scope.isPresenting === true) {
  14424. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  14425. }
  14426. };
  14427. this.getReferenceSpace = function () {
  14428. return referenceSpace;
  14429. };
  14430. this.getBaseLayer = function () {
  14431. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  14432. };
  14433. this.getBinding = function () {
  14434. return glBinding;
  14435. };
  14436. this.getFrame = function () {
  14437. return xrFrame;
  14438. };
  14439. this.getSession = function () {
  14440. return session;
  14441. };
  14442. this.setSession = async function (value) {
  14443. session = value;
  14444. if (session !== null) {
  14445. session.addEventListener('select', onSessionEvent);
  14446. session.addEventListener('selectstart', onSessionEvent);
  14447. session.addEventListener('selectend', onSessionEvent);
  14448. session.addEventListener('squeeze', onSessionEvent);
  14449. session.addEventListener('squeezestart', onSessionEvent);
  14450. session.addEventListener('squeezeend', onSessionEvent);
  14451. session.addEventListener('end', onSessionEnd);
  14452. session.addEventListener('inputsourceschange', onInputSourcesChange);
  14453. const attributes = gl.getContextAttributes();
  14454. if (attributes.xrCompatible !== true) {
  14455. await gl.makeXRCompatible();
  14456. }
  14457. if (session.renderState.layers === undefined) {
  14458. const layerInit = {
  14459. antialias: attributes.antialias,
  14460. alpha: attributes.alpha,
  14461. depth: attributes.depth,
  14462. stencil: attributes.stencil,
  14463. framebufferScaleFactor: framebufferScaleFactor
  14464. };
  14465. glBaseLayer = new XRWebGLLayer(session, gl, layerInit);
  14466. session.updateRenderState({
  14467. baseLayer: glBaseLayer
  14468. });
  14469. } else if (gl instanceof WebGLRenderingContext) {
  14470. // Use old style webgl layer because we can't use MSAA
  14471. // WebGL2 support.
  14472. const layerInit = {
  14473. antialias: true,
  14474. alpha: attributes.alpha,
  14475. depth: attributes.depth,
  14476. stencil: attributes.stencil,
  14477. framebufferScaleFactor: framebufferScaleFactor
  14478. };
  14479. glBaseLayer = new XRWebGLLayer(session, gl, layerInit);
  14480. session.updateRenderState({
  14481. layers: [glBaseLayer]
  14482. });
  14483. } else {
  14484. isMultisample = attributes.antialias;
  14485. let depthFormat = null;
  14486. if (attributes.depth) {
  14487. clearStyle = gl.DEPTH_BUFFER_BIT;
  14488. if (attributes.stencil) clearStyle |= gl.STENCIL_BUFFER_BIT;
  14489. depthStyle = attributes.stencil ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  14490. depthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  14491. }
  14492. const projectionlayerInit = {
  14493. colorFormat: attributes.alpha ? gl.RGBA8 : gl.RGB8,
  14494. depthFormat: depthFormat,
  14495. scaleFactor: framebufferScaleFactor
  14496. };
  14497. glBinding = new XRWebGLBinding(session, gl);
  14498. glProjLayer = glBinding.createProjectionLayer(projectionlayerInit);
  14499. glFramebuffer = gl.createFramebuffer();
  14500. session.updateRenderState({
  14501. layers: [glProjLayer]
  14502. });
  14503. if (isMultisample && msaartcSupported) {
  14504. msaaExt = renderer.extensions.get('EXT_multisampled_render_to_texture');
  14505. } else if (isMultisample) {
  14506. glMultisampledFramebuffer = gl.createFramebuffer();
  14507. glColorRenderbuffer = gl.createRenderbuffer();
  14508. gl.bindRenderbuffer(gl.RENDERBUFFER, glColorRenderbuffer);
  14509. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, 4, gl.RGBA8, glProjLayer.textureWidth, glProjLayer.textureHeight);
  14510. state.bindFramebuffer(gl.FRAMEBUFFER, glMultisampledFramebuffer);
  14511. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, glColorRenderbuffer);
  14512. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14513. if (depthFormat !== null) {
  14514. glDepthRenderbuffer = gl.createRenderbuffer();
  14515. gl.bindRenderbuffer(gl.RENDERBUFFER, glDepthRenderbuffer);
  14516. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, 4, depthFormat, glProjLayer.textureWidth, glProjLayer.textureHeight);
  14517. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, glDepthRenderbuffer);
  14518. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14519. }
  14520. state.bindFramebuffer(gl.FRAMEBUFFER, null);
  14521. }
  14522. }
  14523. referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
  14524. animation.setContext(session);
  14525. animation.start();
  14526. scope.isPresenting = true;
  14527. scope.dispatchEvent({
  14528. type: 'sessionstart'
  14529. });
  14530. }
  14531. };
  14532. function onInputSourcesChange(event) {
  14533. const inputSources = session.inputSources; // Assign inputSources to available controllers
  14534. for (let i = 0; i < controllers.length; i++) {
  14535. inputSourcesMap.set(inputSources[i], controllers[i]);
  14536. } // Notify disconnected
  14537. for (let i = 0; i < event.removed.length; i++) {
  14538. const inputSource = event.removed[i];
  14539. const controller = inputSourcesMap.get(inputSource);
  14540. if (controller) {
  14541. controller.dispatchEvent({
  14542. type: 'disconnected',
  14543. data: inputSource
  14544. });
  14545. inputSourcesMap.delete(inputSource);
  14546. }
  14547. } // Notify connected
  14548. for (let i = 0; i < event.added.length; i++) {
  14549. const inputSource = event.added[i];
  14550. const controller = inputSourcesMap.get(inputSource);
  14551. if (controller) {
  14552. controller.dispatchEvent({
  14553. type: 'connected',
  14554. data: inputSource
  14555. });
  14556. }
  14557. }
  14558. } //
  14559. const cameraLPos = new Vector3();
  14560. const cameraRPos = new Vector3();
  14561. /**
  14562. * Assumes 2 cameras that are parallel and share an X-axis, and that
  14563. * the cameras' projection and world matrices have already been set.
  14564. * And that near and far planes are identical for both cameras.
  14565. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  14566. */
  14567. function setProjectionFromUnion(camera, cameraL, cameraR) {
  14568. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  14569. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  14570. const ipd = cameraLPos.distanceTo(cameraRPos);
  14571. const projL = cameraL.projectionMatrix.elements;
  14572. const projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  14573. // most likely identical top and bottom frustum extents.
  14574. // Use the left camera for these values.
  14575. const near = projL[14] / (projL[10] - 1);
  14576. const far = projL[14] / (projL[10] + 1);
  14577. const topFov = (projL[9] + 1) / projL[5];
  14578. const bottomFov = (projL[9] - 1) / projL[5];
  14579. const leftFov = (projL[8] - 1) / projL[0];
  14580. const rightFov = (projR[8] + 1) / projR[0];
  14581. const left = near * leftFov;
  14582. const right = near * rightFov; // Calculate the new camera's position offset from the
  14583. // left camera. xOffset should be roughly half `ipd`.
  14584. const zOffset = ipd / (-leftFov + rightFov);
  14585. const xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  14586. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  14587. camera.translateX(xOffset);
  14588. camera.translateZ(zOffset);
  14589. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  14590. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  14591. // the values so that the near plane's position does not change in world space,
  14592. // although must now be relative to the new union camera.
  14593. const near2 = near + zOffset;
  14594. const far2 = far + zOffset;
  14595. const left2 = left - xOffset;
  14596. const right2 = right + (ipd - xOffset);
  14597. const top2 = topFov * far / far2 * near2;
  14598. const bottom2 = bottomFov * far / far2 * near2;
  14599. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  14600. }
  14601. function updateCamera(camera, parent) {
  14602. if (parent === null) {
  14603. camera.matrixWorld.copy(camera.matrix);
  14604. } else {
  14605. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  14606. }
  14607. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  14608. }
  14609. this.updateCamera = function (camera) {
  14610. if (session === null) return;
  14611. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  14612. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  14613. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  14614. // Note that the new renderState won't apply until the next frame. See #18320
  14615. session.updateRenderState({
  14616. depthNear: cameraVR.near,
  14617. depthFar: cameraVR.far
  14618. });
  14619. _currentDepthNear = cameraVR.near;
  14620. _currentDepthFar = cameraVR.far;
  14621. }
  14622. const parent = camera.parent;
  14623. const cameras = cameraVR.cameras;
  14624. updateCamera(cameraVR, parent);
  14625. for (let i = 0; i < cameras.length; i++) {
  14626. updateCamera(cameras[i], parent);
  14627. }
  14628. cameraVR.matrixWorld.decompose(cameraVR.position, cameraVR.quaternion, cameraVR.scale); // update user camera and its children
  14629. camera.position.copy(cameraVR.position);
  14630. camera.quaternion.copy(cameraVR.quaternion);
  14631. camera.scale.copy(cameraVR.scale);
  14632. camera.matrix.copy(cameraVR.matrix);
  14633. camera.matrixWorld.copy(cameraVR.matrixWorld);
  14634. const children = camera.children;
  14635. for (let i = 0, l = children.length; i < l; i++) {
  14636. children[i].updateMatrixWorld(true);
  14637. } // update projection matrix for proper view frustum culling
  14638. if (cameras.length === 2) {
  14639. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  14640. } else {
  14641. // assume single camera setup (AR)
  14642. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  14643. }
  14644. };
  14645. this.getCamera = function () {
  14646. return cameraVR;
  14647. };
  14648. this.getFoveation = function () {
  14649. if (glProjLayer !== null) {
  14650. return glProjLayer.fixedFoveation;
  14651. }
  14652. if (glBaseLayer !== null) {
  14653. return glBaseLayer.fixedFoveation;
  14654. }
  14655. return undefined;
  14656. };
  14657. this.setFoveation = function (foveation) {
  14658. // 0 = no foveation = full resolution
  14659. // 1 = maximum foveation = the edges render at lower resolution
  14660. if (glProjLayer !== null) {
  14661. glProjLayer.fixedFoveation = foveation;
  14662. }
  14663. if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined) {
  14664. glBaseLayer.fixedFoveation = foveation;
  14665. }
  14666. }; // Animation Loop
  14667. let onAnimationFrameCallback = null;
  14668. function onAnimationFrame(time, frame) {
  14669. pose = frame.getViewerPose(referenceSpace);
  14670. xrFrame = frame;
  14671. if (pose !== null) {
  14672. const views = pose.views;
  14673. if (glBaseLayer !== null) {
  14674. state.bindXRFramebuffer(glBaseLayer.framebuffer);
  14675. }
  14676. let cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  14677. if (views.length !== cameraVR.cameras.length) {
  14678. cameraVR.cameras.length = 0;
  14679. cameraVRNeedsUpdate = true;
  14680. }
  14681. for (let i = 0; i < views.length; i++) {
  14682. const view = views[i];
  14683. let viewport = null;
  14684. if (glBaseLayer !== null) {
  14685. viewport = glBaseLayer.getViewport(view);
  14686. } else {
  14687. const glSubImage = glBinding.getViewSubImage(glProjLayer, view);
  14688. state.bindXRFramebuffer(glFramebuffer);
  14689. if (isMultisample && msaartcSupported) {
  14690. if (glSubImage.depthStencilTexture !== undefined) {
  14691. msaaExt.framebufferTexture2DMultisampleEXT(gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, glSubImage.depthStencilTexture, 0, 4);
  14692. }
  14693. msaaExt.framebufferTexture2DMultisampleEXT(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, glSubImage.colorTexture, 0, 4);
  14694. } else {
  14695. if (glSubImage.depthStencilTexture !== undefined) {
  14696. gl.framebufferTexture2D(gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, glSubImage.depthStencilTexture, 0);
  14697. }
  14698. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, glSubImage.colorTexture, 0);
  14699. }
  14700. viewport = glSubImage.viewport;
  14701. }
  14702. const camera = cameras[i];
  14703. camera.matrix.fromArray(view.transform.matrix);
  14704. camera.projectionMatrix.fromArray(view.projectionMatrix);
  14705. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  14706. if (i === 0) {
  14707. cameraVR.matrix.copy(camera.matrix);
  14708. }
  14709. if (cameraVRNeedsUpdate === true) {
  14710. cameraVR.cameras.push(camera);
  14711. }
  14712. }
  14713. if (isMultisample && !msaartcSupported) {
  14714. state.bindXRFramebuffer(glMultisampledFramebuffer);
  14715. if (clearStyle !== null) gl.clear(clearStyle);
  14716. }
  14717. } //
  14718. const inputSources = session.inputSources;
  14719. for (let i = 0; i < controllers.length; i++) {
  14720. const controller = controllers[i];
  14721. const inputSource = inputSources[i];
  14722. controller.update(inputSource, frame, referenceSpace);
  14723. }
  14724. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  14725. if (isMultisample && !msaartcSupported) {
  14726. const width = glProjLayer.textureWidth;
  14727. const height = glProjLayer.textureHeight;
  14728. state.bindFramebuffer(gl.READ_FRAMEBUFFER, glMultisampledFramebuffer);
  14729. state.bindFramebuffer(gl.DRAW_FRAMEBUFFER, glFramebuffer); // Invalidate the depth here to avoid flush of the depth data to main memory.
  14730. gl.invalidateFramebuffer(gl.READ_FRAMEBUFFER, [depthStyle]);
  14731. gl.invalidateFramebuffer(gl.DRAW_FRAMEBUFFER, [depthStyle]);
  14732. gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST); // Invalidate the MSAA buffer because it's not needed anymore.
  14733. gl.invalidateFramebuffer(gl.READ_FRAMEBUFFER, [gl.COLOR_ATTACHMENT0]);
  14734. state.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  14735. state.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  14736. state.bindFramebuffer(gl.FRAMEBUFFER, glMultisampledFramebuffer);
  14737. }
  14738. xrFrame = null;
  14739. }
  14740. const animation = new WebGLAnimation();
  14741. animation.setAnimationLoop(onAnimationFrame);
  14742. this.setAnimationLoop = function (callback) {
  14743. onAnimationFrameCallback = callback;
  14744. };
  14745. this.dispose = function () {};
  14746. }
  14747. }
  14748. function WebGLMaterials(properties) {
  14749. function refreshFogUniforms(uniforms, fog) {
  14750. uniforms.fogColor.value.copy(fog.color);
  14751. if (fog.isFog) {
  14752. uniforms.fogNear.value = fog.near;
  14753. uniforms.fogFar.value = fog.far;
  14754. } else if (fog.isFogExp2) {
  14755. uniforms.fogDensity.value = fog.density;
  14756. }
  14757. }
  14758. function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) {
  14759. if (material.isMeshBasicMaterial) {
  14760. refreshUniformsCommon(uniforms, material);
  14761. } else if (material.isMeshLambertMaterial) {
  14762. refreshUniformsCommon(uniforms, material);
  14763. refreshUniformsLambert(uniforms, material);
  14764. } else if (material.isMeshToonMaterial) {
  14765. refreshUniformsCommon(uniforms, material);
  14766. refreshUniformsToon(uniforms, material);
  14767. } else if (material.isMeshPhongMaterial) {
  14768. refreshUniformsCommon(uniforms, material);
  14769. refreshUniformsPhong(uniforms, material);
  14770. } else if (material.isMeshStandardMaterial) {
  14771. refreshUniformsCommon(uniforms, material);
  14772. if (material.isMeshPhysicalMaterial) {
  14773. refreshUniformsPhysical(uniforms, material, transmissionRenderTarget);
  14774. } else {
  14775. refreshUniformsStandard(uniforms, material);
  14776. }
  14777. } else if (material.isMeshMatcapMaterial) {
  14778. refreshUniformsCommon(uniforms, material);
  14779. refreshUniformsMatcap(uniforms, material);
  14780. } else if (material.isMeshDepthMaterial) {
  14781. refreshUniformsCommon(uniforms, material);
  14782. refreshUniformsDepth(uniforms, material);
  14783. } else if (material.isMeshDistanceMaterial) {
  14784. refreshUniformsCommon(uniforms, material);
  14785. refreshUniformsDistance(uniforms, material);
  14786. } else if (material.isMeshNormalMaterial) {
  14787. refreshUniformsCommon(uniforms, material);
  14788. refreshUniformsNormal(uniforms, material);
  14789. } else if (material.isLineBasicMaterial) {
  14790. refreshUniformsLine(uniforms, material);
  14791. if (material.isLineDashedMaterial) {
  14792. refreshUniformsDash(uniforms, material);
  14793. }
  14794. } else if (material.isPointsMaterial) {
  14795. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  14796. } else if (material.isSpriteMaterial) {
  14797. refreshUniformsSprites(uniforms, material);
  14798. } else if (material.isShadowMaterial) {
  14799. uniforms.color.value.copy(material.color);
  14800. uniforms.opacity.value = material.opacity;
  14801. } else if (material.isShaderMaterial) {
  14802. material.uniformsNeedUpdate = false; // #15581
  14803. }
  14804. }
  14805. function refreshUniformsCommon(uniforms, material) {
  14806. uniforms.opacity.value = material.opacity;
  14807. if (material.color) {
  14808. uniforms.diffuse.value.copy(material.color);
  14809. }
  14810. if (material.emissive) {
  14811. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  14812. }
  14813. if (material.map) {
  14814. uniforms.map.value = material.map;
  14815. }
  14816. if (material.alphaMap) {
  14817. uniforms.alphaMap.value = material.alphaMap;
  14818. }
  14819. if (material.specularMap) {
  14820. uniforms.specularMap.value = material.specularMap;
  14821. }
  14822. if (material.alphaTest > 0) {
  14823. uniforms.alphaTest.value = material.alphaTest;
  14824. }
  14825. const envMap = properties.get(material).envMap;
  14826. if (envMap) {
  14827. uniforms.envMap.value = envMap;
  14828. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1;
  14829. uniforms.reflectivity.value = material.reflectivity;
  14830. uniforms.ior.value = material.ior;
  14831. uniforms.refractionRatio.value = material.refractionRatio;
  14832. const maxMipLevel = properties.get(envMap).__maxMipLevel;
  14833. if (maxMipLevel !== undefined) {
  14834. uniforms.maxMipLevel.value = maxMipLevel;
  14835. }
  14836. }
  14837. if (material.lightMap) {
  14838. uniforms.lightMap.value = material.lightMap;
  14839. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  14840. }
  14841. if (material.aoMap) {
  14842. uniforms.aoMap.value = material.aoMap;
  14843. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  14844. } // uv repeat and offset setting priorities
  14845. // 1. color map
  14846. // 2. specular map
  14847. // 3. displacementMap map
  14848. // 4. normal map
  14849. // 5. bump map
  14850. // 6. roughnessMap map
  14851. // 7. metalnessMap map
  14852. // 8. alphaMap map
  14853. // 9. emissiveMap map
  14854. // 10. clearcoat map
  14855. // 11. clearcoat normal map
  14856. // 12. clearcoat roughnessMap map
  14857. // 13. specular intensity map
  14858. // 14. specular tint map
  14859. // 15. transmission map
  14860. // 16. thickness map
  14861. let uvScaleMap;
  14862. if (material.map) {
  14863. uvScaleMap = material.map;
  14864. } else if (material.specularMap) {
  14865. uvScaleMap = material.specularMap;
  14866. } else if (material.displacementMap) {
  14867. uvScaleMap = material.displacementMap;
  14868. } else if (material.normalMap) {
  14869. uvScaleMap = material.normalMap;
  14870. } else if (material.bumpMap) {
  14871. uvScaleMap = material.bumpMap;
  14872. } else if (material.roughnessMap) {
  14873. uvScaleMap = material.roughnessMap;
  14874. } else if (material.metalnessMap) {
  14875. uvScaleMap = material.metalnessMap;
  14876. } else if (material.alphaMap) {
  14877. uvScaleMap = material.alphaMap;
  14878. } else if (material.emissiveMap) {
  14879. uvScaleMap = material.emissiveMap;
  14880. } else if (material.clearcoatMap) {
  14881. uvScaleMap = material.clearcoatMap;
  14882. } else if (material.clearcoatNormalMap) {
  14883. uvScaleMap = material.clearcoatNormalMap;
  14884. } else if (material.clearcoatRoughnessMap) {
  14885. uvScaleMap = material.clearcoatRoughnessMap;
  14886. } else if (material.specularIntensityMap) {
  14887. uvScaleMap = material.specularIntensityMap;
  14888. } else if (material.specularTintMap) {
  14889. uvScaleMap = material.specularTintMap;
  14890. } else if (material.transmissionMap) {
  14891. uvScaleMap = material.transmissionMap;
  14892. } else if (material.thicknessMap) {
  14893. uvScaleMap = material.thicknessMap;
  14894. }
  14895. if (uvScaleMap !== undefined) {
  14896. // backwards compatibility
  14897. if (uvScaleMap.isWebGLRenderTarget) {
  14898. uvScaleMap = uvScaleMap.texture;
  14899. }
  14900. if (uvScaleMap.matrixAutoUpdate === true) {
  14901. uvScaleMap.updateMatrix();
  14902. }
  14903. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  14904. } // uv repeat and offset setting priorities for uv2
  14905. // 1. ao map
  14906. // 2. light map
  14907. let uv2ScaleMap;
  14908. if (material.aoMap) {
  14909. uv2ScaleMap = material.aoMap;
  14910. } else if (material.lightMap) {
  14911. uv2ScaleMap = material.lightMap;
  14912. }
  14913. if (uv2ScaleMap !== undefined) {
  14914. // backwards compatibility
  14915. if (uv2ScaleMap.isWebGLRenderTarget) {
  14916. uv2ScaleMap = uv2ScaleMap.texture;
  14917. }
  14918. if (uv2ScaleMap.matrixAutoUpdate === true) {
  14919. uv2ScaleMap.updateMatrix();
  14920. }
  14921. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  14922. }
  14923. }
  14924. function refreshUniformsLine(uniforms, material) {
  14925. uniforms.diffuse.value.copy(material.color);
  14926. uniforms.opacity.value = material.opacity;
  14927. }
  14928. function refreshUniformsDash(uniforms, material) {
  14929. uniforms.dashSize.value = material.dashSize;
  14930. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14931. uniforms.scale.value = material.scale;
  14932. }
  14933. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  14934. uniforms.diffuse.value.copy(material.color);
  14935. uniforms.opacity.value = material.opacity;
  14936. uniforms.size.value = material.size * pixelRatio;
  14937. uniforms.scale.value = height * 0.5;
  14938. if (material.map) {
  14939. uniforms.map.value = material.map;
  14940. }
  14941. if (material.alphaMap) {
  14942. uniforms.alphaMap.value = material.alphaMap;
  14943. }
  14944. if (material.alphaTest > 0) {
  14945. uniforms.alphaTest.value = material.alphaTest;
  14946. } // uv repeat and offset setting priorities
  14947. // 1. color map
  14948. // 2. alpha map
  14949. let uvScaleMap;
  14950. if (material.map) {
  14951. uvScaleMap = material.map;
  14952. } else if (material.alphaMap) {
  14953. uvScaleMap = material.alphaMap;
  14954. }
  14955. if (uvScaleMap !== undefined) {
  14956. if (uvScaleMap.matrixAutoUpdate === true) {
  14957. uvScaleMap.updateMatrix();
  14958. }
  14959. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  14960. }
  14961. }
  14962. function refreshUniformsSprites(uniforms, material) {
  14963. uniforms.diffuse.value.copy(material.color);
  14964. uniforms.opacity.value = material.opacity;
  14965. uniforms.rotation.value = material.rotation;
  14966. if (material.map) {
  14967. uniforms.map.value = material.map;
  14968. }
  14969. if (material.alphaMap) {
  14970. uniforms.alphaMap.value = material.alphaMap;
  14971. }
  14972. if (material.alphaTest > 0) {
  14973. uniforms.alphaTest.value = material.alphaTest;
  14974. } // uv repeat and offset setting priorities
  14975. // 1. color map
  14976. // 2. alpha map
  14977. let uvScaleMap;
  14978. if (material.map) {
  14979. uvScaleMap = material.map;
  14980. } else if (material.alphaMap) {
  14981. uvScaleMap = material.alphaMap;
  14982. }
  14983. if (uvScaleMap !== undefined) {
  14984. if (uvScaleMap.matrixAutoUpdate === true) {
  14985. uvScaleMap.updateMatrix();
  14986. }
  14987. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  14988. }
  14989. }
  14990. function refreshUniformsLambert(uniforms, material) {
  14991. if (material.emissiveMap) {
  14992. uniforms.emissiveMap.value = material.emissiveMap;
  14993. }
  14994. }
  14995. function refreshUniformsPhong(uniforms, material) {
  14996. uniforms.specular.value.copy(material.specular);
  14997. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  14998. if (material.emissiveMap) {
  14999. uniforms.emissiveMap.value = material.emissiveMap;
  15000. }
  15001. if (material.bumpMap) {
  15002. uniforms.bumpMap.value = material.bumpMap;
  15003. uniforms.bumpScale.value = material.bumpScale;
  15004. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15005. }
  15006. if (material.normalMap) {
  15007. uniforms.normalMap.value = material.normalMap;
  15008. uniforms.normalScale.value.copy(material.normalScale);
  15009. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15010. }
  15011. if (material.displacementMap) {
  15012. uniforms.displacementMap.value = material.displacementMap;
  15013. uniforms.displacementScale.value = material.displacementScale;
  15014. uniforms.displacementBias.value = material.displacementBias;
  15015. }
  15016. }
  15017. function refreshUniformsToon(uniforms, material) {
  15018. if (material.gradientMap) {
  15019. uniforms.gradientMap.value = material.gradientMap;
  15020. }
  15021. if (material.emissiveMap) {
  15022. uniforms.emissiveMap.value = material.emissiveMap;
  15023. }
  15024. if (material.bumpMap) {
  15025. uniforms.bumpMap.value = material.bumpMap;
  15026. uniforms.bumpScale.value = material.bumpScale;
  15027. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15028. }
  15029. if (material.normalMap) {
  15030. uniforms.normalMap.value = material.normalMap;
  15031. uniforms.normalScale.value.copy(material.normalScale);
  15032. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15033. }
  15034. if (material.displacementMap) {
  15035. uniforms.displacementMap.value = material.displacementMap;
  15036. uniforms.displacementScale.value = material.displacementScale;
  15037. uniforms.displacementBias.value = material.displacementBias;
  15038. }
  15039. }
  15040. function refreshUniformsStandard(uniforms, material) {
  15041. uniforms.roughness.value = material.roughness;
  15042. uniforms.metalness.value = material.metalness;
  15043. if (material.roughnessMap) {
  15044. uniforms.roughnessMap.value = material.roughnessMap;
  15045. }
  15046. if (material.metalnessMap) {
  15047. uniforms.metalnessMap.value = material.metalnessMap;
  15048. }
  15049. if (material.emissiveMap) {
  15050. uniforms.emissiveMap.value = material.emissiveMap;
  15051. }
  15052. if (material.bumpMap) {
  15053. uniforms.bumpMap.value = material.bumpMap;
  15054. uniforms.bumpScale.value = material.bumpScale;
  15055. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15056. }
  15057. if (material.normalMap) {
  15058. uniforms.normalMap.value = material.normalMap;
  15059. uniforms.normalScale.value.copy(material.normalScale);
  15060. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15061. }
  15062. if (material.displacementMap) {
  15063. uniforms.displacementMap.value = material.displacementMap;
  15064. uniforms.displacementScale.value = material.displacementScale;
  15065. uniforms.displacementBias.value = material.displacementBias;
  15066. }
  15067. const envMap = properties.get(material).envMap;
  15068. if (envMap) {
  15069. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15070. uniforms.envMapIntensity.value = material.envMapIntensity;
  15071. }
  15072. }
  15073. function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) {
  15074. refreshUniformsStandard(uniforms, material);
  15075. uniforms.ior.value = material.ior; // also part of uniforms common
  15076. if (material.sheen > 0) {
  15077. uniforms.sheenTint.value.copy(material.sheenTint).multiplyScalar(material.sheen);
  15078. uniforms.sheenRoughness.value = material.sheenRoughness;
  15079. }
  15080. if (material.clearcoat > 0) {
  15081. uniforms.clearcoat.value = material.clearcoat;
  15082. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15083. if (material.clearcoatMap) {
  15084. uniforms.clearcoatMap.value = material.clearcoatMap;
  15085. }
  15086. if (material.clearcoatRoughnessMap) {
  15087. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  15088. }
  15089. if (material.clearcoatNormalMap) {
  15090. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  15091. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15092. if (material.side === BackSide) {
  15093. uniforms.clearcoatNormalScale.value.negate();
  15094. }
  15095. }
  15096. }
  15097. if (material.transmission > 0) {
  15098. uniforms.transmission.value = material.transmission;
  15099. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  15100. uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height);
  15101. if (material.transmissionMap) {
  15102. uniforms.transmissionMap.value = material.transmissionMap;
  15103. }
  15104. uniforms.thickness.value = material.thickness;
  15105. if (material.thicknessMap) {
  15106. uniforms.thicknessMap.value = material.thicknessMap;
  15107. }
  15108. uniforms.attenuationDistance.value = material.attenuationDistance;
  15109. uniforms.attenuationTint.value.copy(material.attenuationTint);
  15110. }
  15111. uniforms.specularIntensity.value = material.specularIntensity;
  15112. uniforms.specularTint.value.copy(material.specularTint);
  15113. if (material.specularIntensityMap) {
  15114. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  15115. }
  15116. if (material.specularTintMap) {
  15117. uniforms.specularTintMap.value = material.specularTintMap;
  15118. }
  15119. }
  15120. function refreshUniformsMatcap(uniforms, material) {
  15121. if (material.matcap) {
  15122. uniforms.matcap.value = material.matcap;
  15123. }
  15124. if (material.bumpMap) {
  15125. uniforms.bumpMap.value = material.bumpMap;
  15126. uniforms.bumpScale.value = material.bumpScale;
  15127. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15128. }
  15129. if (material.normalMap) {
  15130. uniforms.normalMap.value = material.normalMap;
  15131. uniforms.normalScale.value.copy(material.normalScale);
  15132. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15133. }
  15134. if (material.displacementMap) {
  15135. uniforms.displacementMap.value = material.displacementMap;
  15136. uniforms.displacementScale.value = material.displacementScale;
  15137. uniforms.displacementBias.value = material.displacementBias;
  15138. }
  15139. }
  15140. function refreshUniformsDepth(uniforms, material) {
  15141. if (material.displacementMap) {
  15142. uniforms.displacementMap.value = material.displacementMap;
  15143. uniforms.displacementScale.value = material.displacementScale;
  15144. uniforms.displacementBias.value = material.displacementBias;
  15145. }
  15146. }
  15147. function refreshUniformsDistance(uniforms, material) {
  15148. if (material.displacementMap) {
  15149. uniforms.displacementMap.value = material.displacementMap;
  15150. uniforms.displacementScale.value = material.displacementScale;
  15151. uniforms.displacementBias.value = material.displacementBias;
  15152. }
  15153. uniforms.referencePosition.value.copy(material.referencePosition);
  15154. uniforms.nearDistance.value = material.nearDistance;
  15155. uniforms.farDistance.value = material.farDistance;
  15156. }
  15157. function refreshUniformsNormal(uniforms, material) {
  15158. if (material.bumpMap) {
  15159. uniforms.bumpMap.value = material.bumpMap;
  15160. uniforms.bumpScale.value = material.bumpScale;
  15161. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15162. }
  15163. if (material.normalMap) {
  15164. uniforms.normalMap.value = material.normalMap;
  15165. uniforms.normalScale.value.copy(material.normalScale);
  15166. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15167. }
  15168. if (material.displacementMap) {
  15169. uniforms.displacementMap.value = material.displacementMap;
  15170. uniforms.displacementScale.value = material.displacementScale;
  15171. uniforms.displacementBias.value = material.displacementBias;
  15172. }
  15173. }
  15174. return {
  15175. refreshFogUniforms: refreshFogUniforms,
  15176. refreshMaterialUniforms: refreshMaterialUniforms
  15177. };
  15178. }
  15179. function createCanvasElement() {
  15180. const canvas = createElementNS('canvas');
  15181. canvas.style.display = 'block';
  15182. return canvas;
  15183. }
  15184. function WebGLRenderer(parameters = {}) {
  15185. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  15186. _context = parameters.context !== undefined ? parameters.context : null,
  15187. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  15188. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15189. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15190. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15191. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15192. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  15193. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  15194. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  15195. let currentRenderList = null;
  15196. let currentRenderState = null; // render() can be called from within a callback triggered by another render.
  15197. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  15198. const renderListStack = [];
  15199. const renderStateStack = []; // public properties
  15200. this.domElement = _canvas; // Debug configuration container
  15201. this.debug = {
  15202. /**
  15203. * Enables error checking and reporting when shader programs are being compiled
  15204. * @type {boolean}
  15205. */
  15206. checkShaderErrors: true
  15207. }; // clearing
  15208. this.autoClear = true;
  15209. this.autoClearColor = true;
  15210. this.autoClearDepth = true;
  15211. this.autoClearStencil = true; // scene graph
  15212. this.sortObjects = true; // user-defined clipping
  15213. this.clippingPlanes = [];
  15214. this.localClippingEnabled = false; // physically based shading
  15215. this.gammaFactor = 2.0; // for backwards compatibility
  15216. this.outputEncoding = LinearEncoding; // physical lights
  15217. this.physicallyCorrectLights = false; // tone mapping
  15218. this.toneMapping = NoToneMapping;
  15219. this.toneMappingExposure = 1.0; // internal properties
  15220. const _this = this;
  15221. let _isContextLost = false; // internal state cache
  15222. let _currentActiveCubeFace = 0;
  15223. let _currentActiveMipmapLevel = 0;
  15224. let _currentRenderTarget = null;
  15225. let _currentMaterialId = -1;
  15226. let _currentCamera = null;
  15227. const _currentViewport = new Vector4();
  15228. const _currentScissor = new Vector4();
  15229. let _currentScissorTest = null; //
  15230. let _width = _canvas.width;
  15231. let _height = _canvas.height;
  15232. let _pixelRatio = 1;
  15233. let _opaqueSort = null;
  15234. let _transparentSort = null;
  15235. const _viewport = new Vector4(0, 0, _width, _height);
  15236. const _scissor = new Vector4(0, 0, _width, _height);
  15237. let _scissorTest = false; //
  15238. const _currentDrawBuffers = []; // frustum
  15239. const _frustum = new Frustum(); // clipping
  15240. let _clippingEnabled = false;
  15241. let _localClippingEnabled = false; // transmission
  15242. let _transmissionRenderTarget = null; // camera matrices cache
  15243. const _projScreenMatrix = new Matrix4();
  15244. const _vector3 = new Vector3();
  15245. const _emptyScene = {
  15246. background: null,
  15247. fog: null,
  15248. environment: null,
  15249. overrideMaterial: null,
  15250. isScene: true
  15251. };
  15252. function getTargetPixelRatio() {
  15253. return _currentRenderTarget === null ? _pixelRatio : 1;
  15254. } // initialize
  15255. let _gl = _context;
  15256. function getContext(contextNames, contextAttributes) {
  15257. for (let i = 0; i < contextNames.length; i++) {
  15258. const contextName = contextNames[i];
  15259. const context = _canvas.getContext(contextName, contextAttributes);
  15260. if (context !== null) return context;
  15261. }
  15262. return null;
  15263. }
  15264. try {
  15265. const contextAttributes = {
  15266. alpha: _alpha,
  15267. depth: _depth,
  15268. stencil: _stencil,
  15269. antialias: _antialias,
  15270. premultipliedAlpha: _premultipliedAlpha,
  15271. preserveDrawingBuffer: _preserveDrawingBuffer,
  15272. powerPreference: _powerPreference,
  15273. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  15274. }; // event listeners must be registered before WebGL context is created, see #12753
  15275. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  15276. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  15277. if (_gl === null) {
  15278. const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  15279. if (_this.isWebGL1Renderer === true) {
  15280. contextNames.shift();
  15281. }
  15282. _gl = getContext(contextNames, contextAttributes);
  15283. if (_gl === null) {
  15284. if (getContext(contextNames)) {
  15285. throw new Error('Error creating WebGL context with your selected attributes.');
  15286. } else {
  15287. throw new Error('Error creating WebGL context.');
  15288. }
  15289. }
  15290. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  15291. if (_gl.getShaderPrecisionFormat === undefined) {
  15292. _gl.getShaderPrecisionFormat = function () {
  15293. return {
  15294. 'rangeMin': 1,
  15295. 'rangeMax': 1,
  15296. 'precision': 1
  15297. };
  15298. };
  15299. }
  15300. } catch (error) {
  15301. console.error('THREE.WebGLRenderer: ' + error.message);
  15302. throw error;
  15303. }
  15304. let extensions, capabilities, state, info;
  15305. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  15306. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  15307. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  15308. let utils, bindingStates;
  15309. function initGLContext() {
  15310. extensions = new WebGLExtensions(_gl);
  15311. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  15312. extensions.init(capabilities);
  15313. utils = new WebGLUtils(_gl, extensions, capabilities);
  15314. state = new WebGLState(_gl, extensions, capabilities);
  15315. _currentDrawBuffers[0] = _gl.BACK;
  15316. info = new WebGLInfo(_gl);
  15317. properties = new WebGLProperties();
  15318. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  15319. cubemaps = new WebGLCubeMaps(_this);
  15320. cubeuvmaps = new WebGLCubeUVMaps(_this);
  15321. attributes = new WebGLAttributes(_gl, capabilities);
  15322. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  15323. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  15324. objects = new WebGLObjects(_gl, geometries, attributes, info);
  15325. morphtargets = new WebGLMorphtargets(_gl, capabilities, textures);
  15326. clipping = new WebGLClipping(properties);
  15327. programCache = new WebGLPrograms(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping);
  15328. materials = new WebGLMaterials(properties);
  15329. renderLists = new WebGLRenderLists(properties);
  15330. renderStates = new WebGLRenderStates(extensions, capabilities);
  15331. background = new WebGLBackground(_this, cubemaps, state, objects, _premultipliedAlpha);
  15332. shadowMap = new WebGLShadowMap(_this, objects, capabilities);
  15333. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  15334. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  15335. info.programs = programCache.programs;
  15336. _this.capabilities = capabilities;
  15337. _this.extensions = extensions;
  15338. _this.properties = properties;
  15339. _this.renderLists = renderLists;
  15340. _this.shadowMap = shadowMap;
  15341. _this.state = state;
  15342. _this.info = info;
  15343. }
  15344. initGLContext(); // xr
  15345. const xr = new WebXRManager(_this, _gl);
  15346. this.xr = xr; // API
  15347. this.getContext = function () {
  15348. return _gl;
  15349. };
  15350. this.getContextAttributes = function () {
  15351. return _gl.getContextAttributes();
  15352. };
  15353. this.forceContextLoss = function () {
  15354. const extension = extensions.get('WEBGL_lose_context');
  15355. if (extension) extension.loseContext();
  15356. };
  15357. this.forceContextRestore = function () {
  15358. const extension = extensions.get('WEBGL_lose_context');
  15359. if (extension) extension.restoreContext();
  15360. };
  15361. this.getPixelRatio = function () {
  15362. return _pixelRatio;
  15363. };
  15364. this.setPixelRatio = function (value) {
  15365. if (value === undefined) return;
  15366. _pixelRatio = value;
  15367. this.setSize(_width, _height, false);
  15368. };
  15369. this.getSize = function (target) {
  15370. return target.set(_width, _height);
  15371. };
  15372. this.setSize = function (width, height, updateStyle) {
  15373. if (xr.isPresenting) {
  15374. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  15375. return;
  15376. }
  15377. _width = width;
  15378. _height = height;
  15379. _canvas.width = Math.floor(width * _pixelRatio);
  15380. _canvas.height = Math.floor(height * _pixelRatio);
  15381. if (updateStyle !== false) {
  15382. _canvas.style.width = width + 'px';
  15383. _canvas.style.height = height + 'px';
  15384. }
  15385. this.setViewport(0, 0, width, height);
  15386. };
  15387. this.getDrawingBufferSize = function (target) {
  15388. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  15389. };
  15390. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  15391. _width = width;
  15392. _height = height;
  15393. _pixelRatio = pixelRatio;
  15394. _canvas.width = Math.floor(width * pixelRatio);
  15395. _canvas.height = Math.floor(height * pixelRatio);
  15396. this.setViewport(0, 0, width, height);
  15397. };
  15398. this.getCurrentViewport = function (target) {
  15399. return target.copy(_currentViewport);
  15400. };
  15401. this.getViewport = function (target) {
  15402. return target.copy(_viewport);
  15403. };
  15404. this.setViewport = function (x, y, width, height) {
  15405. if (x.isVector4) {
  15406. _viewport.set(x.x, x.y, x.z, x.w);
  15407. } else {
  15408. _viewport.set(x, y, width, height);
  15409. }
  15410. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  15411. };
  15412. this.getScissor = function (target) {
  15413. return target.copy(_scissor);
  15414. };
  15415. this.setScissor = function (x, y, width, height) {
  15416. if (x.isVector4) {
  15417. _scissor.set(x.x, x.y, x.z, x.w);
  15418. } else {
  15419. _scissor.set(x, y, width, height);
  15420. }
  15421. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  15422. };
  15423. this.getScissorTest = function () {
  15424. return _scissorTest;
  15425. };
  15426. this.setScissorTest = function (boolean) {
  15427. state.setScissorTest(_scissorTest = boolean);
  15428. };
  15429. this.setOpaqueSort = function (method) {
  15430. _opaqueSort = method;
  15431. };
  15432. this.setTransparentSort = function (method) {
  15433. _transparentSort = method;
  15434. }; // Clearing
  15435. this.getClearColor = function (target) {
  15436. return target.copy(background.getClearColor());
  15437. };
  15438. this.setClearColor = function () {
  15439. background.setClearColor.apply(background, arguments);
  15440. };
  15441. this.getClearAlpha = function () {
  15442. return background.getClearAlpha();
  15443. };
  15444. this.setClearAlpha = function () {
  15445. background.setClearAlpha.apply(background, arguments);
  15446. };
  15447. this.clear = function (color, depth, stencil) {
  15448. let bits = 0;
  15449. if (color === undefined || color) bits |= _gl.COLOR_BUFFER_BIT;
  15450. if (depth === undefined || depth) bits |= _gl.DEPTH_BUFFER_BIT;
  15451. if (stencil === undefined || stencil) bits |= _gl.STENCIL_BUFFER_BIT;
  15452. _gl.clear(bits);
  15453. };
  15454. this.clearColor = function () {
  15455. this.clear(true, false, false);
  15456. };
  15457. this.clearDepth = function () {
  15458. this.clear(false, true, false);
  15459. };
  15460. this.clearStencil = function () {
  15461. this.clear(false, false, true);
  15462. }; //
  15463. this.dispose = function () {
  15464. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  15465. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  15466. renderLists.dispose();
  15467. renderStates.dispose();
  15468. properties.dispose();
  15469. cubemaps.dispose();
  15470. cubeuvmaps.dispose();
  15471. objects.dispose();
  15472. bindingStates.dispose();
  15473. xr.dispose();
  15474. xr.removeEventListener('sessionstart', onXRSessionStart);
  15475. xr.removeEventListener('sessionend', onXRSessionEnd);
  15476. if (_transmissionRenderTarget) {
  15477. _transmissionRenderTarget.dispose();
  15478. _transmissionRenderTarget = null;
  15479. }
  15480. animation.stop();
  15481. }; // Events
  15482. function onContextLost(event) {
  15483. event.preventDefault();
  15484. console.log('THREE.WebGLRenderer: Context Lost.');
  15485. _isContextLost = true;
  15486. }
  15487. function onContextRestore() {
  15488. console.log('THREE.WebGLRenderer: Context Restored.');
  15489. _isContextLost = false;
  15490. const infoAutoReset = info.autoReset;
  15491. const shadowMapEnabled = shadowMap.enabled;
  15492. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  15493. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  15494. const shadowMapType = shadowMap.type;
  15495. initGLContext();
  15496. info.autoReset = infoAutoReset;
  15497. shadowMap.enabled = shadowMapEnabled;
  15498. shadowMap.autoUpdate = shadowMapAutoUpdate;
  15499. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  15500. shadowMap.type = shadowMapType;
  15501. }
  15502. function onMaterialDispose(event) {
  15503. const material = event.target;
  15504. material.removeEventListener('dispose', onMaterialDispose);
  15505. deallocateMaterial(material);
  15506. } // Buffer deallocation
  15507. function deallocateMaterial(material) {
  15508. releaseMaterialProgramReferences(material);
  15509. properties.remove(material);
  15510. }
  15511. function releaseMaterialProgramReferences(material) {
  15512. const programs = properties.get(material).programs;
  15513. if (programs !== undefined) {
  15514. programs.forEach(function (program) {
  15515. programCache.releaseProgram(program);
  15516. });
  15517. }
  15518. } // Buffer rendering
  15519. function renderObjectImmediate(object, program) {
  15520. object.render(function (object) {
  15521. _this.renderBufferImmediate(object, program);
  15522. });
  15523. }
  15524. this.renderBufferImmediate = function (object, program) {
  15525. bindingStates.initAttributes();
  15526. const buffers = properties.get(object);
  15527. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  15528. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  15529. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  15530. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  15531. const programAttributes = program.getAttributes();
  15532. if (object.hasPositions) {
  15533. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.position);
  15534. _gl.bufferData(_gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW);
  15535. bindingStates.enableAttribute(programAttributes.position.location);
  15536. _gl.vertexAttribPointer(programAttributes.position.location, 3, _gl.FLOAT, false, 0, 0);
  15537. }
  15538. if (object.hasNormals) {
  15539. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.normal);
  15540. _gl.bufferData(_gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW);
  15541. bindingStates.enableAttribute(programAttributes.normal.location);
  15542. _gl.vertexAttribPointer(programAttributes.normal.location, 3, _gl.FLOAT, false, 0, 0);
  15543. }
  15544. if (object.hasUvs) {
  15545. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.uv);
  15546. _gl.bufferData(_gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW);
  15547. bindingStates.enableAttribute(programAttributes.uv.location);
  15548. _gl.vertexAttribPointer(programAttributes.uv.location, 2, _gl.FLOAT, false, 0, 0);
  15549. }
  15550. if (object.hasColors) {
  15551. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.color);
  15552. _gl.bufferData(_gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW);
  15553. bindingStates.enableAttribute(programAttributes.color.location);
  15554. _gl.vertexAttribPointer(programAttributes.color.location, 3, _gl.FLOAT, false, 0, 0);
  15555. }
  15556. bindingStates.disableUnusedAttributes();
  15557. _gl.drawArrays(_gl.TRIANGLES, 0, object.count);
  15558. object.count = 0;
  15559. };
  15560. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  15561. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  15562. const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  15563. const program = setProgram(camera, scene, material, object);
  15564. state.setMaterial(material, frontFaceCW); //
  15565. let index = geometry.index;
  15566. const position = geometry.attributes.position; //
  15567. if (index === null) {
  15568. if (position === undefined || position.count === 0) return;
  15569. } else if (index.count === 0) {
  15570. return;
  15571. } //
  15572. let rangeFactor = 1;
  15573. if (material.wireframe === true) {
  15574. index = geometries.getWireframeAttribute(geometry);
  15575. rangeFactor = 2;
  15576. }
  15577. if (geometry.morphAttributes.position !== undefined || geometry.morphAttributes.normal !== undefined) {
  15578. morphtargets.update(object, geometry, material, program);
  15579. }
  15580. bindingStates.setup(object, material, program, geometry, index);
  15581. let attribute;
  15582. let renderer = bufferRenderer;
  15583. if (index !== null) {
  15584. attribute = attributes.get(index);
  15585. renderer = indexedBufferRenderer;
  15586. renderer.setIndex(attribute);
  15587. } //
  15588. const dataCount = index !== null ? index.count : position.count;
  15589. const rangeStart = geometry.drawRange.start * rangeFactor;
  15590. const rangeCount = geometry.drawRange.count * rangeFactor;
  15591. const groupStart = group !== null ? group.start * rangeFactor : 0;
  15592. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  15593. const drawStart = Math.max(rangeStart, groupStart);
  15594. const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  15595. const drawCount = Math.max(0, drawEnd - drawStart + 1);
  15596. if (drawCount === 0) return; //
  15597. if (object.isMesh) {
  15598. if (material.wireframe === true) {
  15599. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  15600. renderer.setMode(_gl.LINES);
  15601. } else {
  15602. renderer.setMode(_gl.TRIANGLES);
  15603. }
  15604. } else if (object.isLine) {
  15605. let lineWidth = material.linewidth;
  15606. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  15607. state.setLineWidth(lineWidth * getTargetPixelRatio());
  15608. if (object.isLineSegments) {
  15609. renderer.setMode(_gl.LINES);
  15610. } else if (object.isLineLoop) {
  15611. renderer.setMode(_gl.LINE_LOOP);
  15612. } else {
  15613. renderer.setMode(_gl.LINE_STRIP);
  15614. }
  15615. } else if (object.isPoints) {
  15616. renderer.setMode(_gl.POINTS);
  15617. } else if (object.isSprite) {
  15618. renderer.setMode(_gl.TRIANGLES);
  15619. }
  15620. if (object.isInstancedMesh) {
  15621. renderer.renderInstances(drawStart, drawCount, object.count);
  15622. } else if (geometry.isInstancedBufferGeometry) {
  15623. const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  15624. renderer.renderInstances(drawStart, drawCount, instanceCount);
  15625. } else {
  15626. renderer.render(drawStart, drawCount);
  15627. }
  15628. }; // Compile
  15629. this.compile = function (scene, camera) {
  15630. currentRenderState = renderStates.get(scene);
  15631. currentRenderState.init();
  15632. renderStateStack.push(currentRenderState);
  15633. scene.traverseVisible(function (object) {
  15634. if (object.isLight && object.layers.test(camera.layers)) {
  15635. currentRenderState.pushLight(object);
  15636. if (object.castShadow) {
  15637. currentRenderState.pushShadow(object);
  15638. }
  15639. }
  15640. });
  15641. currentRenderState.setupLights(_this.physicallyCorrectLights);
  15642. scene.traverse(function (object) {
  15643. const material = object.material;
  15644. if (material) {
  15645. if (Array.isArray(material)) {
  15646. for (let i = 0; i < material.length; i++) {
  15647. const material2 = material[i];
  15648. getProgram(material2, scene, object);
  15649. }
  15650. } else {
  15651. getProgram(material, scene, object);
  15652. }
  15653. }
  15654. });
  15655. renderStateStack.pop();
  15656. currentRenderState = null;
  15657. }; // Animation Loop
  15658. let onAnimationFrameCallback = null;
  15659. function onAnimationFrame(time) {
  15660. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  15661. }
  15662. function onXRSessionStart() {
  15663. animation.stop();
  15664. }
  15665. function onXRSessionEnd() {
  15666. animation.start();
  15667. }
  15668. const animation = new WebGLAnimation();
  15669. animation.setAnimationLoop(onAnimationFrame);
  15670. if (typeof window !== 'undefined') animation.setContext(window);
  15671. this.setAnimationLoop = function (callback) {
  15672. onAnimationFrameCallback = callback;
  15673. xr.setAnimationLoop(callback);
  15674. callback === null ? animation.stop() : animation.start();
  15675. };
  15676. xr.addEventListener('sessionstart', onXRSessionStart);
  15677. xr.addEventListener('sessionend', onXRSessionEnd); // Rendering
  15678. this.render = function (scene, camera) {
  15679. if (camera !== undefined && camera.isCamera !== true) {
  15680. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  15681. return;
  15682. }
  15683. if (_isContextLost === true) return; // update scene graph
  15684. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  15685. if (camera.parent === null) camera.updateMatrixWorld();
  15686. if (xr.enabled === true && xr.isPresenting === true) {
  15687. if (xr.cameraAutoUpdate === true) xr.updateCamera(camera);
  15688. camera = xr.getCamera(); // use XR camera for rendering
  15689. } //
  15690. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget);
  15691. currentRenderState = renderStates.get(scene, renderStateStack.length);
  15692. currentRenderState.init();
  15693. renderStateStack.push(currentRenderState);
  15694. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  15695. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  15696. _localClippingEnabled = this.localClippingEnabled;
  15697. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  15698. currentRenderList = renderLists.get(scene, renderListStack.length);
  15699. currentRenderList.init();
  15700. renderListStack.push(currentRenderList);
  15701. projectObject(scene, camera, 0, _this.sortObjects);
  15702. currentRenderList.finish();
  15703. if (_this.sortObjects === true) {
  15704. currentRenderList.sort(_opaqueSort, _transparentSort);
  15705. } //
  15706. if (_clippingEnabled === true) clipping.beginShadows();
  15707. const shadowsArray = currentRenderState.state.shadowsArray;
  15708. shadowMap.render(shadowsArray, scene, camera);
  15709. if (_clippingEnabled === true) clipping.endShadows(); //
  15710. if (this.info.autoReset === true) this.info.reset(); //
  15711. background.render(currentRenderList, scene); // render scene
  15712. currentRenderState.setupLights(_this.physicallyCorrectLights);
  15713. if (camera.isArrayCamera) {
  15714. const cameras = camera.cameras;
  15715. for (let i = 0, l = cameras.length; i < l; i++) {
  15716. const camera2 = cameras[i];
  15717. renderScene(currentRenderList, scene, camera2, camera2.viewport);
  15718. }
  15719. } else {
  15720. renderScene(currentRenderList, scene, camera);
  15721. } //
  15722. if (_currentRenderTarget !== null) {
  15723. // resolve multisample renderbuffers to a single-sample texture if necessary
  15724. textures.updateMultisampleRenderTarget(_currentRenderTarget); // Generate mipmap if we're using any kind of mipmap filtering
  15725. textures.updateRenderTargetMipmap(_currentRenderTarget);
  15726. } //
  15727. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); // Ensure depth buffer writing is enabled so it can be cleared on next render
  15728. state.buffers.depth.setTest(true);
  15729. state.buffers.depth.setMask(true);
  15730. state.buffers.color.setMask(true);
  15731. state.setPolygonOffset(false); // _gl.finish();
  15732. bindingStates.resetDefaultState();
  15733. _currentMaterialId = -1;
  15734. _currentCamera = null;
  15735. renderStateStack.pop();
  15736. if (renderStateStack.length > 0) {
  15737. currentRenderState = renderStateStack[renderStateStack.length - 1];
  15738. } else {
  15739. currentRenderState = null;
  15740. }
  15741. renderListStack.pop();
  15742. if (renderListStack.length > 0) {
  15743. currentRenderList = renderListStack[renderListStack.length - 1];
  15744. } else {
  15745. currentRenderList = null;
  15746. }
  15747. };
  15748. function projectObject(object, camera, groupOrder, sortObjects) {
  15749. if (object.visible === false) return;
  15750. const visible = object.layers.test(camera.layers);
  15751. if (visible) {
  15752. if (object.isGroup) {
  15753. groupOrder = object.renderOrder;
  15754. } else if (object.isLOD) {
  15755. if (object.autoUpdate === true) object.update(camera);
  15756. } else if (object.isLight) {
  15757. currentRenderState.pushLight(object);
  15758. if (object.castShadow) {
  15759. currentRenderState.pushShadow(object);
  15760. }
  15761. } else if (object.isSprite) {
  15762. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  15763. if (sortObjects) {
  15764. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15765. }
  15766. const geometry = objects.update(object);
  15767. const material = object.material;
  15768. if (material.visible) {
  15769. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  15770. }
  15771. }
  15772. } else if (object.isImmediateRenderObject) {
  15773. if (sortObjects) {
  15774. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15775. }
  15776. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  15777. } else if (object.isMesh || object.isLine || object.isPoints) {
  15778. if (object.isSkinnedMesh) {
  15779. // update skeleton only once in a frame
  15780. if (object.skeleton.frame !== info.render.frame) {
  15781. object.skeleton.update();
  15782. object.skeleton.frame = info.render.frame;
  15783. }
  15784. }
  15785. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  15786. if (sortObjects) {
  15787. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15788. }
  15789. const geometry = objects.update(object);
  15790. const material = object.material;
  15791. if (Array.isArray(material)) {
  15792. const groups = geometry.groups;
  15793. for (let i = 0, l = groups.length; i < l; i++) {
  15794. const group = groups[i];
  15795. const groupMaterial = material[group.materialIndex];
  15796. if (groupMaterial && groupMaterial.visible) {
  15797. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  15798. }
  15799. }
  15800. } else if (material.visible) {
  15801. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  15802. }
  15803. }
  15804. }
  15805. }
  15806. const children = object.children;
  15807. for (let i = 0, l = children.length; i < l; i++) {
  15808. projectObject(children[i], camera, groupOrder, sortObjects);
  15809. }
  15810. }
  15811. function renderScene(currentRenderList, scene, camera, viewport) {
  15812. const opaqueObjects = currentRenderList.opaque;
  15813. const transmissiveObjects = currentRenderList.transmissive;
  15814. const transparentObjects = currentRenderList.transparent;
  15815. currentRenderState.setupLightsView(camera);
  15816. if (transmissiveObjects.length > 0) renderTransmissionPass(opaqueObjects, scene, camera);
  15817. if (viewport) state.viewport(_currentViewport.copy(viewport));
  15818. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  15819. if (transmissiveObjects.length > 0) renderObjects(transmissiveObjects, scene, camera);
  15820. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera);
  15821. }
  15822. function renderTransmissionPass(opaqueObjects, scene, camera) {
  15823. if (_transmissionRenderTarget === null) {
  15824. const needsAntialias = _antialias === true && capabilities.isWebGL2 === true;
  15825. const renderTargetType = needsAntialias ? WebGLMultisampleRenderTarget : WebGLRenderTarget;
  15826. _transmissionRenderTarget = new renderTargetType(1024, 1024, {
  15827. generateMipmaps: true,
  15828. type: utils.convert(HalfFloatType) !== null ? HalfFloatType : UnsignedByteType,
  15829. minFilter: LinearMipmapLinearFilter,
  15830. magFilter: NearestFilter,
  15831. wrapS: ClampToEdgeWrapping,
  15832. wrapT: ClampToEdgeWrapping
  15833. });
  15834. }
  15835. const currentRenderTarget = _this.getRenderTarget();
  15836. _this.setRenderTarget(_transmissionRenderTarget);
  15837. _this.clear(); // Turn off the features which can affect the frag color for opaque objects pass.
  15838. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  15839. const currentToneMapping = _this.toneMapping;
  15840. _this.toneMapping = NoToneMapping;
  15841. renderObjects(opaqueObjects, scene, camera);
  15842. _this.toneMapping = currentToneMapping;
  15843. textures.updateMultisampleRenderTarget(_transmissionRenderTarget);
  15844. textures.updateRenderTargetMipmap(_transmissionRenderTarget);
  15845. _this.setRenderTarget(currentRenderTarget);
  15846. }
  15847. function renderObjects(renderList, scene, camera) {
  15848. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  15849. for (let i = 0, l = renderList.length; i < l; i++) {
  15850. const renderItem = renderList[i];
  15851. const object = renderItem.object;
  15852. const geometry = renderItem.geometry;
  15853. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  15854. const group = renderItem.group;
  15855. if (object.layers.test(camera.layers)) {
  15856. renderObject(object, scene, camera, geometry, material, group);
  15857. }
  15858. }
  15859. }
  15860. function renderObject(object, scene, camera, geometry, material, group) {
  15861. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  15862. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  15863. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  15864. material.onBeforeRender(_this, scene, camera, geometry, object, group);
  15865. if (object.isImmediateRenderObject) {
  15866. const program = setProgram(camera, scene, material, object);
  15867. state.setMaterial(material);
  15868. bindingStates.reset();
  15869. renderObjectImmediate(object, program);
  15870. } else {
  15871. if (material.transparent === true && material.side === DoubleSide) {
  15872. material.side = BackSide;
  15873. material.needsUpdate = true;
  15874. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  15875. material.side = FrontSide;
  15876. material.needsUpdate = true;
  15877. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  15878. material.side = DoubleSide;
  15879. } else {
  15880. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  15881. }
  15882. }
  15883. object.onAfterRender(_this, scene, camera, geometry, material, group);
  15884. }
  15885. function getProgram(material, scene, object) {
  15886. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15887. const materialProperties = properties.get(material);
  15888. const lights = currentRenderState.state.lights;
  15889. const shadowsArray = currentRenderState.state.shadowsArray;
  15890. const lightsStateVersion = lights.state.version;
  15891. const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  15892. const programCacheKey = programCache.getProgramCacheKey(parameters);
  15893. 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
  15894. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  15895. materialProperties.fog = scene.fog;
  15896. materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment);
  15897. if (programs === undefined) {
  15898. // new material
  15899. material.addEventListener('dispose', onMaterialDispose);
  15900. programs = new Map();
  15901. materialProperties.programs = programs;
  15902. }
  15903. let program = programs.get(programCacheKey);
  15904. if (program !== undefined) {
  15905. // early out if program and light state is identical
  15906. if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) {
  15907. updateCommonMaterialProperties(material, parameters);
  15908. return program;
  15909. }
  15910. } else {
  15911. parameters.uniforms = programCache.getUniforms(material);
  15912. material.onBuild(parameters, _this);
  15913. material.onBeforeCompile(parameters, _this);
  15914. program = programCache.acquireProgram(parameters, programCacheKey);
  15915. programs.set(programCacheKey, program);
  15916. materialProperties.uniforms = parameters.uniforms;
  15917. }
  15918. const uniforms = materialProperties.uniforms;
  15919. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  15920. uniforms.clippingPlanes = clipping.uniform;
  15921. }
  15922. updateCommonMaterialProperties(material, parameters); // store the light setup it was created for
  15923. materialProperties.needsLights = materialNeedsLights(material);
  15924. materialProperties.lightsStateVersion = lightsStateVersion;
  15925. if (materialProperties.needsLights) {
  15926. // wire up the material to this renderer's lighting state
  15927. uniforms.ambientLightColor.value = lights.state.ambient;
  15928. uniforms.lightProbe.value = lights.state.probe;
  15929. uniforms.directionalLights.value = lights.state.directional;
  15930. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  15931. uniforms.spotLights.value = lights.state.spot;
  15932. uniforms.spotLightShadows.value = lights.state.spotShadow;
  15933. uniforms.rectAreaLights.value = lights.state.rectArea;
  15934. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  15935. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  15936. uniforms.pointLights.value = lights.state.point;
  15937. uniforms.pointLightShadows.value = lights.state.pointShadow;
  15938. uniforms.hemisphereLights.value = lights.state.hemi;
  15939. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  15940. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  15941. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  15942. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  15943. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  15944. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  15945. }
  15946. const progUniforms = program.getUniforms();
  15947. const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  15948. materialProperties.currentProgram = program;
  15949. materialProperties.uniformsList = uniformsList;
  15950. return program;
  15951. }
  15952. function updateCommonMaterialProperties(material, parameters) {
  15953. const materialProperties = properties.get(material);
  15954. materialProperties.outputEncoding = parameters.outputEncoding;
  15955. materialProperties.instancing = parameters.instancing;
  15956. materialProperties.skinning = parameters.skinning;
  15957. materialProperties.morphTargets = parameters.morphTargets;
  15958. materialProperties.morphNormals = parameters.morphNormals;
  15959. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  15960. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  15961. materialProperties.numIntersection = parameters.numClipIntersection;
  15962. materialProperties.vertexAlphas = parameters.vertexAlphas;
  15963. materialProperties.vertexTangents = parameters.vertexTangents;
  15964. }
  15965. function setProgram(camera, scene, material, object) {
  15966. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15967. textures.resetTextureUnits();
  15968. const fog = scene.fog;
  15969. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  15970. const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  15971. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  15972. const vertexAlphas = material.vertexColors === true && !!object.geometry && !!object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4;
  15973. const vertexTangents = !!material.normalMap && !!object.geometry && !!object.geometry.attributes.tangent;
  15974. const morphTargets = !!object.geometry && !!object.geometry.morphAttributes.position;
  15975. const morphNormals = !!object.geometry && !!object.geometry.morphAttributes.normal;
  15976. const morphTargetsCount = !!object.geometry && !!object.geometry.morphAttributes.position ? object.geometry.morphAttributes.position.length : 0;
  15977. const materialProperties = properties.get(material);
  15978. const lights = currentRenderState.state.lights;
  15979. if (_clippingEnabled === true) {
  15980. if (_localClippingEnabled === true || camera !== _currentCamera) {
  15981. const useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  15982. // object instead of the material, once it becomes feasible
  15983. // (#8465, #8379)
  15984. clipping.setState(material, camera, useCache);
  15985. }
  15986. } //
  15987. let needsProgramChange = false;
  15988. if (material.version === materialProperties.__version) {
  15989. if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  15990. needsProgramChange = true;
  15991. } else if (materialProperties.outputEncoding !== encoding) {
  15992. needsProgramChange = true;
  15993. } else if (object.isInstancedMesh && materialProperties.instancing === false) {
  15994. needsProgramChange = true;
  15995. } else if (!object.isInstancedMesh && materialProperties.instancing === true) {
  15996. needsProgramChange = true;
  15997. } else if (object.isSkinnedMesh && materialProperties.skinning === false) {
  15998. needsProgramChange = true;
  15999. } else if (!object.isSkinnedMesh && materialProperties.skinning === true) {
  16000. needsProgramChange = true;
  16001. } else if (materialProperties.envMap !== envMap) {
  16002. needsProgramChange = true;
  16003. } else if (material.fog && materialProperties.fog !== fog) {
  16004. needsProgramChange = true;
  16005. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  16006. needsProgramChange = true;
  16007. } else if (materialProperties.vertexAlphas !== vertexAlphas) {
  16008. needsProgramChange = true;
  16009. } else if (materialProperties.vertexTangents !== vertexTangents) {
  16010. needsProgramChange = true;
  16011. } else if (materialProperties.morphTargets !== morphTargets) {
  16012. needsProgramChange = true;
  16013. } else if (materialProperties.morphNormals !== morphNormals) {
  16014. needsProgramChange = true;
  16015. } else if (capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount) {
  16016. needsProgramChange = true;
  16017. }
  16018. } else {
  16019. needsProgramChange = true;
  16020. materialProperties.__version = material.version;
  16021. } //
  16022. let program = materialProperties.currentProgram;
  16023. if (needsProgramChange === true) {
  16024. program = getProgram(material, scene, object);
  16025. }
  16026. let refreshProgram = false;
  16027. let refreshMaterial = false;
  16028. let refreshLights = false;
  16029. const p_uniforms = program.getUniforms(),
  16030. m_uniforms = materialProperties.uniforms;
  16031. if (state.useProgram(program.program)) {
  16032. refreshProgram = true;
  16033. refreshMaterial = true;
  16034. refreshLights = true;
  16035. }
  16036. if (material.id !== _currentMaterialId) {
  16037. _currentMaterialId = material.id;
  16038. refreshMaterial = true;
  16039. }
  16040. if (refreshProgram || _currentCamera !== camera) {
  16041. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  16042. if (capabilities.logarithmicDepthBuffer) {
  16043. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  16044. }
  16045. if (_currentCamera !== camera) {
  16046. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  16047. // now, in case this material supports lights - or later, when
  16048. // the next material that does gets activated:
  16049. refreshMaterial = true; // set to true on material change
  16050. refreshLights = true; // remains set until update done
  16051. } // load material specific uniforms
  16052. // (shader material also gets them for the sake of genericity)
  16053. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  16054. const uCamPos = p_uniforms.map.cameraPosition;
  16055. if (uCamPos !== undefined) {
  16056. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  16057. }
  16058. }
  16059. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  16060. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  16061. }
  16062. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || object.isSkinnedMesh) {
  16063. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  16064. }
  16065. } // skinning uniforms must be set even if material didn't change
  16066. // auto-setting of texture unit for bone texture must go before other textures
  16067. // otherwise textures used for skinning can take over texture units reserved for other material textures
  16068. if (object.isSkinnedMesh) {
  16069. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  16070. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  16071. const skeleton = object.skeleton;
  16072. if (skeleton) {
  16073. if (capabilities.floatVertexTextures) {
  16074. if (skeleton.boneTexture === null) skeleton.computeBoneTexture();
  16075. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  16076. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  16077. } else {
  16078. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  16079. }
  16080. }
  16081. }
  16082. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  16083. materialProperties.receiveShadow = object.receiveShadow;
  16084. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  16085. }
  16086. if (refreshMaterial) {
  16087. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  16088. if (materialProperties.needsLights) {
  16089. // the current material requires lighting info
  16090. // note: all lighting uniforms are always set correctly
  16091. // they simply reference the renderer's state for their
  16092. // values
  16093. //
  16094. // use the current material's .needsUpdate flags to set
  16095. // the GL state when required
  16096. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  16097. } // refresh uniforms common to several materials
  16098. if (fog && material.fog) {
  16099. materials.refreshFogUniforms(m_uniforms, fog);
  16100. }
  16101. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget);
  16102. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16103. }
  16104. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  16105. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16106. material.uniformsNeedUpdate = false;
  16107. }
  16108. if (material.isSpriteMaterial) {
  16109. p_uniforms.setValue(_gl, 'center', object.center);
  16110. } // common matrices
  16111. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  16112. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  16113. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  16114. return program;
  16115. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  16116. function markUniformsLightsNeedsUpdate(uniforms, value) {
  16117. uniforms.ambientLightColor.needsUpdate = value;
  16118. uniforms.lightProbe.needsUpdate = value;
  16119. uniforms.directionalLights.needsUpdate = value;
  16120. uniforms.directionalLightShadows.needsUpdate = value;
  16121. uniforms.pointLights.needsUpdate = value;
  16122. uniforms.pointLightShadows.needsUpdate = value;
  16123. uniforms.spotLights.needsUpdate = value;
  16124. uniforms.spotLightShadows.needsUpdate = value;
  16125. uniforms.rectAreaLights.needsUpdate = value;
  16126. uniforms.hemisphereLights.needsUpdate = value;
  16127. }
  16128. function materialNeedsLights(material) {
  16129. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  16130. }
  16131. this.getActiveCubeFace = function () {
  16132. return _currentActiveCubeFace;
  16133. };
  16134. this.getActiveMipmapLevel = function () {
  16135. return _currentActiveMipmapLevel;
  16136. };
  16137. this.getRenderTarget = function () {
  16138. return _currentRenderTarget;
  16139. };
  16140. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  16141. _currentRenderTarget = renderTarget;
  16142. _currentActiveCubeFace = activeCubeFace;
  16143. _currentActiveMipmapLevel = activeMipmapLevel;
  16144. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  16145. textures.setupRenderTarget(renderTarget);
  16146. }
  16147. let framebuffer = null;
  16148. let isCube = false;
  16149. let isRenderTarget3D = false;
  16150. if (renderTarget) {
  16151. const texture = renderTarget.texture;
  16152. if (texture.isDataTexture3D || texture.isDataTexture2DArray) {
  16153. isRenderTarget3D = true;
  16154. }
  16155. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  16156. if (renderTarget.isWebGLCubeRenderTarget) {
  16157. framebuffer = __webglFramebuffer[activeCubeFace];
  16158. isCube = true;
  16159. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  16160. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  16161. } else {
  16162. framebuffer = __webglFramebuffer;
  16163. }
  16164. _currentViewport.copy(renderTarget.viewport);
  16165. _currentScissor.copy(renderTarget.scissor);
  16166. _currentScissorTest = renderTarget.scissorTest;
  16167. } else {
  16168. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  16169. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  16170. _currentScissorTest = _scissorTest;
  16171. }
  16172. const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16173. if (framebufferBound && capabilities.drawBuffers) {
  16174. let needsUpdate = false;
  16175. if (renderTarget) {
  16176. if (renderTarget.isWebGLMultipleRenderTargets) {
  16177. const textures = renderTarget.texture;
  16178. if (_currentDrawBuffers.length !== textures.length || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  16179. for (let i = 0, il = textures.length; i < il; i++) {
  16180. _currentDrawBuffers[i] = _gl.COLOR_ATTACHMENT0 + i;
  16181. }
  16182. _currentDrawBuffers.length = textures.length;
  16183. needsUpdate = true;
  16184. }
  16185. } else {
  16186. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  16187. _currentDrawBuffers[0] = _gl.COLOR_ATTACHMENT0;
  16188. _currentDrawBuffers.length = 1;
  16189. needsUpdate = true;
  16190. }
  16191. }
  16192. } else {
  16193. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.BACK) {
  16194. _currentDrawBuffers[0] = _gl.BACK;
  16195. _currentDrawBuffers.length = 1;
  16196. needsUpdate = true;
  16197. }
  16198. }
  16199. if (needsUpdate) {
  16200. if (capabilities.isWebGL2) {
  16201. _gl.drawBuffers(_currentDrawBuffers);
  16202. } else {
  16203. extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(_currentDrawBuffers);
  16204. }
  16205. }
  16206. }
  16207. state.viewport(_currentViewport);
  16208. state.scissor(_currentScissor);
  16209. state.setScissorTest(_currentScissorTest);
  16210. if (isCube) {
  16211. const textureProperties = properties.get(renderTarget.texture);
  16212. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  16213. } else if (isRenderTarget3D) {
  16214. const textureProperties = properties.get(renderTarget.texture);
  16215. const layer = activeCubeFace || 0;
  16216. _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer);
  16217. }
  16218. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  16219. };
  16220. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  16221. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  16222. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  16223. return;
  16224. }
  16225. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  16226. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  16227. framebuffer = framebuffer[activeCubeFaceIndex];
  16228. }
  16229. if (framebuffer) {
  16230. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16231. try {
  16232. const texture = renderTarget.texture;
  16233. const textureFormat = texture.format;
  16234. const textureType = texture.type;
  16235. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) {
  16236. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  16237. return;
  16238. }
  16239. const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
  16240. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513)
  16241. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  16242. !halfFloatSupportedByExt) {
  16243. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  16244. return;
  16245. }
  16246. if (_gl.checkFramebufferStatus(_gl.FRAMEBUFFER) === _gl.FRAMEBUFFER_COMPLETE) {
  16247. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16248. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  16249. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  16250. }
  16251. } else {
  16252. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  16253. }
  16254. } finally {
  16255. // restore framebuffer of current render target if necessary
  16256. const framebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
  16257. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16258. }
  16259. }
  16260. };
  16261. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  16262. const levelScale = Math.pow(2, -level);
  16263. const width = Math.floor(texture.image.width * levelScale);
  16264. const height = Math.floor(texture.image.height * levelScale);
  16265. let glFormat = utils.convert(texture.format);
  16266. if (capabilities.isWebGL2) {
  16267. // Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=1120100
  16268. // Not needed in Chrome 93+
  16269. if (glFormat === _gl.RGB) glFormat = _gl.RGB8;
  16270. if (glFormat === _gl.RGBA) glFormat = _gl.RGBA8;
  16271. }
  16272. textures.setTexture2D(texture, 0);
  16273. _gl.copyTexImage2D(_gl.TEXTURE_2D, level, glFormat, position.x, position.y, width, height, 0);
  16274. state.unbindTexture();
  16275. };
  16276. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  16277. const width = srcTexture.image.width;
  16278. const height = srcTexture.image.height;
  16279. const glFormat = utils.convert(dstTexture.format);
  16280. const glType = utils.convert(dstTexture.type);
  16281. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  16282. // parameters, make sure they are correct for the dstTexture
  16283. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  16284. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  16285. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  16286. if (srcTexture.isDataTexture) {
  16287. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  16288. } else {
  16289. if (srcTexture.isCompressedTexture) {
  16290. _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  16291. } else {
  16292. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image);
  16293. }
  16294. } // Generate mipmaps only when copying level 0
  16295. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D);
  16296. state.unbindTexture();
  16297. };
  16298. this.copyTextureToTexture3D = function (sourceBox, position, srcTexture, dstTexture, level = 0) {
  16299. if (_this.isWebGL1Renderer) {
  16300. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.');
  16301. return;
  16302. }
  16303. const width = sourceBox.max.x - sourceBox.min.x + 1;
  16304. const height = sourceBox.max.y - sourceBox.min.y + 1;
  16305. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  16306. const glFormat = utils.convert(dstTexture.format);
  16307. const glType = utils.convert(dstTexture.type);
  16308. let glTarget;
  16309. if (dstTexture.isDataTexture3D) {
  16310. textures.setTexture3D(dstTexture, 0);
  16311. glTarget = _gl.TEXTURE_3D;
  16312. } else if (dstTexture.isDataTexture2DArray) {
  16313. textures.setTexture2DArray(dstTexture, 0);
  16314. glTarget = _gl.TEXTURE_2D_ARRAY;
  16315. } else {
  16316. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.');
  16317. return;
  16318. }
  16319. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  16320. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  16321. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  16322. const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH);
  16323. const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT);
  16324. const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS);
  16325. const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS);
  16326. const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES);
  16327. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[0] : srcTexture.image;
  16328. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width);
  16329. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height);
  16330. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x);
  16331. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y);
  16332. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z);
  16333. if (srcTexture.isDataTexture || srcTexture.isDataTexture3D) {
  16334. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data);
  16335. } else {
  16336. if (srcTexture.isCompressedTexture) {
  16337. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.');
  16338. _gl.compressedTexSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data);
  16339. } else {
  16340. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image);
  16341. }
  16342. }
  16343. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen);
  16344. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight);
  16345. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels);
  16346. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows);
  16347. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages); // Generate mipmaps only when copying level 0
  16348. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget);
  16349. state.unbindTexture();
  16350. };
  16351. this.initTexture = function (texture) {
  16352. textures.setTexture2D(texture, 0);
  16353. state.unbindTexture();
  16354. };
  16355. this.resetState = function () {
  16356. _currentActiveCubeFace = 0;
  16357. _currentActiveMipmapLevel = 0;
  16358. _currentRenderTarget = null;
  16359. state.reset();
  16360. bindingStates.reset();
  16361. };
  16362. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  16363. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  16364. detail: this
  16365. })); // eslint-disable-line no-undef
  16366. }
  16367. }
  16368. class WebGL1Renderer extends WebGLRenderer {}
  16369. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  16370. class FogExp2 {
  16371. constructor(color, density = 0.00025) {
  16372. this.name = '';
  16373. this.color = new Color(color);
  16374. this.density = density;
  16375. }
  16376. clone() {
  16377. return new FogExp2(this.color, this.density);
  16378. }
  16379. toJSON() {
  16380. return {
  16381. type: 'FogExp2',
  16382. color: this.color.getHex(),
  16383. density: this.density
  16384. };
  16385. }
  16386. }
  16387. FogExp2.prototype.isFogExp2 = true;
  16388. class Fog {
  16389. constructor(color, near = 1, far = 1000) {
  16390. this.name = '';
  16391. this.color = new Color(color);
  16392. this.near = near;
  16393. this.far = far;
  16394. }
  16395. clone() {
  16396. return new Fog(this.color, this.near, this.far);
  16397. }
  16398. toJSON() {
  16399. return {
  16400. type: 'Fog',
  16401. color: this.color.getHex(),
  16402. near: this.near,
  16403. far: this.far
  16404. };
  16405. }
  16406. }
  16407. Fog.prototype.isFog = true;
  16408. class Scene extends Object3D {
  16409. constructor() {
  16410. super();
  16411. this.type = 'Scene';
  16412. this.background = null;
  16413. this.environment = null;
  16414. this.fog = null;
  16415. this.overrideMaterial = null;
  16416. this.autoUpdate = true; // checked by the renderer
  16417. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  16418. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  16419. detail: this
  16420. })); // eslint-disable-line no-undef
  16421. }
  16422. }
  16423. copy(source, recursive) {
  16424. super.copy(source, recursive);
  16425. if (source.background !== null) this.background = source.background.clone();
  16426. if (source.environment !== null) this.environment = source.environment.clone();
  16427. if (source.fog !== null) this.fog = source.fog.clone();
  16428. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  16429. this.autoUpdate = source.autoUpdate;
  16430. this.matrixAutoUpdate = source.matrixAutoUpdate;
  16431. return this;
  16432. }
  16433. toJSON(meta) {
  16434. const data = super.toJSON(meta);
  16435. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  16436. return data;
  16437. }
  16438. }
  16439. Scene.prototype.isScene = true;
  16440. class InterleavedBuffer {
  16441. constructor(array, stride) {
  16442. this.array = array;
  16443. this.stride = stride;
  16444. this.count = array !== undefined ? array.length / stride : 0;
  16445. this.usage = StaticDrawUsage;
  16446. this.updateRange = {
  16447. offset: 0,
  16448. count: -1
  16449. };
  16450. this.version = 0;
  16451. this.uuid = generateUUID();
  16452. }
  16453. onUploadCallback() {}
  16454. set needsUpdate(value) {
  16455. if (value === true) this.version++;
  16456. }
  16457. setUsage(value) {
  16458. this.usage = value;
  16459. return this;
  16460. }
  16461. copy(source) {
  16462. this.array = new source.array.constructor(source.array);
  16463. this.count = source.count;
  16464. this.stride = source.stride;
  16465. this.usage = source.usage;
  16466. return this;
  16467. }
  16468. copyAt(index1, attribute, index2) {
  16469. index1 *= this.stride;
  16470. index2 *= attribute.stride;
  16471. for (let i = 0, l = this.stride; i < l; i++) {
  16472. this.array[index1 + i] = attribute.array[index2 + i];
  16473. }
  16474. return this;
  16475. }
  16476. set(value, offset = 0) {
  16477. this.array.set(value, offset);
  16478. return this;
  16479. }
  16480. clone(data) {
  16481. if (data.arrayBuffers === undefined) {
  16482. data.arrayBuffers = {};
  16483. }
  16484. if (this.array.buffer._uuid === undefined) {
  16485. this.array.buffer._uuid = generateUUID();
  16486. }
  16487. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  16488. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  16489. }
  16490. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  16491. const ib = new this.constructor(array, this.stride);
  16492. ib.setUsage(this.usage);
  16493. return ib;
  16494. }
  16495. onUpload(callback) {
  16496. this.onUploadCallback = callback;
  16497. return this;
  16498. }
  16499. toJSON(data) {
  16500. if (data.arrayBuffers === undefined) {
  16501. data.arrayBuffers = {};
  16502. } // generate UUID for array buffer if necessary
  16503. if (this.array.buffer._uuid === undefined) {
  16504. this.array.buffer._uuid = generateUUID();
  16505. }
  16506. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  16507. data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
  16508. } //
  16509. return {
  16510. uuid: this.uuid,
  16511. buffer: this.array.buffer._uuid,
  16512. type: this.array.constructor.name,
  16513. stride: this.stride
  16514. };
  16515. }
  16516. }
  16517. InterleavedBuffer.prototype.isInterleavedBuffer = true;
  16518. const _vector$6 = /*@__PURE__*/new Vector3();
  16519. class InterleavedBufferAttribute {
  16520. constructor(interleavedBuffer, itemSize, offset, normalized = false) {
  16521. this.name = '';
  16522. this.data = interleavedBuffer;
  16523. this.itemSize = itemSize;
  16524. this.offset = offset;
  16525. this.normalized = normalized === true;
  16526. }
  16527. get count() {
  16528. return this.data.count;
  16529. }
  16530. get array() {
  16531. return this.data.array;
  16532. }
  16533. set needsUpdate(value) {
  16534. this.data.needsUpdate = value;
  16535. }
  16536. applyMatrix4(m) {
  16537. for (let i = 0, l = this.data.count; i < l; i++) {
  16538. _vector$6.x = this.getX(i);
  16539. _vector$6.y = this.getY(i);
  16540. _vector$6.z = this.getZ(i);
  16541. _vector$6.applyMatrix4(m);
  16542. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16543. }
  16544. return this;
  16545. }
  16546. applyNormalMatrix(m) {
  16547. for (let i = 0, l = this.count; i < l; i++) {
  16548. _vector$6.x = this.getX(i);
  16549. _vector$6.y = this.getY(i);
  16550. _vector$6.z = this.getZ(i);
  16551. _vector$6.applyNormalMatrix(m);
  16552. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16553. }
  16554. return this;
  16555. }
  16556. transformDirection(m) {
  16557. for (let i = 0, l = this.count; i < l; i++) {
  16558. _vector$6.x = this.getX(i);
  16559. _vector$6.y = this.getY(i);
  16560. _vector$6.z = this.getZ(i);
  16561. _vector$6.transformDirection(m);
  16562. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16563. }
  16564. return this;
  16565. }
  16566. setX(index, x) {
  16567. this.data.array[index * this.data.stride + this.offset] = x;
  16568. return this;
  16569. }
  16570. setY(index, y) {
  16571. this.data.array[index * this.data.stride + this.offset + 1] = y;
  16572. return this;
  16573. }
  16574. setZ(index, z) {
  16575. this.data.array[index * this.data.stride + this.offset + 2] = z;
  16576. return this;
  16577. }
  16578. setW(index, w) {
  16579. this.data.array[index * this.data.stride + this.offset + 3] = w;
  16580. return this;
  16581. }
  16582. getX(index) {
  16583. return this.data.array[index * this.data.stride + this.offset];
  16584. }
  16585. getY(index) {
  16586. return this.data.array[index * this.data.stride + this.offset + 1];
  16587. }
  16588. getZ(index) {
  16589. return this.data.array[index * this.data.stride + this.offset + 2];
  16590. }
  16591. getW(index) {
  16592. return this.data.array[index * this.data.stride + this.offset + 3];
  16593. }
  16594. setXY(index, x, y) {
  16595. index = index * this.data.stride + this.offset;
  16596. this.data.array[index + 0] = x;
  16597. this.data.array[index + 1] = y;
  16598. return this;
  16599. }
  16600. setXYZ(index, x, y, z) {
  16601. index = index * this.data.stride + this.offset;
  16602. this.data.array[index + 0] = x;
  16603. this.data.array[index + 1] = y;
  16604. this.data.array[index + 2] = z;
  16605. return this;
  16606. }
  16607. setXYZW(index, x, y, z, w) {
  16608. index = index * this.data.stride + this.offset;
  16609. this.data.array[index + 0] = x;
  16610. this.data.array[index + 1] = y;
  16611. this.data.array[index + 2] = z;
  16612. this.data.array[index + 3] = w;
  16613. return this;
  16614. }
  16615. clone(data) {
  16616. if (data === undefined) {
  16617. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');
  16618. const array = [];
  16619. for (let i = 0; i < this.count; i++) {
  16620. const index = i * this.data.stride + this.offset;
  16621. for (let j = 0; j < this.itemSize; j++) {
  16622. array.push(this.data.array[index + j]);
  16623. }
  16624. }
  16625. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  16626. } else {
  16627. if (data.interleavedBuffers === undefined) {
  16628. data.interleavedBuffers = {};
  16629. }
  16630. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  16631. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  16632. }
  16633. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  16634. }
  16635. }
  16636. toJSON(data) {
  16637. if (data === undefined) {
  16638. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');
  16639. const array = [];
  16640. for (let i = 0; i < this.count; i++) {
  16641. const index = i * this.data.stride + this.offset;
  16642. for (let j = 0; j < this.itemSize; j++) {
  16643. array.push(this.data.array[index + j]);
  16644. }
  16645. } // deinterleave data and save it as an ordinary buffer attribute for now
  16646. return {
  16647. itemSize: this.itemSize,
  16648. type: this.array.constructor.name,
  16649. array: array,
  16650. normalized: this.normalized
  16651. };
  16652. } else {
  16653. // save as true interlaved attribtue
  16654. if (data.interleavedBuffers === undefined) {
  16655. data.interleavedBuffers = {};
  16656. }
  16657. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  16658. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  16659. }
  16660. return {
  16661. isInterleavedBufferAttribute: true,
  16662. itemSize: this.itemSize,
  16663. data: this.data.uuid,
  16664. offset: this.offset,
  16665. normalized: this.normalized
  16666. };
  16667. }
  16668. }
  16669. }
  16670. InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
  16671. /**
  16672. * parameters = {
  16673. * color: <hex>,
  16674. * map: new THREE.Texture( <Image> ),
  16675. * alphaMap: new THREE.Texture( <Image> ),
  16676. * rotation: <float>,
  16677. * sizeAttenuation: <bool>
  16678. * }
  16679. */
  16680. class SpriteMaterial extends Material {
  16681. constructor(parameters) {
  16682. super();
  16683. this.type = 'SpriteMaterial';
  16684. this.color = new Color(0xffffff);
  16685. this.map = null;
  16686. this.alphaMap = null;
  16687. this.rotation = 0;
  16688. this.sizeAttenuation = true;
  16689. this.transparent = true;
  16690. this.setValues(parameters);
  16691. }
  16692. copy(source) {
  16693. super.copy(source);
  16694. this.color.copy(source.color);
  16695. this.map = source.map;
  16696. this.alphaMap = source.alphaMap;
  16697. this.rotation = source.rotation;
  16698. this.sizeAttenuation = source.sizeAttenuation;
  16699. return this;
  16700. }
  16701. }
  16702. SpriteMaterial.prototype.isSpriteMaterial = true;
  16703. let _geometry;
  16704. const _intersectPoint = /*@__PURE__*/new Vector3();
  16705. const _worldScale = /*@__PURE__*/new Vector3();
  16706. const _mvPosition = /*@__PURE__*/new Vector3();
  16707. const _alignedPosition = /*@__PURE__*/new Vector2();
  16708. const _rotatedPosition = /*@__PURE__*/new Vector2();
  16709. const _viewWorldMatrix = /*@__PURE__*/new Matrix4();
  16710. const _vA = /*@__PURE__*/new Vector3();
  16711. const _vB = /*@__PURE__*/new Vector3();
  16712. const _vC = /*@__PURE__*/new Vector3();
  16713. const _uvA = /*@__PURE__*/new Vector2();
  16714. const _uvB = /*@__PURE__*/new Vector2();
  16715. const _uvC = /*@__PURE__*/new Vector2();
  16716. class Sprite extends Object3D {
  16717. constructor(material) {
  16718. super();
  16719. this.type = 'Sprite';
  16720. if (_geometry === undefined) {
  16721. _geometry = new BufferGeometry();
  16722. 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]);
  16723. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  16724. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  16725. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  16726. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  16727. }
  16728. this.geometry = _geometry;
  16729. this.material = material !== undefined ? material : new SpriteMaterial();
  16730. this.center = new Vector2(0.5, 0.5);
  16731. }
  16732. raycast(raycaster, intersects) {
  16733. if (raycaster.camera === null) {
  16734. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  16735. }
  16736. _worldScale.setFromMatrixScale(this.matrixWorld);
  16737. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  16738. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  16739. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  16740. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  16741. _worldScale.multiplyScalar(-_mvPosition.z);
  16742. }
  16743. const rotation = this.material.rotation;
  16744. let sin, cos;
  16745. if (rotation !== 0) {
  16746. cos = Math.cos(rotation);
  16747. sin = Math.sin(rotation);
  16748. }
  16749. const center = this.center;
  16750. transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16751. transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16752. transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16753. _uvA.set(0, 0);
  16754. _uvB.set(1, 0);
  16755. _uvC.set(1, 1); // check first triangle
  16756. let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
  16757. if (intersect === null) {
  16758. // check second triangle
  16759. transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16760. _uvB.set(0, 1);
  16761. intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
  16762. if (intersect === null) {
  16763. return;
  16764. }
  16765. }
  16766. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  16767. if (distance < raycaster.near || distance > raycaster.far) return;
  16768. intersects.push({
  16769. distance: distance,
  16770. point: _intersectPoint.clone(),
  16771. uv: Triangle.getUV(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()),
  16772. face: null,
  16773. object: this
  16774. });
  16775. }
  16776. copy(source) {
  16777. super.copy(source);
  16778. if (source.center !== undefined) this.center.copy(source.center);
  16779. this.material = source.material;
  16780. return this;
  16781. }
  16782. }
  16783. Sprite.prototype.isSprite = true;
  16784. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  16785. // compute position in camera space
  16786. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  16787. if (sin !== undefined) {
  16788. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  16789. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  16790. } else {
  16791. _rotatedPosition.copy(_alignedPosition);
  16792. }
  16793. vertexPosition.copy(mvPosition);
  16794. vertexPosition.x += _rotatedPosition.x;
  16795. vertexPosition.y += _rotatedPosition.y; // transform to world space
  16796. vertexPosition.applyMatrix4(_viewWorldMatrix);
  16797. }
  16798. const _v1$2 = /*@__PURE__*/new Vector3();
  16799. const _v2$1 = /*@__PURE__*/new Vector3();
  16800. class LOD extends Object3D {
  16801. constructor() {
  16802. super();
  16803. this._currentLevel = 0;
  16804. this.type = 'LOD';
  16805. Object.defineProperties(this, {
  16806. levels: {
  16807. enumerable: true,
  16808. value: []
  16809. },
  16810. isLOD: {
  16811. value: true
  16812. }
  16813. });
  16814. this.autoUpdate = true;
  16815. }
  16816. copy(source) {
  16817. super.copy(source, false);
  16818. const levels = source.levels;
  16819. for (let i = 0, l = levels.length; i < l; i++) {
  16820. const level = levels[i];
  16821. this.addLevel(level.object.clone(), level.distance);
  16822. }
  16823. this.autoUpdate = source.autoUpdate;
  16824. return this;
  16825. }
  16826. addLevel(object, distance = 0) {
  16827. distance = Math.abs(distance);
  16828. const levels = this.levels;
  16829. let l;
  16830. for (l = 0; l < levels.length; l++) {
  16831. if (distance < levels[l].distance) {
  16832. break;
  16833. }
  16834. }
  16835. levels.splice(l, 0, {
  16836. distance: distance,
  16837. object: object
  16838. });
  16839. this.add(object);
  16840. return this;
  16841. }
  16842. getCurrentLevel() {
  16843. return this._currentLevel;
  16844. }
  16845. getObjectForDistance(distance) {
  16846. const levels = this.levels;
  16847. if (levels.length > 0) {
  16848. let i, l;
  16849. for (i = 1, l = levels.length; i < l; i++) {
  16850. if (distance < levels[i].distance) {
  16851. break;
  16852. }
  16853. }
  16854. return levels[i - 1].object;
  16855. }
  16856. return null;
  16857. }
  16858. raycast(raycaster, intersects) {
  16859. const levels = this.levels;
  16860. if (levels.length > 0) {
  16861. _v1$2.setFromMatrixPosition(this.matrixWorld);
  16862. const distance = raycaster.ray.origin.distanceTo(_v1$2);
  16863. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  16864. }
  16865. }
  16866. update(camera) {
  16867. const levels = this.levels;
  16868. if (levels.length > 1) {
  16869. _v1$2.setFromMatrixPosition(camera.matrixWorld);
  16870. _v2$1.setFromMatrixPosition(this.matrixWorld);
  16871. const distance = _v1$2.distanceTo(_v2$1) / camera.zoom;
  16872. levels[0].object.visible = true;
  16873. let i, l;
  16874. for (i = 1, l = levels.length; i < l; i++) {
  16875. if (distance >= levels[i].distance) {
  16876. levels[i - 1].object.visible = false;
  16877. levels[i].object.visible = true;
  16878. } else {
  16879. break;
  16880. }
  16881. }
  16882. this._currentLevel = i - 1;
  16883. for (; i < l; i++) {
  16884. levels[i].object.visible = false;
  16885. }
  16886. }
  16887. }
  16888. toJSON(meta) {
  16889. const data = super.toJSON(meta);
  16890. if (this.autoUpdate === false) data.object.autoUpdate = false;
  16891. data.object.levels = [];
  16892. const levels = this.levels;
  16893. for (let i = 0, l = levels.length; i < l; i++) {
  16894. const level = levels[i];
  16895. data.object.levels.push({
  16896. object: level.object.uuid,
  16897. distance: level.distance
  16898. });
  16899. }
  16900. return data;
  16901. }
  16902. }
  16903. const _basePosition = /*@__PURE__*/new Vector3();
  16904. const _skinIndex = /*@__PURE__*/new Vector4();
  16905. const _skinWeight = /*@__PURE__*/new Vector4();
  16906. const _vector$5 = /*@__PURE__*/new Vector3();
  16907. const _matrix = /*@__PURE__*/new Matrix4();
  16908. class SkinnedMesh extends Mesh {
  16909. constructor(geometry, material) {
  16910. super(geometry, material);
  16911. this.type = 'SkinnedMesh';
  16912. this.bindMode = 'attached';
  16913. this.bindMatrix = new Matrix4();
  16914. this.bindMatrixInverse = new Matrix4();
  16915. }
  16916. copy(source) {
  16917. super.copy(source);
  16918. this.bindMode = source.bindMode;
  16919. this.bindMatrix.copy(source.bindMatrix);
  16920. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  16921. this.skeleton = source.skeleton;
  16922. return this;
  16923. }
  16924. bind(skeleton, bindMatrix) {
  16925. this.skeleton = skeleton;
  16926. if (bindMatrix === undefined) {
  16927. this.updateMatrixWorld(true);
  16928. this.skeleton.calculateInverses();
  16929. bindMatrix = this.matrixWorld;
  16930. }
  16931. this.bindMatrix.copy(bindMatrix);
  16932. this.bindMatrixInverse.copy(bindMatrix).invert();
  16933. }
  16934. pose() {
  16935. this.skeleton.pose();
  16936. }
  16937. normalizeSkinWeights() {
  16938. const vector = new Vector4();
  16939. const skinWeight = this.geometry.attributes.skinWeight;
  16940. for (let i = 0, l = skinWeight.count; i < l; i++) {
  16941. vector.x = skinWeight.getX(i);
  16942. vector.y = skinWeight.getY(i);
  16943. vector.z = skinWeight.getZ(i);
  16944. vector.w = skinWeight.getW(i);
  16945. const scale = 1.0 / vector.manhattanLength();
  16946. if (scale !== Infinity) {
  16947. vector.multiplyScalar(scale);
  16948. } else {
  16949. vector.set(1, 0, 0, 0); // do something reasonable
  16950. }
  16951. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  16952. }
  16953. }
  16954. updateMatrixWorld(force) {
  16955. super.updateMatrixWorld(force);
  16956. if (this.bindMode === 'attached') {
  16957. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  16958. } else if (this.bindMode === 'detached') {
  16959. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  16960. } else {
  16961. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  16962. }
  16963. }
  16964. boneTransform(index, target) {
  16965. const skeleton = this.skeleton;
  16966. const geometry = this.geometry;
  16967. _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  16968. _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  16969. _basePosition.copy(target).applyMatrix4(this.bindMatrix);
  16970. target.set(0, 0, 0);
  16971. for (let i = 0; i < 4; i++) {
  16972. const weight = _skinWeight.getComponent(i);
  16973. if (weight !== 0) {
  16974. const boneIndex = _skinIndex.getComponent(i);
  16975. _matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  16976. target.addScaledVector(_vector$5.copy(_basePosition).applyMatrix4(_matrix), weight);
  16977. }
  16978. }
  16979. return target.applyMatrix4(this.bindMatrixInverse);
  16980. }
  16981. }
  16982. SkinnedMesh.prototype.isSkinnedMesh = true;
  16983. class Bone extends Object3D {
  16984. constructor() {
  16985. super();
  16986. this.type = 'Bone';
  16987. }
  16988. }
  16989. Bone.prototype.isBone = true;
  16990. class DataTexture extends Texture {
  16991. constructor(data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding) {
  16992. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  16993. this.image = {
  16994. data: data,
  16995. width: width,
  16996. height: height
  16997. };
  16998. this.magFilter = magFilter;
  16999. this.minFilter = minFilter;
  17000. this.generateMipmaps = false;
  17001. this.flipY = false;
  17002. this.unpackAlignment = 1;
  17003. this.needsUpdate = true;
  17004. }
  17005. }
  17006. DataTexture.prototype.isDataTexture = true;
  17007. const _offsetMatrix = /*@__PURE__*/new Matrix4();
  17008. const _identityMatrix = /*@__PURE__*/new Matrix4();
  17009. class Skeleton {
  17010. constructor(bones = [], boneInverses = []) {
  17011. this.uuid = generateUUID();
  17012. this.bones = bones.slice(0);
  17013. this.boneInverses = boneInverses;
  17014. this.boneMatrices = null;
  17015. this.boneTexture = null;
  17016. this.boneTextureSize = 0;
  17017. this.frame = -1;
  17018. this.init();
  17019. }
  17020. init() {
  17021. const bones = this.bones;
  17022. const boneInverses = this.boneInverses;
  17023. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  17024. if (boneInverses.length === 0) {
  17025. this.calculateInverses();
  17026. } else {
  17027. // handle special case
  17028. if (bones.length !== boneInverses.length) {
  17029. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  17030. this.boneInverses = [];
  17031. for (let i = 0, il = this.bones.length; i < il; i++) {
  17032. this.boneInverses.push(new Matrix4());
  17033. }
  17034. }
  17035. }
  17036. }
  17037. calculateInverses() {
  17038. this.boneInverses.length = 0;
  17039. for (let i = 0, il = this.bones.length; i < il; i++) {
  17040. const inverse = new Matrix4();
  17041. if (this.bones[i]) {
  17042. inverse.copy(this.bones[i].matrixWorld).invert();
  17043. }
  17044. this.boneInverses.push(inverse);
  17045. }
  17046. }
  17047. pose() {
  17048. // recover the bind-time world matrices
  17049. for (let i = 0, il = this.bones.length; i < il; i++) {
  17050. const bone = this.bones[i];
  17051. if (bone) {
  17052. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  17053. }
  17054. } // compute the local matrices, positions, rotations and scales
  17055. for (let i = 0, il = this.bones.length; i < il; i++) {
  17056. const bone = this.bones[i];
  17057. if (bone) {
  17058. if (bone.parent && bone.parent.isBone) {
  17059. bone.matrix.copy(bone.parent.matrixWorld).invert();
  17060. bone.matrix.multiply(bone.matrixWorld);
  17061. } else {
  17062. bone.matrix.copy(bone.matrixWorld);
  17063. }
  17064. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  17065. }
  17066. }
  17067. }
  17068. update() {
  17069. const bones = this.bones;
  17070. const boneInverses = this.boneInverses;
  17071. const boneMatrices = this.boneMatrices;
  17072. const boneTexture = this.boneTexture; // flatten bone matrices to array
  17073. for (let i = 0, il = bones.length; i < il; i++) {
  17074. // compute the offset between the current and the original transform
  17075. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  17076. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  17077. _offsetMatrix.toArray(boneMatrices, i * 16);
  17078. }
  17079. if (boneTexture !== null) {
  17080. boneTexture.needsUpdate = true;
  17081. }
  17082. }
  17083. clone() {
  17084. return new Skeleton(this.bones, this.boneInverses);
  17085. }
  17086. computeBoneTexture() {
  17087. // layout (1 matrix = 4 pixels)
  17088. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  17089. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  17090. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  17091. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  17092. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  17093. let size = Math.sqrt(this.bones.length * 4); // 4 pixels needed for 1 matrix
  17094. size = ceilPowerOfTwo(size);
  17095. size = Math.max(size, 4);
  17096. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  17097. boneMatrices.set(this.boneMatrices); // copy current values
  17098. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  17099. this.boneMatrices = boneMatrices;
  17100. this.boneTexture = boneTexture;
  17101. this.boneTextureSize = size;
  17102. return this;
  17103. }
  17104. getBoneByName(name) {
  17105. for (let i = 0, il = this.bones.length; i < il; i++) {
  17106. const bone = this.bones[i];
  17107. if (bone.name === name) {
  17108. return bone;
  17109. }
  17110. }
  17111. return undefined;
  17112. }
  17113. dispose() {
  17114. if (this.boneTexture !== null) {
  17115. this.boneTexture.dispose();
  17116. this.boneTexture = null;
  17117. }
  17118. }
  17119. fromJSON(json, bones) {
  17120. this.uuid = json.uuid;
  17121. for (let i = 0, l = json.bones.length; i < l; i++) {
  17122. const uuid = json.bones[i];
  17123. let bone = bones[uuid];
  17124. if (bone === undefined) {
  17125. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  17126. bone = new Bone();
  17127. }
  17128. this.bones.push(bone);
  17129. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  17130. }
  17131. this.init();
  17132. return this;
  17133. }
  17134. toJSON() {
  17135. const data = {
  17136. metadata: {
  17137. version: 4.5,
  17138. type: 'Skeleton',
  17139. generator: 'Skeleton.toJSON'
  17140. },
  17141. bones: [],
  17142. boneInverses: []
  17143. };
  17144. data.uuid = this.uuid;
  17145. const bones = this.bones;
  17146. const boneInverses = this.boneInverses;
  17147. for (let i = 0, l = bones.length; i < l; i++) {
  17148. const bone = bones[i];
  17149. data.bones.push(bone.uuid);
  17150. const boneInverse = boneInverses[i];
  17151. data.boneInverses.push(boneInverse.toArray());
  17152. }
  17153. return data;
  17154. }
  17155. }
  17156. class InstancedBufferAttribute extends BufferAttribute {
  17157. constructor(array, itemSize, normalized, meshPerAttribute = 1) {
  17158. if (typeof normalized === 'number') {
  17159. meshPerAttribute = normalized;
  17160. normalized = false;
  17161. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  17162. }
  17163. super(array, itemSize, normalized);
  17164. this.meshPerAttribute = meshPerAttribute;
  17165. }
  17166. copy(source) {
  17167. super.copy(source);
  17168. this.meshPerAttribute = source.meshPerAttribute;
  17169. return this;
  17170. }
  17171. toJSON() {
  17172. const data = super.toJSON();
  17173. data.meshPerAttribute = this.meshPerAttribute;
  17174. data.isInstancedBufferAttribute = true;
  17175. return data;
  17176. }
  17177. }
  17178. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  17179. const _instanceLocalMatrix = /*@__PURE__*/new Matrix4();
  17180. const _instanceWorldMatrix = /*@__PURE__*/new Matrix4();
  17181. const _instanceIntersects = [];
  17182. const _mesh = /*@__PURE__*/new Mesh();
  17183. class InstancedMesh extends Mesh {
  17184. constructor(geometry, material, count) {
  17185. super(geometry, material);
  17186. this.instanceMatrix = new InstancedBufferAttribute(new Float32Array(count * 16), 16);
  17187. this.instanceColor = null;
  17188. this.count = count;
  17189. this.frustumCulled = false;
  17190. }
  17191. copy(source) {
  17192. super.copy(source);
  17193. this.instanceMatrix.copy(source.instanceMatrix);
  17194. if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
  17195. this.count = source.count;
  17196. return this;
  17197. }
  17198. getColorAt(index, color) {
  17199. color.fromArray(this.instanceColor.array, index * 3);
  17200. }
  17201. getMatrixAt(index, matrix) {
  17202. matrix.fromArray(this.instanceMatrix.array, index * 16);
  17203. }
  17204. raycast(raycaster, intersects) {
  17205. const matrixWorld = this.matrixWorld;
  17206. const raycastTimes = this.count;
  17207. _mesh.geometry = this.geometry;
  17208. _mesh.material = this.material;
  17209. if (_mesh.material === undefined) return;
  17210. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  17211. // calculate the world matrix for each instance
  17212. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  17213. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  17214. _mesh.matrixWorld = _instanceWorldMatrix;
  17215. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  17216. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  17217. const intersect = _instanceIntersects[i];
  17218. intersect.instanceId = instanceId;
  17219. intersect.object = this;
  17220. intersects.push(intersect);
  17221. }
  17222. _instanceIntersects.length = 0;
  17223. }
  17224. }
  17225. setColorAt(index, color) {
  17226. if (this.instanceColor === null) {
  17227. this.instanceColor = new InstancedBufferAttribute(new Float32Array(this.instanceMatrix.count * 3), 3);
  17228. }
  17229. color.toArray(this.instanceColor.array, index * 3);
  17230. }
  17231. setMatrixAt(index, matrix) {
  17232. matrix.toArray(this.instanceMatrix.array, index * 16);
  17233. }
  17234. updateMorphTargets() {}
  17235. dispose() {
  17236. this.dispatchEvent({
  17237. type: 'dispose'
  17238. });
  17239. }
  17240. }
  17241. InstancedMesh.prototype.isInstancedMesh = true;
  17242. /**
  17243. * parameters = {
  17244. * color: <hex>,
  17245. * opacity: <float>,
  17246. *
  17247. * linewidth: <float>,
  17248. * linecap: "round",
  17249. * linejoin: "round"
  17250. * }
  17251. */
  17252. class LineBasicMaterial extends Material {
  17253. constructor(parameters) {
  17254. super();
  17255. this.type = 'LineBasicMaterial';
  17256. this.color = new Color(0xffffff);
  17257. this.linewidth = 1;
  17258. this.linecap = 'round';
  17259. this.linejoin = 'round';
  17260. this.setValues(parameters);
  17261. }
  17262. copy(source) {
  17263. super.copy(source);
  17264. this.color.copy(source.color);
  17265. this.linewidth = source.linewidth;
  17266. this.linecap = source.linecap;
  17267. this.linejoin = source.linejoin;
  17268. return this;
  17269. }
  17270. }
  17271. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  17272. const _start$1 = /*@__PURE__*/new Vector3();
  17273. const _end$1 = /*@__PURE__*/new Vector3();
  17274. const _inverseMatrix$1 = /*@__PURE__*/new Matrix4();
  17275. const _ray$1 = /*@__PURE__*/new Ray();
  17276. const _sphere$1 = /*@__PURE__*/new Sphere();
  17277. class Line extends Object3D {
  17278. constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) {
  17279. super();
  17280. this.type = 'Line';
  17281. this.geometry = geometry;
  17282. this.material = material;
  17283. this.updateMorphTargets();
  17284. }
  17285. copy(source) {
  17286. super.copy(source);
  17287. this.material = source.material;
  17288. this.geometry = source.geometry;
  17289. return this;
  17290. }
  17291. computeLineDistances() {
  17292. const geometry = this.geometry;
  17293. if (geometry.isBufferGeometry) {
  17294. // we assume non-indexed geometry
  17295. if (geometry.index === null) {
  17296. const positionAttribute = geometry.attributes.position;
  17297. const lineDistances = [0];
  17298. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  17299. _start$1.fromBufferAttribute(positionAttribute, i - 1);
  17300. _end$1.fromBufferAttribute(positionAttribute, i);
  17301. lineDistances[i] = lineDistances[i - 1];
  17302. lineDistances[i] += _start$1.distanceTo(_end$1);
  17303. }
  17304. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17305. } else {
  17306. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17307. }
  17308. } else if (geometry.isGeometry) {
  17309. console.error('THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17310. }
  17311. return this;
  17312. }
  17313. raycast(raycaster, intersects) {
  17314. const geometry = this.geometry;
  17315. const matrixWorld = this.matrixWorld;
  17316. const threshold = raycaster.params.Line.threshold;
  17317. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  17318. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17319. _sphere$1.copy(geometry.boundingSphere);
  17320. _sphere$1.applyMatrix4(matrixWorld);
  17321. _sphere$1.radius += threshold;
  17322. if (raycaster.ray.intersectsSphere(_sphere$1) === false) return; //
  17323. _inverseMatrix$1.copy(matrixWorld).invert();
  17324. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  17325. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17326. const localThresholdSq = localThreshold * localThreshold;
  17327. const vStart = new Vector3();
  17328. const vEnd = new Vector3();
  17329. const interSegment = new Vector3();
  17330. const interRay = new Vector3();
  17331. const step = this.isLineSegments ? 2 : 1;
  17332. if (geometry.isBufferGeometry) {
  17333. const index = geometry.index;
  17334. const attributes = geometry.attributes;
  17335. const positionAttribute = attributes.position;
  17336. if (index !== null) {
  17337. const start = Math.max(0, drawRange.start);
  17338. const end = Math.min(index.count, drawRange.start + drawRange.count);
  17339. for (let i = start, l = end - 1; i < l; i += step) {
  17340. const a = index.getX(i);
  17341. const b = index.getX(i + 1);
  17342. vStart.fromBufferAttribute(positionAttribute, a);
  17343. vEnd.fromBufferAttribute(positionAttribute, b);
  17344. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17345. if (distSq > localThresholdSq) continue;
  17346. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17347. const distance = raycaster.ray.origin.distanceTo(interRay);
  17348. if (distance < raycaster.near || distance > raycaster.far) continue;
  17349. intersects.push({
  17350. distance: distance,
  17351. // What do we want? intersection point on the ray or on the segment??
  17352. // point: raycaster.ray.at( distance ),
  17353. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17354. index: i,
  17355. face: null,
  17356. faceIndex: null,
  17357. object: this
  17358. });
  17359. }
  17360. } else {
  17361. const start = Math.max(0, drawRange.start);
  17362. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  17363. for (let i = start, l = end - 1; i < l; i += step) {
  17364. vStart.fromBufferAttribute(positionAttribute, i);
  17365. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  17366. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17367. if (distSq > localThresholdSq) continue;
  17368. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17369. const distance = raycaster.ray.origin.distanceTo(interRay);
  17370. if (distance < raycaster.near || distance > raycaster.far) continue;
  17371. intersects.push({
  17372. distance: distance,
  17373. // What do we want? intersection point on the ray or on the segment??
  17374. // point: raycaster.ray.at( distance ),
  17375. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17376. index: i,
  17377. face: null,
  17378. faceIndex: null,
  17379. object: this
  17380. });
  17381. }
  17382. }
  17383. } else if (geometry.isGeometry) {
  17384. console.error('THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17385. }
  17386. }
  17387. updateMorphTargets() {
  17388. const geometry = this.geometry;
  17389. if (geometry.isBufferGeometry) {
  17390. const morphAttributes = geometry.morphAttributes;
  17391. const keys = Object.keys(morphAttributes);
  17392. if (keys.length > 0) {
  17393. const morphAttribute = morphAttributes[keys[0]];
  17394. if (morphAttribute !== undefined) {
  17395. this.morphTargetInfluences = [];
  17396. this.morphTargetDictionary = {};
  17397. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  17398. const name = morphAttribute[m].name || String(m);
  17399. this.morphTargetInfluences.push(0);
  17400. this.morphTargetDictionary[name] = m;
  17401. }
  17402. }
  17403. }
  17404. } else {
  17405. const morphTargets = geometry.morphTargets;
  17406. if (morphTargets !== undefined && morphTargets.length > 0) {
  17407. console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17408. }
  17409. }
  17410. }
  17411. }
  17412. Line.prototype.isLine = true;
  17413. const _start = /*@__PURE__*/new Vector3();
  17414. const _end = /*@__PURE__*/new Vector3();
  17415. class LineSegments extends Line {
  17416. constructor(geometry, material) {
  17417. super(geometry, material);
  17418. this.type = 'LineSegments';
  17419. }
  17420. computeLineDistances() {
  17421. const geometry = this.geometry;
  17422. if (geometry.isBufferGeometry) {
  17423. // we assume non-indexed geometry
  17424. if (geometry.index === null) {
  17425. const positionAttribute = geometry.attributes.position;
  17426. const lineDistances = [];
  17427. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  17428. _start.fromBufferAttribute(positionAttribute, i);
  17429. _end.fromBufferAttribute(positionAttribute, i + 1);
  17430. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  17431. lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end);
  17432. }
  17433. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17434. } else {
  17435. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17436. }
  17437. } else if (geometry.isGeometry) {
  17438. console.error('THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17439. }
  17440. return this;
  17441. }
  17442. }
  17443. LineSegments.prototype.isLineSegments = true;
  17444. class LineLoop extends Line {
  17445. constructor(geometry, material) {
  17446. super(geometry, material);
  17447. this.type = 'LineLoop';
  17448. }
  17449. }
  17450. LineLoop.prototype.isLineLoop = true;
  17451. /**
  17452. * parameters = {
  17453. * color: <hex>,
  17454. * opacity: <float>,
  17455. * map: new THREE.Texture( <Image> ),
  17456. * alphaMap: new THREE.Texture( <Image> ),
  17457. *
  17458. * size: <float>,
  17459. * sizeAttenuation: <bool>
  17460. *
  17461. * }
  17462. */
  17463. class PointsMaterial extends Material {
  17464. constructor(parameters) {
  17465. super();
  17466. this.type = 'PointsMaterial';
  17467. this.color = new Color(0xffffff);
  17468. this.map = null;
  17469. this.alphaMap = null;
  17470. this.size = 1;
  17471. this.sizeAttenuation = true;
  17472. this.setValues(parameters);
  17473. }
  17474. copy(source) {
  17475. super.copy(source);
  17476. this.color.copy(source.color);
  17477. this.map = source.map;
  17478. this.alphaMap = source.alphaMap;
  17479. this.size = source.size;
  17480. this.sizeAttenuation = source.sizeAttenuation;
  17481. return this;
  17482. }
  17483. }
  17484. PointsMaterial.prototype.isPointsMaterial = true;
  17485. const _inverseMatrix = /*@__PURE__*/new Matrix4();
  17486. const _ray = /*@__PURE__*/new Ray();
  17487. const _sphere = /*@__PURE__*/new Sphere();
  17488. const _position$2 = /*@__PURE__*/new Vector3();
  17489. class Points extends Object3D {
  17490. constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) {
  17491. super();
  17492. this.type = 'Points';
  17493. this.geometry = geometry;
  17494. this.material = material;
  17495. this.updateMorphTargets();
  17496. }
  17497. copy(source) {
  17498. super.copy(source);
  17499. this.material = source.material;
  17500. this.geometry = source.geometry;
  17501. return this;
  17502. }
  17503. raycast(raycaster, intersects) {
  17504. const geometry = this.geometry;
  17505. const matrixWorld = this.matrixWorld;
  17506. const threshold = raycaster.params.Points.threshold;
  17507. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  17508. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17509. _sphere.copy(geometry.boundingSphere);
  17510. _sphere.applyMatrix4(matrixWorld);
  17511. _sphere.radius += threshold;
  17512. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  17513. _inverseMatrix.copy(matrixWorld).invert();
  17514. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);
  17515. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17516. const localThresholdSq = localThreshold * localThreshold;
  17517. if (geometry.isBufferGeometry) {
  17518. const index = geometry.index;
  17519. const attributes = geometry.attributes;
  17520. const positionAttribute = attributes.position;
  17521. if (index !== null) {
  17522. const start = Math.max(0, drawRange.start);
  17523. const end = Math.min(index.count, drawRange.start + drawRange.count);
  17524. for (let i = start, il = end; i < il; i++) {
  17525. const a = index.getX(i);
  17526. _position$2.fromBufferAttribute(positionAttribute, a);
  17527. testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17528. }
  17529. } else {
  17530. const start = Math.max(0, drawRange.start);
  17531. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  17532. for (let i = start, l = end; i < l; i++) {
  17533. _position$2.fromBufferAttribute(positionAttribute, i);
  17534. testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17535. }
  17536. }
  17537. } else {
  17538. console.error('THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17539. }
  17540. }
  17541. updateMorphTargets() {
  17542. const geometry = this.geometry;
  17543. if (geometry.isBufferGeometry) {
  17544. const morphAttributes = geometry.morphAttributes;
  17545. const keys = Object.keys(morphAttributes);
  17546. if (keys.length > 0) {
  17547. const morphAttribute = morphAttributes[keys[0]];
  17548. if (morphAttribute !== undefined) {
  17549. this.morphTargetInfluences = [];
  17550. this.morphTargetDictionary = {};
  17551. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  17552. const name = morphAttribute[m].name || String(m);
  17553. this.morphTargetInfluences.push(0);
  17554. this.morphTargetDictionary[name] = m;
  17555. }
  17556. }
  17557. }
  17558. } else {
  17559. const morphTargets = geometry.morphTargets;
  17560. if (morphTargets !== undefined && morphTargets.length > 0) {
  17561. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17562. }
  17563. }
  17564. }
  17565. }
  17566. Points.prototype.isPoints = true;
  17567. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  17568. const rayPointDistanceSq = _ray.distanceSqToPoint(point);
  17569. if (rayPointDistanceSq < localThresholdSq) {
  17570. const intersectPoint = new Vector3();
  17571. _ray.closestPointToPoint(point, intersectPoint);
  17572. intersectPoint.applyMatrix4(matrixWorld);
  17573. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  17574. if (distance < raycaster.near || distance > raycaster.far) return;
  17575. intersects.push({
  17576. distance: distance,
  17577. distanceToRay: Math.sqrt(rayPointDistanceSq),
  17578. point: intersectPoint,
  17579. index: index,
  17580. face: null,
  17581. object: object
  17582. });
  17583. }
  17584. }
  17585. class VideoTexture extends Texture {
  17586. constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17587. super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17588. this.format = format !== undefined ? format : RGBFormat;
  17589. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  17590. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  17591. this.generateMipmaps = false;
  17592. const scope = this;
  17593. function updateVideo() {
  17594. scope.needsUpdate = true;
  17595. video.requestVideoFrameCallback(updateVideo);
  17596. }
  17597. if ('requestVideoFrameCallback' in video) {
  17598. video.requestVideoFrameCallback(updateVideo);
  17599. }
  17600. }
  17601. clone() {
  17602. return new this.constructor(this.image).copy(this);
  17603. }
  17604. update() {
  17605. const video = this.image;
  17606. const hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  17607. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  17608. this.needsUpdate = true;
  17609. }
  17610. }
  17611. }
  17612. VideoTexture.prototype.isVideoTexture = true;
  17613. class CompressedTexture extends Texture {
  17614. constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  17615. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  17616. this.image = {
  17617. width: width,
  17618. height: height
  17619. };
  17620. this.mipmaps = mipmaps; // no flipping for cube textures
  17621. // (also flipping doesn't work for compressed textures )
  17622. this.flipY = false; // can't generate mipmaps for compressed textures
  17623. // mips must be embedded in DDS files
  17624. this.generateMipmaps = false;
  17625. }
  17626. }
  17627. CompressedTexture.prototype.isCompressedTexture = true;
  17628. class CanvasTexture extends Texture {
  17629. constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17630. super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17631. this.needsUpdate = true;
  17632. }
  17633. }
  17634. CanvasTexture.prototype.isCanvasTexture = true;
  17635. class DepthTexture extends Texture {
  17636. constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  17637. format = format !== undefined ? format : DepthFormat;
  17638. if (format !== DepthFormat && format !== DepthStencilFormat) {
  17639. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  17640. }
  17641. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  17642. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  17643. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17644. this.image = {
  17645. width: width,
  17646. height: height
  17647. };
  17648. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  17649. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  17650. this.flipY = false;
  17651. this.generateMipmaps = false;
  17652. }
  17653. }
  17654. DepthTexture.prototype.isDepthTexture = true;
  17655. class CircleGeometry extends BufferGeometry {
  17656. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  17657. super();
  17658. this.type = 'CircleGeometry';
  17659. this.parameters = {
  17660. radius: radius,
  17661. segments: segments,
  17662. thetaStart: thetaStart,
  17663. thetaLength: thetaLength
  17664. };
  17665. segments = Math.max(3, segments); // buffers
  17666. const indices = [];
  17667. const vertices = [];
  17668. const normals = [];
  17669. const uvs = []; // helper variables
  17670. const vertex = new Vector3();
  17671. const uv = new Vector2(); // center point
  17672. vertices.push(0, 0, 0);
  17673. normals.push(0, 0, 1);
  17674. uvs.push(0.5, 0.5);
  17675. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  17676. const segment = thetaStart + s / segments * thetaLength; // vertex
  17677. vertex.x = radius * Math.cos(segment);
  17678. vertex.y = radius * Math.sin(segment);
  17679. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17680. normals.push(0, 0, 1); // uvs
  17681. uv.x = (vertices[i] / radius + 1) / 2;
  17682. uv.y = (vertices[i + 1] / radius + 1) / 2;
  17683. uvs.push(uv.x, uv.y);
  17684. } // indices
  17685. for (let i = 1; i <= segments; i++) {
  17686. indices.push(i, i + 1, 0);
  17687. } // build geometry
  17688. this.setIndex(indices);
  17689. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17690. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17691. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17692. }
  17693. static fromJSON(data) {
  17694. return new CircleGeometry(data.radius, data.segments, data.thetaStart, data.thetaLength);
  17695. }
  17696. }
  17697. class CylinderGeometry extends BufferGeometry {
  17698. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  17699. super();
  17700. this.type = 'CylinderGeometry';
  17701. this.parameters = {
  17702. radiusTop: radiusTop,
  17703. radiusBottom: radiusBottom,
  17704. height: height,
  17705. radialSegments: radialSegments,
  17706. heightSegments: heightSegments,
  17707. openEnded: openEnded,
  17708. thetaStart: thetaStart,
  17709. thetaLength: thetaLength
  17710. };
  17711. const scope = this;
  17712. radialSegments = Math.floor(radialSegments);
  17713. heightSegments = Math.floor(heightSegments); // buffers
  17714. const indices = [];
  17715. const vertices = [];
  17716. const normals = [];
  17717. const uvs = []; // helper variables
  17718. let index = 0;
  17719. const indexArray = [];
  17720. const halfHeight = height / 2;
  17721. let groupStart = 0; // generate geometry
  17722. generateTorso();
  17723. if (openEnded === false) {
  17724. if (radiusTop > 0) generateCap(true);
  17725. if (radiusBottom > 0) generateCap(false);
  17726. } // build geometry
  17727. this.setIndex(indices);
  17728. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17729. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17730. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17731. function generateTorso() {
  17732. const normal = new Vector3();
  17733. const vertex = new Vector3();
  17734. let groupCount = 0; // this will be used to calculate the normal
  17735. const slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  17736. for (let y = 0; y <= heightSegments; y++) {
  17737. const indexRow = [];
  17738. const v = y / heightSegments; // calculate the radius of the current row
  17739. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  17740. for (let x = 0; x <= radialSegments; x++) {
  17741. const u = x / radialSegments;
  17742. const theta = u * thetaLength + thetaStart;
  17743. const sinTheta = Math.sin(theta);
  17744. const cosTheta = Math.cos(theta); // vertex
  17745. vertex.x = radius * sinTheta;
  17746. vertex.y = -v * height + halfHeight;
  17747. vertex.z = radius * cosTheta;
  17748. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17749. normal.set(sinTheta, slope, cosTheta).normalize();
  17750. normals.push(normal.x, normal.y, normal.z); // uv
  17751. uvs.push(u, 1 - v); // save index of vertex in respective row
  17752. indexRow.push(index++);
  17753. } // now save vertices of the row in our index array
  17754. indexArray.push(indexRow);
  17755. } // generate indices
  17756. for (let x = 0; x < radialSegments; x++) {
  17757. for (let y = 0; y < heightSegments; y++) {
  17758. // we use the index array to access the correct indices
  17759. const a = indexArray[y][x];
  17760. const b = indexArray[y + 1][x];
  17761. const c = indexArray[y + 1][x + 1];
  17762. const d = indexArray[y][x + 1]; // faces
  17763. indices.push(a, b, d);
  17764. indices.push(b, c, d); // update group counter
  17765. groupCount += 6;
  17766. }
  17767. } // add a group to the geometry. this will ensure multi material support
  17768. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  17769. groupStart += groupCount;
  17770. }
  17771. function generateCap(top) {
  17772. // save the index of the first center vertex
  17773. const centerIndexStart = index;
  17774. const uv = new Vector2();
  17775. const vertex = new Vector3();
  17776. let groupCount = 0;
  17777. const radius = top === true ? radiusTop : radiusBottom;
  17778. const sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  17779. // because the geometry needs one set of uvs per face,
  17780. // we must generate a center vertex per face/segment
  17781. for (let x = 1; x <= radialSegments; x++) {
  17782. // vertex
  17783. vertices.push(0, halfHeight * sign, 0); // normal
  17784. normals.push(0, sign, 0); // uv
  17785. uvs.push(0.5, 0.5); // increase index
  17786. index++;
  17787. } // save the index of the last center vertex
  17788. const centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  17789. for (let x = 0; x <= radialSegments; x++) {
  17790. const u = x / radialSegments;
  17791. const theta = u * thetaLength + thetaStart;
  17792. const cosTheta = Math.cos(theta);
  17793. const sinTheta = Math.sin(theta); // vertex
  17794. vertex.x = radius * sinTheta;
  17795. vertex.y = halfHeight * sign;
  17796. vertex.z = radius * cosTheta;
  17797. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17798. normals.push(0, sign, 0); // uv
  17799. uv.x = cosTheta * 0.5 + 0.5;
  17800. uv.y = sinTheta * 0.5 * sign + 0.5;
  17801. uvs.push(uv.x, uv.y); // increase index
  17802. index++;
  17803. } // generate indices
  17804. for (let x = 0; x < radialSegments; x++) {
  17805. const c = centerIndexStart + x;
  17806. const i = centerIndexEnd + x;
  17807. if (top === true) {
  17808. // face top
  17809. indices.push(i, i + 1, c);
  17810. } else {
  17811. // face bottom
  17812. indices.push(i + 1, i, c);
  17813. }
  17814. groupCount += 3;
  17815. } // add a group to the geometry. this will ensure multi material support
  17816. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  17817. groupStart += groupCount;
  17818. }
  17819. }
  17820. static fromJSON(data) {
  17821. return new CylinderGeometry(data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  17822. }
  17823. }
  17824. class ConeGeometry extends CylinderGeometry {
  17825. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  17826. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  17827. this.type = 'ConeGeometry';
  17828. this.parameters = {
  17829. radius: radius,
  17830. height: height,
  17831. radialSegments: radialSegments,
  17832. heightSegments: heightSegments,
  17833. openEnded: openEnded,
  17834. thetaStart: thetaStart,
  17835. thetaLength: thetaLength
  17836. };
  17837. }
  17838. static fromJSON(data) {
  17839. return new ConeGeometry(data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  17840. }
  17841. }
  17842. class PolyhedronGeometry extends BufferGeometry {
  17843. constructor(vertices = [], indices = [], radius = 1, detail = 0) {
  17844. super();
  17845. this.type = 'PolyhedronGeometry';
  17846. this.parameters = {
  17847. vertices: vertices,
  17848. indices: indices,
  17849. radius: radius,
  17850. detail: detail
  17851. }; // default buffer data
  17852. const vertexBuffer = [];
  17853. const uvBuffer = []; // the subdivision creates the vertex buffer data
  17854. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  17855. applyRadius(radius); // finally, create the uv data
  17856. generateUVs(); // build non-indexed geometry
  17857. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  17858. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  17859. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  17860. if (detail === 0) {
  17861. this.computeVertexNormals(); // flat normals
  17862. } else {
  17863. this.normalizeNormals(); // smooth normals
  17864. } // helper functions
  17865. function subdivide(detail) {
  17866. const a = new Vector3();
  17867. const b = new Vector3();
  17868. const c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  17869. for (let i = 0; i < indices.length; i += 3) {
  17870. // get the vertices of the face
  17871. getVertexByIndex(indices[i + 0], a);
  17872. getVertexByIndex(indices[i + 1], b);
  17873. getVertexByIndex(indices[i + 2], c); // perform subdivision
  17874. subdivideFace(a, b, c, detail);
  17875. }
  17876. }
  17877. function subdivideFace(a, b, c, detail) {
  17878. const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  17879. const v = []; // construct all of the vertices for this subdivision
  17880. for (let i = 0; i <= cols; i++) {
  17881. v[i] = [];
  17882. const aj = a.clone().lerp(c, i / cols);
  17883. const bj = b.clone().lerp(c, i / cols);
  17884. const rows = cols - i;
  17885. for (let j = 0; j <= rows; j++) {
  17886. if (j === 0 && i === cols) {
  17887. v[i][j] = aj;
  17888. } else {
  17889. v[i][j] = aj.clone().lerp(bj, j / rows);
  17890. }
  17891. }
  17892. } // construct all of the faces
  17893. for (let i = 0; i < cols; i++) {
  17894. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  17895. const k = Math.floor(j / 2);
  17896. if (j % 2 === 0) {
  17897. pushVertex(v[i][k + 1]);
  17898. pushVertex(v[i + 1][k]);
  17899. pushVertex(v[i][k]);
  17900. } else {
  17901. pushVertex(v[i][k + 1]);
  17902. pushVertex(v[i + 1][k + 1]);
  17903. pushVertex(v[i + 1][k]);
  17904. }
  17905. }
  17906. }
  17907. }
  17908. function applyRadius(radius) {
  17909. const vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  17910. for (let i = 0; i < vertexBuffer.length; i += 3) {
  17911. vertex.x = vertexBuffer[i + 0];
  17912. vertex.y = vertexBuffer[i + 1];
  17913. vertex.z = vertexBuffer[i + 2];
  17914. vertex.normalize().multiplyScalar(radius);
  17915. vertexBuffer[i + 0] = vertex.x;
  17916. vertexBuffer[i + 1] = vertex.y;
  17917. vertexBuffer[i + 2] = vertex.z;
  17918. }
  17919. }
  17920. function generateUVs() {
  17921. const vertex = new Vector3();
  17922. for (let i = 0; i < vertexBuffer.length; i += 3) {
  17923. vertex.x = vertexBuffer[i + 0];
  17924. vertex.y = vertexBuffer[i + 1];
  17925. vertex.z = vertexBuffer[i + 2];
  17926. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  17927. const v = inclination(vertex) / Math.PI + 0.5;
  17928. uvBuffer.push(u, 1 - v);
  17929. }
  17930. correctUVs();
  17931. correctSeam();
  17932. }
  17933. function correctSeam() {
  17934. // handle case when face straddles the seam, see #3269
  17935. for (let i = 0; i < uvBuffer.length; i += 6) {
  17936. // uv data of a single face
  17937. const x0 = uvBuffer[i + 0];
  17938. const x1 = uvBuffer[i + 2];
  17939. const x2 = uvBuffer[i + 4];
  17940. const max = Math.max(x0, x1, x2);
  17941. const min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  17942. if (max > 0.9 && min < 0.1) {
  17943. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  17944. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  17945. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  17946. }
  17947. }
  17948. }
  17949. function pushVertex(vertex) {
  17950. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  17951. }
  17952. function getVertexByIndex(index, vertex) {
  17953. const stride = index * 3;
  17954. vertex.x = vertices[stride + 0];
  17955. vertex.y = vertices[stride + 1];
  17956. vertex.z = vertices[stride + 2];
  17957. }
  17958. function correctUVs() {
  17959. const a = new Vector3();
  17960. const b = new Vector3();
  17961. const c = new Vector3();
  17962. const centroid = new Vector3();
  17963. const uvA = new Vector2();
  17964. const uvB = new Vector2();
  17965. const uvC = new Vector2();
  17966. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  17967. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  17968. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  17969. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  17970. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  17971. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  17972. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  17973. centroid.copy(a).add(b).add(c).divideScalar(3);
  17974. const azi = azimuth(centroid);
  17975. correctUV(uvA, j + 0, a, azi);
  17976. correctUV(uvB, j + 2, b, azi);
  17977. correctUV(uvC, j + 4, c, azi);
  17978. }
  17979. }
  17980. function correctUV(uv, stride, vector, azimuth) {
  17981. if (azimuth < 0 && uv.x === 1) {
  17982. uvBuffer[stride] = uv.x - 1;
  17983. }
  17984. if (vector.x === 0 && vector.z === 0) {
  17985. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  17986. }
  17987. } // Angle around the Y axis, counter-clockwise when looking from above.
  17988. function azimuth(vector) {
  17989. return Math.atan2(vector.z, -vector.x);
  17990. } // Angle above the XZ plane.
  17991. function inclination(vector) {
  17992. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  17993. }
  17994. }
  17995. static fromJSON(data) {
  17996. return new PolyhedronGeometry(data.vertices, data.indices, data.radius, data.details);
  17997. }
  17998. }
  17999. class DodecahedronGeometry extends PolyhedronGeometry {
  18000. constructor(radius = 1, detail = 0) {
  18001. const t = (1 + Math.sqrt(5)) / 2;
  18002. const r = 1 / t;
  18003. const vertices = [// (±1, ±1, ±1)
  18004. -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/φ, ±φ)
  18005. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  18006. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  18007. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  18008. 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];
  18009. super(vertices, indices, radius, detail);
  18010. this.type = 'DodecahedronGeometry';
  18011. this.parameters = {
  18012. radius: radius,
  18013. detail: detail
  18014. };
  18015. }
  18016. static fromJSON(data) {
  18017. return new DodecahedronGeometry(data.radius, data.detail);
  18018. }
  18019. }
  18020. const _v0 = new Vector3();
  18021. const _v1$1 = new Vector3();
  18022. const _normal = new Vector3();
  18023. const _triangle = new Triangle();
  18024. class EdgesGeometry extends BufferGeometry {
  18025. constructor(geometry = null, thresholdAngle = 1) {
  18026. super();
  18027. this.type = 'EdgesGeometry';
  18028. this.parameters = {
  18029. geometry: geometry,
  18030. thresholdAngle: thresholdAngle
  18031. };
  18032. if (geometry !== null) {
  18033. const precisionPoints = 4;
  18034. const precision = Math.pow(10, precisionPoints);
  18035. const thresholdDot = Math.cos(DEG2RAD * thresholdAngle);
  18036. const indexAttr = geometry.getIndex();
  18037. const positionAttr = geometry.getAttribute('position');
  18038. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  18039. const indexArr = [0, 0, 0];
  18040. const vertKeys = ['a', 'b', 'c'];
  18041. const hashes = new Array(3);
  18042. const edgeData = {};
  18043. const vertices = [];
  18044. for (let i = 0; i < indexCount; i += 3) {
  18045. if (indexAttr) {
  18046. indexArr[0] = indexAttr.getX(i);
  18047. indexArr[1] = indexAttr.getX(i + 1);
  18048. indexArr[2] = indexAttr.getX(i + 2);
  18049. } else {
  18050. indexArr[0] = i;
  18051. indexArr[1] = i + 1;
  18052. indexArr[2] = i + 2;
  18053. }
  18054. const {
  18055. a,
  18056. b,
  18057. c
  18058. } = _triangle;
  18059. a.fromBufferAttribute(positionAttr, indexArr[0]);
  18060. b.fromBufferAttribute(positionAttr, indexArr[1]);
  18061. c.fromBufferAttribute(positionAttr, indexArr[2]);
  18062. _triangle.getNormal(_normal); // create hashes for the edge from the vertices
  18063. hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`;
  18064. hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`;
  18065. hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; // skip degenerate triangles
  18066. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  18067. continue;
  18068. } // iterate over every edge
  18069. for (let j = 0; j < 3; j++) {
  18070. // get the first and next vertex making up the edge
  18071. const jNext = (j + 1) % 3;
  18072. const vecHash0 = hashes[j];
  18073. const vecHash1 = hashes[jNext];
  18074. const v0 = _triangle[vertKeys[j]];
  18075. const v1 = _triangle[vertKeys[jNext]];
  18076. const hash = `${vecHash0}_${vecHash1}`;
  18077. const reverseHash = `${vecHash1}_${vecHash0}`;
  18078. if (reverseHash in edgeData && edgeData[reverseHash]) {
  18079. // if we found a sibling edge add it into the vertex array if
  18080. // it meets the angle threshold and delete the edge from the map.
  18081. if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  18082. vertices.push(v0.x, v0.y, v0.z);
  18083. vertices.push(v1.x, v1.y, v1.z);
  18084. }
  18085. edgeData[reverseHash] = null;
  18086. } else if (!(hash in edgeData)) {
  18087. // if we've already got an edge here then skip adding a new one
  18088. edgeData[hash] = {
  18089. index0: indexArr[j],
  18090. index1: indexArr[jNext],
  18091. normal: _normal.clone()
  18092. };
  18093. }
  18094. }
  18095. } // iterate over all remaining, unmatched edges and add them to the vertex array
  18096. for (const key in edgeData) {
  18097. if (edgeData[key]) {
  18098. const {
  18099. index0,
  18100. index1
  18101. } = edgeData[key];
  18102. _v0.fromBufferAttribute(positionAttr, index0);
  18103. _v1$1.fromBufferAttribute(positionAttr, index1);
  18104. vertices.push(_v0.x, _v0.y, _v0.z);
  18105. vertices.push(_v1$1.x, _v1$1.y, _v1$1.z);
  18106. }
  18107. }
  18108. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18109. }
  18110. }
  18111. }
  18112. /**
  18113. * Extensible curve object.
  18114. *
  18115. * Some common of curve methods:
  18116. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18117. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18118. * .getPoints(), .getSpacedPoints()
  18119. * .getLength()
  18120. * .updateArcLengths()
  18121. *
  18122. * This following curves inherit from THREE.Curve:
  18123. *
  18124. * -- 2D curves --
  18125. * THREE.ArcCurve
  18126. * THREE.CubicBezierCurve
  18127. * THREE.EllipseCurve
  18128. * THREE.LineCurve
  18129. * THREE.QuadraticBezierCurve
  18130. * THREE.SplineCurve
  18131. *
  18132. * -- 3D curves --
  18133. * THREE.CatmullRomCurve3
  18134. * THREE.CubicBezierCurve3
  18135. * THREE.LineCurve3
  18136. * THREE.QuadraticBezierCurve3
  18137. *
  18138. * A series of curves can be represented as a THREE.CurvePath.
  18139. *
  18140. **/
  18141. class Curve {
  18142. constructor() {
  18143. this.type = 'Curve';
  18144. this.arcLengthDivisions = 200;
  18145. } // Virtual base class method to overwrite and implement in subclasses
  18146. // - t [0 .. 1]
  18147. getPoint() {
  18148. console.warn('THREE.Curve: .getPoint() not implemented.');
  18149. return null;
  18150. } // Get point at relative position in curve according to arc length
  18151. // - u [0 .. 1]
  18152. getPointAt(u, optionalTarget) {
  18153. const t = this.getUtoTmapping(u);
  18154. return this.getPoint(t, optionalTarget);
  18155. } // Get sequence of points using getPoint( t )
  18156. getPoints(divisions = 5) {
  18157. const points = [];
  18158. for (let d = 0; d <= divisions; d++) {
  18159. points.push(this.getPoint(d / divisions));
  18160. }
  18161. return points;
  18162. } // Get sequence of points using getPointAt( u )
  18163. getSpacedPoints(divisions = 5) {
  18164. const points = [];
  18165. for (let d = 0; d <= divisions; d++) {
  18166. points.push(this.getPointAt(d / divisions));
  18167. }
  18168. return points;
  18169. } // Get total curve arc length
  18170. getLength() {
  18171. const lengths = this.getLengths();
  18172. return lengths[lengths.length - 1];
  18173. } // Get list of cumulative segment lengths
  18174. getLengths(divisions = this.arcLengthDivisions) {
  18175. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  18176. return this.cacheArcLengths;
  18177. }
  18178. this.needsUpdate = false;
  18179. const cache = [];
  18180. let current,
  18181. last = this.getPoint(0);
  18182. let sum = 0;
  18183. cache.push(0);
  18184. for (let p = 1; p <= divisions; p++) {
  18185. current = this.getPoint(p / divisions);
  18186. sum += current.distanceTo(last);
  18187. cache.push(sum);
  18188. last = current;
  18189. }
  18190. this.cacheArcLengths = cache;
  18191. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18192. }
  18193. updateArcLengths() {
  18194. this.needsUpdate = true;
  18195. this.getLengths();
  18196. } // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18197. getUtoTmapping(u, distance) {
  18198. const arcLengths = this.getLengths();
  18199. let i = 0;
  18200. const il = arcLengths.length;
  18201. let targetArcLength; // The targeted u distance value to get
  18202. if (distance) {
  18203. targetArcLength = distance;
  18204. } else {
  18205. targetArcLength = u * arcLengths[il - 1];
  18206. } // binary search for the index with largest value smaller than target u distance
  18207. let low = 0,
  18208. high = il - 1,
  18209. comparison;
  18210. while (low <= high) {
  18211. 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
  18212. comparison = arcLengths[i] - targetArcLength;
  18213. if (comparison < 0) {
  18214. low = i + 1;
  18215. } else if (comparison > 0) {
  18216. high = i - 1;
  18217. } else {
  18218. high = i;
  18219. break; // DONE
  18220. }
  18221. }
  18222. i = high;
  18223. if (arcLengths[i] === targetArcLength) {
  18224. return i / (il - 1);
  18225. } // we could get finer grain at lengths, or use simple interpolation between two points
  18226. const lengthBefore = arcLengths[i];
  18227. const lengthAfter = arcLengths[i + 1];
  18228. const segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  18229. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  18230. const t = (i + segmentFraction) / (il - 1);
  18231. return t;
  18232. } // Returns a unit vector tangent at t
  18233. // In case any sub curve does not implement its tangent derivation,
  18234. // 2 points a small delta apart will be used to find its gradient
  18235. // which seems to give a reasonable approximation
  18236. getTangent(t, optionalTarget) {
  18237. const delta = 0.0001;
  18238. let t1 = t - delta;
  18239. let t2 = t + delta; // Capping in case of danger
  18240. if (t1 < 0) t1 = 0;
  18241. if (t2 > 1) t2 = 1;
  18242. const pt1 = this.getPoint(t1);
  18243. const pt2 = this.getPoint(t2);
  18244. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  18245. tangent.copy(pt2).sub(pt1).normalize();
  18246. return tangent;
  18247. }
  18248. getTangentAt(u, optionalTarget) {
  18249. const t = this.getUtoTmapping(u);
  18250. return this.getTangent(t, optionalTarget);
  18251. }
  18252. computeFrenetFrames(segments, closed) {
  18253. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18254. const normal = new Vector3();
  18255. const tangents = [];
  18256. const normals = [];
  18257. const binormals = [];
  18258. const vec = new Vector3();
  18259. const mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  18260. for (let i = 0; i <= segments; i++) {
  18261. const u = i / segments;
  18262. tangents[i] = this.getTangentAt(u, new Vector3());
  18263. } // select an initial normal vector perpendicular to the first tangent vector,
  18264. // and in the direction of the minimum tangent xyz component
  18265. normals[0] = new Vector3();
  18266. binormals[0] = new Vector3();
  18267. let min = Number.MAX_VALUE;
  18268. const tx = Math.abs(tangents[0].x);
  18269. const ty = Math.abs(tangents[0].y);
  18270. const tz = Math.abs(tangents[0].z);
  18271. if (tx <= min) {
  18272. min = tx;
  18273. normal.set(1, 0, 0);
  18274. }
  18275. if (ty <= min) {
  18276. min = ty;
  18277. normal.set(0, 1, 0);
  18278. }
  18279. if (tz <= min) {
  18280. normal.set(0, 0, 1);
  18281. }
  18282. vec.crossVectors(tangents[0], normal).normalize();
  18283. normals[0].crossVectors(tangents[0], vec);
  18284. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18285. for (let i = 1; i <= segments; i++) {
  18286. normals[i] = normals[i - 1].clone();
  18287. binormals[i] = binormals[i - 1].clone();
  18288. vec.crossVectors(tangents[i - 1], tangents[i]);
  18289. if (vec.length() > Number.EPSILON) {
  18290. vec.normalize();
  18291. const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  18292. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  18293. }
  18294. binormals[i].crossVectors(tangents[i], normals[i]);
  18295. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18296. if (closed === true) {
  18297. let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1));
  18298. theta /= segments;
  18299. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  18300. theta = -theta;
  18301. }
  18302. for (let i = 1; i <= segments; i++) {
  18303. // twist a little...
  18304. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  18305. binormals[i].crossVectors(tangents[i], normals[i]);
  18306. }
  18307. }
  18308. return {
  18309. tangents: tangents,
  18310. normals: normals,
  18311. binormals: binormals
  18312. };
  18313. }
  18314. clone() {
  18315. return new this.constructor().copy(this);
  18316. }
  18317. copy(source) {
  18318. this.arcLengthDivisions = source.arcLengthDivisions;
  18319. return this;
  18320. }
  18321. toJSON() {
  18322. const data = {
  18323. metadata: {
  18324. version: 4.5,
  18325. type: 'Curve',
  18326. generator: 'Curve.toJSON'
  18327. }
  18328. };
  18329. data.arcLengthDivisions = this.arcLengthDivisions;
  18330. data.type = this.type;
  18331. return data;
  18332. }
  18333. fromJSON(json) {
  18334. this.arcLengthDivisions = json.arcLengthDivisions;
  18335. return this;
  18336. }
  18337. }
  18338. class EllipseCurve extends Curve {
  18339. constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) {
  18340. super();
  18341. this.type = 'EllipseCurve';
  18342. this.aX = aX;
  18343. this.aY = aY;
  18344. this.xRadius = xRadius;
  18345. this.yRadius = yRadius;
  18346. this.aStartAngle = aStartAngle;
  18347. this.aEndAngle = aEndAngle;
  18348. this.aClockwise = aClockwise;
  18349. this.aRotation = aRotation;
  18350. }
  18351. getPoint(t, optionalTarget) {
  18352. const point = optionalTarget || new Vector2();
  18353. const twoPi = Math.PI * 2;
  18354. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18355. const samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  18356. while (deltaAngle < 0) deltaAngle += twoPi;
  18357. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  18358. if (deltaAngle < Number.EPSILON) {
  18359. if (samePoints) {
  18360. deltaAngle = 0;
  18361. } else {
  18362. deltaAngle = twoPi;
  18363. }
  18364. }
  18365. if (this.aClockwise === true && !samePoints) {
  18366. if (deltaAngle === twoPi) {
  18367. deltaAngle = -twoPi;
  18368. } else {
  18369. deltaAngle = deltaAngle - twoPi;
  18370. }
  18371. }
  18372. const angle = this.aStartAngle + t * deltaAngle;
  18373. let x = this.aX + this.xRadius * Math.cos(angle);
  18374. let y = this.aY + this.yRadius * Math.sin(angle);
  18375. if (this.aRotation !== 0) {
  18376. const cos = Math.cos(this.aRotation);
  18377. const sin = Math.sin(this.aRotation);
  18378. const tx = x - this.aX;
  18379. const ty = y - this.aY; // Rotate the point about the center of the ellipse.
  18380. x = tx * cos - ty * sin + this.aX;
  18381. y = tx * sin + ty * cos + this.aY;
  18382. }
  18383. return point.set(x, y);
  18384. }
  18385. copy(source) {
  18386. super.copy(source);
  18387. this.aX = source.aX;
  18388. this.aY = source.aY;
  18389. this.xRadius = source.xRadius;
  18390. this.yRadius = source.yRadius;
  18391. this.aStartAngle = source.aStartAngle;
  18392. this.aEndAngle = source.aEndAngle;
  18393. this.aClockwise = source.aClockwise;
  18394. this.aRotation = source.aRotation;
  18395. return this;
  18396. }
  18397. toJSON() {
  18398. const data = super.toJSON();
  18399. data.aX = this.aX;
  18400. data.aY = this.aY;
  18401. data.xRadius = this.xRadius;
  18402. data.yRadius = this.yRadius;
  18403. data.aStartAngle = this.aStartAngle;
  18404. data.aEndAngle = this.aEndAngle;
  18405. data.aClockwise = this.aClockwise;
  18406. data.aRotation = this.aRotation;
  18407. return data;
  18408. }
  18409. fromJSON(json) {
  18410. super.fromJSON(json);
  18411. this.aX = json.aX;
  18412. this.aY = json.aY;
  18413. this.xRadius = json.xRadius;
  18414. this.yRadius = json.yRadius;
  18415. this.aStartAngle = json.aStartAngle;
  18416. this.aEndAngle = json.aEndAngle;
  18417. this.aClockwise = json.aClockwise;
  18418. this.aRotation = json.aRotation;
  18419. return this;
  18420. }
  18421. }
  18422. EllipseCurve.prototype.isEllipseCurve = true;
  18423. class ArcCurve extends EllipseCurve {
  18424. constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  18425. super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  18426. this.type = 'ArcCurve';
  18427. }
  18428. }
  18429. ArcCurve.prototype.isArcCurve = true;
  18430. /**
  18431. * Centripetal CatmullRom Curve - which is useful for avoiding
  18432. * cusps and self-intersections in non-uniform catmull rom curves.
  18433. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18434. *
  18435. * curve.type accepts centripetal(default), chordal and catmullrom
  18436. * curve.tension is used for catmullrom which defaults to 0.5
  18437. */
  18438. /*
  18439. Based on an optimized c++ solution in
  18440. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  18441. - http://ideone.com/NoEbVM
  18442. This CubicPoly class could be used for reusing some variables and calculations,
  18443. but for three.js curve use, it could be possible inlined and flatten into a single function call
  18444. which can be placed in CurveUtils.
  18445. */
  18446. function CubicPoly() {
  18447. let c0 = 0,
  18448. c1 = 0,
  18449. c2 = 0,
  18450. c3 = 0;
  18451. /*
  18452. * Compute coefficients for a cubic polynomial
  18453. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  18454. * such that
  18455. * p(0) = x0, p(1) = x1
  18456. * and
  18457. * p'(0) = t0, p'(1) = t1.
  18458. */
  18459. function init(x0, x1, t0, t1) {
  18460. c0 = x0;
  18461. c1 = t0;
  18462. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  18463. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  18464. }
  18465. return {
  18466. initCatmullRom: function (x0, x1, x2, x3, tension) {
  18467. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  18468. },
  18469. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  18470. // compute tangents when parameterized in [t1,t2]
  18471. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  18472. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  18473. t1 *= dt1;
  18474. t2 *= dt1;
  18475. init(x1, x2, t1, t2);
  18476. },
  18477. calc: function (t) {
  18478. const t2 = t * t;
  18479. const t3 = t2 * t;
  18480. return c0 + c1 * t + c2 * t2 + c3 * t3;
  18481. }
  18482. };
  18483. } //
  18484. const tmp = new Vector3();
  18485. const px = new CubicPoly(),
  18486. py = new CubicPoly(),
  18487. pz = new CubicPoly();
  18488. class CatmullRomCurve3 extends Curve {
  18489. constructor(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  18490. super();
  18491. this.type = 'CatmullRomCurve3';
  18492. this.points = points;
  18493. this.closed = closed;
  18494. this.curveType = curveType;
  18495. this.tension = tension;
  18496. }
  18497. getPoint(t, optionalTarget = new Vector3()) {
  18498. const point = optionalTarget;
  18499. const points = this.points;
  18500. const l = points.length;
  18501. const p = (l - (this.closed ? 0 : 1)) * t;
  18502. let intPoint = Math.floor(p);
  18503. let weight = p - intPoint;
  18504. if (this.closed) {
  18505. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  18506. } else if (weight === 0 && intPoint === l - 1) {
  18507. intPoint = l - 2;
  18508. weight = 1;
  18509. }
  18510. let p0, p3; // 4 points (p1 & p2 defined below)
  18511. if (this.closed || intPoint > 0) {
  18512. p0 = points[(intPoint - 1) % l];
  18513. } else {
  18514. // extrapolate first point
  18515. tmp.subVectors(points[0], points[1]).add(points[0]);
  18516. p0 = tmp;
  18517. }
  18518. const p1 = points[intPoint % l];
  18519. const p2 = points[(intPoint + 1) % l];
  18520. if (this.closed || intPoint + 2 < l) {
  18521. p3 = points[(intPoint + 2) % l];
  18522. } else {
  18523. // extrapolate last point
  18524. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  18525. p3 = tmp;
  18526. }
  18527. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  18528. // init Centripetal / Chordal Catmull-Rom
  18529. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  18530. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  18531. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  18532. let dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  18533. if (dt1 < 1e-4) dt1 = 1.0;
  18534. if (dt0 < 1e-4) dt0 = dt1;
  18535. if (dt2 < 1e-4) dt2 = dt1;
  18536. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  18537. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  18538. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  18539. } else if (this.curveType === 'catmullrom') {
  18540. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  18541. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  18542. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  18543. }
  18544. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  18545. return point;
  18546. }
  18547. copy(source) {
  18548. super.copy(source);
  18549. this.points = [];
  18550. for (let i = 0, l = source.points.length; i < l; i++) {
  18551. const point = source.points[i];
  18552. this.points.push(point.clone());
  18553. }
  18554. this.closed = source.closed;
  18555. this.curveType = source.curveType;
  18556. this.tension = source.tension;
  18557. return this;
  18558. }
  18559. toJSON() {
  18560. const data = super.toJSON();
  18561. data.points = [];
  18562. for (let i = 0, l = this.points.length; i < l; i++) {
  18563. const point = this.points[i];
  18564. data.points.push(point.toArray());
  18565. }
  18566. data.closed = this.closed;
  18567. data.curveType = this.curveType;
  18568. data.tension = this.tension;
  18569. return data;
  18570. }
  18571. fromJSON(json) {
  18572. super.fromJSON(json);
  18573. this.points = [];
  18574. for (let i = 0, l = json.points.length; i < l; i++) {
  18575. const point = json.points[i];
  18576. this.points.push(new Vector3().fromArray(point));
  18577. }
  18578. this.closed = json.closed;
  18579. this.curveType = json.curveType;
  18580. this.tension = json.tension;
  18581. return this;
  18582. }
  18583. }
  18584. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  18585. /**
  18586. * Bezier Curves formulas obtained from
  18587. * http://en.wikipedia.org/wiki/Bézier_curve
  18588. */
  18589. function CatmullRom(t, p0, p1, p2, p3) {
  18590. const v0 = (p2 - p0) * 0.5;
  18591. const v1 = (p3 - p1) * 0.5;
  18592. const t2 = t * t;
  18593. const t3 = t * t2;
  18594. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  18595. } //
  18596. function QuadraticBezierP0(t, p) {
  18597. const k = 1 - t;
  18598. return k * k * p;
  18599. }
  18600. function QuadraticBezierP1(t, p) {
  18601. return 2 * (1 - t) * t * p;
  18602. }
  18603. function QuadraticBezierP2(t, p) {
  18604. return t * t * p;
  18605. }
  18606. function QuadraticBezier(t, p0, p1, p2) {
  18607. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  18608. } //
  18609. function CubicBezierP0(t, p) {
  18610. const k = 1 - t;
  18611. return k * k * k * p;
  18612. }
  18613. function CubicBezierP1(t, p) {
  18614. const k = 1 - t;
  18615. return 3 * k * k * t * p;
  18616. }
  18617. function CubicBezierP2(t, p) {
  18618. return 3 * (1 - t) * t * t * p;
  18619. }
  18620. function CubicBezierP3(t, p) {
  18621. return t * t * t * p;
  18622. }
  18623. function CubicBezier(t, p0, p1, p2, p3) {
  18624. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  18625. }
  18626. class CubicBezierCurve extends Curve {
  18627. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  18628. super();
  18629. this.type = 'CubicBezierCurve';
  18630. this.v0 = v0;
  18631. this.v1 = v1;
  18632. this.v2 = v2;
  18633. this.v3 = v3;
  18634. }
  18635. getPoint(t, optionalTarget = new Vector2()) {
  18636. const point = optionalTarget;
  18637. const v0 = this.v0,
  18638. v1 = this.v1,
  18639. v2 = this.v2,
  18640. v3 = this.v3;
  18641. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  18642. return point;
  18643. }
  18644. copy(source) {
  18645. super.copy(source);
  18646. this.v0.copy(source.v0);
  18647. this.v1.copy(source.v1);
  18648. this.v2.copy(source.v2);
  18649. this.v3.copy(source.v3);
  18650. return this;
  18651. }
  18652. toJSON() {
  18653. const data = super.toJSON();
  18654. data.v0 = this.v0.toArray();
  18655. data.v1 = this.v1.toArray();
  18656. data.v2 = this.v2.toArray();
  18657. data.v3 = this.v3.toArray();
  18658. return data;
  18659. }
  18660. fromJSON(json) {
  18661. super.fromJSON(json);
  18662. this.v0.fromArray(json.v0);
  18663. this.v1.fromArray(json.v1);
  18664. this.v2.fromArray(json.v2);
  18665. this.v3.fromArray(json.v3);
  18666. return this;
  18667. }
  18668. }
  18669. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  18670. class CubicBezierCurve3 extends Curve {
  18671. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  18672. super();
  18673. this.type = 'CubicBezierCurve3';
  18674. this.v0 = v0;
  18675. this.v1 = v1;
  18676. this.v2 = v2;
  18677. this.v3 = v3;
  18678. }
  18679. getPoint(t, optionalTarget = new Vector3()) {
  18680. const point = optionalTarget;
  18681. const v0 = this.v0,
  18682. v1 = this.v1,
  18683. v2 = this.v2,
  18684. v3 = this.v3;
  18685. 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));
  18686. return point;
  18687. }
  18688. copy(source) {
  18689. super.copy(source);
  18690. this.v0.copy(source.v0);
  18691. this.v1.copy(source.v1);
  18692. this.v2.copy(source.v2);
  18693. this.v3.copy(source.v3);
  18694. return this;
  18695. }
  18696. toJSON() {
  18697. const data = super.toJSON();
  18698. data.v0 = this.v0.toArray();
  18699. data.v1 = this.v1.toArray();
  18700. data.v2 = this.v2.toArray();
  18701. data.v3 = this.v3.toArray();
  18702. return data;
  18703. }
  18704. fromJSON(json) {
  18705. super.fromJSON(json);
  18706. this.v0.fromArray(json.v0);
  18707. this.v1.fromArray(json.v1);
  18708. this.v2.fromArray(json.v2);
  18709. this.v3.fromArray(json.v3);
  18710. return this;
  18711. }
  18712. }
  18713. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  18714. class LineCurve extends Curve {
  18715. constructor(v1 = new Vector2(), v2 = new Vector2()) {
  18716. super();
  18717. this.type = 'LineCurve';
  18718. this.v1 = v1;
  18719. this.v2 = v2;
  18720. }
  18721. getPoint(t, optionalTarget = new Vector2()) {
  18722. const point = optionalTarget;
  18723. if (t === 1) {
  18724. point.copy(this.v2);
  18725. } else {
  18726. point.copy(this.v2).sub(this.v1);
  18727. point.multiplyScalar(t).add(this.v1);
  18728. }
  18729. return point;
  18730. } // Line curve is linear, so we can overwrite default getPointAt
  18731. getPointAt(u, optionalTarget) {
  18732. return this.getPoint(u, optionalTarget);
  18733. }
  18734. getTangent(t, optionalTarget) {
  18735. const tangent = optionalTarget || new Vector2();
  18736. tangent.copy(this.v2).sub(this.v1).normalize();
  18737. return tangent;
  18738. }
  18739. copy(source) {
  18740. super.copy(source);
  18741. this.v1.copy(source.v1);
  18742. this.v2.copy(source.v2);
  18743. return this;
  18744. }
  18745. toJSON() {
  18746. const data = super.toJSON();
  18747. data.v1 = this.v1.toArray();
  18748. data.v2 = this.v2.toArray();
  18749. return data;
  18750. }
  18751. fromJSON(json) {
  18752. super.fromJSON(json);
  18753. this.v1.fromArray(json.v1);
  18754. this.v2.fromArray(json.v2);
  18755. return this;
  18756. }
  18757. }
  18758. LineCurve.prototype.isLineCurve = true;
  18759. class LineCurve3 extends Curve {
  18760. constructor(v1 = new Vector3(), v2 = new Vector3()) {
  18761. super();
  18762. this.type = 'LineCurve3';
  18763. this.isLineCurve3 = true;
  18764. this.v1 = v1;
  18765. this.v2 = v2;
  18766. }
  18767. getPoint(t, optionalTarget = new Vector3()) {
  18768. const point = optionalTarget;
  18769. if (t === 1) {
  18770. point.copy(this.v2);
  18771. } else {
  18772. point.copy(this.v2).sub(this.v1);
  18773. point.multiplyScalar(t).add(this.v1);
  18774. }
  18775. return point;
  18776. } // Line curve is linear, so we can overwrite default getPointAt
  18777. getPointAt(u, optionalTarget) {
  18778. return this.getPoint(u, optionalTarget);
  18779. }
  18780. copy(source) {
  18781. super.copy(source);
  18782. this.v1.copy(source.v1);
  18783. this.v2.copy(source.v2);
  18784. return this;
  18785. }
  18786. toJSON() {
  18787. const data = super.toJSON();
  18788. data.v1 = this.v1.toArray();
  18789. data.v2 = this.v2.toArray();
  18790. return data;
  18791. }
  18792. fromJSON(json) {
  18793. super.fromJSON(json);
  18794. this.v1.fromArray(json.v1);
  18795. this.v2.fromArray(json.v2);
  18796. return this;
  18797. }
  18798. }
  18799. class QuadraticBezierCurve extends Curve {
  18800. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  18801. super();
  18802. this.type = 'QuadraticBezierCurve';
  18803. this.v0 = v0;
  18804. this.v1 = v1;
  18805. this.v2 = v2;
  18806. }
  18807. getPoint(t, optionalTarget = new Vector2()) {
  18808. const point = optionalTarget;
  18809. const v0 = this.v0,
  18810. v1 = this.v1,
  18811. v2 = this.v2;
  18812. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  18813. return point;
  18814. }
  18815. copy(source) {
  18816. super.copy(source);
  18817. this.v0.copy(source.v0);
  18818. this.v1.copy(source.v1);
  18819. this.v2.copy(source.v2);
  18820. return this;
  18821. }
  18822. toJSON() {
  18823. const data = super.toJSON();
  18824. data.v0 = this.v0.toArray();
  18825. data.v1 = this.v1.toArray();
  18826. data.v2 = this.v2.toArray();
  18827. return data;
  18828. }
  18829. fromJSON(json) {
  18830. super.fromJSON(json);
  18831. this.v0.fromArray(json.v0);
  18832. this.v1.fromArray(json.v1);
  18833. this.v2.fromArray(json.v2);
  18834. return this;
  18835. }
  18836. }
  18837. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  18838. class QuadraticBezierCurve3 extends Curve {
  18839. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  18840. super();
  18841. this.type = 'QuadraticBezierCurve3';
  18842. this.v0 = v0;
  18843. this.v1 = v1;
  18844. this.v2 = v2;
  18845. }
  18846. getPoint(t, optionalTarget = new Vector3()) {
  18847. const point = optionalTarget;
  18848. const v0 = this.v0,
  18849. v1 = this.v1,
  18850. v2 = this.v2;
  18851. 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));
  18852. return point;
  18853. }
  18854. copy(source) {
  18855. super.copy(source);
  18856. this.v0.copy(source.v0);
  18857. this.v1.copy(source.v1);
  18858. this.v2.copy(source.v2);
  18859. return this;
  18860. }
  18861. toJSON() {
  18862. const data = super.toJSON();
  18863. data.v0 = this.v0.toArray();
  18864. data.v1 = this.v1.toArray();
  18865. data.v2 = this.v2.toArray();
  18866. return data;
  18867. }
  18868. fromJSON(json) {
  18869. super.fromJSON(json);
  18870. this.v0.fromArray(json.v0);
  18871. this.v1.fromArray(json.v1);
  18872. this.v2.fromArray(json.v2);
  18873. return this;
  18874. }
  18875. }
  18876. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  18877. class SplineCurve extends Curve {
  18878. constructor(points = []) {
  18879. super();
  18880. this.type = 'SplineCurve';
  18881. this.points = points;
  18882. }
  18883. getPoint(t, optionalTarget = new Vector2()) {
  18884. const point = optionalTarget;
  18885. const points = this.points;
  18886. const p = (points.length - 1) * t;
  18887. const intPoint = Math.floor(p);
  18888. const weight = p - intPoint;
  18889. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  18890. const p1 = points[intPoint];
  18891. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  18892. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  18893. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  18894. return point;
  18895. }
  18896. copy(source) {
  18897. super.copy(source);
  18898. this.points = [];
  18899. for (let i = 0, l = source.points.length; i < l; i++) {
  18900. const point = source.points[i];
  18901. this.points.push(point.clone());
  18902. }
  18903. return this;
  18904. }
  18905. toJSON() {
  18906. const data = super.toJSON();
  18907. data.points = [];
  18908. for (let i = 0, l = this.points.length; i < l; i++) {
  18909. const point = this.points[i];
  18910. data.points.push(point.toArray());
  18911. }
  18912. return data;
  18913. }
  18914. fromJSON(json) {
  18915. super.fromJSON(json);
  18916. this.points = [];
  18917. for (let i = 0, l = json.points.length; i < l; i++) {
  18918. const point = json.points[i];
  18919. this.points.push(new Vector2().fromArray(point));
  18920. }
  18921. return this;
  18922. }
  18923. }
  18924. SplineCurve.prototype.isSplineCurve = true;
  18925. var Curves = /*#__PURE__*/Object.freeze({
  18926. __proto__: null,
  18927. ArcCurve: ArcCurve,
  18928. CatmullRomCurve3: CatmullRomCurve3,
  18929. CubicBezierCurve: CubicBezierCurve,
  18930. CubicBezierCurve3: CubicBezierCurve3,
  18931. EllipseCurve: EllipseCurve,
  18932. LineCurve: LineCurve,
  18933. LineCurve3: LineCurve3,
  18934. QuadraticBezierCurve: QuadraticBezierCurve,
  18935. QuadraticBezierCurve3: QuadraticBezierCurve3,
  18936. SplineCurve: SplineCurve
  18937. });
  18938. /**************************************************************
  18939. * Curved Path - a curve path is simply a array of connected
  18940. * curves, but retains the api of a curve
  18941. **************************************************************/
  18942. class CurvePath extends Curve {
  18943. constructor() {
  18944. super();
  18945. this.type = 'CurvePath';
  18946. this.curves = [];
  18947. this.autoClose = false; // Automatically closes the path
  18948. }
  18949. add(curve) {
  18950. this.curves.push(curve);
  18951. }
  18952. closePath() {
  18953. // Add a line curve if start and end of lines are not connected
  18954. const startPoint = this.curves[0].getPoint(0);
  18955. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  18956. if (!startPoint.equals(endPoint)) {
  18957. this.curves.push(new LineCurve(endPoint, startPoint));
  18958. }
  18959. } // To get accurate point with reference to
  18960. // entire path distance at time t,
  18961. // following has to be done:
  18962. // 1. Length of each sub path have to be known
  18963. // 2. Locate and identify type of curve
  18964. // 3. Get t for the curve
  18965. // 4. Return curve.getPointAt(t')
  18966. getPoint(t, optionalTarget) {
  18967. const d = t * this.getLength();
  18968. const curveLengths = this.getCurveLengths();
  18969. let i = 0; // To think about boundaries points.
  18970. while (i < curveLengths.length) {
  18971. if (curveLengths[i] >= d) {
  18972. const diff = curveLengths[i] - d;
  18973. const curve = this.curves[i];
  18974. const segmentLength = curve.getLength();
  18975. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  18976. return curve.getPointAt(u, optionalTarget);
  18977. }
  18978. i++;
  18979. }
  18980. return null; // loop where sum != 0, sum > d , sum+1 <d
  18981. } // We cannot use the default THREE.Curve getPoint() with getLength() because in
  18982. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  18983. // getPoint() depends on getLength
  18984. getLength() {
  18985. const lens = this.getCurveLengths();
  18986. return lens[lens.length - 1];
  18987. } // cacheLengths must be recalculated.
  18988. updateArcLengths() {
  18989. this.needsUpdate = true;
  18990. this.cacheLengths = null;
  18991. this.getCurveLengths();
  18992. } // Compute lengths and cache them
  18993. // We cannot overwrite getLengths() because UtoT mapping uses it.
  18994. getCurveLengths() {
  18995. // We use cache values if curves and cache array are same length
  18996. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  18997. return this.cacheLengths;
  18998. } // Get length of sub-curve
  18999. // Push sums into cached array
  19000. const lengths = [];
  19001. let sums = 0;
  19002. for (let i = 0, l = this.curves.length; i < l; i++) {
  19003. sums += this.curves[i].getLength();
  19004. lengths.push(sums);
  19005. }
  19006. this.cacheLengths = lengths;
  19007. return lengths;
  19008. }
  19009. getSpacedPoints(divisions = 40) {
  19010. const points = [];
  19011. for (let i = 0; i <= divisions; i++) {
  19012. points.push(this.getPoint(i / divisions));
  19013. }
  19014. if (this.autoClose) {
  19015. points.push(points[0]);
  19016. }
  19017. return points;
  19018. }
  19019. getPoints(divisions = 12) {
  19020. const points = [];
  19021. let last;
  19022. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  19023. const curve = curves[i];
  19024. const resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  19025. const pts = curve.getPoints(resolution);
  19026. for (let j = 0; j < pts.length; j++) {
  19027. const point = pts[j];
  19028. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  19029. points.push(point);
  19030. last = point;
  19031. }
  19032. }
  19033. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  19034. points.push(points[0]);
  19035. }
  19036. return points;
  19037. }
  19038. copy(source) {
  19039. super.copy(source);
  19040. this.curves = [];
  19041. for (let i = 0, l = source.curves.length; i < l; i++) {
  19042. const curve = source.curves[i];
  19043. this.curves.push(curve.clone());
  19044. }
  19045. this.autoClose = source.autoClose;
  19046. return this;
  19047. }
  19048. toJSON() {
  19049. const data = super.toJSON();
  19050. data.autoClose = this.autoClose;
  19051. data.curves = [];
  19052. for (let i = 0, l = this.curves.length; i < l; i++) {
  19053. const curve = this.curves[i];
  19054. data.curves.push(curve.toJSON());
  19055. }
  19056. return data;
  19057. }
  19058. fromJSON(json) {
  19059. super.fromJSON(json);
  19060. this.autoClose = json.autoClose;
  19061. this.curves = [];
  19062. for (let i = 0, l = json.curves.length; i < l; i++) {
  19063. const curve = json.curves[i];
  19064. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  19065. }
  19066. return this;
  19067. }
  19068. }
  19069. class Path extends CurvePath {
  19070. constructor(points) {
  19071. super();
  19072. this.type = 'Path';
  19073. this.currentPoint = new Vector2();
  19074. if (points) {
  19075. this.setFromPoints(points);
  19076. }
  19077. }
  19078. setFromPoints(points) {
  19079. this.moveTo(points[0].x, points[0].y);
  19080. for (let i = 1, l = points.length; i < l; i++) {
  19081. this.lineTo(points[i].x, points[i].y);
  19082. }
  19083. return this;
  19084. }
  19085. moveTo(x, y) {
  19086. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  19087. return this;
  19088. }
  19089. lineTo(x, y) {
  19090. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  19091. this.curves.push(curve);
  19092. this.currentPoint.set(x, y);
  19093. return this;
  19094. }
  19095. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  19096. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  19097. this.curves.push(curve);
  19098. this.currentPoint.set(aX, aY);
  19099. return this;
  19100. }
  19101. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  19102. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  19103. this.curves.push(curve);
  19104. this.currentPoint.set(aX, aY);
  19105. return this;
  19106. }
  19107. splineThru(pts
  19108. /*Array of Vector*/
  19109. ) {
  19110. const npts = [this.currentPoint.clone()].concat(pts);
  19111. const curve = new SplineCurve(npts);
  19112. this.curves.push(curve);
  19113. this.currentPoint.copy(pts[pts.length - 1]);
  19114. return this;
  19115. }
  19116. arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  19117. const x0 = this.currentPoint.x;
  19118. const y0 = this.currentPoint.y;
  19119. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  19120. return this;
  19121. }
  19122. absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  19123. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  19124. return this;
  19125. }
  19126. ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  19127. const x0 = this.currentPoint.x;
  19128. const y0 = this.currentPoint.y;
  19129. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  19130. return this;
  19131. }
  19132. absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  19133. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  19134. if (this.curves.length > 0) {
  19135. // if a previous curve is present, attempt to join
  19136. const firstPoint = curve.getPoint(0);
  19137. if (!firstPoint.equals(this.currentPoint)) {
  19138. this.lineTo(firstPoint.x, firstPoint.y);
  19139. }
  19140. }
  19141. this.curves.push(curve);
  19142. const lastPoint = curve.getPoint(1);
  19143. this.currentPoint.copy(lastPoint);
  19144. return this;
  19145. }
  19146. copy(source) {
  19147. super.copy(source);
  19148. this.currentPoint.copy(source.currentPoint);
  19149. return this;
  19150. }
  19151. toJSON() {
  19152. const data = super.toJSON();
  19153. data.currentPoint = this.currentPoint.toArray();
  19154. return data;
  19155. }
  19156. fromJSON(json) {
  19157. super.fromJSON(json);
  19158. this.currentPoint.fromArray(json.currentPoint);
  19159. return this;
  19160. }
  19161. }
  19162. class Shape extends Path {
  19163. constructor(points) {
  19164. super(points);
  19165. this.uuid = generateUUID();
  19166. this.type = 'Shape';
  19167. this.holes = [];
  19168. }
  19169. getPointsHoles(divisions) {
  19170. const holesPts = [];
  19171. for (let i = 0, l = this.holes.length; i < l; i++) {
  19172. holesPts[i] = this.holes[i].getPoints(divisions);
  19173. }
  19174. return holesPts;
  19175. } // get points of shape and holes (keypoints based on segments parameter)
  19176. extractPoints(divisions) {
  19177. return {
  19178. shape: this.getPoints(divisions),
  19179. holes: this.getPointsHoles(divisions)
  19180. };
  19181. }
  19182. copy(source) {
  19183. super.copy(source);
  19184. this.holes = [];
  19185. for (let i = 0, l = source.holes.length; i < l; i++) {
  19186. const hole = source.holes[i];
  19187. this.holes.push(hole.clone());
  19188. }
  19189. return this;
  19190. }
  19191. toJSON() {
  19192. const data = super.toJSON();
  19193. data.uuid = this.uuid;
  19194. data.holes = [];
  19195. for (let i = 0, l = this.holes.length; i < l; i++) {
  19196. const hole = this.holes[i];
  19197. data.holes.push(hole.toJSON());
  19198. }
  19199. return data;
  19200. }
  19201. fromJSON(json) {
  19202. super.fromJSON(json);
  19203. this.uuid = json.uuid;
  19204. this.holes = [];
  19205. for (let i = 0, l = json.holes.length; i < l; i++) {
  19206. const hole = json.holes[i];
  19207. this.holes.push(new Path().fromJSON(hole));
  19208. }
  19209. return this;
  19210. }
  19211. }
  19212. /**
  19213. * Port from https://github.com/mapbox/earcut (v2.2.2)
  19214. */
  19215. const Earcut = {
  19216. triangulate: function (data, holeIndices, dim = 2) {
  19217. const hasHoles = holeIndices && holeIndices.length;
  19218. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  19219. let outerNode = linkedList(data, 0, outerLen, dim, true);
  19220. const triangles = [];
  19221. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  19222. let minX, minY, maxX, maxY, x, y, invSize;
  19223. 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
  19224. if (data.length > 80 * dim) {
  19225. minX = maxX = data[0];
  19226. minY = maxY = data[1];
  19227. for (let i = dim; i < outerLen; i += dim) {
  19228. x = data[i];
  19229. y = data[i + 1];
  19230. if (x < minX) minX = x;
  19231. if (y < minY) minY = y;
  19232. if (x > maxX) maxX = x;
  19233. if (y > maxY) maxY = y;
  19234. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  19235. invSize = Math.max(maxX - minX, maxY - minY);
  19236. invSize = invSize !== 0 ? 1 / invSize : 0;
  19237. }
  19238. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  19239. return triangles;
  19240. }
  19241. }; // create a circular doubly linked list from polygon points in the specified winding order
  19242. function linkedList(data, start, end, dim, clockwise) {
  19243. let i, last;
  19244. if (clockwise === signedArea(data, start, end, dim) > 0) {
  19245. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  19246. } else {
  19247. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  19248. }
  19249. if (last && equals(last, last.next)) {
  19250. removeNode(last);
  19251. last = last.next;
  19252. }
  19253. return last;
  19254. } // eliminate colinear or duplicate points
  19255. function filterPoints(start, end) {
  19256. if (!start) return start;
  19257. if (!end) end = start;
  19258. let p = start,
  19259. again;
  19260. do {
  19261. again = false;
  19262. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  19263. removeNode(p);
  19264. p = end = p.prev;
  19265. if (p === p.next) break;
  19266. again = true;
  19267. } else {
  19268. p = p.next;
  19269. }
  19270. } while (again || p !== end);
  19271. return end;
  19272. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  19273. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  19274. if (!ear) return; // interlink polygon nodes in z-order
  19275. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  19276. let stop = ear,
  19277. prev,
  19278. next; // iterate through ears, slicing them one by one
  19279. while (ear.prev !== ear.next) {
  19280. prev = ear.prev;
  19281. next = ear.next;
  19282. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  19283. // cut off the triangle
  19284. triangles.push(prev.i / dim);
  19285. triangles.push(ear.i / dim);
  19286. triangles.push(next.i / dim);
  19287. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  19288. ear = next.next;
  19289. stop = next.next;
  19290. continue;
  19291. }
  19292. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  19293. if (ear === stop) {
  19294. // try filtering points and slicing again
  19295. if (!pass) {
  19296. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  19297. } else if (pass === 1) {
  19298. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  19299. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  19300. } else if (pass === 2) {
  19301. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  19302. }
  19303. break;
  19304. }
  19305. }
  19306. } // check whether a polygon node forms a valid ear with adjacent nodes
  19307. function isEar(ear) {
  19308. const a = ear.prev,
  19309. b = ear,
  19310. c = ear.next;
  19311. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  19312. // now make sure we don't have other points inside the potential ear
  19313. let p = ear.next.next;
  19314. while (p !== ear.prev) {
  19315. 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;
  19316. p = p.next;
  19317. }
  19318. return true;
  19319. }
  19320. function isEarHashed(ear, minX, minY, invSize) {
  19321. const a = ear.prev,
  19322. b = ear,
  19323. c = ear.next;
  19324. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  19325. // triangle bbox; min & max are calculated like this for speed
  19326. const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  19327. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  19328. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  19329. 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;
  19330. const minZ = zOrder(minTX, minTY, minX, minY, invSize),
  19331. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  19332. let p = ear.prevZ,
  19333. n = ear.nextZ; // look for points inside the triangle in both directions
  19334. while (p && p.z >= minZ && n && n.z <= maxZ) {
  19335. 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;
  19336. p = p.prevZ;
  19337. 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;
  19338. n = n.nextZ;
  19339. } // look for remaining points in decreasing z-order
  19340. while (p && p.z >= minZ) {
  19341. 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;
  19342. p = p.prevZ;
  19343. } // look for remaining points in increasing z-order
  19344. while (n && n.z <= maxZ) {
  19345. 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;
  19346. n = n.nextZ;
  19347. }
  19348. return true;
  19349. } // go through all polygon nodes and cure small local self-intersections
  19350. function cureLocalIntersections(start, triangles, dim) {
  19351. let p = start;
  19352. do {
  19353. const a = p.prev,
  19354. b = p.next.next;
  19355. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  19356. triangles.push(a.i / dim);
  19357. triangles.push(p.i / dim);
  19358. triangles.push(b.i / dim); // remove two nodes involved
  19359. removeNode(p);
  19360. removeNode(p.next);
  19361. p = start = b;
  19362. }
  19363. p = p.next;
  19364. } while (p !== start);
  19365. return filterPoints(p);
  19366. } // try splitting polygon into two and triangulate them independently
  19367. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  19368. // look for a valid diagonal that divides the polygon into two
  19369. let a = start;
  19370. do {
  19371. let b = a.next.next;
  19372. while (b !== a.prev) {
  19373. if (a.i !== b.i && isValidDiagonal(a, b)) {
  19374. // split the polygon in two by the diagonal
  19375. let c = splitPolygon(a, b); // filter colinear points around the cuts
  19376. a = filterPoints(a, a.next);
  19377. c = filterPoints(c, c.next); // run earcut on each half
  19378. earcutLinked(a, triangles, dim, minX, minY, invSize);
  19379. earcutLinked(c, triangles, dim, minX, minY, invSize);
  19380. return;
  19381. }
  19382. b = b.next;
  19383. }
  19384. a = a.next;
  19385. } while (a !== start);
  19386. } // link every hole into the outer loop, producing a single-ring polygon without holes
  19387. function eliminateHoles(data, holeIndices, outerNode, dim) {
  19388. const queue = [];
  19389. let i, len, start, end, list;
  19390. for (i = 0, len = holeIndices.length; i < len; i++) {
  19391. start = holeIndices[i] * dim;
  19392. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  19393. list = linkedList(data, start, end, dim, false);
  19394. if (list === list.next) list.steiner = true;
  19395. queue.push(getLeftmost(list));
  19396. }
  19397. queue.sort(compareX); // process holes from left to right
  19398. for (i = 0; i < queue.length; i++) {
  19399. eliminateHole(queue[i], outerNode);
  19400. outerNode = filterPoints(outerNode, outerNode.next);
  19401. }
  19402. return outerNode;
  19403. }
  19404. function compareX(a, b) {
  19405. return a.x - b.x;
  19406. } // find a bridge between vertices that connects hole with an outer ring and and link it
  19407. function eliminateHole(hole, outerNode) {
  19408. outerNode = findHoleBridge(hole, outerNode);
  19409. if (outerNode) {
  19410. const b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  19411. filterPoints(outerNode, outerNode.next);
  19412. filterPoints(b, b.next);
  19413. }
  19414. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  19415. function findHoleBridge(hole, outerNode) {
  19416. let p = outerNode;
  19417. const hx = hole.x;
  19418. const hy = hole.y;
  19419. let qx = -Infinity,
  19420. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  19421. // segment's endpoint with lesser x will be potential connection point
  19422. do {
  19423. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  19424. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  19425. if (x <= hx && x > qx) {
  19426. qx = x;
  19427. if (x === hx) {
  19428. if (hy === p.y) return p;
  19429. if (hy === p.next.y) return p.next;
  19430. }
  19431. m = p.x < p.next.x ? p : p.next;
  19432. }
  19433. }
  19434. p = p.next;
  19435. } while (p !== outerNode);
  19436. if (!m) return null;
  19437. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  19438. // look for points inside the triangle of hole point, segment intersection and endpoint;
  19439. // if there are no points found, we have a valid connection;
  19440. // otherwise choose the point of the minimum angle with the ray as connection point
  19441. const stop = m,
  19442. mx = m.x,
  19443. my = m.y;
  19444. let tanMin = Infinity,
  19445. tan;
  19446. p = m;
  19447. do {
  19448. 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)) {
  19449. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  19450. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  19451. m = p;
  19452. tanMin = tan;
  19453. }
  19454. }
  19455. p = p.next;
  19456. } while (p !== stop);
  19457. return m;
  19458. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  19459. function sectorContainsSector(m, p) {
  19460. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  19461. } // interlink polygon nodes in z-order
  19462. function indexCurve(start, minX, minY, invSize) {
  19463. let p = start;
  19464. do {
  19465. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  19466. p.prevZ = p.prev;
  19467. p.nextZ = p.next;
  19468. p = p.next;
  19469. } while (p !== start);
  19470. p.prevZ.nextZ = null;
  19471. p.prevZ = null;
  19472. sortLinked(p);
  19473. } // Simon Tatham's linked list merge sort algorithm
  19474. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  19475. function sortLinked(list) {
  19476. let i,
  19477. p,
  19478. q,
  19479. e,
  19480. tail,
  19481. numMerges,
  19482. pSize,
  19483. qSize,
  19484. inSize = 1;
  19485. do {
  19486. p = list;
  19487. list = null;
  19488. tail = null;
  19489. numMerges = 0;
  19490. while (p) {
  19491. numMerges++;
  19492. q = p;
  19493. pSize = 0;
  19494. for (i = 0; i < inSize; i++) {
  19495. pSize++;
  19496. q = q.nextZ;
  19497. if (!q) break;
  19498. }
  19499. qSize = inSize;
  19500. while (pSize > 0 || qSize > 0 && q) {
  19501. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  19502. e = p;
  19503. p = p.nextZ;
  19504. pSize--;
  19505. } else {
  19506. e = q;
  19507. q = q.nextZ;
  19508. qSize--;
  19509. }
  19510. if (tail) tail.nextZ = e;else list = e;
  19511. e.prevZ = tail;
  19512. tail = e;
  19513. }
  19514. p = q;
  19515. }
  19516. tail.nextZ = null;
  19517. inSize *= 2;
  19518. } while (numMerges > 1);
  19519. return list;
  19520. } // z-order of a point given coords and inverse of the longer side of data bbox
  19521. function zOrder(x, y, minX, minY, invSize) {
  19522. // coords are transformed into non-negative 15-bit integer range
  19523. x = 32767 * (x - minX) * invSize;
  19524. y = 32767 * (y - minY) * invSize;
  19525. x = (x | x << 8) & 0x00FF00FF;
  19526. x = (x | x << 4) & 0x0F0F0F0F;
  19527. x = (x | x << 2) & 0x33333333;
  19528. x = (x | x << 1) & 0x55555555;
  19529. y = (y | y << 8) & 0x00FF00FF;
  19530. y = (y | y << 4) & 0x0F0F0F0F;
  19531. y = (y | y << 2) & 0x33333333;
  19532. y = (y | y << 1) & 0x55555555;
  19533. return x | y << 1;
  19534. } // find the leftmost node of a polygon ring
  19535. function getLeftmost(start) {
  19536. let p = start,
  19537. leftmost = start;
  19538. do {
  19539. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  19540. p = p.next;
  19541. } while (p !== start);
  19542. return leftmost;
  19543. } // check if a point lies within a convex triangle
  19544. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  19545. 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;
  19546. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  19547. function isValidDiagonal(a, b) {
  19548. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  19549. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  19550. } // signed area of a triangle
  19551. function area(p, q, r) {
  19552. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  19553. } // check if two points are equal
  19554. function equals(p1, p2) {
  19555. return p1.x === p2.x && p1.y === p2.y;
  19556. } // check if two segments intersect
  19557. function intersects(p1, q1, p2, q2) {
  19558. const o1 = sign(area(p1, q1, p2));
  19559. const o2 = sign(area(p1, q1, q2));
  19560. const o3 = sign(area(p2, q2, p1));
  19561. const o4 = sign(area(p2, q2, q1));
  19562. if (o1 !== o2 && o3 !== o4) return true; // general case
  19563. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  19564. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  19565. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  19566. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  19567. return false;
  19568. } // for collinear points p, q, r, check if point q lies on segment pr
  19569. function onSegment(p, q, r) {
  19570. 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);
  19571. }
  19572. function sign(num) {
  19573. return num > 0 ? 1 : num < 0 ? -1 : 0;
  19574. } // check if a polygon diagonal intersects any polygon segments
  19575. function intersectsPolygon(a, b) {
  19576. let p = a;
  19577. do {
  19578. 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;
  19579. p = p.next;
  19580. } while (p !== a);
  19581. return false;
  19582. } // check if a polygon diagonal is locally inside the polygon
  19583. function locallyInside(a, b) {
  19584. 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;
  19585. } // check if the middle point of a polygon diagonal is inside the polygon
  19586. function middleInside(a, b) {
  19587. let p = a,
  19588. inside = false;
  19589. const px = (a.x + b.x) / 2,
  19590. py = (a.y + b.y) / 2;
  19591. do {
  19592. 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;
  19593. p = p.next;
  19594. } while (p !== a);
  19595. return inside;
  19596. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  19597. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  19598. function splitPolygon(a, b) {
  19599. const a2 = new Node(a.i, a.x, a.y),
  19600. b2 = new Node(b.i, b.x, b.y),
  19601. an = a.next,
  19602. bp = b.prev;
  19603. a.next = b;
  19604. b.prev = a;
  19605. a2.next = an;
  19606. an.prev = a2;
  19607. b2.next = a2;
  19608. a2.prev = b2;
  19609. bp.next = b2;
  19610. b2.prev = bp;
  19611. return b2;
  19612. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  19613. function insertNode(i, x, y, last) {
  19614. const p = new Node(i, x, y);
  19615. if (!last) {
  19616. p.prev = p;
  19617. p.next = p;
  19618. } else {
  19619. p.next = last.next;
  19620. p.prev = last;
  19621. last.next.prev = p;
  19622. last.next = p;
  19623. }
  19624. return p;
  19625. }
  19626. function removeNode(p) {
  19627. p.next.prev = p.prev;
  19628. p.prev.next = p.next;
  19629. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  19630. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  19631. }
  19632. function Node(i, x, y) {
  19633. // vertex index in coordinates array
  19634. this.i = i; // vertex coordinates
  19635. this.x = x;
  19636. this.y = y; // previous and next vertex nodes in a polygon ring
  19637. this.prev = null;
  19638. this.next = null; // z-order curve value
  19639. this.z = null; // previous and next nodes in z-order
  19640. this.prevZ = null;
  19641. this.nextZ = null; // indicates whether this is a steiner point
  19642. this.steiner = false;
  19643. }
  19644. function signedArea(data, start, end, dim) {
  19645. let sum = 0;
  19646. for (let i = start, j = end - dim; i < end; i += dim) {
  19647. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  19648. j = i;
  19649. }
  19650. return sum;
  19651. }
  19652. class ShapeUtils {
  19653. // calculate area of the contour polygon
  19654. static area(contour) {
  19655. const n = contour.length;
  19656. let a = 0.0;
  19657. for (let p = n - 1, q = 0; q < n; p = q++) {
  19658. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  19659. }
  19660. return a * 0.5;
  19661. }
  19662. static isClockWise(pts) {
  19663. return ShapeUtils.area(pts) < 0;
  19664. }
  19665. static triangulateShape(contour, holes) {
  19666. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  19667. const holeIndices = []; // array of hole indices
  19668. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  19669. removeDupEndPts(contour);
  19670. addContour(vertices, contour); //
  19671. let holeIndex = contour.length;
  19672. holes.forEach(removeDupEndPts);
  19673. for (let i = 0; i < holes.length; i++) {
  19674. holeIndices.push(holeIndex);
  19675. holeIndex += holes[i].length;
  19676. addContour(vertices, holes[i]);
  19677. } //
  19678. const triangles = Earcut.triangulate(vertices, holeIndices); //
  19679. for (let i = 0; i < triangles.length; i += 3) {
  19680. faces.push(triangles.slice(i, i + 3));
  19681. }
  19682. return faces;
  19683. }
  19684. }
  19685. function removeDupEndPts(points) {
  19686. const l = points.length;
  19687. if (l > 2 && points[l - 1].equals(points[0])) {
  19688. points.pop();
  19689. }
  19690. }
  19691. function addContour(vertices, contour) {
  19692. for (let i = 0; i < contour.length; i++) {
  19693. vertices.push(contour[i].x);
  19694. vertices.push(contour[i].y);
  19695. }
  19696. }
  19697. /**
  19698. * Creates extruded geometry from a path shape.
  19699. *
  19700. * parameters = {
  19701. *
  19702. * curveSegments: <int>, // number of points on the curves
  19703. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19704. * depth: <float>, // Depth to extrude the shape
  19705. *
  19706. * bevelEnabled: <bool>, // turn on bevel
  19707. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19708. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  19709. * bevelOffset: <float>, // how far from shape outline does bevel start
  19710. * bevelSegments: <int>, // number of bevel layers
  19711. *
  19712. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19713. *
  19714. * UVGenerator: <Object> // object that provides UV generator functions
  19715. *
  19716. * }
  19717. */
  19718. class ExtrudeGeometry extends BufferGeometry {
  19719. constructor(shapes = new Shape([new Vector2(0.5, 0.5), new Vector2(-0.5, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), options = {}) {
  19720. super();
  19721. this.type = 'ExtrudeGeometry';
  19722. this.parameters = {
  19723. shapes: shapes,
  19724. options: options
  19725. };
  19726. shapes = Array.isArray(shapes) ? shapes : [shapes];
  19727. const scope = this;
  19728. const verticesArray = [];
  19729. const uvArray = [];
  19730. for (let i = 0, l = shapes.length; i < l; i++) {
  19731. const shape = shapes[i];
  19732. addShape(shape);
  19733. } // build geometry
  19734. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  19735. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  19736. this.computeVertexNormals(); // functions
  19737. function addShape(shape) {
  19738. const placeholder = []; // options
  19739. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19740. const steps = options.steps !== undefined ? options.steps : 1;
  19741. let depth = options.depth !== undefined ? options.depth : 1;
  19742. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  19743. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  19744. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  19745. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  19746. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19747. const extrudePath = options.extrudePath;
  19748. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  19749. if (options.amount !== undefined) {
  19750. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  19751. depth = options.amount;
  19752. } //
  19753. let extrudePts,
  19754. extrudeByPath = false;
  19755. let splineTube, binormal, normal, position2;
  19756. if (extrudePath) {
  19757. extrudePts = extrudePath.getSpacedPoints(steps);
  19758. extrudeByPath = true;
  19759. bevelEnabled = false; // bevels not supported for path extrusion
  19760. // SETUP TNB variables
  19761. // TODO1 - have a .isClosed in spline?
  19762. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19763. binormal = new Vector3();
  19764. normal = new Vector3();
  19765. position2 = new Vector3();
  19766. } // Safeguards if bevels are not enabled
  19767. if (!bevelEnabled) {
  19768. bevelSegments = 0;
  19769. bevelThickness = 0;
  19770. bevelSize = 0;
  19771. bevelOffset = 0;
  19772. } // Variables initialization
  19773. const shapePoints = shape.extractPoints(curveSegments);
  19774. let vertices = shapePoints.shape;
  19775. const holes = shapePoints.holes;
  19776. const reverse = !ShapeUtils.isClockWise(vertices);
  19777. if (reverse) {
  19778. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19779. for (let h = 0, hl = holes.length; h < hl; h++) {
  19780. const ahole = holes[h];
  19781. if (ShapeUtils.isClockWise(ahole)) {
  19782. holes[h] = ahole.reverse();
  19783. }
  19784. }
  19785. }
  19786. const faces = ShapeUtils.triangulateShape(vertices, holes);
  19787. /* Vertices */
  19788. const contour = vertices; // vertices has all points but contour has only points of circumference
  19789. for (let h = 0, hl = holes.length; h < hl; h++) {
  19790. const ahole = holes[h];
  19791. vertices = vertices.concat(ahole);
  19792. }
  19793. function scalePt2(pt, vec, size) {
  19794. if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
  19795. return vec.clone().multiplyScalar(size).add(pt);
  19796. }
  19797. const vlen = vertices.length,
  19798. flen = faces.length; // Find directions for point movement
  19799. function getBevelVec(inPt, inPrev, inNext) {
  19800. // computes for inPt the corresponding point inPt' on a new contour
  19801. // shifted by 1 unit (length of normalized vector) to the left
  19802. // if we walk along contour clockwise, this new contour is outside the old one
  19803. //
  19804. // inPt' is the intersection of the two lines parallel to the two
  19805. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19806. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  19807. // good reading for geometry algorithms (here: line-line intersection)
  19808. // http://geomalgorithms.com/a05-_intersect-1.html
  19809. const v_prev_x = inPt.x - inPrev.x,
  19810. v_prev_y = inPt.y - inPrev.y;
  19811. const v_next_x = inNext.x - inPt.x,
  19812. v_next_y = inNext.y - inPt.y;
  19813. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  19814. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  19815. if (Math.abs(collinear0) > Number.EPSILON) {
  19816. // not collinear
  19817. // length of vectors for normalizing
  19818. const v_prev_len = Math.sqrt(v_prev_lensq);
  19819. 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
  19820. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  19821. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  19822. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  19823. const ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  19824. 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
  19825. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  19826. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  19827. // but prevent crazy spikes
  19828. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  19829. if (v_trans_lensq <= 2) {
  19830. return new Vector2(v_trans_x, v_trans_y);
  19831. } else {
  19832. shrink_by = Math.sqrt(v_trans_lensq / 2);
  19833. }
  19834. } else {
  19835. // handle special case of collinear edges
  19836. let direction_eq = false; // assumes: opposite
  19837. if (v_prev_x > Number.EPSILON) {
  19838. if (v_next_x > Number.EPSILON) {
  19839. direction_eq = true;
  19840. }
  19841. } else {
  19842. if (v_prev_x < -Number.EPSILON) {
  19843. if (v_next_x < -Number.EPSILON) {
  19844. direction_eq = true;
  19845. }
  19846. } else {
  19847. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  19848. direction_eq = true;
  19849. }
  19850. }
  19851. }
  19852. if (direction_eq) {
  19853. // console.log("Warning: lines are a straight sequence");
  19854. v_trans_x = -v_prev_y;
  19855. v_trans_y = v_prev_x;
  19856. shrink_by = Math.sqrt(v_prev_lensq);
  19857. } else {
  19858. // console.log("Warning: lines are a straight spike");
  19859. v_trans_x = v_prev_x;
  19860. v_trans_y = v_prev_y;
  19861. shrink_by = Math.sqrt(v_prev_lensq / 2);
  19862. }
  19863. }
  19864. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  19865. }
  19866. const contourMovements = [];
  19867. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  19868. if (j === il) j = 0;
  19869. if (k === il) k = 0; // (j)---(i)---(k)
  19870. // console.log('i,j,k', i, j , k)
  19871. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  19872. }
  19873. const holesMovements = [];
  19874. let oneHoleMovements,
  19875. verticesMovements = contourMovements.concat();
  19876. for (let h = 0, hl = holes.length; h < hl; h++) {
  19877. const ahole = holes[h];
  19878. oneHoleMovements = [];
  19879. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  19880. if (j === il) j = 0;
  19881. if (k === il) k = 0; // (j)---(i)---(k)
  19882. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  19883. }
  19884. holesMovements.push(oneHoleMovements);
  19885. verticesMovements = verticesMovements.concat(oneHoleMovements);
  19886. } // Loop bevelSegments, 1 for the front, 1 for the back
  19887. for (let b = 0; b < bevelSegments; b++) {
  19888. //for ( b = bevelSegments; b > 0; b -- ) {
  19889. const t = b / bevelSegments;
  19890. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  19891. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  19892. for (let i = 0, il = contour.length; i < il; i++) {
  19893. const vert = scalePt2(contour[i], contourMovements[i], bs);
  19894. v(vert.x, vert.y, -z);
  19895. } // expand holes
  19896. for (let h = 0, hl = holes.length; h < hl; h++) {
  19897. const ahole = holes[h];
  19898. oneHoleMovements = holesMovements[h];
  19899. for (let i = 0, il = ahole.length; i < il; i++) {
  19900. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  19901. v(vert.x, vert.y, -z);
  19902. }
  19903. }
  19904. }
  19905. const bs = bevelSize + bevelOffset; // Back facing vertices
  19906. for (let i = 0; i < vlen; i++) {
  19907. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  19908. if (!extrudeByPath) {
  19909. v(vert.x, vert.y, 0);
  19910. } else {
  19911. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19912. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  19913. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  19914. position2.copy(extrudePts[0]).add(normal).add(binormal);
  19915. v(position2.x, position2.y, position2.z);
  19916. }
  19917. } // Add stepped vertices...
  19918. // Including front facing vertices
  19919. for (let s = 1; s <= steps; s++) {
  19920. for (let i = 0; i < vlen; i++) {
  19921. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  19922. if (!extrudeByPath) {
  19923. v(vert.x, vert.y, depth / steps * s);
  19924. } else {
  19925. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19926. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  19927. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  19928. position2.copy(extrudePts[s]).add(normal).add(binormal);
  19929. v(position2.x, position2.y, position2.z);
  19930. }
  19931. }
  19932. } // Add bevel segments planes
  19933. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19934. for (let b = bevelSegments - 1; b >= 0; b--) {
  19935. const t = b / bevelSegments;
  19936. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  19937. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  19938. for (let i = 0, il = contour.length; i < il; i++) {
  19939. const vert = scalePt2(contour[i], contourMovements[i], bs);
  19940. v(vert.x, vert.y, depth + z);
  19941. } // expand holes
  19942. for (let h = 0, hl = holes.length; h < hl; h++) {
  19943. const ahole = holes[h];
  19944. oneHoleMovements = holesMovements[h];
  19945. for (let i = 0, il = ahole.length; i < il; i++) {
  19946. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  19947. if (!extrudeByPath) {
  19948. v(vert.x, vert.y, depth + z);
  19949. } else {
  19950. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  19951. }
  19952. }
  19953. }
  19954. }
  19955. /* Faces */
  19956. // Top and bottom faces
  19957. buildLidFaces(); // Sides faces
  19958. buildSideFaces(); ///// Internal functions
  19959. function buildLidFaces() {
  19960. const start = verticesArray.length / 3;
  19961. if (bevelEnabled) {
  19962. let layer = 0; // steps + 1
  19963. let offset = vlen * layer; // Bottom faces
  19964. for (let i = 0; i < flen; i++) {
  19965. const face = faces[i];
  19966. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  19967. }
  19968. layer = steps + bevelSegments * 2;
  19969. offset = vlen * layer; // Top faces
  19970. for (let i = 0; i < flen; i++) {
  19971. const face = faces[i];
  19972. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  19973. }
  19974. } else {
  19975. // Bottom faces
  19976. for (let i = 0; i < flen; i++) {
  19977. const face = faces[i];
  19978. f3(face[2], face[1], face[0]);
  19979. } // Top faces
  19980. for (let i = 0; i < flen; i++) {
  19981. const face = faces[i];
  19982. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  19983. }
  19984. }
  19985. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  19986. } // Create faces for the z-sides of the shape
  19987. function buildSideFaces() {
  19988. const start = verticesArray.length / 3;
  19989. let layeroffset = 0;
  19990. sidewalls(contour, layeroffset);
  19991. layeroffset += contour.length;
  19992. for (let h = 0, hl = holes.length; h < hl; h++) {
  19993. const ahole = holes[h];
  19994. sidewalls(ahole, layeroffset); //, true
  19995. layeroffset += ahole.length;
  19996. }
  19997. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  19998. }
  19999. function sidewalls(contour, layeroffset) {
  20000. let i = contour.length;
  20001. while (--i >= 0) {
  20002. const j = i;
  20003. let k = i - 1;
  20004. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  20005. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  20006. const slen1 = vlen * s;
  20007. const slen2 = vlen * (s + 1);
  20008. const a = layeroffset + j + slen1,
  20009. b = layeroffset + k + slen1,
  20010. c = layeroffset + k + slen2,
  20011. d = layeroffset + j + slen2;
  20012. f4(a, b, c, d);
  20013. }
  20014. }
  20015. }
  20016. function v(x, y, z) {
  20017. placeholder.push(x);
  20018. placeholder.push(y);
  20019. placeholder.push(z);
  20020. }
  20021. function f3(a, b, c) {
  20022. addVertex(a);
  20023. addVertex(b);
  20024. addVertex(c);
  20025. const nextIndex = verticesArray.length / 3;
  20026. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  20027. addUV(uvs[0]);
  20028. addUV(uvs[1]);
  20029. addUV(uvs[2]);
  20030. }
  20031. function f4(a, b, c, d) {
  20032. addVertex(a);
  20033. addVertex(b);
  20034. addVertex(d);
  20035. addVertex(b);
  20036. addVertex(c);
  20037. addVertex(d);
  20038. const nextIndex = verticesArray.length / 3;
  20039. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  20040. addUV(uvs[0]);
  20041. addUV(uvs[1]);
  20042. addUV(uvs[3]);
  20043. addUV(uvs[1]);
  20044. addUV(uvs[2]);
  20045. addUV(uvs[3]);
  20046. }
  20047. function addVertex(index) {
  20048. verticesArray.push(placeholder[index * 3 + 0]);
  20049. verticesArray.push(placeholder[index * 3 + 1]);
  20050. verticesArray.push(placeholder[index * 3 + 2]);
  20051. }
  20052. function addUV(vector2) {
  20053. uvArray.push(vector2.x);
  20054. uvArray.push(vector2.y);
  20055. }
  20056. }
  20057. }
  20058. toJSON() {
  20059. const data = super.toJSON();
  20060. const shapes = this.parameters.shapes;
  20061. const options = this.parameters.options;
  20062. return toJSON$1(shapes, options, data);
  20063. }
  20064. static fromJSON(data, shapes) {
  20065. const geometryShapes = [];
  20066. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  20067. const shape = shapes[data.shapes[j]];
  20068. geometryShapes.push(shape);
  20069. }
  20070. const extrudePath = data.options.extrudePath;
  20071. if (extrudePath !== undefined) {
  20072. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  20073. }
  20074. return new ExtrudeGeometry(geometryShapes, data.options);
  20075. }
  20076. }
  20077. const WorldUVGenerator = {
  20078. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  20079. const a_x = vertices[indexA * 3];
  20080. const a_y = vertices[indexA * 3 + 1];
  20081. const b_x = vertices[indexB * 3];
  20082. const b_y = vertices[indexB * 3 + 1];
  20083. const c_x = vertices[indexC * 3];
  20084. const c_y = vertices[indexC * 3 + 1];
  20085. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  20086. },
  20087. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  20088. const a_x = vertices[indexA * 3];
  20089. const a_y = vertices[indexA * 3 + 1];
  20090. const a_z = vertices[indexA * 3 + 2];
  20091. const b_x = vertices[indexB * 3];
  20092. const b_y = vertices[indexB * 3 + 1];
  20093. const b_z = vertices[indexB * 3 + 2];
  20094. const c_x = vertices[indexC * 3];
  20095. const c_y = vertices[indexC * 3 + 1];
  20096. const c_z = vertices[indexC * 3 + 2];
  20097. const d_x = vertices[indexD * 3];
  20098. const d_y = vertices[indexD * 3 + 1];
  20099. const d_z = vertices[indexD * 3 + 2];
  20100. if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) {
  20101. 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)];
  20102. } else {
  20103. 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)];
  20104. }
  20105. }
  20106. };
  20107. function toJSON$1(shapes, options, data) {
  20108. data.shapes = [];
  20109. if (Array.isArray(shapes)) {
  20110. for (let i = 0, l = shapes.length; i < l; i++) {
  20111. const shape = shapes[i];
  20112. data.shapes.push(shape.uuid);
  20113. }
  20114. } else {
  20115. data.shapes.push(shapes.uuid);
  20116. }
  20117. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  20118. return data;
  20119. }
  20120. class IcosahedronGeometry extends PolyhedronGeometry {
  20121. constructor(radius = 1, detail = 0) {
  20122. const t = (1 + Math.sqrt(5)) / 2;
  20123. 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];
  20124. 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];
  20125. super(vertices, indices, radius, detail);
  20126. this.type = 'IcosahedronGeometry';
  20127. this.parameters = {
  20128. radius: radius,
  20129. detail: detail
  20130. };
  20131. }
  20132. static fromJSON(data) {
  20133. return new IcosahedronGeometry(data.radius, data.detail);
  20134. }
  20135. }
  20136. class LatheGeometry extends BufferGeometry {
  20137. constructor(points = [new Vector2(0, 0.5), new Vector2(0.5, 0), new Vector2(0, -0.5)], segments = 12, phiStart = 0, phiLength = Math.PI * 2) {
  20138. super();
  20139. this.type = 'LatheGeometry';
  20140. this.parameters = {
  20141. points: points,
  20142. segments: segments,
  20143. phiStart: phiStart,
  20144. phiLength: phiLength
  20145. };
  20146. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  20147. phiLength = clamp(phiLength, 0, Math.PI * 2); // buffers
  20148. const indices = [];
  20149. const vertices = [];
  20150. const uvs = []; // helper variables
  20151. const inverseSegments = 1.0 / segments;
  20152. const vertex = new Vector3();
  20153. const uv = new Vector2(); // generate vertices and uvs
  20154. for (let i = 0; i <= segments; i++) {
  20155. const phi = phiStart + i * inverseSegments * phiLength;
  20156. const sin = Math.sin(phi);
  20157. const cos = Math.cos(phi);
  20158. for (let j = 0; j <= points.length - 1; j++) {
  20159. // vertex
  20160. vertex.x = points[j].x * sin;
  20161. vertex.y = points[j].y;
  20162. vertex.z = points[j].x * cos;
  20163. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  20164. uv.x = i / segments;
  20165. uv.y = j / (points.length - 1);
  20166. uvs.push(uv.x, uv.y);
  20167. }
  20168. } // indices
  20169. for (let i = 0; i < segments; i++) {
  20170. for (let j = 0; j < points.length - 1; j++) {
  20171. const base = j + i * points.length;
  20172. const a = base;
  20173. const b = base + points.length;
  20174. const c = base + points.length + 1;
  20175. const d = base + 1; // faces
  20176. indices.push(a, b, d);
  20177. indices.push(b, c, d);
  20178. }
  20179. } // build geometry
  20180. this.setIndex(indices);
  20181. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20182. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  20183. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  20184. // because the corresponding vertices are identical (but still have different UVs).
  20185. if (phiLength === Math.PI * 2) {
  20186. const normals = this.attributes.normal.array;
  20187. const n1 = new Vector3();
  20188. const n2 = new Vector3();
  20189. const n = new Vector3(); // this is the buffer offset for the last line of vertices
  20190. const base = segments * points.length * 3;
  20191. for (let i = 0, j = 0; i < points.length; i++, j += 3) {
  20192. // select the normal of the vertex in the first line
  20193. n1.x = normals[j + 0];
  20194. n1.y = normals[j + 1];
  20195. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  20196. n2.x = normals[base + j + 0];
  20197. n2.y = normals[base + j + 1];
  20198. n2.z = normals[base + j + 2]; // average normals
  20199. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  20200. normals[j + 0] = normals[base + j + 0] = n.x;
  20201. normals[j + 1] = normals[base + j + 1] = n.y;
  20202. normals[j + 2] = normals[base + j + 2] = n.z;
  20203. }
  20204. }
  20205. }
  20206. static fromJSON(data) {
  20207. return new LatheGeometry(data.points, data.segments, data.phiStart, data.phiLength);
  20208. }
  20209. }
  20210. class OctahedronGeometry extends PolyhedronGeometry {
  20211. constructor(radius = 1, detail = 0) {
  20212. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  20213. 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];
  20214. super(vertices, indices, radius, detail);
  20215. this.type = 'OctahedronGeometry';
  20216. this.parameters = {
  20217. radius: radius,
  20218. detail: detail
  20219. };
  20220. }
  20221. static fromJSON(data) {
  20222. return new OctahedronGeometry(data.radius, data.detail);
  20223. }
  20224. }
  20225. class RingGeometry extends BufferGeometry {
  20226. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  20227. super();
  20228. this.type = 'RingGeometry';
  20229. this.parameters = {
  20230. innerRadius: innerRadius,
  20231. outerRadius: outerRadius,
  20232. thetaSegments: thetaSegments,
  20233. phiSegments: phiSegments,
  20234. thetaStart: thetaStart,
  20235. thetaLength: thetaLength
  20236. };
  20237. thetaSegments = Math.max(3, thetaSegments);
  20238. phiSegments = Math.max(1, phiSegments); // buffers
  20239. const indices = [];
  20240. const vertices = [];
  20241. const normals = [];
  20242. const uvs = []; // some helper variables
  20243. let radius = innerRadius;
  20244. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  20245. const vertex = new Vector3();
  20246. const uv = new Vector2(); // generate vertices, normals and uvs
  20247. for (let j = 0; j <= phiSegments; j++) {
  20248. for (let i = 0; i <= thetaSegments; i++) {
  20249. // values are generate from the inside of the ring to the outside
  20250. const segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  20251. vertex.x = radius * Math.cos(segment);
  20252. vertex.y = radius * Math.sin(segment);
  20253. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20254. normals.push(0, 0, 1); // uv
  20255. uv.x = (vertex.x / outerRadius + 1) / 2;
  20256. uv.y = (vertex.y / outerRadius + 1) / 2;
  20257. uvs.push(uv.x, uv.y);
  20258. } // increase the radius for next row of vertices
  20259. radius += radiusStep;
  20260. } // indices
  20261. for (let j = 0; j < phiSegments; j++) {
  20262. const thetaSegmentLevel = j * (thetaSegments + 1);
  20263. for (let i = 0; i < thetaSegments; i++) {
  20264. const segment = i + thetaSegmentLevel;
  20265. const a = segment;
  20266. const b = segment + thetaSegments + 1;
  20267. const c = segment + thetaSegments + 2;
  20268. const d = segment + 1; // faces
  20269. indices.push(a, b, d);
  20270. indices.push(b, c, d);
  20271. }
  20272. } // build geometry
  20273. this.setIndex(indices);
  20274. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20275. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20276. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20277. }
  20278. static fromJSON(data) {
  20279. return new RingGeometry(data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  20280. }
  20281. }
  20282. class ShapeGeometry extends BufferGeometry {
  20283. constructor(shapes = new Shape([new Vector2(0, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), curveSegments = 12) {
  20284. super();
  20285. this.type = 'ShapeGeometry';
  20286. this.parameters = {
  20287. shapes: shapes,
  20288. curveSegments: curveSegments
  20289. }; // buffers
  20290. const indices = [];
  20291. const vertices = [];
  20292. const normals = [];
  20293. const uvs = []; // helper variables
  20294. let groupStart = 0;
  20295. let groupCount = 0; // allow single and array values for "shapes" parameter
  20296. if (Array.isArray(shapes) === false) {
  20297. addShape(shapes);
  20298. } else {
  20299. for (let i = 0; i < shapes.length; i++) {
  20300. addShape(shapes[i]);
  20301. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  20302. groupStart += groupCount;
  20303. groupCount = 0;
  20304. }
  20305. } // build geometry
  20306. this.setIndex(indices);
  20307. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20308. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20309. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  20310. function addShape(shape) {
  20311. const indexOffset = vertices.length / 3;
  20312. const points = shape.extractPoints(curveSegments);
  20313. let shapeVertices = points.shape;
  20314. const shapeHoles = points.holes; // check direction of vertices
  20315. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  20316. shapeVertices = shapeVertices.reverse();
  20317. }
  20318. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  20319. const shapeHole = shapeHoles[i];
  20320. if (ShapeUtils.isClockWise(shapeHole) === true) {
  20321. shapeHoles[i] = shapeHole.reverse();
  20322. }
  20323. }
  20324. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  20325. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  20326. const shapeHole = shapeHoles[i];
  20327. shapeVertices = shapeVertices.concat(shapeHole);
  20328. } // vertices, normals, uvs
  20329. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  20330. const vertex = shapeVertices[i];
  20331. vertices.push(vertex.x, vertex.y, 0);
  20332. normals.push(0, 0, 1);
  20333. uvs.push(vertex.x, vertex.y); // world uvs
  20334. } // incides
  20335. for (let i = 0, l = faces.length; i < l; i++) {
  20336. const face = faces[i];
  20337. const a = face[0] + indexOffset;
  20338. const b = face[1] + indexOffset;
  20339. const c = face[2] + indexOffset;
  20340. indices.push(a, b, c);
  20341. groupCount += 3;
  20342. }
  20343. }
  20344. }
  20345. toJSON() {
  20346. const data = super.toJSON();
  20347. const shapes = this.parameters.shapes;
  20348. return toJSON(shapes, data);
  20349. }
  20350. static fromJSON(data, shapes) {
  20351. const geometryShapes = [];
  20352. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  20353. const shape = shapes[data.shapes[j]];
  20354. geometryShapes.push(shape);
  20355. }
  20356. return new ShapeGeometry(geometryShapes, data.curveSegments);
  20357. }
  20358. }
  20359. function toJSON(shapes, data) {
  20360. data.shapes = [];
  20361. if (Array.isArray(shapes)) {
  20362. for (let i = 0, l = shapes.length; i < l; i++) {
  20363. const shape = shapes[i];
  20364. data.shapes.push(shape.uuid);
  20365. }
  20366. } else {
  20367. data.shapes.push(shapes.uuid);
  20368. }
  20369. return data;
  20370. }
  20371. class SphereGeometry extends BufferGeometry {
  20372. constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  20373. super();
  20374. this.type = 'SphereGeometry';
  20375. this.parameters = {
  20376. radius: radius,
  20377. widthSegments: widthSegments,
  20378. heightSegments: heightSegments,
  20379. phiStart: phiStart,
  20380. phiLength: phiLength,
  20381. thetaStart: thetaStart,
  20382. thetaLength: thetaLength
  20383. };
  20384. widthSegments = Math.max(3, Math.floor(widthSegments));
  20385. heightSegments = Math.max(2, Math.floor(heightSegments));
  20386. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  20387. let index = 0;
  20388. const grid = [];
  20389. const vertex = new Vector3();
  20390. const normal = new Vector3(); // buffers
  20391. const indices = [];
  20392. const vertices = [];
  20393. const normals = [];
  20394. const uvs = []; // generate vertices, normals and uvs
  20395. for (let iy = 0; iy <= heightSegments; iy++) {
  20396. const verticesRow = [];
  20397. const v = iy / heightSegments; // special case for the poles
  20398. let uOffset = 0;
  20399. if (iy == 0 && thetaStart == 0) {
  20400. uOffset = 0.5 / widthSegments;
  20401. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  20402. uOffset = -0.5 / widthSegments;
  20403. }
  20404. for (let ix = 0; ix <= widthSegments; ix++) {
  20405. const u = ix / widthSegments; // vertex
  20406. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  20407. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  20408. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  20409. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20410. normal.copy(vertex).normalize();
  20411. normals.push(normal.x, normal.y, normal.z); // uv
  20412. uvs.push(u + uOffset, 1 - v);
  20413. verticesRow.push(index++);
  20414. }
  20415. grid.push(verticesRow);
  20416. } // indices
  20417. for (let iy = 0; iy < heightSegments; iy++) {
  20418. for (let ix = 0; ix < widthSegments; ix++) {
  20419. const a = grid[iy][ix + 1];
  20420. const b = grid[iy][ix];
  20421. const c = grid[iy + 1][ix];
  20422. const d = grid[iy + 1][ix + 1];
  20423. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  20424. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  20425. }
  20426. } // build geometry
  20427. this.setIndex(indices);
  20428. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20429. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20430. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20431. }
  20432. static fromJSON(data) {
  20433. return new SphereGeometry(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  20434. }
  20435. }
  20436. class TetrahedronGeometry extends PolyhedronGeometry {
  20437. constructor(radius = 1, detail = 0) {
  20438. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  20439. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  20440. super(vertices, indices, radius, detail);
  20441. this.type = 'TetrahedronGeometry';
  20442. this.parameters = {
  20443. radius: radius,
  20444. detail: detail
  20445. };
  20446. }
  20447. static fromJSON(data) {
  20448. return new TetrahedronGeometry(data.radius, data.detail);
  20449. }
  20450. }
  20451. class TorusGeometry extends BufferGeometry {
  20452. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  20453. super();
  20454. this.type = 'TorusGeometry';
  20455. this.parameters = {
  20456. radius: radius,
  20457. tube: tube,
  20458. radialSegments: radialSegments,
  20459. tubularSegments: tubularSegments,
  20460. arc: arc
  20461. };
  20462. radialSegments = Math.floor(radialSegments);
  20463. tubularSegments = Math.floor(tubularSegments); // buffers
  20464. const indices = [];
  20465. const vertices = [];
  20466. const normals = [];
  20467. const uvs = []; // helper variables
  20468. const center = new Vector3();
  20469. const vertex = new Vector3();
  20470. const normal = new Vector3(); // generate vertices, normals and uvs
  20471. for (let j = 0; j <= radialSegments; j++) {
  20472. for (let i = 0; i <= tubularSegments; i++) {
  20473. const u = i / tubularSegments * arc;
  20474. const v = j / radialSegments * Math.PI * 2; // vertex
  20475. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  20476. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  20477. vertex.z = tube * Math.sin(v);
  20478. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20479. center.x = radius * Math.cos(u);
  20480. center.y = radius * Math.sin(u);
  20481. normal.subVectors(vertex, center).normalize();
  20482. normals.push(normal.x, normal.y, normal.z); // uv
  20483. uvs.push(i / tubularSegments);
  20484. uvs.push(j / radialSegments);
  20485. }
  20486. } // generate indices
  20487. for (let j = 1; j <= radialSegments; j++) {
  20488. for (let i = 1; i <= tubularSegments; i++) {
  20489. // indices
  20490. const a = (tubularSegments + 1) * j + i - 1;
  20491. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  20492. const c = (tubularSegments + 1) * (j - 1) + i;
  20493. const d = (tubularSegments + 1) * j + i; // faces
  20494. indices.push(a, b, d);
  20495. indices.push(b, c, d);
  20496. }
  20497. } // build geometry
  20498. this.setIndex(indices);
  20499. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20500. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20501. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20502. }
  20503. static fromJSON(data) {
  20504. return new TorusGeometry(data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  20505. }
  20506. }
  20507. class TorusKnotGeometry extends BufferGeometry {
  20508. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  20509. super();
  20510. this.type = 'TorusKnotGeometry';
  20511. this.parameters = {
  20512. radius: radius,
  20513. tube: tube,
  20514. tubularSegments: tubularSegments,
  20515. radialSegments: radialSegments,
  20516. p: p,
  20517. q: q
  20518. };
  20519. tubularSegments = Math.floor(tubularSegments);
  20520. radialSegments = Math.floor(radialSegments); // buffers
  20521. const indices = [];
  20522. const vertices = [];
  20523. const normals = [];
  20524. const uvs = []; // helper variables
  20525. const vertex = new Vector3();
  20526. const normal = new Vector3();
  20527. const P1 = new Vector3();
  20528. const P2 = new Vector3();
  20529. const B = new Vector3();
  20530. const T = new Vector3();
  20531. const N = new Vector3(); // generate vertices, normals and uvs
  20532. for (let i = 0; i <= tubularSegments; ++i) {
  20533. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  20534. 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.
  20535. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  20536. calculatePositionOnCurve(u, p, q, radius, P1);
  20537. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  20538. T.subVectors(P2, P1);
  20539. N.addVectors(P2, P1);
  20540. B.crossVectors(T, N);
  20541. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  20542. B.normalize();
  20543. N.normalize();
  20544. for (let j = 0; j <= radialSegments; ++j) {
  20545. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  20546. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  20547. const v = j / radialSegments * Math.PI * 2;
  20548. const cx = -tube * Math.cos(v);
  20549. const cy = tube * Math.sin(v); // now calculate the final vertex position.
  20550. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  20551. vertex.x = P1.x + (cx * N.x + cy * B.x);
  20552. vertex.y = P1.y + (cx * N.y + cy * B.y);
  20553. vertex.z = P1.z + (cx * N.z + cy * B.z);
  20554. 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)
  20555. normal.subVectors(vertex, P1).normalize();
  20556. normals.push(normal.x, normal.y, normal.z); // uv
  20557. uvs.push(i / tubularSegments);
  20558. uvs.push(j / radialSegments);
  20559. }
  20560. } // generate indices
  20561. for (let j = 1; j <= tubularSegments; j++) {
  20562. for (let i = 1; i <= radialSegments; i++) {
  20563. // indices
  20564. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  20565. const b = (radialSegments + 1) * j + (i - 1);
  20566. const c = (radialSegments + 1) * j + i;
  20567. const d = (radialSegments + 1) * (j - 1) + i; // faces
  20568. indices.push(a, b, d);
  20569. indices.push(b, c, d);
  20570. }
  20571. } // build geometry
  20572. this.setIndex(indices);
  20573. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20574. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20575. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  20576. function calculatePositionOnCurve(u, p, q, radius, position) {
  20577. const cu = Math.cos(u);
  20578. const su = Math.sin(u);
  20579. const quOverP = q / p * u;
  20580. const cs = Math.cos(quOverP);
  20581. position.x = radius * (2 + cs) * 0.5 * cu;
  20582. position.y = radius * (2 + cs) * su * 0.5;
  20583. position.z = radius * Math.sin(quOverP) * 0.5;
  20584. }
  20585. }
  20586. static fromJSON(data) {
  20587. return new TorusKnotGeometry(data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  20588. }
  20589. }
  20590. class TubeGeometry extends BufferGeometry {
  20591. constructor(path = new QuadraticBezierCurve3(new Vector3(-1, -1, 0), new Vector3(-1, 1, 0), new Vector3(1, 1, 0)), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) {
  20592. super();
  20593. this.type = 'TubeGeometry';
  20594. this.parameters = {
  20595. path: path,
  20596. tubularSegments: tubularSegments,
  20597. radius: radius,
  20598. radialSegments: radialSegments,
  20599. closed: closed
  20600. };
  20601. const frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  20602. this.tangents = frames.tangents;
  20603. this.normals = frames.normals;
  20604. this.binormals = frames.binormals; // helper variables
  20605. const vertex = new Vector3();
  20606. const normal = new Vector3();
  20607. const uv = new Vector2();
  20608. let P = new Vector3(); // buffer
  20609. const vertices = [];
  20610. const normals = [];
  20611. const uvs = [];
  20612. const indices = []; // create buffer data
  20613. generateBufferData(); // build geometry
  20614. this.setIndex(indices);
  20615. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20616. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20617. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  20618. function generateBufferData() {
  20619. for (let i = 0; i < tubularSegments; i++) {
  20620. generateSegment(i);
  20621. } // if the geometry is not closed, generate the last row of vertices and normals
  20622. // at the regular position on the given path
  20623. //
  20624. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  20625. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  20626. // this makes it easy compute correct values for closed geometries
  20627. generateUVs(); // finally create faces
  20628. generateIndices();
  20629. }
  20630. function generateSegment(i) {
  20631. // we use getPointAt to sample evenly distributed points from the given path
  20632. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  20633. const N = frames.normals[i];
  20634. const B = frames.binormals[i]; // generate normals and vertices for the current segment
  20635. for (let j = 0; j <= radialSegments; j++) {
  20636. const v = j / radialSegments * Math.PI * 2;
  20637. const sin = Math.sin(v);
  20638. const cos = -Math.cos(v); // normal
  20639. normal.x = cos * N.x + sin * B.x;
  20640. normal.y = cos * N.y + sin * B.y;
  20641. normal.z = cos * N.z + sin * B.z;
  20642. normal.normalize();
  20643. normals.push(normal.x, normal.y, normal.z); // vertex
  20644. vertex.x = P.x + radius * normal.x;
  20645. vertex.y = P.y + radius * normal.y;
  20646. vertex.z = P.z + radius * normal.z;
  20647. vertices.push(vertex.x, vertex.y, vertex.z);
  20648. }
  20649. }
  20650. function generateIndices() {
  20651. for (let j = 1; j <= tubularSegments; j++) {
  20652. for (let i = 1; i <= radialSegments; i++) {
  20653. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  20654. const b = (radialSegments + 1) * j + (i - 1);
  20655. const c = (radialSegments + 1) * j + i;
  20656. const d = (radialSegments + 1) * (j - 1) + i; // faces
  20657. indices.push(a, b, d);
  20658. indices.push(b, c, d);
  20659. }
  20660. }
  20661. }
  20662. function generateUVs() {
  20663. for (let i = 0; i <= tubularSegments; i++) {
  20664. for (let j = 0; j <= radialSegments; j++) {
  20665. uv.x = i / tubularSegments;
  20666. uv.y = j / radialSegments;
  20667. uvs.push(uv.x, uv.y);
  20668. }
  20669. }
  20670. }
  20671. }
  20672. toJSON() {
  20673. const data = super.toJSON();
  20674. data.path = this.parameters.path.toJSON();
  20675. return data;
  20676. }
  20677. static fromJSON(data) {
  20678. // This only works for built-in curves (e.g. CatmullRomCurve3).
  20679. // User defined curves or instances of CurvePath will not be deserialized.
  20680. return new TubeGeometry(new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  20681. }
  20682. }
  20683. class WireframeGeometry extends BufferGeometry {
  20684. constructor(geometry = null) {
  20685. super();
  20686. this.type = 'WireframeGeometry';
  20687. this.parameters = {
  20688. geometry: geometry
  20689. };
  20690. if (geometry !== null) {
  20691. // buffer
  20692. const vertices = [];
  20693. const edges = new Set(); // helper variables
  20694. const start = new Vector3();
  20695. const end = new Vector3();
  20696. if (geometry.index !== null) {
  20697. // indexed BufferGeometry
  20698. const position = geometry.attributes.position;
  20699. const indices = geometry.index;
  20700. let groups = geometry.groups;
  20701. if (groups.length === 0) {
  20702. groups = [{
  20703. start: 0,
  20704. count: indices.count,
  20705. materialIndex: 0
  20706. }];
  20707. } // create a data structure that contains all eges without duplicates
  20708. for (let o = 0, ol = groups.length; o < ol; ++o) {
  20709. const group = groups[o];
  20710. const groupStart = group.start;
  20711. const groupCount = group.count;
  20712. for (let i = groupStart, l = groupStart + groupCount; i < l; i += 3) {
  20713. for (let j = 0; j < 3; j++) {
  20714. const index1 = indices.getX(i + j);
  20715. const index2 = indices.getX(i + (j + 1) % 3);
  20716. start.fromBufferAttribute(position, index1);
  20717. end.fromBufferAttribute(position, index2);
  20718. if (isUniqueEdge(start, end, edges) === true) {
  20719. vertices.push(start.x, start.y, start.z);
  20720. vertices.push(end.x, end.y, end.z);
  20721. }
  20722. }
  20723. }
  20724. }
  20725. } else {
  20726. // non-indexed BufferGeometry
  20727. const position = geometry.attributes.position;
  20728. for (let i = 0, l = position.count / 3; i < l; i++) {
  20729. for (let j = 0; j < 3; j++) {
  20730. // three edges per triangle, an edge is represented as (index1, index2)
  20731. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  20732. const index1 = 3 * i + j;
  20733. const index2 = 3 * i + (j + 1) % 3;
  20734. start.fromBufferAttribute(position, index1);
  20735. end.fromBufferAttribute(position, index2);
  20736. if (isUniqueEdge(start, end, edges) === true) {
  20737. vertices.push(start.x, start.y, start.z);
  20738. vertices.push(end.x, end.y, end.z);
  20739. }
  20740. }
  20741. }
  20742. } // build geometry
  20743. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20744. }
  20745. }
  20746. }
  20747. function isUniqueEdge(start, end, edges) {
  20748. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  20749. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  20750. if (edges.has(hash1) === true || edges.has(hash2) === true) {
  20751. return false;
  20752. } else {
  20753. edges.add(hash1, hash2);
  20754. return true;
  20755. }
  20756. }
  20757. var Geometries = /*#__PURE__*/Object.freeze({
  20758. __proto__: null,
  20759. BoxGeometry: BoxGeometry,
  20760. BoxBufferGeometry: BoxGeometry,
  20761. CircleGeometry: CircleGeometry,
  20762. CircleBufferGeometry: CircleGeometry,
  20763. ConeGeometry: ConeGeometry,
  20764. ConeBufferGeometry: ConeGeometry,
  20765. CylinderGeometry: CylinderGeometry,
  20766. CylinderBufferGeometry: CylinderGeometry,
  20767. DodecahedronGeometry: DodecahedronGeometry,
  20768. DodecahedronBufferGeometry: DodecahedronGeometry,
  20769. EdgesGeometry: EdgesGeometry,
  20770. ExtrudeGeometry: ExtrudeGeometry,
  20771. ExtrudeBufferGeometry: ExtrudeGeometry,
  20772. IcosahedronGeometry: IcosahedronGeometry,
  20773. IcosahedronBufferGeometry: IcosahedronGeometry,
  20774. LatheGeometry: LatheGeometry,
  20775. LatheBufferGeometry: LatheGeometry,
  20776. OctahedronGeometry: OctahedronGeometry,
  20777. OctahedronBufferGeometry: OctahedronGeometry,
  20778. PlaneGeometry: PlaneGeometry,
  20779. PlaneBufferGeometry: PlaneGeometry,
  20780. PolyhedronGeometry: PolyhedronGeometry,
  20781. PolyhedronBufferGeometry: PolyhedronGeometry,
  20782. RingGeometry: RingGeometry,
  20783. RingBufferGeometry: RingGeometry,
  20784. ShapeGeometry: ShapeGeometry,
  20785. ShapeBufferGeometry: ShapeGeometry,
  20786. SphereGeometry: SphereGeometry,
  20787. SphereBufferGeometry: SphereGeometry,
  20788. TetrahedronGeometry: TetrahedronGeometry,
  20789. TetrahedronBufferGeometry: TetrahedronGeometry,
  20790. TorusGeometry: TorusGeometry,
  20791. TorusBufferGeometry: TorusGeometry,
  20792. TorusKnotGeometry: TorusKnotGeometry,
  20793. TorusKnotBufferGeometry: TorusKnotGeometry,
  20794. TubeGeometry: TubeGeometry,
  20795. TubeBufferGeometry: TubeGeometry,
  20796. WireframeGeometry: WireframeGeometry
  20797. });
  20798. /**
  20799. * parameters = {
  20800. * color: <THREE.Color>
  20801. * }
  20802. */
  20803. class ShadowMaterial extends Material {
  20804. constructor(parameters) {
  20805. super();
  20806. this.type = 'ShadowMaterial';
  20807. this.color = new Color(0x000000);
  20808. this.transparent = true;
  20809. this.setValues(parameters);
  20810. }
  20811. copy(source) {
  20812. super.copy(source);
  20813. this.color.copy(source.color);
  20814. return this;
  20815. }
  20816. }
  20817. ShadowMaterial.prototype.isShadowMaterial = true;
  20818. /**
  20819. * parameters = {
  20820. * color: <hex>,
  20821. * roughness: <float>,
  20822. * metalness: <float>,
  20823. * opacity: <float>,
  20824. *
  20825. * map: new THREE.Texture( <Image> ),
  20826. *
  20827. * lightMap: new THREE.Texture( <Image> ),
  20828. * lightMapIntensity: <float>
  20829. *
  20830. * aoMap: new THREE.Texture( <Image> ),
  20831. * aoMapIntensity: <float>
  20832. *
  20833. * emissive: <hex>,
  20834. * emissiveIntensity: <float>
  20835. * emissiveMap: new THREE.Texture( <Image> ),
  20836. *
  20837. * bumpMap: new THREE.Texture( <Image> ),
  20838. * bumpScale: <float>,
  20839. *
  20840. * normalMap: new THREE.Texture( <Image> ),
  20841. * normalMapType: THREE.TangentSpaceNormalMap,
  20842. * normalScale: <Vector2>,
  20843. *
  20844. * displacementMap: new THREE.Texture( <Image> ),
  20845. * displacementScale: <float>,
  20846. * displacementBias: <float>,
  20847. *
  20848. * roughnessMap: new THREE.Texture( <Image> ),
  20849. *
  20850. * metalnessMap: new THREE.Texture( <Image> ),
  20851. *
  20852. * alphaMap: new THREE.Texture( <Image> ),
  20853. *
  20854. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20855. * envMapIntensity: <float>
  20856. *
  20857. * refractionRatio: <float>,
  20858. *
  20859. * wireframe: <boolean>,
  20860. * wireframeLinewidth: <float>,
  20861. *
  20862. * flatShading: <bool>
  20863. * }
  20864. */
  20865. class MeshStandardMaterial extends Material {
  20866. constructor(parameters) {
  20867. super();
  20868. this.defines = {
  20869. 'STANDARD': ''
  20870. };
  20871. this.type = 'MeshStandardMaterial';
  20872. this.color = new Color(0xffffff); // diffuse
  20873. this.roughness = 1.0;
  20874. this.metalness = 0.0;
  20875. this.map = null;
  20876. this.lightMap = null;
  20877. this.lightMapIntensity = 1.0;
  20878. this.aoMap = null;
  20879. this.aoMapIntensity = 1.0;
  20880. this.emissive = new Color(0x000000);
  20881. this.emissiveIntensity = 1.0;
  20882. this.emissiveMap = null;
  20883. this.bumpMap = null;
  20884. this.bumpScale = 1;
  20885. this.normalMap = null;
  20886. this.normalMapType = TangentSpaceNormalMap;
  20887. this.normalScale = new Vector2(1, 1);
  20888. this.displacementMap = null;
  20889. this.displacementScale = 1;
  20890. this.displacementBias = 0;
  20891. this.roughnessMap = null;
  20892. this.metalnessMap = null;
  20893. this.alphaMap = null;
  20894. this.envMap = null;
  20895. this.envMapIntensity = 1.0;
  20896. this.refractionRatio = 0.98;
  20897. this.wireframe = false;
  20898. this.wireframeLinewidth = 1;
  20899. this.wireframeLinecap = 'round';
  20900. this.wireframeLinejoin = 'round';
  20901. this.flatShading = false;
  20902. this.setValues(parameters);
  20903. }
  20904. copy(source) {
  20905. super.copy(source);
  20906. this.defines = {
  20907. 'STANDARD': ''
  20908. };
  20909. this.color.copy(source.color);
  20910. this.roughness = source.roughness;
  20911. this.metalness = source.metalness;
  20912. this.map = source.map;
  20913. this.lightMap = source.lightMap;
  20914. this.lightMapIntensity = source.lightMapIntensity;
  20915. this.aoMap = source.aoMap;
  20916. this.aoMapIntensity = source.aoMapIntensity;
  20917. this.emissive.copy(source.emissive);
  20918. this.emissiveMap = source.emissiveMap;
  20919. this.emissiveIntensity = source.emissiveIntensity;
  20920. this.bumpMap = source.bumpMap;
  20921. this.bumpScale = source.bumpScale;
  20922. this.normalMap = source.normalMap;
  20923. this.normalMapType = source.normalMapType;
  20924. this.normalScale.copy(source.normalScale);
  20925. this.displacementMap = source.displacementMap;
  20926. this.displacementScale = source.displacementScale;
  20927. this.displacementBias = source.displacementBias;
  20928. this.roughnessMap = source.roughnessMap;
  20929. this.metalnessMap = source.metalnessMap;
  20930. this.alphaMap = source.alphaMap;
  20931. this.envMap = source.envMap;
  20932. this.envMapIntensity = source.envMapIntensity;
  20933. this.refractionRatio = source.refractionRatio;
  20934. this.wireframe = source.wireframe;
  20935. this.wireframeLinewidth = source.wireframeLinewidth;
  20936. this.wireframeLinecap = source.wireframeLinecap;
  20937. this.wireframeLinejoin = source.wireframeLinejoin;
  20938. this.flatShading = source.flatShading;
  20939. return this;
  20940. }
  20941. }
  20942. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  20943. /**
  20944. * parameters = {
  20945. * clearcoat: <float>,
  20946. * clearcoatMap: new THREE.Texture( <Image> ),
  20947. * clearcoatRoughness: <float>,
  20948. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  20949. * clearcoatNormalScale: <Vector2>,
  20950. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  20951. *
  20952. * ior: <float>,
  20953. * reflectivity: <float>,
  20954. *
  20955. * sheen: <float>,
  20956. * sheenTint: <Color>,
  20957. * sheenRoughness: <float>,
  20958. *
  20959. * transmission: <float>,
  20960. * transmissionMap: new THREE.Texture( <Image> ),
  20961. *
  20962. * thickness: <float>,
  20963. * thicknessMap: new THREE.Texture( <Image> ),
  20964. * attenuationDistance: <float>,
  20965. * attenuationTint: <Color>,
  20966. *
  20967. * specularIntensity: <float>,
  20968. * specularIntensityhMap: new THREE.Texture( <Image> ),
  20969. * specularTint: <Color>,
  20970. * specularTintMap: new THREE.Texture( <Image> )
  20971. * }
  20972. */
  20973. class MeshPhysicalMaterial extends MeshStandardMaterial {
  20974. constructor(parameters) {
  20975. super();
  20976. this.defines = {
  20977. 'STANDARD': '',
  20978. 'PHYSICAL': ''
  20979. };
  20980. this.type = 'MeshPhysicalMaterial';
  20981. this.clearcoatMap = null;
  20982. this.clearcoatRoughness = 0.0;
  20983. this.clearcoatRoughnessMap = null;
  20984. this.clearcoatNormalScale = new Vector2(1, 1);
  20985. this.clearcoatNormalMap = null;
  20986. this.ior = 1.5;
  20987. Object.defineProperty(this, 'reflectivity', {
  20988. get: function () {
  20989. return clamp(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1);
  20990. },
  20991. set: function (reflectivity) {
  20992. this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity);
  20993. }
  20994. });
  20995. this.sheenTint = new Color(0x000000);
  20996. this.sheenRoughness = 1.0;
  20997. this.transmissionMap = null;
  20998. this.thickness = 0.01;
  20999. this.thicknessMap = null;
  21000. this.attenuationDistance = 0.0;
  21001. this.attenuationTint = new Color(1, 1, 1);
  21002. this.specularIntensity = 1.0;
  21003. this.specularIntensityMap = null;
  21004. this.specularTint = new Color(1, 1, 1);
  21005. this.specularTintMap = null;
  21006. this._sheen = 0.0;
  21007. this._clearcoat = 0;
  21008. this._transmission = 0;
  21009. this.setValues(parameters);
  21010. }
  21011. get sheen() {
  21012. return this._sheen;
  21013. }
  21014. set sheen(value) {
  21015. if (this._sheen > 0 !== value > 0) {
  21016. this.version++;
  21017. }
  21018. this._sheen = value;
  21019. }
  21020. get clearcoat() {
  21021. return this._clearcoat;
  21022. }
  21023. set clearcoat(value) {
  21024. if (this._clearcoat > 0 !== value > 0) {
  21025. this.version++;
  21026. }
  21027. this._clearcoat = value;
  21028. }
  21029. get transmission() {
  21030. return this._transmission;
  21031. }
  21032. set transmission(value) {
  21033. if (this._transmission > 0 !== value > 0) {
  21034. this.version++;
  21035. }
  21036. this._transmission = value;
  21037. }
  21038. copy(source) {
  21039. super.copy(source);
  21040. this.defines = {
  21041. 'STANDARD': '',
  21042. 'PHYSICAL': ''
  21043. };
  21044. this.clearcoat = source.clearcoat;
  21045. this.clearcoatMap = source.clearcoatMap;
  21046. this.clearcoatRoughness = source.clearcoatRoughness;
  21047. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  21048. this.clearcoatNormalMap = source.clearcoatNormalMap;
  21049. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  21050. this.ior = source.ior;
  21051. this.sheen = source.sheen;
  21052. this.sheenTint.copy(source.sheenTint);
  21053. this.sheenRoughness = source.sheenRoughness;
  21054. this.transmission = source.transmission;
  21055. this.transmissionMap = source.transmissionMap;
  21056. this.thickness = source.thickness;
  21057. this.thicknessMap = source.thicknessMap;
  21058. this.attenuationDistance = source.attenuationDistance;
  21059. this.attenuationTint.copy(source.attenuationTint);
  21060. this.specularIntensity = source.specularIntensity;
  21061. this.specularIntensityMap = source.specularIntensityMap;
  21062. this.specularTint.copy(source.specularTint);
  21063. this.specularTintMap = source.specularTintMap;
  21064. return this;
  21065. }
  21066. }
  21067. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  21068. /**
  21069. * parameters = {
  21070. * color: <hex>,
  21071. * specular: <hex>,
  21072. * shininess: <float>,
  21073. * opacity: <float>,
  21074. *
  21075. * map: new THREE.Texture( <Image> ),
  21076. *
  21077. * lightMap: new THREE.Texture( <Image> ),
  21078. * lightMapIntensity: <float>
  21079. *
  21080. * aoMap: new THREE.Texture( <Image> ),
  21081. * aoMapIntensity: <float>
  21082. *
  21083. * emissive: <hex>,
  21084. * emissiveIntensity: <float>
  21085. * emissiveMap: new THREE.Texture( <Image> ),
  21086. *
  21087. * bumpMap: new THREE.Texture( <Image> ),
  21088. * bumpScale: <float>,
  21089. *
  21090. * normalMap: new THREE.Texture( <Image> ),
  21091. * normalMapType: THREE.TangentSpaceNormalMap,
  21092. * normalScale: <Vector2>,
  21093. *
  21094. * displacementMap: new THREE.Texture( <Image> ),
  21095. * displacementScale: <float>,
  21096. * displacementBias: <float>,
  21097. *
  21098. * specularMap: new THREE.Texture( <Image> ),
  21099. *
  21100. * alphaMap: new THREE.Texture( <Image> ),
  21101. *
  21102. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21103. * combine: THREE.MultiplyOperation,
  21104. * reflectivity: <float>,
  21105. * refractionRatio: <float>,
  21106. *
  21107. * wireframe: <boolean>,
  21108. * wireframeLinewidth: <float>,
  21109. *
  21110. * flatShading: <bool>
  21111. * }
  21112. */
  21113. class MeshPhongMaterial extends Material {
  21114. constructor(parameters) {
  21115. super();
  21116. this.type = 'MeshPhongMaterial';
  21117. this.color = new Color(0xffffff); // diffuse
  21118. this.specular = new Color(0x111111);
  21119. this.shininess = 30;
  21120. this.map = null;
  21121. this.lightMap = null;
  21122. this.lightMapIntensity = 1.0;
  21123. this.aoMap = null;
  21124. this.aoMapIntensity = 1.0;
  21125. this.emissive = new Color(0x000000);
  21126. this.emissiveIntensity = 1.0;
  21127. this.emissiveMap = null;
  21128. this.bumpMap = null;
  21129. this.bumpScale = 1;
  21130. this.normalMap = null;
  21131. this.normalMapType = TangentSpaceNormalMap;
  21132. this.normalScale = new Vector2(1, 1);
  21133. this.displacementMap = null;
  21134. this.displacementScale = 1;
  21135. this.displacementBias = 0;
  21136. this.specularMap = null;
  21137. this.alphaMap = null;
  21138. this.envMap = null;
  21139. this.combine = MultiplyOperation;
  21140. this.reflectivity = 1;
  21141. this.refractionRatio = 0.98;
  21142. this.wireframe = false;
  21143. this.wireframeLinewidth = 1;
  21144. this.wireframeLinecap = 'round';
  21145. this.wireframeLinejoin = 'round';
  21146. this.flatShading = false;
  21147. this.setValues(parameters);
  21148. }
  21149. copy(source) {
  21150. super.copy(source);
  21151. this.color.copy(source.color);
  21152. this.specular.copy(source.specular);
  21153. this.shininess = source.shininess;
  21154. this.map = source.map;
  21155. this.lightMap = source.lightMap;
  21156. this.lightMapIntensity = source.lightMapIntensity;
  21157. this.aoMap = source.aoMap;
  21158. this.aoMapIntensity = source.aoMapIntensity;
  21159. this.emissive.copy(source.emissive);
  21160. this.emissiveMap = source.emissiveMap;
  21161. this.emissiveIntensity = source.emissiveIntensity;
  21162. this.bumpMap = source.bumpMap;
  21163. this.bumpScale = source.bumpScale;
  21164. this.normalMap = source.normalMap;
  21165. this.normalMapType = source.normalMapType;
  21166. this.normalScale.copy(source.normalScale);
  21167. this.displacementMap = source.displacementMap;
  21168. this.displacementScale = source.displacementScale;
  21169. this.displacementBias = source.displacementBias;
  21170. this.specularMap = source.specularMap;
  21171. this.alphaMap = source.alphaMap;
  21172. this.envMap = source.envMap;
  21173. this.combine = source.combine;
  21174. this.reflectivity = source.reflectivity;
  21175. this.refractionRatio = source.refractionRatio;
  21176. this.wireframe = source.wireframe;
  21177. this.wireframeLinewidth = source.wireframeLinewidth;
  21178. this.wireframeLinecap = source.wireframeLinecap;
  21179. this.wireframeLinejoin = source.wireframeLinejoin;
  21180. this.flatShading = source.flatShading;
  21181. return this;
  21182. }
  21183. }
  21184. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  21185. /**
  21186. * parameters = {
  21187. * color: <hex>,
  21188. *
  21189. * map: new THREE.Texture( <Image> ),
  21190. * gradientMap: new THREE.Texture( <Image> ),
  21191. *
  21192. * lightMap: new THREE.Texture( <Image> ),
  21193. * lightMapIntensity: <float>
  21194. *
  21195. * aoMap: new THREE.Texture( <Image> ),
  21196. * aoMapIntensity: <float>
  21197. *
  21198. * emissive: <hex>,
  21199. * emissiveIntensity: <float>
  21200. * emissiveMap: new THREE.Texture( <Image> ),
  21201. *
  21202. * bumpMap: new THREE.Texture( <Image> ),
  21203. * bumpScale: <float>,
  21204. *
  21205. * normalMap: new THREE.Texture( <Image> ),
  21206. * normalMapType: THREE.TangentSpaceNormalMap,
  21207. * normalScale: <Vector2>,
  21208. *
  21209. * displacementMap: new THREE.Texture( <Image> ),
  21210. * displacementScale: <float>,
  21211. * displacementBias: <float>,
  21212. *
  21213. * alphaMap: new THREE.Texture( <Image> ),
  21214. *
  21215. * wireframe: <boolean>,
  21216. * wireframeLinewidth: <float>,
  21217. *
  21218. * }
  21219. */
  21220. class MeshToonMaterial extends Material {
  21221. constructor(parameters) {
  21222. super();
  21223. this.defines = {
  21224. 'TOON': ''
  21225. };
  21226. this.type = 'MeshToonMaterial';
  21227. this.color = new Color(0xffffff);
  21228. this.map = null;
  21229. this.gradientMap = null;
  21230. this.lightMap = null;
  21231. this.lightMapIntensity = 1.0;
  21232. this.aoMap = null;
  21233. this.aoMapIntensity = 1.0;
  21234. this.emissive = new Color(0x000000);
  21235. this.emissiveIntensity = 1.0;
  21236. this.emissiveMap = null;
  21237. this.bumpMap = null;
  21238. this.bumpScale = 1;
  21239. this.normalMap = null;
  21240. this.normalMapType = TangentSpaceNormalMap;
  21241. this.normalScale = new Vector2(1, 1);
  21242. this.displacementMap = null;
  21243. this.displacementScale = 1;
  21244. this.displacementBias = 0;
  21245. this.alphaMap = null;
  21246. this.wireframe = false;
  21247. this.wireframeLinewidth = 1;
  21248. this.wireframeLinecap = 'round';
  21249. this.wireframeLinejoin = 'round';
  21250. this.setValues(parameters);
  21251. }
  21252. copy(source) {
  21253. super.copy(source);
  21254. this.color.copy(source.color);
  21255. this.map = source.map;
  21256. this.gradientMap = source.gradientMap;
  21257. this.lightMap = source.lightMap;
  21258. this.lightMapIntensity = source.lightMapIntensity;
  21259. this.aoMap = source.aoMap;
  21260. this.aoMapIntensity = source.aoMapIntensity;
  21261. this.emissive.copy(source.emissive);
  21262. this.emissiveMap = source.emissiveMap;
  21263. this.emissiveIntensity = source.emissiveIntensity;
  21264. this.bumpMap = source.bumpMap;
  21265. this.bumpScale = source.bumpScale;
  21266. this.normalMap = source.normalMap;
  21267. this.normalMapType = source.normalMapType;
  21268. this.normalScale.copy(source.normalScale);
  21269. this.displacementMap = source.displacementMap;
  21270. this.displacementScale = source.displacementScale;
  21271. this.displacementBias = source.displacementBias;
  21272. this.alphaMap = source.alphaMap;
  21273. this.wireframe = source.wireframe;
  21274. this.wireframeLinewidth = source.wireframeLinewidth;
  21275. this.wireframeLinecap = source.wireframeLinecap;
  21276. this.wireframeLinejoin = source.wireframeLinejoin;
  21277. return this;
  21278. }
  21279. }
  21280. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  21281. /**
  21282. * parameters = {
  21283. * opacity: <float>,
  21284. *
  21285. * bumpMap: new THREE.Texture( <Image> ),
  21286. * bumpScale: <float>,
  21287. *
  21288. * normalMap: new THREE.Texture( <Image> ),
  21289. * normalMapType: THREE.TangentSpaceNormalMap,
  21290. * normalScale: <Vector2>,
  21291. *
  21292. * displacementMap: new THREE.Texture( <Image> ),
  21293. * displacementScale: <float>,
  21294. * displacementBias: <float>,
  21295. *
  21296. * wireframe: <boolean>,
  21297. * wireframeLinewidth: <float>
  21298. *
  21299. * flatShading: <bool>
  21300. * }
  21301. */
  21302. class MeshNormalMaterial extends Material {
  21303. constructor(parameters) {
  21304. super();
  21305. this.type = 'MeshNormalMaterial';
  21306. this.bumpMap = null;
  21307. this.bumpScale = 1;
  21308. this.normalMap = null;
  21309. this.normalMapType = TangentSpaceNormalMap;
  21310. this.normalScale = new Vector2(1, 1);
  21311. this.displacementMap = null;
  21312. this.displacementScale = 1;
  21313. this.displacementBias = 0;
  21314. this.wireframe = false;
  21315. this.wireframeLinewidth = 1;
  21316. this.fog = false;
  21317. this.flatShading = false;
  21318. this.setValues(parameters);
  21319. }
  21320. copy(source) {
  21321. super.copy(source);
  21322. this.bumpMap = source.bumpMap;
  21323. this.bumpScale = source.bumpScale;
  21324. this.normalMap = source.normalMap;
  21325. this.normalMapType = source.normalMapType;
  21326. this.normalScale.copy(source.normalScale);
  21327. this.displacementMap = source.displacementMap;
  21328. this.displacementScale = source.displacementScale;
  21329. this.displacementBias = source.displacementBias;
  21330. this.wireframe = source.wireframe;
  21331. this.wireframeLinewidth = source.wireframeLinewidth;
  21332. this.flatShading = source.flatShading;
  21333. return this;
  21334. }
  21335. }
  21336. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  21337. /**
  21338. * parameters = {
  21339. * color: <hex>,
  21340. * opacity: <float>,
  21341. *
  21342. * map: new THREE.Texture( <Image> ),
  21343. *
  21344. * lightMap: new THREE.Texture( <Image> ),
  21345. * lightMapIntensity: <float>
  21346. *
  21347. * aoMap: new THREE.Texture( <Image> ),
  21348. * aoMapIntensity: <float>
  21349. *
  21350. * emissive: <hex>,
  21351. * emissiveIntensity: <float>
  21352. * emissiveMap: new THREE.Texture( <Image> ),
  21353. *
  21354. * specularMap: new THREE.Texture( <Image> ),
  21355. *
  21356. * alphaMap: new THREE.Texture( <Image> ),
  21357. *
  21358. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21359. * combine: THREE.Multiply,
  21360. * reflectivity: <float>,
  21361. * refractionRatio: <float>,
  21362. *
  21363. * wireframe: <boolean>,
  21364. * wireframeLinewidth: <float>,
  21365. *
  21366. * }
  21367. */
  21368. class MeshLambertMaterial extends Material {
  21369. constructor(parameters) {
  21370. super();
  21371. this.type = 'MeshLambertMaterial';
  21372. this.color = new Color(0xffffff); // diffuse
  21373. this.map = null;
  21374. this.lightMap = null;
  21375. this.lightMapIntensity = 1.0;
  21376. this.aoMap = null;
  21377. this.aoMapIntensity = 1.0;
  21378. this.emissive = new Color(0x000000);
  21379. this.emissiveIntensity = 1.0;
  21380. this.emissiveMap = null;
  21381. this.specularMap = null;
  21382. this.alphaMap = null;
  21383. this.envMap = null;
  21384. this.combine = MultiplyOperation;
  21385. this.reflectivity = 1;
  21386. this.refractionRatio = 0.98;
  21387. this.wireframe = false;
  21388. this.wireframeLinewidth = 1;
  21389. this.wireframeLinecap = 'round';
  21390. this.wireframeLinejoin = 'round';
  21391. this.setValues(parameters);
  21392. }
  21393. copy(source) {
  21394. super.copy(source);
  21395. this.color.copy(source.color);
  21396. this.map = source.map;
  21397. this.lightMap = source.lightMap;
  21398. this.lightMapIntensity = source.lightMapIntensity;
  21399. this.aoMap = source.aoMap;
  21400. this.aoMapIntensity = source.aoMapIntensity;
  21401. this.emissive.copy(source.emissive);
  21402. this.emissiveMap = source.emissiveMap;
  21403. this.emissiveIntensity = source.emissiveIntensity;
  21404. this.specularMap = source.specularMap;
  21405. this.alphaMap = source.alphaMap;
  21406. this.envMap = source.envMap;
  21407. this.combine = source.combine;
  21408. this.reflectivity = source.reflectivity;
  21409. this.refractionRatio = source.refractionRatio;
  21410. this.wireframe = source.wireframe;
  21411. this.wireframeLinewidth = source.wireframeLinewidth;
  21412. this.wireframeLinecap = source.wireframeLinecap;
  21413. this.wireframeLinejoin = source.wireframeLinejoin;
  21414. return this;
  21415. }
  21416. }
  21417. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  21418. /**
  21419. * parameters = {
  21420. * color: <hex>,
  21421. * opacity: <float>,
  21422. *
  21423. * matcap: new THREE.Texture( <Image> ),
  21424. *
  21425. * map: new THREE.Texture( <Image> ),
  21426. *
  21427. * bumpMap: new THREE.Texture( <Image> ),
  21428. * bumpScale: <float>,
  21429. *
  21430. * normalMap: new THREE.Texture( <Image> ),
  21431. * normalMapType: THREE.TangentSpaceNormalMap,
  21432. * normalScale: <Vector2>,
  21433. *
  21434. * displacementMap: new THREE.Texture( <Image> ),
  21435. * displacementScale: <float>,
  21436. * displacementBias: <float>,
  21437. *
  21438. * alphaMap: new THREE.Texture( <Image> ),
  21439. *
  21440. * flatShading: <bool>
  21441. * }
  21442. */
  21443. class MeshMatcapMaterial extends Material {
  21444. constructor(parameters) {
  21445. super();
  21446. this.defines = {
  21447. 'MATCAP': ''
  21448. };
  21449. this.type = 'MeshMatcapMaterial';
  21450. this.color = new Color(0xffffff); // diffuse
  21451. this.matcap = null;
  21452. this.map = null;
  21453. this.bumpMap = null;
  21454. this.bumpScale = 1;
  21455. this.normalMap = null;
  21456. this.normalMapType = TangentSpaceNormalMap;
  21457. this.normalScale = new Vector2(1, 1);
  21458. this.displacementMap = null;
  21459. this.displacementScale = 1;
  21460. this.displacementBias = 0;
  21461. this.alphaMap = null;
  21462. this.flatShading = false;
  21463. this.setValues(parameters);
  21464. }
  21465. copy(source) {
  21466. super.copy(source);
  21467. this.defines = {
  21468. 'MATCAP': ''
  21469. };
  21470. this.color.copy(source.color);
  21471. this.matcap = source.matcap;
  21472. this.map = source.map;
  21473. this.bumpMap = source.bumpMap;
  21474. this.bumpScale = source.bumpScale;
  21475. this.normalMap = source.normalMap;
  21476. this.normalMapType = source.normalMapType;
  21477. this.normalScale.copy(source.normalScale);
  21478. this.displacementMap = source.displacementMap;
  21479. this.displacementScale = source.displacementScale;
  21480. this.displacementBias = source.displacementBias;
  21481. this.alphaMap = source.alphaMap;
  21482. this.flatShading = source.flatShading;
  21483. return this;
  21484. }
  21485. }
  21486. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  21487. /**
  21488. * parameters = {
  21489. * color: <hex>,
  21490. * opacity: <float>,
  21491. *
  21492. * linewidth: <float>,
  21493. *
  21494. * scale: <float>,
  21495. * dashSize: <float>,
  21496. * gapSize: <float>
  21497. * }
  21498. */
  21499. class LineDashedMaterial extends LineBasicMaterial {
  21500. constructor(parameters) {
  21501. super();
  21502. this.type = 'LineDashedMaterial';
  21503. this.scale = 1;
  21504. this.dashSize = 3;
  21505. this.gapSize = 1;
  21506. this.setValues(parameters);
  21507. }
  21508. copy(source) {
  21509. super.copy(source);
  21510. this.scale = source.scale;
  21511. this.dashSize = source.dashSize;
  21512. this.gapSize = source.gapSize;
  21513. return this;
  21514. }
  21515. }
  21516. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  21517. var Materials = /*#__PURE__*/Object.freeze({
  21518. __proto__: null,
  21519. ShadowMaterial: ShadowMaterial,
  21520. SpriteMaterial: SpriteMaterial,
  21521. RawShaderMaterial: RawShaderMaterial,
  21522. ShaderMaterial: ShaderMaterial,
  21523. PointsMaterial: PointsMaterial,
  21524. MeshPhysicalMaterial: MeshPhysicalMaterial,
  21525. MeshStandardMaterial: MeshStandardMaterial,
  21526. MeshPhongMaterial: MeshPhongMaterial,
  21527. MeshToonMaterial: MeshToonMaterial,
  21528. MeshNormalMaterial: MeshNormalMaterial,
  21529. MeshLambertMaterial: MeshLambertMaterial,
  21530. MeshDepthMaterial: MeshDepthMaterial,
  21531. MeshDistanceMaterial: MeshDistanceMaterial,
  21532. MeshBasicMaterial: MeshBasicMaterial,
  21533. MeshMatcapMaterial: MeshMatcapMaterial,
  21534. LineDashedMaterial: LineDashedMaterial,
  21535. LineBasicMaterial: LineBasicMaterial,
  21536. Material: Material
  21537. });
  21538. const AnimationUtils = {
  21539. // same as Array.prototype.slice, but also works on typed arrays
  21540. arraySlice: function (array, from, to) {
  21541. if (AnimationUtils.isTypedArray(array)) {
  21542. // in ios9 array.subarray(from, undefined) will return empty array
  21543. // but array.subarray(from) or array.subarray(from, len) is correct
  21544. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  21545. }
  21546. return array.slice(from, to);
  21547. },
  21548. // converts an array to a specific type
  21549. convertArray: function (array, type, forceClone) {
  21550. if (!array || // let 'undefined' and 'null' pass
  21551. !forceClone && array.constructor === type) return array;
  21552. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  21553. return new type(array); // create typed array
  21554. }
  21555. return Array.prototype.slice.call(array); // create Array
  21556. },
  21557. isTypedArray: function (object) {
  21558. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  21559. },
  21560. // returns an array by which times and values can be sorted
  21561. getKeyframeOrder: function (times) {
  21562. function compareTime(i, j) {
  21563. return times[i] - times[j];
  21564. }
  21565. const n = times.length;
  21566. const result = new Array(n);
  21567. for (let i = 0; i !== n; ++i) result[i] = i;
  21568. result.sort(compareTime);
  21569. return result;
  21570. },
  21571. // uses the array previously returned by 'getKeyframeOrder' to sort data
  21572. sortedArray: function (values, stride, order) {
  21573. const nValues = values.length;
  21574. const result = new values.constructor(nValues);
  21575. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  21576. const srcOffset = order[i] * stride;
  21577. for (let j = 0; j !== stride; ++j) {
  21578. result[dstOffset++] = values[srcOffset + j];
  21579. }
  21580. }
  21581. return result;
  21582. },
  21583. // function for parsing AOS keyframe formats
  21584. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  21585. let i = 1,
  21586. key = jsonKeys[0];
  21587. while (key !== undefined && key[valuePropertyName] === undefined) {
  21588. key = jsonKeys[i++];
  21589. }
  21590. if (key === undefined) return; // no data
  21591. let value = key[valuePropertyName];
  21592. if (value === undefined) return; // no data
  21593. if (Array.isArray(value)) {
  21594. do {
  21595. value = key[valuePropertyName];
  21596. if (value !== undefined) {
  21597. times.push(key.time);
  21598. values.push.apply(values, value); // push all elements
  21599. }
  21600. key = jsonKeys[i++];
  21601. } while (key !== undefined);
  21602. } else if (value.toArray !== undefined) {
  21603. // ...assume THREE.Math-ish
  21604. do {
  21605. value = key[valuePropertyName];
  21606. if (value !== undefined) {
  21607. times.push(key.time);
  21608. value.toArray(values, values.length);
  21609. }
  21610. key = jsonKeys[i++];
  21611. } while (key !== undefined);
  21612. } else {
  21613. // otherwise push as-is
  21614. do {
  21615. value = key[valuePropertyName];
  21616. if (value !== undefined) {
  21617. times.push(key.time);
  21618. values.push(value);
  21619. }
  21620. key = jsonKeys[i++];
  21621. } while (key !== undefined);
  21622. }
  21623. },
  21624. subclip: function (sourceClip, name, startFrame, endFrame, fps = 30) {
  21625. const clip = sourceClip.clone();
  21626. clip.name = name;
  21627. const tracks = [];
  21628. for (let i = 0; i < clip.tracks.length; ++i) {
  21629. const track = clip.tracks[i];
  21630. const valueSize = track.getValueSize();
  21631. const times = [];
  21632. const values = [];
  21633. for (let j = 0; j < track.times.length; ++j) {
  21634. const frame = track.times[j] * fps;
  21635. if (frame < startFrame || frame >= endFrame) continue;
  21636. times.push(track.times[j]);
  21637. for (let k = 0; k < valueSize; ++k) {
  21638. values.push(track.values[j * valueSize + k]);
  21639. }
  21640. }
  21641. if (times.length === 0) continue;
  21642. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  21643. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  21644. tracks.push(track);
  21645. }
  21646. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  21647. let minStartTime = Infinity;
  21648. for (let i = 0; i < clip.tracks.length; ++i) {
  21649. if (minStartTime > clip.tracks[i].times[0]) {
  21650. minStartTime = clip.tracks[i].times[0];
  21651. }
  21652. } // shift all tracks such that clip begins at t=0
  21653. for (let i = 0; i < clip.tracks.length; ++i) {
  21654. clip.tracks[i].shift(-1 * minStartTime);
  21655. }
  21656. clip.resetDuration();
  21657. return clip;
  21658. },
  21659. makeClipAdditive: function (targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  21660. if (fps <= 0) fps = 30;
  21661. const numTracks = referenceClip.tracks.length;
  21662. const referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  21663. for (let i = 0; i < numTracks; ++i) {
  21664. const referenceTrack = referenceClip.tracks[i];
  21665. const referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  21666. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue; // Find the track in the target clip whose name and type matches the reference track
  21667. const targetTrack = targetClip.tracks.find(function (track) {
  21668. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  21669. });
  21670. if (targetTrack === undefined) continue;
  21671. let referenceOffset = 0;
  21672. const referenceValueSize = referenceTrack.getValueSize();
  21673. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  21674. referenceOffset = referenceValueSize / 3;
  21675. }
  21676. let targetOffset = 0;
  21677. const targetValueSize = targetTrack.getValueSize();
  21678. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  21679. targetOffset = targetValueSize / 3;
  21680. }
  21681. const lastIndex = referenceTrack.times.length - 1;
  21682. let referenceValue; // Find the value to subtract out of the track
  21683. if (referenceTime <= referenceTrack.times[0]) {
  21684. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  21685. const startIndex = referenceOffset;
  21686. const endIndex = referenceValueSize - referenceOffset;
  21687. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  21688. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  21689. // Reference frame is after the last keyframe, so just use the last keyframe
  21690. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  21691. const endIndex = startIndex + referenceValueSize - referenceOffset;
  21692. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  21693. } else {
  21694. // Interpolate to the reference value
  21695. const interpolant = referenceTrack.createInterpolant();
  21696. const startIndex = referenceOffset;
  21697. const endIndex = referenceValueSize - referenceOffset;
  21698. interpolant.evaluate(referenceTime);
  21699. referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  21700. } // Conjugate the quaternion
  21701. if (referenceTrackType === 'quaternion') {
  21702. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  21703. referenceQuat.toArray(referenceValue);
  21704. } // Subtract the reference value from all of the track values
  21705. const numTimes = targetTrack.times.length;
  21706. for (let j = 0; j < numTimes; ++j) {
  21707. const valueStart = j * targetValueSize + targetOffset;
  21708. if (referenceTrackType === 'quaternion') {
  21709. // Multiply the conjugate for quaternion track types
  21710. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  21711. } else {
  21712. const valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  21713. for (let k = 0; k < valueEnd; ++k) {
  21714. targetTrack.values[valueStart + k] -= referenceValue[k];
  21715. }
  21716. }
  21717. }
  21718. }
  21719. targetClip.blendMode = AdditiveAnimationBlendMode;
  21720. return targetClip;
  21721. }
  21722. };
  21723. /**
  21724. * Abstract base class of interpolants over parametric samples.
  21725. *
  21726. * The parameter domain is one dimensional, typically the time or a path
  21727. * along a curve defined by the data.
  21728. *
  21729. * The sample values can have any dimensionality and derived classes may
  21730. * apply special interpretations to the data.
  21731. *
  21732. * This class provides the interval seek in a Template Method, deferring
  21733. * the actual interpolation to derived classes.
  21734. *
  21735. * Time complexity is O(1) for linear access crossing at most two points
  21736. * and O(log N) for random access, where N is the number of positions.
  21737. *
  21738. * References:
  21739. *
  21740. * http://www.oodesign.com/template-method-pattern.html
  21741. *
  21742. */
  21743. class Interpolant {
  21744. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21745. this.parameterPositions = parameterPositions;
  21746. this._cachedIndex = 0;
  21747. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  21748. this.sampleValues = sampleValues;
  21749. this.valueSize = sampleSize;
  21750. this.settings = null;
  21751. this.DefaultSettings_ = {};
  21752. }
  21753. evaluate(t) {
  21754. const pp = this.parameterPositions;
  21755. let i1 = this._cachedIndex,
  21756. t1 = pp[i1],
  21757. t0 = pp[i1 - 1];
  21758. validate_interval: {
  21759. seek: {
  21760. let right;
  21761. linear_scan: {
  21762. //- See http://jsperf.com/comparison-to-undefined/3
  21763. //- slower code:
  21764. //-
  21765. //- if ( t >= t1 || t1 === undefined ) {
  21766. forward_scan: if (!(t < t1)) {
  21767. for (let giveUpAt = i1 + 2;;) {
  21768. if (t1 === undefined) {
  21769. if (t < t0) break forward_scan; // after end
  21770. i1 = pp.length;
  21771. this._cachedIndex = i1;
  21772. return this.afterEnd_(i1 - 1, t, t0);
  21773. }
  21774. if (i1 === giveUpAt) break; // this loop
  21775. t0 = t1;
  21776. t1 = pp[++i1];
  21777. if (t < t1) {
  21778. // we have arrived at the sought interval
  21779. break seek;
  21780. }
  21781. } // prepare binary search on the right side of the index
  21782. right = pp.length;
  21783. break linear_scan;
  21784. } //- slower code:
  21785. //- if ( t < t0 || t0 === undefined ) {
  21786. if (!(t >= t0)) {
  21787. // looping?
  21788. const t1global = pp[1];
  21789. if (t < t1global) {
  21790. i1 = 2; // + 1, using the scan for the details
  21791. t0 = t1global;
  21792. } // linear reverse scan
  21793. for (let giveUpAt = i1 - 2;;) {
  21794. if (t0 === undefined) {
  21795. // before start
  21796. this._cachedIndex = 0;
  21797. return this.beforeStart_(0, t, t1);
  21798. }
  21799. if (i1 === giveUpAt) break; // this loop
  21800. t1 = t0;
  21801. t0 = pp[--i1 - 1];
  21802. if (t >= t0) {
  21803. // we have arrived at the sought interval
  21804. break seek;
  21805. }
  21806. } // prepare binary search on the left side of the index
  21807. right = i1;
  21808. i1 = 0;
  21809. break linear_scan;
  21810. } // the interval is valid
  21811. break validate_interval;
  21812. } // linear scan
  21813. // binary search
  21814. while (i1 < right) {
  21815. const mid = i1 + right >>> 1;
  21816. if (t < pp[mid]) {
  21817. right = mid;
  21818. } else {
  21819. i1 = mid + 1;
  21820. }
  21821. }
  21822. t1 = pp[i1];
  21823. t0 = pp[i1 - 1]; // check boundary cases, again
  21824. if (t0 === undefined) {
  21825. this._cachedIndex = 0;
  21826. return this.beforeStart_(0, t, t1);
  21827. }
  21828. if (t1 === undefined) {
  21829. i1 = pp.length;
  21830. this._cachedIndex = i1;
  21831. return this.afterEnd_(i1 - 1, t0, t);
  21832. }
  21833. } // seek
  21834. this._cachedIndex = i1;
  21835. this.intervalChanged_(i1, t0, t1);
  21836. } // validate_interval
  21837. return this.interpolate_(i1, t0, t, t1);
  21838. }
  21839. getSettings_() {
  21840. return this.settings || this.DefaultSettings_;
  21841. }
  21842. copySampleValue_(index) {
  21843. // copies a sample value to the result buffer
  21844. const result = this.resultBuffer,
  21845. values = this.sampleValues,
  21846. stride = this.valueSize,
  21847. offset = index * stride;
  21848. for (let i = 0; i !== stride; ++i) {
  21849. result[i] = values[offset + i];
  21850. }
  21851. return result;
  21852. } // Template methods for derived classes:
  21853. interpolate_() {
  21854. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  21855. }
  21856. intervalChanged_() {// empty
  21857. }
  21858. } // ALIAS DEFINITIONS
  21859. Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
  21860. Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
  21861. /**
  21862. * Fast and simple cubic spline interpolant.
  21863. *
  21864. * It was derived from a Hermitian construction setting the first derivative
  21865. * at each sample position to the linear slope between neighboring positions
  21866. * over their parameter interval.
  21867. */
  21868. class CubicInterpolant extends Interpolant {
  21869. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21870. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  21871. this._weightPrev = -0;
  21872. this._offsetPrev = -0;
  21873. this._weightNext = -0;
  21874. this._offsetNext = -0;
  21875. this.DefaultSettings_ = {
  21876. endingStart: ZeroCurvatureEnding,
  21877. endingEnd: ZeroCurvatureEnding
  21878. };
  21879. }
  21880. intervalChanged_(i1, t0, t1) {
  21881. const pp = this.parameterPositions;
  21882. let iPrev = i1 - 2,
  21883. iNext = i1 + 1,
  21884. tPrev = pp[iPrev],
  21885. tNext = pp[iNext];
  21886. if (tPrev === undefined) {
  21887. switch (this.getSettings_().endingStart) {
  21888. case ZeroSlopeEnding:
  21889. // f'(t0) = 0
  21890. iPrev = i1;
  21891. tPrev = 2 * t0 - t1;
  21892. break;
  21893. case WrapAroundEnding:
  21894. // use the other end of the curve
  21895. iPrev = pp.length - 2;
  21896. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  21897. break;
  21898. default:
  21899. // ZeroCurvatureEnding
  21900. // f''(t0) = 0 a.k.a. Natural Spline
  21901. iPrev = i1;
  21902. tPrev = t1;
  21903. }
  21904. }
  21905. if (tNext === undefined) {
  21906. switch (this.getSettings_().endingEnd) {
  21907. case ZeroSlopeEnding:
  21908. // f'(tN) = 0
  21909. iNext = i1;
  21910. tNext = 2 * t1 - t0;
  21911. break;
  21912. case WrapAroundEnding:
  21913. // use the other end of the curve
  21914. iNext = 1;
  21915. tNext = t1 + pp[1] - pp[0];
  21916. break;
  21917. default:
  21918. // ZeroCurvatureEnding
  21919. // f''(tN) = 0, a.k.a. Natural Spline
  21920. iNext = i1 - 1;
  21921. tNext = t0;
  21922. }
  21923. }
  21924. const halfDt = (t1 - t0) * 0.5,
  21925. stride = this.valueSize;
  21926. this._weightPrev = halfDt / (t0 - tPrev);
  21927. this._weightNext = halfDt / (tNext - t1);
  21928. this._offsetPrev = iPrev * stride;
  21929. this._offsetNext = iNext * stride;
  21930. }
  21931. interpolate_(i1, t0, t, t1) {
  21932. const result = this.resultBuffer,
  21933. values = this.sampleValues,
  21934. stride = this.valueSize,
  21935. o1 = i1 * stride,
  21936. o0 = o1 - stride,
  21937. oP = this._offsetPrev,
  21938. oN = this._offsetNext,
  21939. wP = this._weightPrev,
  21940. wN = this._weightNext,
  21941. p = (t - t0) / (t1 - t0),
  21942. pp = p * p,
  21943. ppp = pp * p; // evaluate polynomials
  21944. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  21945. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  21946. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  21947. const sN = wN * ppp - wN * pp; // combine data linearly
  21948. for (let i = 0; i !== stride; ++i) {
  21949. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  21950. }
  21951. return result;
  21952. }
  21953. }
  21954. class LinearInterpolant extends Interpolant {
  21955. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21956. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  21957. }
  21958. interpolate_(i1, t0, t, t1) {
  21959. const result = this.resultBuffer,
  21960. values = this.sampleValues,
  21961. stride = this.valueSize,
  21962. offset1 = i1 * stride,
  21963. offset0 = offset1 - stride,
  21964. weight1 = (t - t0) / (t1 - t0),
  21965. weight0 = 1 - weight1;
  21966. for (let i = 0; i !== stride; ++i) {
  21967. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  21968. }
  21969. return result;
  21970. }
  21971. }
  21972. /**
  21973. *
  21974. * Interpolant that evaluates to the sample value at the position preceeding
  21975. * the parameter.
  21976. */
  21977. class DiscreteInterpolant extends Interpolant {
  21978. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21979. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  21980. }
  21981. interpolate_(i1
  21982. /*, t0, t, t1 */
  21983. ) {
  21984. return this.copySampleValue_(i1 - 1);
  21985. }
  21986. }
  21987. class KeyframeTrack {
  21988. constructor(name, times, values, interpolation) {
  21989. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  21990. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  21991. this.name = name;
  21992. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  21993. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  21994. this.setInterpolation(interpolation || this.DefaultInterpolation);
  21995. } // Serialization (in static context, because of constructor invocation
  21996. // and automatic invocation of .toJSON):
  21997. static toJSON(track) {
  21998. const trackType = track.constructor;
  21999. let json; // derived classes can define a static toJSON method
  22000. if (trackType.toJSON !== this.toJSON) {
  22001. json = trackType.toJSON(track);
  22002. } else {
  22003. // by default, we assume the data can be serialized as-is
  22004. json = {
  22005. 'name': track.name,
  22006. 'times': AnimationUtils.convertArray(track.times, Array),
  22007. 'values': AnimationUtils.convertArray(track.values, Array)
  22008. };
  22009. const interpolation = track.getInterpolation();
  22010. if (interpolation !== track.DefaultInterpolation) {
  22011. json.interpolation = interpolation;
  22012. }
  22013. }
  22014. json.type = track.ValueTypeName; // mandatory
  22015. return json;
  22016. }
  22017. InterpolantFactoryMethodDiscrete(result) {
  22018. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  22019. }
  22020. InterpolantFactoryMethodLinear(result) {
  22021. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  22022. }
  22023. InterpolantFactoryMethodSmooth(result) {
  22024. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  22025. }
  22026. setInterpolation(interpolation) {
  22027. let factoryMethod;
  22028. switch (interpolation) {
  22029. case InterpolateDiscrete:
  22030. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  22031. break;
  22032. case InterpolateLinear:
  22033. factoryMethod = this.InterpolantFactoryMethodLinear;
  22034. break;
  22035. case InterpolateSmooth:
  22036. factoryMethod = this.InterpolantFactoryMethodSmooth;
  22037. break;
  22038. }
  22039. if (factoryMethod === undefined) {
  22040. const message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
  22041. if (this.createInterpolant === undefined) {
  22042. // fall back to default, unless the default itself is messed up
  22043. if (interpolation !== this.DefaultInterpolation) {
  22044. this.setInterpolation(this.DefaultInterpolation);
  22045. } else {
  22046. throw new Error(message); // fatal, in this case
  22047. }
  22048. }
  22049. console.warn('THREE.KeyframeTrack:', message);
  22050. return this;
  22051. }
  22052. this.createInterpolant = factoryMethod;
  22053. return this;
  22054. }
  22055. getInterpolation() {
  22056. switch (this.createInterpolant) {
  22057. case this.InterpolantFactoryMethodDiscrete:
  22058. return InterpolateDiscrete;
  22059. case this.InterpolantFactoryMethodLinear:
  22060. return InterpolateLinear;
  22061. case this.InterpolantFactoryMethodSmooth:
  22062. return InterpolateSmooth;
  22063. }
  22064. }
  22065. getValueSize() {
  22066. return this.values.length / this.times.length;
  22067. } // move all keyframes either forwards or backwards in time
  22068. shift(timeOffset) {
  22069. if (timeOffset !== 0.0) {
  22070. const times = this.times;
  22071. for (let i = 0, n = times.length; i !== n; ++i) {
  22072. times[i] += timeOffset;
  22073. }
  22074. }
  22075. return this;
  22076. } // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  22077. scale(timeScale) {
  22078. if (timeScale !== 1.0) {
  22079. const times = this.times;
  22080. for (let i = 0, n = times.length; i !== n; ++i) {
  22081. times[i] *= timeScale;
  22082. }
  22083. }
  22084. return this;
  22085. } // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  22086. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  22087. trim(startTime, endTime) {
  22088. const times = this.times,
  22089. nKeys = times.length;
  22090. let from = 0,
  22091. to = nKeys - 1;
  22092. while (from !== nKeys && times[from] < startTime) {
  22093. ++from;
  22094. }
  22095. while (to !== -1 && times[to] > endTime) {
  22096. --to;
  22097. }
  22098. ++to; // inclusive -> exclusive bound
  22099. if (from !== 0 || to !== nKeys) {
  22100. // empty tracks are forbidden, so keep at least one keyframe
  22101. if (from >= to) {
  22102. to = Math.max(to, 1);
  22103. from = to - 1;
  22104. }
  22105. const stride = this.getValueSize();
  22106. this.times = AnimationUtils.arraySlice(times, from, to);
  22107. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  22108. }
  22109. return this;
  22110. } // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  22111. validate() {
  22112. let valid = true;
  22113. const valueSize = this.getValueSize();
  22114. if (valueSize - Math.floor(valueSize) !== 0) {
  22115. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  22116. valid = false;
  22117. }
  22118. const times = this.times,
  22119. values = this.values,
  22120. nKeys = times.length;
  22121. if (nKeys === 0) {
  22122. console.error('THREE.KeyframeTrack: Track is empty.', this);
  22123. valid = false;
  22124. }
  22125. let prevTime = null;
  22126. for (let i = 0; i !== nKeys; i++) {
  22127. const currTime = times[i];
  22128. if (typeof currTime === 'number' && isNaN(currTime)) {
  22129. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  22130. valid = false;
  22131. break;
  22132. }
  22133. if (prevTime !== null && prevTime > currTime) {
  22134. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  22135. valid = false;
  22136. break;
  22137. }
  22138. prevTime = currTime;
  22139. }
  22140. if (values !== undefined) {
  22141. if (AnimationUtils.isTypedArray(values)) {
  22142. for (let i = 0, n = values.length; i !== n; ++i) {
  22143. const value = values[i];
  22144. if (isNaN(value)) {
  22145. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  22146. valid = false;
  22147. break;
  22148. }
  22149. }
  22150. }
  22151. }
  22152. return valid;
  22153. } // removes equivalent sequential keys as common in morph target sequences
  22154. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  22155. optimize() {
  22156. // times or values may be shared with other tracks, so overwriting is unsafe
  22157. const times = AnimationUtils.arraySlice(this.times),
  22158. values = AnimationUtils.arraySlice(this.values),
  22159. stride = this.getValueSize(),
  22160. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  22161. lastIndex = times.length - 1;
  22162. let writeIndex = 1;
  22163. for (let i = 1; i < lastIndex; ++i) {
  22164. let keep = false;
  22165. const time = times[i];
  22166. const timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  22167. if (time !== timeNext && (i !== 1 || time !== times[0])) {
  22168. if (!smoothInterpolation) {
  22169. // remove unnecessary keyframes same as their neighbors
  22170. const offset = i * stride,
  22171. offsetP = offset - stride,
  22172. offsetN = offset + stride;
  22173. for (let j = 0; j !== stride; ++j) {
  22174. const value = values[offset + j];
  22175. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  22176. keep = true;
  22177. break;
  22178. }
  22179. }
  22180. } else {
  22181. keep = true;
  22182. }
  22183. } // in-place compaction
  22184. if (keep) {
  22185. if (i !== writeIndex) {
  22186. times[writeIndex] = times[i];
  22187. const readOffset = i * stride,
  22188. writeOffset = writeIndex * stride;
  22189. for (let j = 0; j !== stride; ++j) {
  22190. values[writeOffset + j] = values[readOffset + j];
  22191. }
  22192. }
  22193. ++writeIndex;
  22194. }
  22195. } // flush last keyframe (compaction looks ahead)
  22196. if (lastIndex > 0) {
  22197. times[writeIndex] = times[lastIndex];
  22198. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  22199. values[writeOffset + j] = values[readOffset + j];
  22200. }
  22201. ++writeIndex;
  22202. }
  22203. if (writeIndex !== times.length) {
  22204. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  22205. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  22206. } else {
  22207. this.times = times;
  22208. this.values = values;
  22209. }
  22210. return this;
  22211. }
  22212. clone() {
  22213. const times = AnimationUtils.arraySlice(this.times, 0);
  22214. const values = AnimationUtils.arraySlice(this.values, 0);
  22215. const TypedKeyframeTrack = this.constructor;
  22216. const track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  22217. track.createInterpolant = this.createInterpolant;
  22218. return track;
  22219. }
  22220. }
  22221. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  22222. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  22223. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22224. /**
  22225. * A Track of Boolean keyframe values.
  22226. */
  22227. class BooleanKeyframeTrack extends KeyframeTrack {}
  22228. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  22229. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  22230. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22231. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22232. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; // Note: Actually this track could have a optimized / compressed
  22233. /**
  22234. * A Track of keyframe values that represent color.
  22235. */
  22236. class ColorKeyframeTrack extends KeyframeTrack {}
  22237. ColorKeyframeTrack.prototype.ValueTypeName = 'color'; // ValueBufferType is inherited
  22238. /**
  22239. * A Track of numeric keyframe values.
  22240. */
  22241. class NumberKeyframeTrack extends KeyframeTrack {}
  22242. NumberKeyframeTrack.prototype.ValueTypeName = 'number'; // ValueBufferType is inherited
  22243. /**
  22244. * Spherical linear unit quaternion interpolant.
  22245. */
  22246. class QuaternionLinearInterpolant extends Interpolant {
  22247. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22248. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22249. }
  22250. interpolate_(i1, t0, t, t1) {
  22251. const result = this.resultBuffer,
  22252. values = this.sampleValues,
  22253. stride = this.valueSize,
  22254. alpha = (t - t0) / (t1 - t0);
  22255. let offset = i1 * stride;
  22256. for (let end = offset + stride; offset !== end; offset += 4) {
  22257. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  22258. }
  22259. return result;
  22260. }
  22261. }
  22262. /**
  22263. * A Track of quaternion keyframe values.
  22264. */
  22265. class QuaternionKeyframeTrack extends KeyframeTrack {
  22266. InterpolantFactoryMethodLinear(result) {
  22267. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  22268. }
  22269. }
  22270. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; // ValueBufferType is inherited
  22271. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22272. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22273. /**
  22274. * A Track that interpolates Strings
  22275. */
  22276. class StringKeyframeTrack extends KeyframeTrack {}
  22277. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  22278. StringKeyframeTrack.prototype.ValueBufferType = Array;
  22279. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22280. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22281. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22282. /**
  22283. * A Track of vectored keyframe values.
  22284. */
  22285. class VectorKeyframeTrack extends KeyframeTrack {}
  22286. VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; // ValueBufferType is inherited
  22287. class AnimationClip {
  22288. constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) {
  22289. this.name = name;
  22290. this.tracks = tracks;
  22291. this.duration = duration;
  22292. this.blendMode = blendMode;
  22293. this.uuid = generateUUID(); // this means it should figure out its duration by scanning the tracks
  22294. if (this.duration < 0) {
  22295. this.resetDuration();
  22296. }
  22297. }
  22298. static parse(json) {
  22299. const tracks = [],
  22300. jsonTracks = json.tracks,
  22301. frameTime = 1.0 / (json.fps || 1.0);
  22302. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  22303. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  22304. }
  22305. const clip = new this(json.name, json.duration, tracks, json.blendMode);
  22306. clip.uuid = json.uuid;
  22307. return clip;
  22308. }
  22309. static toJSON(clip) {
  22310. const tracks = [],
  22311. clipTracks = clip.tracks;
  22312. const json = {
  22313. 'name': clip.name,
  22314. 'duration': clip.duration,
  22315. 'tracks': tracks,
  22316. 'uuid': clip.uuid,
  22317. 'blendMode': clip.blendMode
  22318. };
  22319. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  22320. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  22321. }
  22322. return json;
  22323. }
  22324. static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  22325. const numMorphTargets = morphTargetSequence.length;
  22326. const tracks = [];
  22327. for (let i = 0; i < numMorphTargets; i++) {
  22328. let times = [];
  22329. let values = [];
  22330. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  22331. values.push(0, 1, 0);
  22332. const order = AnimationUtils.getKeyframeOrder(times);
  22333. times = AnimationUtils.sortedArray(times, 1, order);
  22334. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  22335. // last frame as well for perfect loop.
  22336. if (!noLoop && times[0] === 0) {
  22337. times.push(numMorphTargets);
  22338. values.push(values[0]);
  22339. }
  22340. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  22341. }
  22342. return new this(name, -1, tracks);
  22343. }
  22344. static findByName(objectOrClipArray, name) {
  22345. let clipArray = objectOrClipArray;
  22346. if (!Array.isArray(objectOrClipArray)) {
  22347. const o = objectOrClipArray;
  22348. clipArray = o.geometry && o.geometry.animations || o.animations;
  22349. }
  22350. for (let i = 0; i < clipArray.length; i++) {
  22351. if (clipArray[i].name === name) {
  22352. return clipArray[i];
  22353. }
  22354. }
  22355. return null;
  22356. }
  22357. static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  22358. const animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  22359. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22360. const pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  22361. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22362. for (let i = 0, il = morphTargets.length; i < il; i++) {
  22363. const morphTarget = morphTargets[i];
  22364. const parts = morphTarget.name.match(pattern);
  22365. if (parts && parts.length > 1) {
  22366. const name = parts[1];
  22367. let animationMorphTargets = animationToMorphTargets[name];
  22368. if (!animationMorphTargets) {
  22369. animationToMorphTargets[name] = animationMorphTargets = [];
  22370. }
  22371. animationMorphTargets.push(morphTarget);
  22372. }
  22373. }
  22374. const clips = [];
  22375. for (const name in animationToMorphTargets) {
  22376. clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  22377. }
  22378. return clips;
  22379. } // parse the animation.hierarchy format
  22380. static parseAnimation(animation, bones) {
  22381. if (!animation) {
  22382. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  22383. return null;
  22384. }
  22385. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  22386. // only return track if there are actually keys.
  22387. if (animationKeys.length !== 0) {
  22388. const times = [];
  22389. const values = [];
  22390. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  22391. if (times.length !== 0) {
  22392. destTracks.push(new trackType(trackName, times, values));
  22393. }
  22394. }
  22395. };
  22396. const tracks = [];
  22397. const clipName = animation.name || 'default';
  22398. const fps = animation.fps || 30;
  22399. const blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  22400. let duration = animation.length || -1;
  22401. const hierarchyTracks = animation.hierarchy || [];
  22402. for (let h = 0; h < hierarchyTracks.length; h++) {
  22403. const animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  22404. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  22405. if (animationKeys[0].morphTargets) {
  22406. // figure out all morph targets used in this track
  22407. const morphTargetNames = {};
  22408. let k;
  22409. for (k = 0; k < animationKeys.length; k++) {
  22410. if (animationKeys[k].morphTargets) {
  22411. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  22412. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  22413. }
  22414. }
  22415. } // create a track for each morph target with all zero
  22416. // morphTargetInfluences except for the keys in which
  22417. // the morphTarget is named.
  22418. for (const morphTargetName in morphTargetNames) {
  22419. const times = [];
  22420. const values = [];
  22421. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  22422. const animationKey = animationKeys[k];
  22423. times.push(animationKey.time);
  22424. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  22425. }
  22426. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  22427. }
  22428. duration = morphTargetNames.length * (fps || 1.0);
  22429. } else {
  22430. // ...assume skeletal animation
  22431. const boneName = '.bones[' + bones[h].name + ']';
  22432. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  22433. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  22434. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  22435. }
  22436. }
  22437. if (tracks.length === 0) {
  22438. return null;
  22439. }
  22440. const clip = new this(clipName, duration, tracks, blendMode);
  22441. return clip;
  22442. }
  22443. resetDuration() {
  22444. const tracks = this.tracks;
  22445. let duration = 0;
  22446. for (let i = 0, n = tracks.length; i !== n; ++i) {
  22447. const track = this.tracks[i];
  22448. duration = Math.max(duration, track.times[track.times.length - 1]);
  22449. }
  22450. this.duration = duration;
  22451. return this;
  22452. }
  22453. trim() {
  22454. for (let i = 0; i < this.tracks.length; i++) {
  22455. this.tracks[i].trim(0, this.duration);
  22456. }
  22457. return this;
  22458. }
  22459. validate() {
  22460. let valid = true;
  22461. for (let i = 0; i < this.tracks.length; i++) {
  22462. valid = valid && this.tracks[i].validate();
  22463. }
  22464. return valid;
  22465. }
  22466. optimize() {
  22467. for (let i = 0; i < this.tracks.length; i++) {
  22468. this.tracks[i].optimize();
  22469. }
  22470. return this;
  22471. }
  22472. clone() {
  22473. const tracks = [];
  22474. for (let i = 0; i < this.tracks.length; i++) {
  22475. tracks.push(this.tracks[i].clone());
  22476. }
  22477. return new this.constructor(this.name, this.duration, tracks, this.blendMode);
  22478. }
  22479. toJSON() {
  22480. return this.constructor.toJSON(this);
  22481. }
  22482. }
  22483. function getTrackTypeForValueTypeName(typeName) {
  22484. switch (typeName.toLowerCase()) {
  22485. case 'scalar':
  22486. case 'double':
  22487. case 'float':
  22488. case 'number':
  22489. case 'integer':
  22490. return NumberKeyframeTrack;
  22491. case 'vector':
  22492. case 'vector2':
  22493. case 'vector3':
  22494. case 'vector4':
  22495. return VectorKeyframeTrack;
  22496. case 'color':
  22497. return ColorKeyframeTrack;
  22498. case 'quaternion':
  22499. return QuaternionKeyframeTrack;
  22500. case 'bool':
  22501. case 'boolean':
  22502. return BooleanKeyframeTrack;
  22503. case 'string':
  22504. return StringKeyframeTrack;
  22505. }
  22506. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  22507. }
  22508. function parseKeyframeTrack(json) {
  22509. if (json.type === undefined) {
  22510. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  22511. }
  22512. const trackType = getTrackTypeForValueTypeName(json.type);
  22513. if (json.times === undefined) {
  22514. const times = [],
  22515. values = [];
  22516. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  22517. json.times = times;
  22518. json.values = values;
  22519. } // derived classes can define a static parse method
  22520. if (trackType.parse !== undefined) {
  22521. return trackType.parse(json);
  22522. } else {
  22523. // by default, we assume a constructor compatible with the base
  22524. return new trackType(json.name, json.times, json.values, json.interpolation);
  22525. }
  22526. }
  22527. const Cache = {
  22528. enabled: false,
  22529. files: {},
  22530. add: function (key, file) {
  22531. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  22532. this.files[key] = file;
  22533. },
  22534. get: function (key) {
  22535. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  22536. return this.files[key];
  22537. },
  22538. remove: function (key) {
  22539. delete this.files[key];
  22540. },
  22541. clear: function () {
  22542. this.files = {};
  22543. }
  22544. };
  22545. class LoadingManager {
  22546. constructor(onLoad, onProgress, onError) {
  22547. const scope = this;
  22548. let isLoading = false;
  22549. let itemsLoaded = 0;
  22550. let itemsTotal = 0;
  22551. let urlModifier = undefined;
  22552. const handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  22553. // in the constructor
  22554. this.onStart = undefined;
  22555. this.onLoad = onLoad;
  22556. this.onProgress = onProgress;
  22557. this.onError = onError;
  22558. this.itemStart = function (url) {
  22559. itemsTotal++;
  22560. if (isLoading === false) {
  22561. if (scope.onStart !== undefined) {
  22562. scope.onStart(url, itemsLoaded, itemsTotal);
  22563. }
  22564. }
  22565. isLoading = true;
  22566. };
  22567. this.itemEnd = function (url) {
  22568. itemsLoaded++;
  22569. if (scope.onProgress !== undefined) {
  22570. scope.onProgress(url, itemsLoaded, itemsTotal);
  22571. }
  22572. if (itemsLoaded === itemsTotal) {
  22573. isLoading = false;
  22574. if (scope.onLoad !== undefined) {
  22575. scope.onLoad();
  22576. }
  22577. }
  22578. };
  22579. this.itemError = function (url) {
  22580. if (scope.onError !== undefined) {
  22581. scope.onError(url);
  22582. }
  22583. };
  22584. this.resolveURL = function (url) {
  22585. if (urlModifier) {
  22586. return urlModifier(url);
  22587. }
  22588. return url;
  22589. };
  22590. this.setURLModifier = function (transform) {
  22591. urlModifier = transform;
  22592. return this;
  22593. };
  22594. this.addHandler = function (regex, loader) {
  22595. handlers.push(regex, loader);
  22596. return this;
  22597. };
  22598. this.removeHandler = function (regex) {
  22599. const index = handlers.indexOf(regex);
  22600. if (index !== -1) {
  22601. handlers.splice(index, 2);
  22602. }
  22603. return this;
  22604. };
  22605. this.getHandler = function (file) {
  22606. for (let i = 0, l = handlers.length; i < l; i += 2) {
  22607. const regex = handlers[i];
  22608. const loader = handlers[i + 1];
  22609. if (regex.global) regex.lastIndex = 0; // see #17920
  22610. if (regex.test(file)) {
  22611. return loader;
  22612. }
  22613. }
  22614. return null;
  22615. };
  22616. }
  22617. }
  22618. const DefaultLoadingManager = new LoadingManager();
  22619. class Loader {
  22620. constructor(manager) {
  22621. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  22622. this.crossOrigin = 'anonymous';
  22623. this.withCredentials = false;
  22624. this.path = '';
  22625. this.resourcePath = '';
  22626. this.requestHeader = {};
  22627. }
  22628. load() {}
  22629. loadAsync(url, onProgress) {
  22630. const scope = this;
  22631. return new Promise(function (resolve, reject) {
  22632. scope.load(url, resolve, onProgress, reject);
  22633. });
  22634. }
  22635. parse() {}
  22636. setCrossOrigin(crossOrigin) {
  22637. this.crossOrigin = crossOrigin;
  22638. return this;
  22639. }
  22640. setWithCredentials(value) {
  22641. this.withCredentials = value;
  22642. return this;
  22643. }
  22644. setPath(path) {
  22645. this.path = path;
  22646. return this;
  22647. }
  22648. setResourcePath(resourcePath) {
  22649. this.resourcePath = resourcePath;
  22650. return this;
  22651. }
  22652. setRequestHeader(requestHeader) {
  22653. this.requestHeader = requestHeader;
  22654. return this;
  22655. }
  22656. }
  22657. const loading = {};
  22658. class FileLoader extends Loader {
  22659. constructor(manager) {
  22660. super(manager);
  22661. }
  22662. load(url, onLoad, onProgress, onError) {
  22663. if (url === undefined) url = '';
  22664. if (this.path !== undefined) url = this.path + url;
  22665. url = this.manager.resolveURL(url);
  22666. const scope = this;
  22667. const cached = Cache.get(url);
  22668. if (cached !== undefined) {
  22669. scope.manager.itemStart(url);
  22670. setTimeout(function () {
  22671. if (onLoad) onLoad(cached);
  22672. scope.manager.itemEnd(url);
  22673. }, 0);
  22674. return cached;
  22675. } // Check if request is duplicate
  22676. if (loading[url] !== undefined) {
  22677. loading[url].push({
  22678. onLoad: onLoad,
  22679. onProgress: onProgress,
  22680. onError: onError
  22681. });
  22682. return;
  22683. } // Check for data: URI
  22684. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  22685. const dataUriRegexResult = url.match(dataUriRegex);
  22686. let request; // Safari can not handle Data URIs through XMLHttpRequest so process manually
  22687. if (dataUriRegexResult) {
  22688. const mimeType = dataUriRegexResult[1];
  22689. const isBase64 = !!dataUriRegexResult[2];
  22690. let data = dataUriRegexResult[3];
  22691. data = decodeURIComponent(data);
  22692. if (isBase64) data = atob(data);
  22693. try {
  22694. let response;
  22695. const responseType = (this.responseType || '').toLowerCase();
  22696. switch (responseType) {
  22697. case 'arraybuffer':
  22698. case 'blob':
  22699. const view = new Uint8Array(data.length);
  22700. for (let i = 0; i < data.length; i++) {
  22701. view[i] = data.charCodeAt(i);
  22702. }
  22703. if (responseType === 'blob') {
  22704. response = new Blob([view.buffer], {
  22705. type: mimeType
  22706. });
  22707. } else {
  22708. response = view.buffer;
  22709. }
  22710. break;
  22711. case 'document':
  22712. const parser = new DOMParser();
  22713. response = parser.parseFromString(data, mimeType);
  22714. break;
  22715. case 'json':
  22716. response = JSON.parse(data);
  22717. break;
  22718. default:
  22719. // 'text' or other
  22720. response = data;
  22721. break;
  22722. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22723. setTimeout(function () {
  22724. if (onLoad) onLoad(response);
  22725. scope.manager.itemEnd(url);
  22726. }, 0);
  22727. } catch (error) {
  22728. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22729. setTimeout(function () {
  22730. if (onError) onError(error);
  22731. scope.manager.itemError(url);
  22732. scope.manager.itemEnd(url);
  22733. }, 0);
  22734. }
  22735. } else {
  22736. // Initialise array for duplicate requests
  22737. loading[url] = [];
  22738. loading[url].push({
  22739. onLoad: onLoad,
  22740. onProgress: onProgress,
  22741. onError: onError
  22742. });
  22743. request = new XMLHttpRequest();
  22744. request.open('GET', url, true);
  22745. request.addEventListener('load', function (event) {
  22746. const response = this.response;
  22747. const callbacks = loading[url];
  22748. delete loading[url];
  22749. if (this.status === 200 || this.status === 0) {
  22750. // Some browsers return HTTP Status 0 when using non-http protocol
  22751. // e.g. 'file://' or 'data://'. Handle as success.
  22752. 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
  22753. // error response bodies as proper responses to requests.
  22754. Cache.add(url, response);
  22755. for (let i = 0, il = callbacks.length; i < il; i++) {
  22756. const callback = callbacks[i];
  22757. if (callback.onLoad) callback.onLoad(response);
  22758. }
  22759. scope.manager.itemEnd(url);
  22760. } else {
  22761. for (let i = 0, il = callbacks.length; i < il; i++) {
  22762. const callback = callbacks[i];
  22763. if (callback.onError) callback.onError(event);
  22764. }
  22765. scope.manager.itemError(url);
  22766. scope.manager.itemEnd(url);
  22767. }
  22768. }, false);
  22769. request.addEventListener('progress', function (event) {
  22770. const callbacks = loading[url];
  22771. for (let i = 0, il = callbacks.length; i < il; i++) {
  22772. const callback = callbacks[i];
  22773. if (callback.onProgress) callback.onProgress(event);
  22774. }
  22775. }, false);
  22776. request.addEventListener('error', function (event) {
  22777. const callbacks = loading[url];
  22778. delete loading[url];
  22779. for (let i = 0, il = callbacks.length; i < il; i++) {
  22780. const callback = callbacks[i];
  22781. if (callback.onError) callback.onError(event);
  22782. }
  22783. scope.manager.itemError(url);
  22784. scope.manager.itemEnd(url);
  22785. }, false);
  22786. request.addEventListener('abort', function (event) {
  22787. const callbacks = loading[url];
  22788. delete loading[url];
  22789. for (let i = 0, il = callbacks.length; i < il; i++) {
  22790. const callback = callbacks[i];
  22791. if (callback.onError) callback.onError(event);
  22792. }
  22793. scope.manager.itemError(url);
  22794. scope.manager.itemEnd(url);
  22795. }, false);
  22796. if (this.responseType !== undefined) request.responseType = this.responseType;
  22797. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  22798. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  22799. for (const header in this.requestHeader) {
  22800. request.setRequestHeader(header, this.requestHeader[header]);
  22801. }
  22802. request.send(null);
  22803. }
  22804. scope.manager.itemStart(url);
  22805. return request;
  22806. }
  22807. setResponseType(value) {
  22808. this.responseType = value;
  22809. return this;
  22810. }
  22811. setMimeType(value) {
  22812. this.mimeType = value;
  22813. return this;
  22814. }
  22815. }
  22816. class AnimationLoader extends Loader {
  22817. constructor(manager) {
  22818. super(manager);
  22819. }
  22820. load(url, onLoad, onProgress, onError) {
  22821. const scope = this;
  22822. const loader = new FileLoader(this.manager);
  22823. loader.setPath(this.path);
  22824. loader.setRequestHeader(this.requestHeader);
  22825. loader.setWithCredentials(this.withCredentials);
  22826. loader.load(url, function (text) {
  22827. try {
  22828. onLoad(scope.parse(JSON.parse(text)));
  22829. } catch (e) {
  22830. if (onError) {
  22831. onError(e);
  22832. } else {
  22833. console.error(e);
  22834. }
  22835. scope.manager.itemError(url);
  22836. }
  22837. }, onProgress, onError);
  22838. }
  22839. parse(json) {
  22840. const animations = [];
  22841. for (let i = 0; i < json.length; i++) {
  22842. const clip = AnimationClip.parse(json[i]);
  22843. animations.push(clip);
  22844. }
  22845. return animations;
  22846. }
  22847. }
  22848. /**
  22849. * Abstract Base class to block based textures loader (dds, pvr, ...)
  22850. *
  22851. * Sub classes have to implement the parse() method which will be used in load().
  22852. */
  22853. class CompressedTextureLoader extends Loader {
  22854. constructor(manager) {
  22855. super(manager);
  22856. }
  22857. load(url, onLoad, onProgress, onError) {
  22858. const scope = this;
  22859. const images = [];
  22860. const texture = new CompressedTexture();
  22861. const loader = new FileLoader(this.manager);
  22862. loader.setPath(this.path);
  22863. loader.setResponseType('arraybuffer');
  22864. loader.setRequestHeader(this.requestHeader);
  22865. loader.setWithCredentials(scope.withCredentials);
  22866. let loaded = 0;
  22867. function loadTexture(i) {
  22868. loader.load(url[i], function (buffer) {
  22869. const texDatas = scope.parse(buffer, true);
  22870. images[i] = {
  22871. width: texDatas.width,
  22872. height: texDatas.height,
  22873. format: texDatas.format,
  22874. mipmaps: texDatas.mipmaps
  22875. };
  22876. loaded += 1;
  22877. if (loaded === 6) {
  22878. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  22879. texture.image = images;
  22880. texture.format = texDatas.format;
  22881. texture.needsUpdate = true;
  22882. if (onLoad) onLoad(texture);
  22883. }
  22884. }, onProgress, onError);
  22885. }
  22886. if (Array.isArray(url)) {
  22887. for (let i = 0, il = url.length; i < il; ++i) {
  22888. loadTexture(i);
  22889. }
  22890. } else {
  22891. // compressed cubemap texture stored in a single DDS file
  22892. loader.load(url, function (buffer) {
  22893. const texDatas = scope.parse(buffer, true);
  22894. if (texDatas.isCubemap) {
  22895. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  22896. for (let f = 0; f < faces; f++) {
  22897. images[f] = {
  22898. mipmaps: []
  22899. };
  22900. for (let i = 0; i < texDatas.mipmapCount; i++) {
  22901. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  22902. images[f].format = texDatas.format;
  22903. images[f].width = texDatas.width;
  22904. images[f].height = texDatas.height;
  22905. }
  22906. }
  22907. texture.image = images;
  22908. } else {
  22909. texture.image.width = texDatas.width;
  22910. texture.image.height = texDatas.height;
  22911. texture.mipmaps = texDatas.mipmaps;
  22912. }
  22913. if (texDatas.mipmapCount === 1) {
  22914. texture.minFilter = LinearFilter;
  22915. }
  22916. texture.format = texDatas.format;
  22917. texture.needsUpdate = true;
  22918. if (onLoad) onLoad(texture);
  22919. }, onProgress, onError);
  22920. }
  22921. return texture;
  22922. }
  22923. }
  22924. class ImageLoader extends Loader {
  22925. constructor(manager) {
  22926. super(manager);
  22927. }
  22928. load(url, onLoad, onProgress, onError) {
  22929. if (this.path !== undefined) url = this.path + url;
  22930. url = this.manager.resolveURL(url);
  22931. const scope = this;
  22932. const cached = Cache.get(url);
  22933. if (cached !== undefined) {
  22934. scope.manager.itemStart(url);
  22935. setTimeout(function () {
  22936. if (onLoad) onLoad(cached);
  22937. scope.manager.itemEnd(url);
  22938. }, 0);
  22939. return cached;
  22940. }
  22941. const image = createElementNS('img');
  22942. function onImageLoad() {
  22943. image.removeEventListener('load', onImageLoad, false);
  22944. image.removeEventListener('error', onImageError, false);
  22945. Cache.add(url, this);
  22946. if (onLoad) onLoad(this);
  22947. scope.manager.itemEnd(url);
  22948. }
  22949. function onImageError(event) {
  22950. image.removeEventListener('load', onImageLoad, false);
  22951. image.removeEventListener('error', onImageError, false);
  22952. if (onError) onError(event);
  22953. scope.manager.itemError(url);
  22954. scope.manager.itemEnd(url);
  22955. }
  22956. image.addEventListener('load', onImageLoad, false);
  22957. image.addEventListener('error', onImageError, false);
  22958. if (url.substr(0, 5) !== 'data:') {
  22959. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  22960. }
  22961. scope.manager.itemStart(url);
  22962. image.src = url;
  22963. return image;
  22964. }
  22965. }
  22966. class CubeTextureLoader extends Loader {
  22967. constructor(manager) {
  22968. super(manager);
  22969. }
  22970. load(urls, onLoad, onProgress, onError) {
  22971. const texture = new CubeTexture();
  22972. const loader = new ImageLoader(this.manager);
  22973. loader.setCrossOrigin(this.crossOrigin);
  22974. loader.setPath(this.path);
  22975. let loaded = 0;
  22976. function loadTexture(i) {
  22977. loader.load(urls[i], function (image) {
  22978. texture.images[i] = image;
  22979. loaded++;
  22980. if (loaded === 6) {
  22981. texture.needsUpdate = true;
  22982. if (onLoad) onLoad(texture);
  22983. }
  22984. }, undefined, onError);
  22985. }
  22986. for (let i = 0; i < urls.length; ++i) {
  22987. loadTexture(i);
  22988. }
  22989. return texture;
  22990. }
  22991. }
  22992. /**
  22993. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  22994. *
  22995. * Sub classes have to implement the parse() method which will be used in load().
  22996. */
  22997. class DataTextureLoader extends Loader {
  22998. constructor(manager) {
  22999. super(manager);
  23000. }
  23001. load(url, onLoad, onProgress, onError) {
  23002. const scope = this;
  23003. const texture = new DataTexture();
  23004. const loader = new FileLoader(this.manager);
  23005. loader.setResponseType('arraybuffer');
  23006. loader.setRequestHeader(this.requestHeader);
  23007. loader.setPath(this.path);
  23008. loader.setWithCredentials(scope.withCredentials);
  23009. loader.load(url, function (buffer) {
  23010. const texData = scope.parse(buffer);
  23011. if (!texData) return;
  23012. if (texData.image !== undefined) {
  23013. texture.image = texData.image;
  23014. } else if (texData.data !== undefined) {
  23015. texture.image.width = texData.width;
  23016. texture.image.height = texData.height;
  23017. texture.image.data = texData.data;
  23018. }
  23019. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  23020. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  23021. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  23022. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  23023. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  23024. if (texData.encoding !== undefined) {
  23025. texture.encoding = texData.encoding;
  23026. }
  23027. if (texData.flipY !== undefined) {
  23028. texture.flipY = texData.flipY;
  23029. }
  23030. if (texData.format !== undefined) {
  23031. texture.format = texData.format;
  23032. }
  23033. if (texData.type !== undefined) {
  23034. texture.type = texData.type;
  23035. }
  23036. if (texData.mipmaps !== undefined) {
  23037. texture.mipmaps = texData.mipmaps;
  23038. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  23039. }
  23040. if (texData.mipmapCount === 1) {
  23041. texture.minFilter = LinearFilter;
  23042. }
  23043. if (texData.generateMipmaps !== undefined) {
  23044. texture.generateMipmaps = texData.generateMipmaps;
  23045. }
  23046. texture.needsUpdate = true;
  23047. if (onLoad) onLoad(texture, texData);
  23048. }, onProgress, onError);
  23049. return texture;
  23050. }
  23051. }
  23052. class TextureLoader extends Loader {
  23053. constructor(manager) {
  23054. super(manager);
  23055. }
  23056. load(url, onLoad, onProgress, onError) {
  23057. const texture = new Texture();
  23058. const loader = new ImageLoader(this.manager);
  23059. loader.setCrossOrigin(this.crossOrigin);
  23060. loader.setPath(this.path);
  23061. loader.load(url, function (image) {
  23062. texture.image = image;
  23063. texture.needsUpdate = true;
  23064. if (onLoad !== undefined) {
  23065. onLoad(texture);
  23066. }
  23067. }, onProgress, onError);
  23068. return texture;
  23069. }
  23070. }
  23071. class Light extends Object3D {
  23072. constructor(color, intensity = 1) {
  23073. super();
  23074. this.type = 'Light';
  23075. this.color = new Color(color);
  23076. this.intensity = intensity;
  23077. }
  23078. dispose() {// Empty here in base class; some subclasses override.
  23079. }
  23080. copy(source) {
  23081. super.copy(source);
  23082. this.color.copy(source.color);
  23083. this.intensity = source.intensity;
  23084. return this;
  23085. }
  23086. toJSON(meta) {
  23087. const data = super.toJSON(meta);
  23088. data.object.color = this.color.getHex();
  23089. data.object.intensity = this.intensity;
  23090. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  23091. if (this.distance !== undefined) data.object.distance = this.distance;
  23092. if (this.angle !== undefined) data.object.angle = this.angle;
  23093. if (this.decay !== undefined) data.object.decay = this.decay;
  23094. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  23095. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  23096. return data;
  23097. }
  23098. }
  23099. Light.prototype.isLight = true;
  23100. class HemisphereLight extends Light {
  23101. constructor(skyColor, groundColor, intensity) {
  23102. super(skyColor, intensity);
  23103. this.type = 'HemisphereLight';
  23104. this.position.copy(Object3D.DefaultUp);
  23105. this.updateMatrix();
  23106. this.groundColor = new Color(groundColor);
  23107. }
  23108. copy(source) {
  23109. Light.prototype.copy.call(this, source);
  23110. this.groundColor.copy(source.groundColor);
  23111. return this;
  23112. }
  23113. }
  23114. HemisphereLight.prototype.isHemisphereLight = true;
  23115. const _projScreenMatrix$1 = /*@__PURE__*/new Matrix4();
  23116. const _lightPositionWorld$1 = /*@__PURE__*/new Vector3();
  23117. const _lookTarget$1 = /*@__PURE__*/new Vector3();
  23118. class LightShadow {
  23119. constructor(camera) {
  23120. this.camera = camera;
  23121. this.bias = 0;
  23122. this.normalBias = 0;
  23123. this.radius = 1;
  23124. this.blurSamples = 8;
  23125. this.mapSize = new Vector2(512, 512);
  23126. this.map = null;
  23127. this.mapPass = null;
  23128. this.matrix = new Matrix4();
  23129. this.autoUpdate = true;
  23130. this.needsUpdate = false;
  23131. this._frustum = new Frustum();
  23132. this._frameExtents = new Vector2(1, 1);
  23133. this._viewportCount = 1;
  23134. this._viewports = [new Vector4(0, 0, 1, 1)];
  23135. }
  23136. getViewportCount() {
  23137. return this._viewportCount;
  23138. }
  23139. getFrustum() {
  23140. return this._frustum;
  23141. }
  23142. updateMatrices(light) {
  23143. const shadowCamera = this.camera;
  23144. const shadowMatrix = this.matrix;
  23145. _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld);
  23146. shadowCamera.position.copy(_lightPositionWorld$1);
  23147. _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld);
  23148. shadowCamera.lookAt(_lookTarget$1);
  23149. shadowCamera.updateMatrixWorld();
  23150. _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  23151. this._frustum.setFromProjectionMatrix(_projScreenMatrix$1);
  23152. 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);
  23153. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  23154. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  23155. }
  23156. getViewport(viewportIndex) {
  23157. return this._viewports[viewportIndex];
  23158. }
  23159. getFrameExtents() {
  23160. return this._frameExtents;
  23161. }
  23162. dispose() {
  23163. if (this.map) {
  23164. this.map.dispose();
  23165. }
  23166. if (this.mapPass) {
  23167. this.mapPass.dispose();
  23168. }
  23169. }
  23170. copy(source) {
  23171. this.camera = source.camera.clone();
  23172. this.bias = source.bias;
  23173. this.radius = source.radius;
  23174. this.mapSize.copy(source.mapSize);
  23175. return this;
  23176. }
  23177. clone() {
  23178. return new this.constructor().copy(this);
  23179. }
  23180. toJSON() {
  23181. const object = {};
  23182. if (this.bias !== 0) object.bias = this.bias;
  23183. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  23184. if (this.radius !== 1) object.radius = this.radius;
  23185. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  23186. object.camera = this.camera.toJSON(false).object;
  23187. delete object.camera.matrix;
  23188. return object;
  23189. }
  23190. }
  23191. class SpotLightShadow extends LightShadow {
  23192. constructor() {
  23193. super(new PerspectiveCamera(50, 1, 0.5, 500));
  23194. this.focus = 1;
  23195. }
  23196. updateMatrices(light) {
  23197. const camera = this.camera;
  23198. const fov = RAD2DEG * 2 * light.angle * this.focus;
  23199. const aspect = this.mapSize.width / this.mapSize.height;
  23200. const far = light.distance || camera.far;
  23201. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  23202. camera.fov = fov;
  23203. camera.aspect = aspect;
  23204. camera.far = far;
  23205. camera.updateProjectionMatrix();
  23206. }
  23207. super.updateMatrices(light);
  23208. }
  23209. copy(source) {
  23210. super.copy(source);
  23211. this.focus = source.focus;
  23212. return this;
  23213. }
  23214. }
  23215. SpotLightShadow.prototype.isSpotLightShadow = true;
  23216. class SpotLight extends Light {
  23217. constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1) {
  23218. super(color, intensity);
  23219. this.type = 'SpotLight';
  23220. this.position.copy(Object3D.DefaultUp);
  23221. this.updateMatrix();
  23222. this.target = new Object3D();
  23223. this.distance = distance;
  23224. this.angle = angle;
  23225. this.penumbra = penumbra;
  23226. this.decay = decay; // for physically correct lights, should be 2.
  23227. this.shadow = new SpotLightShadow();
  23228. }
  23229. get power() {
  23230. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23231. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  23232. return this.intensity * Math.PI;
  23233. }
  23234. set power(power) {
  23235. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23236. this.intensity = power / Math.PI;
  23237. }
  23238. dispose() {
  23239. this.shadow.dispose();
  23240. }
  23241. copy(source) {
  23242. super.copy(source);
  23243. this.distance = source.distance;
  23244. this.angle = source.angle;
  23245. this.penumbra = source.penumbra;
  23246. this.decay = source.decay;
  23247. this.target = source.target.clone();
  23248. this.shadow = source.shadow.clone();
  23249. return this;
  23250. }
  23251. }
  23252. SpotLight.prototype.isSpotLight = true;
  23253. const _projScreenMatrix = /*@__PURE__*/new Matrix4();
  23254. const _lightPositionWorld = /*@__PURE__*/new Vector3();
  23255. const _lookTarget = /*@__PURE__*/new Vector3();
  23256. class PointLightShadow extends LightShadow {
  23257. constructor() {
  23258. super(new PerspectiveCamera(90, 1, 0.5, 500));
  23259. this._frameExtents = new Vector2(4, 2);
  23260. this._viewportCount = 6;
  23261. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  23262. // following orientation:
  23263. //
  23264. // xzXZ
  23265. // y Y
  23266. //
  23267. // X - Positive x direction
  23268. // x - Negative x direction
  23269. // Y - Positive y direction
  23270. // y - Negative y direction
  23271. // Z - Positive z direction
  23272. // z - Negative z direction
  23273. // positive X
  23274. new Vector4(2, 1, 1, 1), // negative X
  23275. new Vector4(0, 1, 1, 1), // positive Z
  23276. new Vector4(3, 1, 1, 1), // negative Z
  23277. new Vector4(1, 1, 1, 1), // positive Y
  23278. new Vector4(3, 0, 1, 1), // negative Y
  23279. new Vector4(1, 0, 1, 1)];
  23280. 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)];
  23281. 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)];
  23282. }
  23283. updateMatrices(light, viewportIndex = 0) {
  23284. const camera = this.camera;
  23285. const shadowMatrix = this.matrix;
  23286. const far = light.distance || camera.far;
  23287. if (far !== camera.far) {
  23288. camera.far = far;
  23289. camera.updateProjectionMatrix();
  23290. }
  23291. _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23292. camera.position.copy(_lightPositionWorld);
  23293. _lookTarget.copy(camera.position);
  23294. _lookTarget.add(this._cubeDirections[viewportIndex]);
  23295. camera.up.copy(this._cubeUps[viewportIndex]);
  23296. camera.lookAt(_lookTarget);
  23297. camera.updateMatrixWorld();
  23298. shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
  23299. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  23300. this._frustum.setFromProjectionMatrix(_projScreenMatrix);
  23301. }
  23302. }
  23303. PointLightShadow.prototype.isPointLightShadow = true;
  23304. class PointLight extends Light {
  23305. constructor(color, intensity, distance = 0, decay = 1) {
  23306. super(color, intensity);
  23307. this.type = 'PointLight';
  23308. this.distance = distance;
  23309. this.decay = decay; // for physically correct lights, should be 2.
  23310. this.shadow = new PointLightShadow();
  23311. }
  23312. get power() {
  23313. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23314. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  23315. return this.intensity * 4 * Math.PI;
  23316. }
  23317. set power(power) {
  23318. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23319. this.intensity = power / (4 * Math.PI);
  23320. }
  23321. dispose() {
  23322. this.shadow.dispose();
  23323. }
  23324. copy(source) {
  23325. super.copy(source);
  23326. this.distance = source.distance;
  23327. this.decay = source.decay;
  23328. this.shadow = source.shadow.clone();
  23329. return this;
  23330. }
  23331. }
  23332. PointLight.prototype.isPointLight = true;
  23333. class DirectionalLightShadow extends LightShadow {
  23334. constructor() {
  23335. super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  23336. }
  23337. }
  23338. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  23339. class DirectionalLight extends Light {
  23340. constructor(color, intensity) {
  23341. super(color, intensity);
  23342. this.type = 'DirectionalLight';
  23343. this.position.copy(Object3D.DefaultUp);
  23344. this.updateMatrix();
  23345. this.target = new Object3D();
  23346. this.shadow = new DirectionalLightShadow();
  23347. }
  23348. dispose() {
  23349. this.shadow.dispose();
  23350. }
  23351. copy(source) {
  23352. super.copy(source);
  23353. this.target = source.target.clone();
  23354. this.shadow = source.shadow.clone();
  23355. return this;
  23356. }
  23357. }
  23358. DirectionalLight.prototype.isDirectionalLight = true;
  23359. class AmbientLight extends Light {
  23360. constructor(color, intensity) {
  23361. super(color, intensity);
  23362. this.type = 'AmbientLight';
  23363. }
  23364. }
  23365. AmbientLight.prototype.isAmbientLight = true;
  23366. class RectAreaLight extends Light {
  23367. constructor(color, intensity, width = 10, height = 10) {
  23368. super(color, intensity);
  23369. this.type = 'RectAreaLight';
  23370. this.width = width;
  23371. this.height = height;
  23372. }
  23373. get power() {
  23374. // compute the light's luminous power (in lumens) from its intensity (in nits)
  23375. return this.intensity * this.width * this.height * Math.PI;
  23376. }
  23377. set power(power) {
  23378. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  23379. this.intensity = power / (this.width * this.height * Math.PI);
  23380. }
  23381. copy(source) {
  23382. super.copy(source);
  23383. this.width = source.width;
  23384. this.height = source.height;
  23385. return this;
  23386. }
  23387. toJSON(meta) {
  23388. const data = super.toJSON(meta);
  23389. data.object.width = this.width;
  23390. data.object.height = this.height;
  23391. return data;
  23392. }
  23393. }
  23394. RectAreaLight.prototype.isRectAreaLight = true;
  23395. /**
  23396. * Primary reference:
  23397. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23398. *
  23399. * Secondary reference:
  23400. * https://www.ppsloan.org/publications/StupidSH36.pdf
  23401. */
  23402. // 3-band SH defined by 9 coefficients
  23403. class SphericalHarmonics3 {
  23404. constructor() {
  23405. this.coefficients = [];
  23406. for (let i = 0; i < 9; i++) {
  23407. this.coefficients.push(new Vector3());
  23408. }
  23409. }
  23410. set(coefficients) {
  23411. for (let i = 0; i < 9; i++) {
  23412. this.coefficients[i].copy(coefficients[i]);
  23413. }
  23414. return this;
  23415. }
  23416. zero() {
  23417. for (let i = 0; i < 9; i++) {
  23418. this.coefficients[i].set(0, 0, 0);
  23419. }
  23420. return this;
  23421. } // get the radiance in the direction of the normal
  23422. // target is a Vector3
  23423. getAt(normal, target) {
  23424. // normal is assumed to be unit length
  23425. const x = normal.x,
  23426. y = normal.y,
  23427. z = normal.z;
  23428. const coeff = this.coefficients; // band 0
  23429. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  23430. target.addScaledVector(coeff[1], 0.488603 * y);
  23431. target.addScaledVector(coeff[2], 0.488603 * z);
  23432. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  23433. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  23434. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  23435. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  23436. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  23437. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  23438. return target;
  23439. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  23440. // target is a Vector3
  23441. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23442. getIrradianceAt(normal, target) {
  23443. // normal is assumed to be unit length
  23444. const x = normal.x,
  23445. y = normal.y,
  23446. z = normal.z;
  23447. const coeff = this.coefficients; // band 0
  23448. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  23449. // band 1
  23450. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  23451. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  23452. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  23453. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  23454. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  23455. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  23456. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  23457. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  23458. return target;
  23459. }
  23460. add(sh) {
  23461. for (let i = 0; i < 9; i++) {
  23462. this.coefficients[i].add(sh.coefficients[i]);
  23463. }
  23464. return this;
  23465. }
  23466. addScaledSH(sh, s) {
  23467. for (let i = 0; i < 9; i++) {
  23468. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  23469. }
  23470. return this;
  23471. }
  23472. scale(s) {
  23473. for (let i = 0; i < 9; i++) {
  23474. this.coefficients[i].multiplyScalar(s);
  23475. }
  23476. return this;
  23477. }
  23478. lerp(sh, alpha) {
  23479. for (let i = 0; i < 9; i++) {
  23480. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  23481. }
  23482. return this;
  23483. }
  23484. equals(sh) {
  23485. for (let i = 0; i < 9; i++) {
  23486. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  23487. return false;
  23488. }
  23489. }
  23490. return true;
  23491. }
  23492. copy(sh) {
  23493. return this.set(sh.coefficients);
  23494. }
  23495. clone() {
  23496. return new this.constructor().copy(this);
  23497. }
  23498. fromArray(array, offset = 0) {
  23499. const coefficients = this.coefficients;
  23500. for (let i = 0; i < 9; i++) {
  23501. coefficients[i].fromArray(array, offset + i * 3);
  23502. }
  23503. return this;
  23504. }
  23505. toArray(array = [], offset = 0) {
  23506. const coefficients = this.coefficients;
  23507. for (let i = 0; i < 9; i++) {
  23508. coefficients[i].toArray(array, offset + i * 3);
  23509. }
  23510. return array;
  23511. } // evaluate the basis functions
  23512. // shBasis is an Array[ 9 ]
  23513. static getBasisAt(normal, shBasis) {
  23514. // normal is assumed to be unit length
  23515. const x = normal.x,
  23516. y = normal.y,
  23517. z = normal.z; // band 0
  23518. shBasis[0] = 0.282095; // band 1
  23519. shBasis[1] = 0.488603 * y;
  23520. shBasis[2] = 0.488603 * z;
  23521. shBasis[3] = 0.488603 * x; // band 2
  23522. shBasis[4] = 1.092548 * x * y;
  23523. shBasis[5] = 1.092548 * y * z;
  23524. shBasis[6] = 0.315392 * (3 * z * z - 1);
  23525. shBasis[7] = 1.092548 * x * z;
  23526. shBasis[8] = 0.546274 * (x * x - y * y);
  23527. }
  23528. }
  23529. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  23530. class LightProbe extends Light {
  23531. constructor(sh = new SphericalHarmonics3(), intensity = 1) {
  23532. super(undefined, intensity);
  23533. this.sh = sh;
  23534. }
  23535. copy(source) {
  23536. super.copy(source);
  23537. this.sh.copy(source.sh);
  23538. return this;
  23539. }
  23540. fromJSON(json) {
  23541. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  23542. this.sh.fromArray(json.sh);
  23543. return this;
  23544. }
  23545. toJSON(meta) {
  23546. const data = super.toJSON(meta);
  23547. data.object.sh = this.sh.toArray();
  23548. return data;
  23549. }
  23550. }
  23551. LightProbe.prototype.isLightProbe = true;
  23552. class MaterialLoader extends Loader {
  23553. constructor(manager) {
  23554. super(manager);
  23555. this.textures = {};
  23556. }
  23557. load(url, onLoad, onProgress, onError) {
  23558. const scope = this;
  23559. const loader = new FileLoader(scope.manager);
  23560. loader.setPath(scope.path);
  23561. loader.setRequestHeader(scope.requestHeader);
  23562. loader.setWithCredentials(scope.withCredentials);
  23563. loader.load(url, function (text) {
  23564. try {
  23565. onLoad(scope.parse(JSON.parse(text)));
  23566. } catch (e) {
  23567. if (onError) {
  23568. onError(e);
  23569. } else {
  23570. console.error(e);
  23571. }
  23572. scope.manager.itemError(url);
  23573. }
  23574. }, onProgress, onError);
  23575. }
  23576. parse(json) {
  23577. const textures = this.textures;
  23578. function getTexture(name) {
  23579. if (textures[name] === undefined) {
  23580. console.warn('THREE.MaterialLoader: Undefined texture', name);
  23581. }
  23582. return textures[name];
  23583. }
  23584. const material = new Materials[json.type]();
  23585. if (json.uuid !== undefined) material.uuid = json.uuid;
  23586. if (json.name !== undefined) material.name = json.name;
  23587. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  23588. if (json.roughness !== undefined) material.roughness = json.roughness;
  23589. if (json.metalness !== undefined) material.metalness = json.metalness;
  23590. if (json.sheen !== undefined) material.sheen = json.sheen;
  23591. if (json.sheenTint !== undefined) material.sheenTint = new Color().setHex(json.sheenTint);
  23592. if (json.sheenRoughness !== undefined) material.sheenRoughness = json.sheenRoughness;
  23593. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  23594. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  23595. if (json.specularIntensity !== undefined) material.specularIntensity = json.specularIntensity;
  23596. if (json.specularTint !== undefined && material.specularTint !== undefined) material.specularTint.setHex(json.specularTint);
  23597. if (json.shininess !== undefined) material.shininess = json.shininess;
  23598. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  23599. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  23600. if (json.transmission !== undefined) material.transmission = json.transmission;
  23601. if (json.thickness !== undefined) material.thickness = json.thickness;
  23602. if (json.attenuationDistance !== undefined) material.attenuationDistance = json.attenuationDistance;
  23603. if (json.attenuationTint !== undefined && material.attenuationTint !== undefined) material.attenuationTint.setHex(json.attenuationTint);
  23604. if (json.fog !== undefined) material.fog = json.fog;
  23605. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  23606. if (json.blending !== undefined) material.blending = json.blending;
  23607. if (json.combine !== undefined) material.combine = json.combine;
  23608. if (json.side !== undefined) material.side = json.side;
  23609. if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
  23610. if (json.opacity !== undefined) material.opacity = json.opacity;
  23611. if (json.format !== undefined) material.format = json.format;
  23612. if (json.transparent !== undefined) material.transparent = json.transparent;
  23613. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  23614. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  23615. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  23616. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  23617. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  23618. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  23619. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  23620. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  23621. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  23622. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  23623. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  23624. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  23625. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  23626. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  23627. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  23628. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  23629. if (json.rotation !== undefined) material.rotation = json.rotation;
  23630. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  23631. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  23632. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  23633. if (json.scale !== undefined) material.scale = json.scale;
  23634. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  23635. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  23636. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  23637. if (json.dithering !== undefined) material.dithering = json.dithering;
  23638. if (json.alphaToCoverage !== undefined) material.alphaToCoverage = json.alphaToCoverage;
  23639. if (json.premultipliedAlpha !== undefined) material.premultipliedAlpha = json.premultipliedAlpha;
  23640. if (json.visible !== undefined) material.visible = json.visible;
  23641. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  23642. if (json.userData !== undefined) material.userData = json.userData;
  23643. if (json.vertexColors !== undefined) {
  23644. if (typeof json.vertexColors === 'number') {
  23645. material.vertexColors = json.vertexColors > 0 ? true : false;
  23646. } else {
  23647. material.vertexColors = json.vertexColors;
  23648. }
  23649. } // Shader Material
  23650. if (json.uniforms !== undefined) {
  23651. for (const name in json.uniforms) {
  23652. const uniform = json.uniforms[name];
  23653. material.uniforms[name] = {};
  23654. switch (uniform.type) {
  23655. case 't':
  23656. material.uniforms[name].value = getTexture(uniform.value);
  23657. break;
  23658. case 'c':
  23659. material.uniforms[name].value = new Color().setHex(uniform.value);
  23660. break;
  23661. case 'v2':
  23662. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  23663. break;
  23664. case 'v3':
  23665. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  23666. break;
  23667. case 'v4':
  23668. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  23669. break;
  23670. case 'm3':
  23671. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  23672. break;
  23673. case 'm4':
  23674. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  23675. break;
  23676. default:
  23677. material.uniforms[name].value = uniform.value;
  23678. }
  23679. }
  23680. }
  23681. if (json.defines !== undefined) material.defines = json.defines;
  23682. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  23683. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  23684. if (json.extensions !== undefined) {
  23685. for (const key in json.extensions) {
  23686. material.extensions[key] = json.extensions[key];
  23687. }
  23688. } // Deprecated
  23689. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  23690. // for PointsMaterial
  23691. if (json.size !== undefined) material.size = json.size;
  23692. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  23693. if (json.map !== undefined) material.map = getTexture(json.map);
  23694. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  23695. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  23696. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  23697. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  23698. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  23699. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  23700. if (json.normalScale !== undefined) {
  23701. let normalScale = json.normalScale;
  23702. if (Array.isArray(normalScale) === false) {
  23703. // Blender exporter used to export a scalar. See #7459
  23704. normalScale = [normalScale, normalScale];
  23705. }
  23706. material.normalScale = new Vector2().fromArray(normalScale);
  23707. }
  23708. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  23709. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  23710. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  23711. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  23712. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  23713. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  23714. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  23715. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  23716. if (json.specularIntensityMap !== undefined) material.specularIntensityMap = getTexture(json.specularIntensityMap);
  23717. if (json.specularTintMap !== undefined) material.specularTintMap = getTexture(json.specularTintMap);
  23718. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  23719. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  23720. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  23721. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  23722. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  23723. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  23724. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  23725. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  23726. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  23727. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  23728. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  23729. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  23730. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  23731. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  23732. if (json.thicknessMap !== undefined) material.thicknessMap = getTexture(json.thicknessMap);
  23733. return material;
  23734. }
  23735. setTextures(value) {
  23736. this.textures = value;
  23737. return this;
  23738. }
  23739. }
  23740. class LoaderUtils {
  23741. static decodeText(array) {
  23742. if (typeof TextDecoder !== 'undefined') {
  23743. return new TextDecoder().decode(array);
  23744. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  23745. // throws a "maximum call stack size exceeded" error for large arrays.
  23746. let s = '';
  23747. for (let i = 0, il = array.length; i < il; i++) {
  23748. // Implicitly assumes little-endian.
  23749. s += String.fromCharCode(array[i]);
  23750. }
  23751. try {
  23752. // merges multi-byte utf-8 characters.
  23753. return decodeURIComponent(escape(s));
  23754. } catch (e) {
  23755. // see #16358
  23756. return s;
  23757. }
  23758. }
  23759. static extractUrlBase(url) {
  23760. const index = url.lastIndexOf('/');
  23761. if (index === -1) return './';
  23762. return url.substr(0, index + 1);
  23763. }
  23764. }
  23765. class InstancedBufferGeometry extends BufferGeometry {
  23766. constructor() {
  23767. super();
  23768. this.type = 'InstancedBufferGeometry';
  23769. this.instanceCount = Infinity;
  23770. }
  23771. copy(source) {
  23772. super.copy(source);
  23773. this.instanceCount = source.instanceCount;
  23774. return this;
  23775. }
  23776. clone() {
  23777. return new this.constructor().copy(this);
  23778. }
  23779. toJSON() {
  23780. const data = super.toJSON(this);
  23781. data.instanceCount = this.instanceCount;
  23782. data.isInstancedBufferGeometry = true;
  23783. return data;
  23784. }
  23785. }
  23786. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  23787. class BufferGeometryLoader extends Loader {
  23788. constructor(manager) {
  23789. super(manager);
  23790. }
  23791. load(url, onLoad, onProgress, onError) {
  23792. const scope = this;
  23793. const loader = new FileLoader(scope.manager);
  23794. loader.setPath(scope.path);
  23795. loader.setRequestHeader(scope.requestHeader);
  23796. loader.setWithCredentials(scope.withCredentials);
  23797. loader.load(url, function (text) {
  23798. try {
  23799. onLoad(scope.parse(JSON.parse(text)));
  23800. } catch (e) {
  23801. if (onError) {
  23802. onError(e);
  23803. } else {
  23804. console.error(e);
  23805. }
  23806. scope.manager.itemError(url);
  23807. }
  23808. }, onProgress, onError);
  23809. }
  23810. parse(json) {
  23811. const interleavedBufferMap = {};
  23812. const arrayBufferMap = {};
  23813. function getInterleavedBuffer(json, uuid) {
  23814. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  23815. const interleavedBuffers = json.interleavedBuffers;
  23816. const interleavedBuffer = interleavedBuffers[uuid];
  23817. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  23818. const array = getTypedArray(interleavedBuffer.type, buffer);
  23819. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  23820. ib.uuid = interleavedBuffer.uuid;
  23821. interleavedBufferMap[uuid] = ib;
  23822. return ib;
  23823. }
  23824. function getArrayBuffer(json, uuid) {
  23825. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  23826. const arrayBuffers = json.arrayBuffers;
  23827. const arrayBuffer = arrayBuffers[uuid];
  23828. const ab = new Uint32Array(arrayBuffer).buffer;
  23829. arrayBufferMap[uuid] = ab;
  23830. return ab;
  23831. }
  23832. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  23833. const index = json.data.index;
  23834. if (index !== undefined) {
  23835. const typedArray = getTypedArray(index.type, index.array);
  23836. geometry.setIndex(new BufferAttribute(typedArray, 1));
  23837. }
  23838. const attributes = json.data.attributes;
  23839. for (const key in attributes) {
  23840. const attribute = attributes[key];
  23841. let bufferAttribute;
  23842. if (attribute.isInterleavedBufferAttribute) {
  23843. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  23844. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  23845. } else {
  23846. const typedArray = getTypedArray(attribute.type, attribute.array);
  23847. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  23848. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  23849. }
  23850. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  23851. if (attribute.usage !== undefined) bufferAttribute.setUsage(attribute.usage);
  23852. if (attribute.updateRange !== undefined) {
  23853. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  23854. bufferAttribute.updateRange.count = attribute.updateRange.count;
  23855. }
  23856. geometry.setAttribute(key, bufferAttribute);
  23857. }
  23858. const morphAttributes = json.data.morphAttributes;
  23859. if (morphAttributes) {
  23860. for (const key in morphAttributes) {
  23861. const attributeArray = morphAttributes[key];
  23862. const array = [];
  23863. for (let i = 0, il = attributeArray.length; i < il; i++) {
  23864. const attribute = attributeArray[i];
  23865. let bufferAttribute;
  23866. if (attribute.isInterleavedBufferAttribute) {
  23867. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  23868. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  23869. } else {
  23870. const typedArray = getTypedArray(attribute.type, attribute.array);
  23871. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  23872. }
  23873. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  23874. array.push(bufferAttribute);
  23875. }
  23876. geometry.morphAttributes[key] = array;
  23877. }
  23878. }
  23879. const morphTargetsRelative = json.data.morphTargetsRelative;
  23880. if (morphTargetsRelative) {
  23881. geometry.morphTargetsRelative = true;
  23882. }
  23883. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  23884. if (groups !== undefined) {
  23885. for (let i = 0, n = groups.length; i !== n; ++i) {
  23886. const group = groups[i];
  23887. geometry.addGroup(group.start, group.count, group.materialIndex);
  23888. }
  23889. }
  23890. const boundingSphere = json.data.boundingSphere;
  23891. if (boundingSphere !== undefined) {
  23892. const center = new Vector3();
  23893. if (boundingSphere.center !== undefined) {
  23894. center.fromArray(boundingSphere.center);
  23895. }
  23896. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  23897. }
  23898. if (json.name) geometry.name = json.name;
  23899. if (json.userData) geometry.userData = json.userData;
  23900. return geometry;
  23901. }
  23902. }
  23903. class ObjectLoader extends Loader {
  23904. constructor(manager) {
  23905. super(manager);
  23906. }
  23907. load(url, onLoad, onProgress, onError) {
  23908. const scope = this;
  23909. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  23910. this.resourcePath = this.resourcePath || path;
  23911. const loader = new FileLoader(this.manager);
  23912. loader.setPath(this.path);
  23913. loader.setRequestHeader(this.requestHeader);
  23914. loader.setWithCredentials(this.withCredentials);
  23915. loader.load(url, function (text) {
  23916. let json = null;
  23917. try {
  23918. json = JSON.parse(text);
  23919. } catch (error) {
  23920. if (onError !== undefined) onError(error);
  23921. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  23922. return;
  23923. }
  23924. const metadata = json.metadata;
  23925. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  23926. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  23927. return;
  23928. }
  23929. scope.parse(json, onLoad);
  23930. }, onProgress, onError);
  23931. }
  23932. async loadAsync(url, onProgress) {
  23933. const scope = this;
  23934. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  23935. this.resourcePath = this.resourcePath || path;
  23936. const loader = new FileLoader(this.manager);
  23937. loader.setPath(this.path);
  23938. loader.setRequestHeader(this.requestHeader);
  23939. loader.setWithCredentials(this.withCredentials);
  23940. const text = await loader.loadAsync(url, onProgress);
  23941. const json = JSON.parse(text);
  23942. const metadata = json.metadata;
  23943. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  23944. throw new Error('THREE.ObjectLoader: Can\'t load ' + url);
  23945. }
  23946. return await scope.parseAsync(json);
  23947. }
  23948. parse(json, onLoad) {
  23949. const animations = this.parseAnimations(json.animations);
  23950. const shapes = this.parseShapes(json.shapes);
  23951. const geometries = this.parseGeometries(json.geometries, shapes);
  23952. const images = this.parseImages(json.images, function () {
  23953. if (onLoad !== undefined) onLoad(object);
  23954. });
  23955. const textures = this.parseTextures(json.textures, images);
  23956. const materials = this.parseMaterials(json.materials, textures);
  23957. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  23958. const skeletons = this.parseSkeletons(json.skeletons, object);
  23959. this.bindSkeletons(object, skeletons); //
  23960. if (onLoad !== undefined) {
  23961. let hasImages = false;
  23962. for (const uuid in images) {
  23963. if (images[uuid] instanceof HTMLImageElement) {
  23964. hasImages = true;
  23965. break;
  23966. }
  23967. }
  23968. if (hasImages === false) onLoad(object);
  23969. }
  23970. return object;
  23971. }
  23972. async parseAsync(json) {
  23973. const animations = this.parseAnimations(json.animations);
  23974. const shapes = this.parseShapes(json.shapes);
  23975. const geometries = this.parseGeometries(json.geometries, shapes);
  23976. const images = await this.parseImagesAsync(json.images);
  23977. const textures = this.parseTextures(json.textures, images);
  23978. const materials = this.parseMaterials(json.materials, textures);
  23979. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  23980. const skeletons = this.parseSkeletons(json.skeletons, object);
  23981. this.bindSkeletons(object, skeletons);
  23982. return object;
  23983. }
  23984. parseShapes(json) {
  23985. const shapes = {};
  23986. if (json !== undefined) {
  23987. for (let i = 0, l = json.length; i < l; i++) {
  23988. const shape = new Shape().fromJSON(json[i]);
  23989. shapes[shape.uuid] = shape;
  23990. }
  23991. }
  23992. return shapes;
  23993. }
  23994. parseSkeletons(json, object) {
  23995. const skeletons = {};
  23996. const bones = {}; // generate bone lookup table
  23997. object.traverse(function (child) {
  23998. if (child.isBone) bones[child.uuid] = child;
  23999. }); // create skeletons
  24000. if (json !== undefined) {
  24001. for (let i = 0, l = json.length; i < l; i++) {
  24002. const skeleton = new Skeleton().fromJSON(json[i], bones);
  24003. skeletons[skeleton.uuid] = skeleton;
  24004. }
  24005. }
  24006. return skeletons;
  24007. }
  24008. parseGeometries(json, shapes) {
  24009. const geometries = {};
  24010. if (json !== undefined) {
  24011. const bufferGeometryLoader = new BufferGeometryLoader();
  24012. for (let i = 0, l = json.length; i < l; i++) {
  24013. let geometry;
  24014. const data = json[i];
  24015. switch (data.type) {
  24016. case 'BufferGeometry':
  24017. case 'InstancedBufferGeometry':
  24018. geometry = bufferGeometryLoader.parse(data);
  24019. break;
  24020. case 'Geometry':
  24021. console.error('THREE.ObjectLoader: The legacy Geometry type is no longer supported.');
  24022. break;
  24023. default:
  24024. if (data.type in Geometries) {
  24025. geometry = Geometries[data.type].fromJSON(data, shapes);
  24026. } else {
  24027. console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data.type}"`);
  24028. }
  24029. }
  24030. geometry.uuid = data.uuid;
  24031. if (data.name !== undefined) geometry.name = data.name;
  24032. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  24033. geometries[data.uuid] = geometry;
  24034. }
  24035. }
  24036. return geometries;
  24037. }
  24038. parseMaterials(json, textures) {
  24039. const cache = {}; // MultiMaterial
  24040. const materials = {};
  24041. if (json !== undefined) {
  24042. const loader = new MaterialLoader();
  24043. loader.setTextures(textures);
  24044. for (let i = 0, l = json.length; i < l; i++) {
  24045. const data = json[i];
  24046. if (data.type === 'MultiMaterial') {
  24047. // Deprecated
  24048. const array = [];
  24049. for (let j = 0; j < data.materials.length; j++) {
  24050. const material = data.materials[j];
  24051. if (cache[material.uuid] === undefined) {
  24052. cache[material.uuid] = loader.parse(material);
  24053. }
  24054. array.push(cache[material.uuid]);
  24055. }
  24056. materials[data.uuid] = array;
  24057. } else {
  24058. if (cache[data.uuid] === undefined) {
  24059. cache[data.uuid] = loader.parse(data);
  24060. }
  24061. materials[data.uuid] = cache[data.uuid];
  24062. }
  24063. }
  24064. }
  24065. return materials;
  24066. }
  24067. parseAnimations(json) {
  24068. const animations = {};
  24069. if (json !== undefined) {
  24070. for (let i = 0; i < json.length; i++) {
  24071. const data = json[i];
  24072. const clip = AnimationClip.parse(data);
  24073. animations[clip.uuid] = clip;
  24074. }
  24075. }
  24076. return animations;
  24077. }
  24078. parseImages(json, onLoad) {
  24079. const scope = this;
  24080. const images = {};
  24081. let loader;
  24082. function loadImage(url) {
  24083. scope.manager.itemStart(url);
  24084. return loader.load(url, function () {
  24085. scope.manager.itemEnd(url);
  24086. }, undefined, function () {
  24087. scope.manager.itemError(url);
  24088. scope.manager.itemEnd(url);
  24089. });
  24090. }
  24091. function deserializeImage(image) {
  24092. if (typeof image === 'string') {
  24093. const url = image;
  24094. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24095. return loadImage(path);
  24096. } else {
  24097. if (image.data) {
  24098. return {
  24099. data: getTypedArray(image.type, image.data),
  24100. width: image.width,
  24101. height: image.height
  24102. };
  24103. } else {
  24104. return null;
  24105. }
  24106. }
  24107. }
  24108. if (json !== undefined && json.length > 0) {
  24109. const manager = new LoadingManager(onLoad);
  24110. loader = new ImageLoader(manager);
  24111. loader.setCrossOrigin(this.crossOrigin);
  24112. for (let i = 0, il = json.length; i < il; i++) {
  24113. const image = json[i];
  24114. const url = image.url;
  24115. if (Array.isArray(url)) {
  24116. // load array of images e.g CubeTexture
  24117. images[image.uuid] = [];
  24118. for (let j = 0, jl = url.length; j < jl; j++) {
  24119. const currentUrl = url[j];
  24120. const deserializedImage = deserializeImage(currentUrl);
  24121. if (deserializedImage !== null) {
  24122. if (deserializedImage instanceof HTMLImageElement) {
  24123. images[image.uuid].push(deserializedImage);
  24124. } else {
  24125. // special case: handle array of data textures for cube textures
  24126. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24127. }
  24128. }
  24129. }
  24130. } else {
  24131. // load single image
  24132. const deserializedImage = deserializeImage(image.url);
  24133. if (deserializedImage !== null) {
  24134. images[image.uuid] = deserializedImage;
  24135. }
  24136. }
  24137. }
  24138. }
  24139. return images;
  24140. }
  24141. async parseImagesAsync(json) {
  24142. const scope = this;
  24143. const images = {};
  24144. let loader;
  24145. async function deserializeImage(image) {
  24146. if (typeof image === 'string') {
  24147. const url = image;
  24148. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24149. return await loader.loadAsync(path);
  24150. } else {
  24151. if (image.data) {
  24152. return {
  24153. data: getTypedArray(image.type, image.data),
  24154. width: image.width,
  24155. height: image.height
  24156. };
  24157. } else {
  24158. return null;
  24159. }
  24160. }
  24161. }
  24162. if (json !== undefined && json.length > 0) {
  24163. loader = new ImageLoader(this.manager);
  24164. loader.setCrossOrigin(this.crossOrigin);
  24165. for (let i = 0, il = json.length; i < il; i++) {
  24166. const image = json[i];
  24167. const url = image.url;
  24168. if (Array.isArray(url)) {
  24169. // load array of images e.g CubeTexture
  24170. images[image.uuid] = [];
  24171. for (let j = 0, jl = url.length; j < jl; j++) {
  24172. const currentUrl = url[j];
  24173. const deserializedImage = await deserializeImage(currentUrl);
  24174. if (deserializedImage !== null) {
  24175. if (deserializedImage instanceof HTMLImageElement) {
  24176. images[image.uuid].push(deserializedImage);
  24177. } else {
  24178. // special case: handle array of data textures for cube textures
  24179. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24180. }
  24181. }
  24182. }
  24183. } else {
  24184. // load single image
  24185. const deserializedImage = await deserializeImage(image.url);
  24186. if (deserializedImage !== null) {
  24187. images[image.uuid] = deserializedImage;
  24188. }
  24189. }
  24190. }
  24191. }
  24192. return images;
  24193. }
  24194. parseTextures(json, images) {
  24195. function parseConstant(value, type) {
  24196. if (typeof value === 'number') return value;
  24197. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24198. return type[value];
  24199. }
  24200. const textures = {};
  24201. if (json !== undefined) {
  24202. for (let i = 0, l = json.length; i < l; i++) {
  24203. const data = json[i];
  24204. if (data.image === undefined) {
  24205. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24206. }
  24207. if (images[data.image] === undefined) {
  24208. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24209. }
  24210. let texture;
  24211. const image = images[data.image];
  24212. if (Array.isArray(image)) {
  24213. texture = new CubeTexture(image);
  24214. if (image.length === 6) texture.needsUpdate = true;
  24215. } else {
  24216. if (image && image.data) {
  24217. texture = new DataTexture(image.data, image.width, image.height);
  24218. } else {
  24219. texture = new Texture(image);
  24220. }
  24221. if (image) texture.needsUpdate = true; // textures can have undefined image data
  24222. }
  24223. texture.uuid = data.uuid;
  24224. if (data.name !== undefined) texture.name = data.name;
  24225. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24226. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24227. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24228. if (data.center !== undefined) texture.center.fromArray(data.center);
  24229. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24230. if (data.wrap !== undefined) {
  24231. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24232. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24233. }
  24234. if (data.format !== undefined) texture.format = data.format;
  24235. if (data.type !== undefined) texture.type = data.type;
  24236. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24237. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24238. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24239. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24240. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24241. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24242. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24243. textures[data.uuid] = texture;
  24244. }
  24245. }
  24246. return textures;
  24247. }
  24248. parseObject(data, geometries, materials, textures, animations) {
  24249. let object;
  24250. function getGeometry(name) {
  24251. if (geometries[name] === undefined) {
  24252. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24253. }
  24254. return geometries[name];
  24255. }
  24256. function getMaterial(name) {
  24257. if (name === undefined) return undefined;
  24258. if (Array.isArray(name)) {
  24259. const array = [];
  24260. for (let i = 0, l = name.length; i < l; i++) {
  24261. const uuid = name[i];
  24262. if (materials[uuid] === undefined) {
  24263. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24264. }
  24265. array.push(materials[uuid]);
  24266. }
  24267. return array;
  24268. }
  24269. if (materials[name] === undefined) {
  24270. console.warn('THREE.ObjectLoader: Undefined material', name);
  24271. }
  24272. return materials[name];
  24273. }
  24274. function getTexture(uuid) {
  24275. if (textures[uuid] === undefined) {
  24276. console.warn('THREE.ObjectLoader: Undefined texture', uuid);
  24277. }
  24278. return textures[uuid];
  24279. }
  24280. let geometry, material;
  24281. switch (data.type) {
  24282. case 'Scene':
  24283. object = new Scene();
  24284. if (data.background !== undefined) {
  24285. if (Number.isInteger(data.background)) {
  24286. object.background = new Color(data.background);
  24287. } else {
  24288. object.background = getTexture(data.background);
  24289. }
  24290. }
  24291. if (data.environment !== undefined) {
  24292. object.environment = getTexture(data.environment);
  24293. }
  24294. if (data.fog !== undefined) {
  24295. if (data.fog.type === 'Fog') {
  24296. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  24297. } else if (data.fog.type === 'FogExp2') {
  24298. object.fog = new FogExp2(data.fog.color, data.fog.density);
  24299. }
  24300. }
  24301. break;
  24302. case 'PerspectiveCamera':
  24303. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  24304. if (data.focus !== undefined) object.focus = data.focus;
  24305. if (data.zoom !== undefined) object.zoom = data.zoom;
  24306. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  24307. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  24308. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24309. break;
  24310. case 'OrthographicCamera':
  24311. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  24312. if (data.zoom !== undefined) object.zoom = data.zoom;
  24313. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24314. break;
  24315. case 'AmbientLight':
  24316. object = new AmbientLight(data.color, data.intensity);
  24317. break;
  24318. case 'DirectionalLight':
  24319. object = new DirectionalLight(data.color, data.intensity);
  24320. break;
  24321. case 'PointLight':
  24322. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  24323. break;
  24324. case 'RectAreaLight':
  24325. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  24326. break;
  24327. case 'SpotLight':
  24328. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  24329. break;
  24330. case 'HemisphereLight':
  24331. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  24332. break;
  24333. case 'LightProbe':
  24334. object = new LightProbe().fromJSON(data);
  24335. break;
  24336. case 'SkinnedMesh':
  24337. geometry = getGeometry(data.geometry);
  24338. material = getMaterial(data.material);
  24339. object = new SkinnedMesh(geometry, material);
  24340. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  24341. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  24342. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  24343. break;
  24344. case 'Mesh':
  24345. geometry = getGeometry(data.geometry);
  24346. material = getMaterial(data.material);
  24347. object = new Mesh(geometry, material);
  24348. break;
  24349. case 'InstancedMesh':
  24350. geometry = getGeometry(data.geometry);
  24351. material = getMaterial(data.material);
  24352. const count = data.count;
  24353. const instanceMatrix = data.instanceMatrix;
  24354. const instanceColor = data.instanceColor;
  24355. object = new InstancedMesh(geometry, material, count);
  24356. object.instanceMatrix = new InstancedBufferAttribute(new Float32Array(instanceMatrix.array), 16);
  24357. if (instanceColor !== undefined) object.instanceColor = new InstancedBufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
  24358. break;
  24359. case 'LOD':
  24360. object = new LOD();
  24361. break;
  24362. case 'Line':
  24363. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  24364. break;
  24365. case 'LineLoop':
  24366. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  24367. break;
  24368. case 'LineSegments':
  24369. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  24370. break;
  24371. case 'PointCloud':
  24372. case 'Points':
  24373. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  24374. break;
  24375. case 'Sprite':
  24376. object = new Sprite(getMaterial(data.material));
  24377. break;
  24378. case 'Group':
  24379. object = new Group();
  24380. break;
  24381. case 'Bone':
  24382. object = new Bone();
  24383. break;
  24384. default:
  24385. object = new Object3D();
  24386. }
  24387. object.uuid = data.uuid;
  24388. if (data.name !== undefined) object.name = data.name;
  24389. if (data.matrix !== undefined) {
  24390. object.matrix.fromArray(data.matrix);
  24391. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  24392. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  24393. } else {
  24394. if (data.position !== undefined) object.position.fromArray(data.position);
  24395. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  24396. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  24397. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  24398. }
  24399. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  24400. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  24401. if (data.shadow) {
  24402. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  24403. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  24404. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  24405. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  24406. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  24407. }
  24408. if (data.visible !== undefined) object.visible = data.visible;
  24409. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  24410. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  24411. if (data.userData !== undefined) object.userData = data.userData;
  24412. if (data.layers !== undefined) object.layers.mask = data.layers;
  24413. if (data.children !== undefined) {
  24414. const children = data.children;
  24415. for (let i = 0; i < children.length; i++) {
  24416. object.add(this.parseObject(children[i], geometries, materials, textures, animations));
  24417. }
  24418. }
  24419. if (data.animations !== undefined) {
  24420. const objectAnimations = data.animations;
  24421. for (let i = 0; i < objectAnimations.length; i++) {
  24422. const uuid = objectAnimations[i];
  24423. object.animations.push(animations[uuid]);
  24424. }
  24425. }
  24426. if (data.type === 'LOD') {
  24427. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  24428. const levels = data.levels;
  24429. for (let l = 0; l < levels.length; l++) {
  24430. const level = levels[l];
  24431. const child = object.getObjectByProperty('uuid', level.object);
  24432. if (child !== undefined) {
  24433. object.addLevel(child, level.distance);
  24434. }
  24435. }
  24436. }
  24437. return object;
  24438. }
  24439. bindSkeletons(object, skeletons) {
  24440. if (Object.keys(skeletons).length === 0) return;
  24441. object.traverse(function (child) {
  24442. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  24443. const skeleton = skeletons[child.skeleton];
  24444. if (skeleton === undefined) {
  24445. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  24446. } else {
  24447. child.bind(skeleton, child.bindMatrix);
  24448. }
  24449. }
  24450. });
  24451. }
  24452. /* DEPRECATED */
  24453. setTexturePath(value) {
  24454. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  24455. return this.setResourcePath(value);
  24456. }
  24457. }
  24458. const TEXTURE_MAPPING = {
  24459. UVMapping: UVMapping,
  24460. CubeReflectionMapping: CubeReflectionMapping,
  24461. CubeRefractionMapping: CubeRefractionMapping,
  24462. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  24463. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  24464. CubeUVReflectionMapping: CubeUVReflectionMapping,
  24465. CubeUVRefractionMapping: CubeUVRefractionMapping
  24466. };
  24467. const TEXTURE_WRAPPING = {
  24468. RepeatWrapping: RepeatWrapping,
  24469. ClampToEdgeWrapping: ClampToEdgeWrapping,
  24470. MirroredRepeatWrapping: MirroredRepeatWrapping
  24471. };
  24472. const TEXTURE_FILTER = {
  24473. NearestFilter: NearestFilter,
  24474. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  24475. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  24476. LinearFilter: LinearFilter,
  24477. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  24478. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  24479. };
  24480. class ImageBitmapLoader extends Loader {
  24481. constructor(manager) {
  24482. super(manager);
  24483. if (typeof createImageBitmap === 'undefined') {
  24484. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  24485. }
  24486. if (typeof fetch === 'undefined') {
  24487. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  24488. }
  24489. this.options = {
  24490. premultiplyAlpha: 'none'
  24491. };
  24492. }
  24493. setOptions(options) {
  24494. this.options = options;
  24495. return this;
  24496. }
  24497. load(url, onLoad, onProgress, onError) {
  24498. if (url === undefined) url = '';
  24499. if (this.path !== undefined) url = this.path + url;
  24500. url = this.manager.resolveURL(url);
  24501. const scope = this;
  24502. const cached = Cache.get(url);
  24503. if (cached !== undefined) {
  24504. scope.manager.itemStart(url);
  24505. setTimeout(function () {
  24506. if (onLoad) onLoad(cached);
  24507. scope.manager.itemEnd(url);
  24508. }, 0);
  24509. return cached;
  24510. }
  24511. const fetchOptions = {};
  24512. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  24513. fetchOptions.headers = this.requestHeader;
  24514. fetch(url, fetchOptions).then(function (res) {
  24515. return res.blob();
  24516. }).then(function (blob) {
  24517. return createImageBitmap(blob, Object.assign(scope.options, {
  24518. colorSpaceConversion: 'none'
  24519. }));
  24520. }).then(function (imageBitmap) {
  24521. Cache.add(url, imageBitmap);
  24522. if (onLoad) onLoad(imageBitmap);
  24523. scope.manager.itemEnd(url);
  24524. }).catch(function (e) {
  24525. if (onError) onError(e);
  24526. scope.manager.itemError(url);
  24527. scope.manager.itemEnd(url);
  24528. });
  24529. scope.manager.itemStart(url);
  24530. }
  24531. }
  24532. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  24533. let _context;
  24534. const AudioContext = {
  24535. getContext: function () {
  24536. if (_context === undefined) {
  24537. _context = new (window.AudioContext || window.webkitAudioContext)();
  24538. }
  24539. return _context;
  24540. },
  24541. setContext: function (value) {
  24542. _context = value;
  24543. }
  24544. };
  24545. class AudioLoader extends Loader {
  24546. constructor(manager) {
  24547. super(manager);
  24548. }
  24549. load(url, onLoad, onProgress, onError) {
  24550. const scope = this;
  24551. const loader = new FileLoader(this.manager);
  24552. loader.setResponseType('arraybuffer');
  24553. loader.setPath(this.path);
  24554. loader.setRequestHeader(this.requestHeader);
  24555. loader.setWithCredentials(this.withCredentials);
  24556. loader.load(url, function (buffer) {
  24557. try {
  24558. // Create a copy of the buffer. The `decodeAudioData` method
  24559. // detaches the buffer when complete, preventing reuse.
  24560. const bufferCopy = buffer.slice(0);
  24561. const context = AudioContext.getContext();
  24562. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  24563. onLoad(audioBuffer);
  24564. });
  24565. } catch (e) {
  24566. if (onError) {
  24567. onError(e);
  24568. } else {
  24569. console.error(e);
  24570. }
  24571. scope.manager.itemError(url);
  24572. }
  24573. }, onProgress, onError);
  24574. }
  24575. }
  24576. class HemisphereLightProbe extends LightProbe {
  24577. constructor(skyColor, groundColor, intensity = 1) {
  24578. super(undefined, intensity);
  24579. const color1 = new Color().set(skyColor);
  24580. const color2 = new Color().set(groundColor);
  24581. const sky = new Vector3(color1.r, color1.g, color1.b);
  24582. const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  24583. const c0 = Math.sqrt(Math.PI);
  24584. const c1 = c0 * Math.sqrt(0.75);
  24585. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  24586. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  24587. }
  24588. }
  24589. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  24590. class AmbientLightProbe extends LightProbe {
  24591. constructor(color, intensity = 1) {
  24592. super(undefined, intensity);
  24593. const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  24594. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  24595. }
  24596. }
  24597. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  24598. const _eyeRight = /*@__PURE__*/new Matrix4();
  24599. const _eyeLeft = /*@__PURE__*/new Matrix4();
  24600. class StereoCamera {
  24601. constructor() {
  24602. this.type = 'StereoCamera';
  24603. this.aspect = 1;
  24604. this.eyeSep = 0.064;
  24605. this.cameraL = new PerspectiveCamera();
  24606. this.cameraL.layers.enable(1);
  24607. this.cameraL.matrixAutoUpdate = false;
  24608. this.cameraR = new PerspectiveCamera();
  24609. this.cameraR.layers.enable(2);
  24610. this.cameraR.matrixAutoUpdate = false;
  24611. this._cache = {
  24612. focus: null,
  24613. fov: null,
  24614. aspect: null,
  24615. near: null,
  24616. far: null,
  24617. zoom: null,
  24618. eyeSep: null
  24619. };
  24620. }
  24621. update(camera) {
  24622. const cache = this._cache;
  24623. 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;
  24624. if (needsUpdate) {
  24625. cache.focus = camera.focus;
  24626. cache.fov = camera.fov;
  24627. cache.aspect = camera.aspect * this.aspect;
  24628. cache.near = camera.near;
  24629. cache.far = camera.far;
  24630. cache.zoom = camera.zoom;
  24631. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  24632. // http://paulbourke.net/stereographics/stereorender/
  24633. const projectionMatrix = camera.projectionMatrix.clone();
  24634. const eyeSepHalf = cache.eyeSep / 2;
  24635. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  24636. const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom;
  24637. let xmin, xmax; // translate xOffset
  24638. _eyeLeft.elements[12] = -eyeSepHalf;
  24639. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  24640. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  24641. xmax = ymax * cache.aspect + eyeSepOnProjection;
  24642. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  24643. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  24644. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  24645. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  24646. xmax = ymax * cache.aspect - eyeSepOnProjection;
  24647. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  24648. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  24649. this.cameraR.projectionMatrix.copy(projectionMatrix);
  24650. }
  24651. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  24652. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  24653. }
  24654. }
  24655. class Clock {
  24656. constructor(autoStart = true) {
  24657. this.autoStart = autoStart;
  24658. this.startTime = 0;
  24659. this.oldTime = 0;
  24660. this.elapsedTime = 0;
  24661. this.running = false;
  24662. }
  24663. start() {
  24664. this.startTime = now();
  24665. this.oldTime = this.startTime;
  24666. this.elapsedTime = 0;
  24667. this.running = true;
  24668. }
  24669. stop() {
  24670. this.getElapsedTime();
  24671. this.running = false;
  24672. this.autoStart = false;
  24673. }
  24674. getElapsedTime() {
  24675. this.getDelta();
  24676. return this.elapsedTime;
  24677. }
  24678. getDelta() {
  24679. let diff = 0;
  24680. if (this.autoStart && !this.running) {
  24681. this.start();
  24682. return 0;
  24683. }
  24684. if (this.running) {
  24685. const newTime = now();
  24686. diff = (newTime - this.oldTime) / 1000;
  24687. this.oldTime = newTime;
  24688. this.elapsedTime += diff;
  24689. }
  24690. return diff;
  24691. }
  24692. }
  24693. function now() {
  24694. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  24695. }
  24696. const _position$1 = /*@__PURE__*/new Vector3();
  24697. const _quaternion$1 = /*@__PURE__*/new Quaternion();
  24698. const _scale$1 = /*@__PURE__*/new Vector3();
  24699. const _orientation$1 = /*@__PURE__*/new Vector3();
  24700. class AudioListener extends Object3D {
  24701. constructor() {
  24702. super();
  24703. this.type = 'AudioListener';
  24704. this.context = AudioContext.getContext();
  24705. this.gain = this.context.createGain();
  24706. this.gain.connect(this.context.destination);
  24707. this.filter = null;
  24708. this.timeDelta = 0; // private
  24709. this._clock = new Clock();
  24710. }
  24711. getInput() {
  24712. return this.gain;
  24713. }
  24714. removeFilter() {
  24715. if (this.filter !== null) {
  24716. this.gain.disconnect(this.filter);
  24717. this.filter.disconnect(this.context.destination);
  24718. this.gain.connect(this.context.destination);
  24719. this.filter = null;
  24720. }
  24721. return this;
  24722. }
  24723. getFilter() {
  24724. return this.filter;
  24725. }
  24726. setFilter(value) {
  24727. if (this.filter !== null) {
  24728. this.gain.disconnect(this.filter);
  24729. this.filter.disconnect(this.context.destination);
  24730. } else {
  24731. this.gain.disconnect(this.context.destination);
  24732. }
  24733. this.filter = value;
  24734. this.gain.connect(this.filter);
  24735. this.filter.connect(this.context.destination);
  24736. return this;
  24737. }
  24738. getMasterVolume() {
  24739. return this.gain.gain.value;
  24740. }
  24741. setMasterVolume(value) {
  24742. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  24743. return this;
  24744. }
  24745. updateMatrixWorld(force) {
  24746. super.updateMatrixWorld(force);
  24747. const listener = this.context.listener;
  24748. const up = this.up;
  24749. this.timeDelta = this._clock.getDelta();
  24750. this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
  24751. _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
  24752. if (listener.positionX) {
  24753. // code path for Chrome (see #14393)
  24754. const endTime = this.context.currentTime + this.timeDelta;
  24755. listener.positionX.linearRampToValueAtTime(_position$1.x, endTime);
  24756. listener.positionY.linearRampToValueAtTime(_position$1.y, endTime);
  24757. listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime);
  24758. listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime);
  24759. listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
  24760. listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  24761. listener.upX.linearRampToValueAtTime(up.x, endTime);
  24762. listener.upY.linearRampToValueAtTime(up.y, endTime);
  24763. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  24764. } else {
  24765. listener.setPosition(_position$1.x, _position$1.y, _position$1.z);
  24766. listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
  24767. }
  24768. }
  24769. }
  24770. class Audio extends Object3D {
  24771. constructor(listener) {
  24772. super();
  24773. this.type = 'Audio';
  24774. this.listener = listener;
  24775. this.context = listener.context;
  24776. this.gain = this.context.createGain();
  24777. this.gain.connect(listener.getInput());
  24778. this.autoplay = false;
  24779. this.buffer = null;
  24780. this.detune = 0;
  24781. this.loop = false;
  24782. this.loopStart = 0;
  24783. this.loopEnd = 0;
  24784. this.offset = 0;
  24785. this.duration = undefined;
  24786. this.playbackRate = 1;
  24787. this.isPlaying = false;
  24788. this.hasPlaybackControl = true;
  24789. this.source = null;
  24790. this.sourceType = 'empty';
  24791. this._startedAt = 0;
  24792. this._progress = 0;
  24793. this._connected = false;
  24794. this.filters = [];
  24795. }
  24796. getOutput() {
  24797. return this.gain;
  24798. }
  24799. setNodeSource(audioNode) {
  24800. this.hasPlaybackControl = false;
  24801. this.sourceType = 'audioNode';
  24802. this.source = audioNode;
  24803. this.connect();
  24804. return this;
  24805. }
  24806. setMediaElementSource(mediaElement) {
  24807. this.hasPlaybackControl = false;
  24808. this.sourceType = 'mediaNode';
  24809. this.source = this.context.createMediaElementSource(mediaElement);
  24810. this.connect();
  24811. return this;
  24812. }
  24813. setMediaStreamSource(mediaStream) {
  24814. this.hasPlaybackControl = false;
  24815. this.sourceType = 'mediaStreamNode';
  24816. this.source = this.context.createMediaStreamSource(mediaStream);
  24817. this.connect();
  24818. return this;
  24819. }
  24820. setBuffer(audioBuffer) {
  24821. this.buffer = audioBuffer;
  24822. this.sourceType = 'buffer';
  24823. if (this.autoplay) this.play();
  24824. return this;
  24825. }
  24826. play(delay = 0) {
  24827. if (this.isPlaying === true) {
  24828. console.warn('THREE.Audio: Audio is already playing.');
  24829. return;
  24830. }
  24831. if (this.hasPlaybackControl === false) {
  24832. console.warn('THREE.Audio: this Audio has no playback control.');
  24833. return;
  24834. }
  24835. this._startedAt = this.context.currentTime + delay;
  24836. const source = this.context.createBufferSource();
  24837. source.buffer = this.buffer;
  24838. source.loop = this.loop;
  24839. source.loopStart = this.loopStart;
  24840. source.loopEnd = this.loopEnd;
  24841. source.onended = this.onEnded.bind(this);
  24842. source.start(this._startedAt, this._progress + this.offset, this.duration);
  24843. this.isPlaying = true;
  24844. this.source = source;
  24845. this.setDetune(this.detune);
  24846. this.setPlaybackRate(this.playbackRate);
  24847. return this.connect();
  24848. }
  24849. pause() {
  24850. if (this.hasPlaybackControl === false) {
  24851. console.warn('THREE.Audio: this Audio has no playback control.');
  24852. return;
  24853. }
  24854. if (this.isPlaying === true) {
  24855. // update current progress
  24856. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  24857. if (this.loop === true) {
  24858. // ensure _progress does not exceed duration with looped audios
  24859. this._progress = this._progress % (this.duration || this.buffer.duration);
  24860. }
  24861. this.source.stop();
  24862. this.source.onended = null;
  24863. this.isPlaying = false;
  24864. }
  24865. return this;
  24866. }
  24867. stop() {
  24868. if (this.hasPlaybackControl === false) {
  24869. console.warn('THREE.Audio: this Audio has no playback control.');
  24870. return;
  24871. }
  24872. this._progress = 0;
  24873. this.source.stop();
  24874. this.source.onended = null;
  24875. this.isPlaying = false;
  24876. return this;
  24877. }
  24878. connect() {
  24879. if (this.filters.length > 0) {
  24880. this.source.connect(this.filters[0]);
  24881. for (let i = 1, l = this.filters.length; i < l; i++) {
  24882. this.filters[i - 1].connect(this.filters[i]);
  24883. }
  24884. this.filters[this.filters.length - 1].connect(this.getOutput());
  24885. } else {
  24886. this.source.connect(this.getOutput());
  24887. }
  24888. this._connected = true;
  24889. return this;
  24890. }
  24891. disconnect() {
  24892. if (this.filters.length > 0) {
  24893. this.source.disconnect(this.filters[0]);
  24894. for (let i = 1, l = this.filters.length; i < l; i++) {
  24895. this.filters[i - 1].disconnect(this.filters[i]);
  24896. }
  24897. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  24898. } else {
  24899. this.source.disconnect(this.getOutput());
  24900. }
  24901. this._connected = false;
  24902. return this;
  24903. }
  24904. getFilters() {
  24905. return this.filters;
  24906. }
  24907. setFilters(value) {
  24908. if (!value) value = [];
  24909. if (this._connected === true) {
  24910. this.disconnect();
  24911. this.filters = value.slice();
  24912. this.connect();
  24913. } else {
  24914. this.filters = value.slice();
  24915. }
  24916. return this;
  24917. }
  24918. setDetune(value) {
  24919. this.detune = value;
  24920. if (this.source.detune === undefined) return; // only set detune when available
  24921. if (this.isPlaying === true) {
  24922. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  24923. }
  24924. return this;
  24925. }
  24926. getDetune() {
  24927. return this.detune;
  24928. }
  24929. getFilter() {
  24930. return this.getFilters()[0];
  24931. }
  24932. setFilter(filter) {
  24933. return this.setFilters(filter ? [filter] : []);
  24934. }
  24935. setPlaybackRate(value) {
  24936. if (this.hasPlaybackControl === false) {
  24937. console.warn('THREE.Audio: this Audio has no playback control.');
  24938. return;
  24939. }
  24940. this.playbackRate = value;
  24941. if (this.isPlaying === true) {
  24942. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  24943. }
  24944. return this;
  24945. }
  24946. getPlaybackRate() {
  24947. return this.playbackRate;
  24948. }
  24949. onEnded() {
  24950. this.isPlaying = false;
  24951. }
  24952. getLoop() {
  24953. if (this.hasPlaybackControl === false) {
  24954. console.warn('THREE.Audio: this Audio has no playback control.');
  24955. return false;
  24956. }
  24957. return this.loop;
  24958. }
  24959. setLoop(value) {
  24960. if (this.hasPlaybackControl === false) {
  24961. console.warn('THREE.Audio: this Audio has no playback control.');
  24962. return;
  24963. }
  24964. this.loop = value;
  24965. if (this.isPlaying === true) {
  24966. this.source.loop = this.loop;
  24967. }
  24968. return this;
  24969. }
  24970. setLoopStart(value) {
  24971. this.loopStart = value;
  24972. return this;
  24973. }
  24974. setLoopEnd(value) {
  24975. this.loopEnd = value;
  24976. return this;
  24977. }
  24978. getVolume() {
  24979. return this.gain.gain.value;
  24980. }
  24981. setVolume(value) {
  24982. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  24983. return this;
  24984. }
  24985. }
  24986. const _position = /*@__PURE__*/new Vector3();
  24987. const _quaternion = /*@__PURE__*/new Quaternion();
  24988. const _scale = /*@__PURE__*/new Vector3();
  24989. const _orientation = /*@__PURE__*/new Vector3();
  24990. class PositionalAudio extends Audio {
  24991. constructor(listener) {
  24992. super(listener);
  24993. this.panner = this.context.createPanner();
  24994. this.panner.panningModel = 'HRTF';
  24995. this.panner.connect(this.gain);
  24996. }
  24997. getOutput() {
  24998. return this.panner;
  24999. }
  25000. getRefDistance() {
  25001. return this.panner.refDistance;
  25002. }
  25003. setRefDistance(value) {
  25004. this.panner.refDistance = value;
  25005. return this;
  25006. }
  25007. getRolloffFactor() {
  25008. return this.panner.rolloffFactor;
  25009. }
  25010. setRolloffFactor(value) {
  25011. this.panner.rolloffFactor = value;
  25012. return this;
  25013. }
  25014. getDistanceModel() {
  25015. return this.panner.distanceModel;
  25016. }
  25017. setDistanceModel(value) {
  25018. this.panner.distanceModel = value;
  25019. return this;
  25020. }
  25021. getMaxDistance() {
  25022. return this.panner.maxDistance;
  25023. }
  25024. setMaxDistance(value) {
  25025. this.panner.maxDistance = value;
  25026. return this;
  25027. }
  25028. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25029. this.panner.coneInnerAngle = coneInnerAngle;
  25030. this.panner.coneOuterAngle = coneOuterAngle;
  25031. this.panner.coneOuterGain = coneOuterGain;
  25032. return this;
  25033. }
  25034. updateMatrixWorld(force) {
  25035. super.updateMatrixWorld(force);
  25036. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  25037. this.matrixWorld.decompose(_position, _quaternion, _scale);
  25038. _orientation.set(0, 0, 1).applyQuaternion(_quaternion);
  25039. const panner = this.panner;
  25040. if (panner.positionX) {
  25041. // code path for Chrome and Firefox (see #14393)
  25042. const endTime = this.context.currentTime + this.listener.timeDelta;
  25043. panner.positionX.linearRampToValueAtTime(_position.x, endTime);
  25044. panner.positionY.linearRampToValueAtTime(_position.y, endTime);
  25045. panner.positionZ.linearRampToValueAtTime(_position.z, endTime);
  25046. panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime);
  25047. panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime);
  25048. panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime);
  25049. } else {
  25050. panner.setPosition(_position.x, _position.y, _position.z);
  25051. panner.setOrientation(_orientation.x, _orientation.y, _orientation.z);
  25052. }
  25053. }
  25054. }
  25055. class AudioAnalyser {
  25056. constructor(audio, fftSize = 2048) {
  25057. this.analyser = audio.context.createAnalyser();
  25058. this.analyser.fftSize = fftSize;
  25059. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  25060. audio.getOutput().connect(this.analyser);
  25061. }
  25062. getFrequencyData() {
  25063. this.analyser.getByteFrequencyData(this.data);
  25064. return this.data;
  25065. }
  25066. getAverageFrequency() {
  25067. let value = 0;
  25068. const data = this.getFrequencyData();
  25069. for (let i = 0; i < data.length; i++) {
  25070. value += data[i];
  25071. }
  25072. return value / data.length;
  25073. }
  25074. }
  25075. class PropertyMixer {
  25076. constructor(binding, typeName, valueSize) {
  25077. this.binding = binding;
  25078. this.valueSize = valueSize;
  25079. let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25080. //
  25081. // interpolators can use .buffer as their .result
  25082. // the data then goes to 'incoming'
  25083. //
  25084. // 'accu0' and 'accu1' are used frame-interleaved for
  25085. // the cumulative result and are compared to detect
  25086. // changes
  25087. //
  25088. // 'orig' stores the original state of the property
  25089. //
  25090. // 'add' is used for additive cumulative results
  25091. //
  25092. // 'work' is optional and is only present for quaternion types. It is used
  25093. // to store intermediate quaternion multiplication results
  25094. switch (typeName) {
  25095. case 'quaternion':
  25096. mixFunction = this._slerp;
  25097. mixFunctionAdditive = this._slerpAdditive;
  25098. setIdentity = this._setAdditiveIdentityQuaternion;
  25099. this.buffer = new Float64Array(valueSize * 6);
  25100. this._workIndex = 5;
  25101. break;
  25102. case 'string':
  25103. case 'bool':
  25104. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  25105. // additive is not relevant for non-numeric types
  25106. mixFunctionAdditive = this._select;
  25107. setIdentity = this._setAdditiveIdentityOther;
  25108. this.buffer = new Array(valueSize * 5);
  25109. break;
  25110. default:
  25111. mixFunction = this._lerp;
  25112. mixFunctionAdditive = this._lerpAdditive;
  25113. setIdentity = this._setAdditiveIdentityNumeric;
  25114. this.buffer = new Float64Array(valueSize * 5);
  25115. }
  25116. this._mixBufferRegion = mixFunction;
  25117. this._mixBufferRegionAdditive = mixFunctionAdditive;
  25118. this._setIdentity = setIdentity;
  25119. this._origIndex = 3;
  25120. this._addIndex = 4;
  25121. this.cumulativeWeight = 0;
  25122. this.cumulativeWeightAdditive = 0;
  25123. this.useCount = 0;
  25124. this.referenceCount = 0;
  25125. } // accumulate data in the 'incoming' region into 'accu<i>'
  25126. accumulate(accuIndex, weight) {
  25127. // note: happily accumulating nothing when weight = 0, the caller knows
  25128. // the weight and shouldn't have made the call in the first place
  25129. const buffer = this.buffer,
  25130. stride = this.valueSize,
  25131. offset = accuIndex * stride + stride;
  25132. let currentWeight = this.cumulativeWeight;
  25133. if (currentWeight === 0) {
  25134. // accuN := incoming * weight
  25135. for (let i = 0; i !== stride; ++i) {
  25136. buffer[offset + i] = buffer[i];
  25137. }
  25138. currentWeight = weight;
  25139. } else {
  25140. // accuN := accuN + incoming * weight
  25141. currentWeight += weight;
  25142. const mix = weight / currentWeight;
  25143. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  25144. }
  25145. this.cumulativeWeight = currentWeight;
  25146. } // accumulate data in the 'incoming' region into 'add'
  25147. accumulateAdditive(weight) {
  25148. const buffer = this.buffer,
  25149. stride = this.valueSize,
  25150. offset = stride * this._addIndex;
  25151. if (this.cumulativeWeightAdditive === 0) {
  25152. // add = identity
  25153. this._setIdentity();
  25154. } // add := add + incoming * weight
  25155. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  25156. this.cumulativeWeightAdditive += weight;
  25157. } // apply the state of 'accu<i>' to the binding when accus differ
  25158. apply(accuIndex) {
  25159. const stride = this.valueSize,
  25160. buffer = this.buffer,
  25161. offset = accuIndex * stride + stride,
  25162. weight = this.cumulativeWeight,
  25163. weightAdditive = this.cumulativeWeightAdditive,
  25164. binding = this.binding;
  25165. this.cumulativeWeight = 0;
  25166. this.cumulativeWeightAdditive = 0;
  25167. if (weight < 1) {
  25168. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25169. const originalValueOffset = stride * this._origIndex;
  25170. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  25171. }
  25172. if (weightAdditive > 0) {
  25173. // accuN := accuN + additive accuN
  25174. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  25175. }
  25176. for (let i = stride, e = stride + stride; i !== e; ++i) {
  25177. if (buffer[i] !== buffer[i + stride]) {
  25178. // value has changed -> update scene graph
  25179. binding.setValue(buffer, offset);
  25180. break;
  25181. }
  25182. }
  25183. } // remember the state of the bound property and copy it to both accus
  25184. saveOriginalState() {
  25185. const binding = this.binding;
  25186. const buffer = this.buffer,
  25187. stride = this.valueSize,
  25188. originalValueOffset = stride * this._origIndex;
  25189. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  25190. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  25191. buffer[i] = buffer[originalValueOffset + i % stride];
  25192. } // Add to identity for additive
  25193. this._setIdentity();
  25194. this.cumulativeWeight = 0;
  25195. this.cumulativeWeightAdditive = 0;
  25196. } // apply the state previously taken via 'saveOriginalState' to the binding
  25197. restoreOriginalState() {
  25198. const originalValueOffset = this.valueSize * 3;
  25199. this.binding.setValue(this.buffer, originalValueOffset);
  25200. }
  25201. _setAdditiveIdentityNumeric() {
  25202. const startIndex = this._addIndex * this.valueSize;
  25203. const endIndex = startIndex + this.valueSize;
  25204. for (let i = startIndex; i < endIndex; i++) {
  25205. this.buffer[i] = 0;
  25206. }
  25207. }
  25208. _setAdditiveIdentityQuaternion() {
  25209. this._setAdditiveIdentityNumeric();
  25210. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  25211. }
  25212. _setAdditiveIdentityOther() {
  25213. const startIndex = this._origIndex * this.valueSize;
  25214. const targetIndex = this._addIndex * this.valueSize;
  25215. for (let i = 0; i < this.valueSize; i++) {
  25216. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  25217. }
  25218. } // mix functions
  25219. _select(buffer, dstOffset, srcOffset, t, stride) {
  25220. if (t >= 0.5) {
  25221. for (let i = 0; i !== stride; ++i) {
  25222. buffer[dstOffset + i] = buffer[srcOffset + i];
  25223. }
  25224. }
  25225. }
  25226. _slerp(buffer, dstOffset, srcOffset, t) {
  25227. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  25228. }
  25229. _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25230. const workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  25231. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  25232. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  25233. }
  25234. _lerp(buffer, dstOffset, srcOffset, t, stride) {
  25235. const s = 1 - t;
  25236. for (let i = 0; i !== stride; ++i) {
  25237. const j = dstOffset + i;
  25238. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  25239. }
  25240. }
  25241. _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25242. for (let i = 0; i !== stride; ++i) {
  25243. const j = dstOffset + i;
  25244. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  25245. }
  25246. }
  25247. }
  25248. // Characters [].:/ are reserved for track binding syntax.
  25249. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  25250. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  25251. // only latin characters, and the unicode \p{L} is not yet supported. So
  25252. // instead, we exclude reserved characters and match everything else.
  25253. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  25254. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  25255. // be matched to parse the rest of the track name.
  25256. const _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  25257. const _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  25258. // characters. Accessor may contain any character except closing bracket.
  25259. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  25260. // contain any non-bracket characters.
  25261. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  25262. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  25263. const _supportedObjectNames = ['material', 'materials', 'bones'];
  25264. class Composite {
  25265. constructor(targetGroup, path, optionalParsedPath) {
  25266. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  25267. this._targetGroup = targetGroup;
  25268. this._bindings = targetGroup.subscribe_(path, parsedPath);
  25269. }
  25270. getValue(array, offset) {
  25271. this.bind(); // bind all binding
  25272. const firstValidIndex = this._targetGroup.nCachedObjects_,
  25273. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  25274. if (binding !== undefined) binding.getValue(array, offset);
  25275. }
  25276. setValue(array, offset) {
  25277. const bindings = this._bindings;
  25278. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25279. bindings[i].setValue(array, offset);
  25280. }
  25281. }
  25282. bind() {
  25283. const bindings = this._bindings;
  25284. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25285. bindings[i].bind();
  25286. }
  25287. }
  25288. unbind() {
  25289. const bindings = this._bindings;
  25290. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25291. bindings[i].unbind();
  25292. }
  25293. }
  25294. } // Note: This class uses a State pattern on a per-method basis:
  25295. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  25296. // prototype version of these methods with one that represents
  25297. // the bound state. When the property is not found, the methods
  25298. // become no-ops.
  25299. class PropertyBinding {
  25300. constructor(rootNode, path, parsedPath) {
  25301. this.path = path;
  25302. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  25303. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  25304. this.rootNode = rootNode; // initial state of these methods that calls 'bind'
  25305. this.getValue = this._getValue_unbound;
  25306. this.setValue = this._setValue_unbound;
  25307. }
  25308. static create(root, path, parsedPath) {
  25309. if (!(root && root.isAnimationObjectGroup)) {
  25310. return new PropertyBinding(root, path, parsedPath);
  25311. } else {
  25312. return new PropertyBinding.Composite(root, path, parsedPath);
  25313. }
  25314. }
  25315. /**
  25316. * Replaces spaces with underscores and removes unsupported characters from
  25317. * node names, to ensure compatibility with parseTrackName().
  25318. *
  25319. * @param {string} name Node name to be sanitized.
  25320. * @return {string}
  25321. */
  25322. static sanitizeNodeName(name) {
  25323. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  25324. }
  25325. static parseTrackName(trackName) {
  25326. const matches = _trackRe.exec(trackName);
  25327. if (!matches) {
  25328. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  25329. }
  25330. const results = {
  25331. // directoryName: matches[ 1 ], // (tschw) currently unused
  25332. nodeName: matches[2],
  25333. objectName: matches[3],
  25334. objectIndex: matches[4],
  25335. propertyName: matches[5],
  25336. // required
  25337. propertyIndex: matches[6]
  25338. };
  25339. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  25340. if (lastDot !== undefined && lastDot !== -1) {
  25341. const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  25342. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  25343. // 'bar' could be the objectName, or part of a nodeName (which can
  25344. // include '.' characters).
  25345. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  25346. results.nodeName = results.nodeName.substring(0, lastDot);
  25347. results.objectName = objectName;
  25348. }
  25349. }
  25350. if (results.propertyName === null || results.propertyName.length === 0) {
  25351. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  25352. }
  25353. return results;
  25354. }
  25355. static findNode(root, nodeName) {
  25356. if (!nodeName || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  25357. return root;
  25358. } // search into skeleton bones.
  25359. if (root.skeleton) {
  25360. const bone = root.skeleton.getBoneByName(nodeName);
  25361. if (bone !== undefined) {
  25362. return bone;
  25363. }
  25364. } // search into node subtree.
  25365. if (root.children) {
  25366. const searchNodeSubtree = function (children) {
  25367. for (let i = 0; i < children.length; i++) {
  25368. const childNode = children[i];
  25369. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  25370. return childNode;
  25371. }
  25372. const result = searchNodeSubtree(childNode.children);
  25373. if (result) return result;
  25374. }
  25375. return null;
  25376. };
  25377. const subTreeNode = searchNodeSubtree(root.children);
  25378. if (subTreeNode) {
  25379. return subTreeNode;
  25380. }
  25381. }
  25382. return null;
  25383. } // these are used to "bind" a nonexistent property
  25384. _getValue_unavailable() {}
  25385. _setValue_unavailable() {} // Getters
  25386. _getValue_direct(buffer, offset) {
  25387. buffer[offset] = this.targetObject[this.propertyName];
  25388. }
  25389. _getValue_array(buffer, offset) {
  25390. const source = this.resolvedProperty;
  25391. for (let i = 0, n = source.length; i !== n; ++i) {
  25392. buffer[offset++] = source[i];
  25393. }
  25394. }
  25395. _getValue_arrayElement(buffer, offset) {
  25396. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  25397. }
  25398. _getValue_toArray(buffer, offset) {
  25399. this.resolvedProperty.toArray(buffer, offset);
  25400. } // Direct
  25401. _setValue_direct(buffer, offset) {
  25402. this.targetObject[this.propertyName] = buffer[offset];
  25403. }
  25404. _setValue_direct_setNeedsUpdate(buffer, offset) {
  25405. this.targetObject[this.propertyName] = buffer[offset];
  25406. this.targetObject.needsUpdate = true;
  25407. }
  25408. _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  25409. this.targetObject[this.propertyName] = buffer[offset];
  25410. this.targetObject.matrixWorldNeedsUpdate = true;
  25411. } // EntireArray
  25412. _setValue_array(buffer, offset) {
  25413. const dest = this.resolvedProperty;
  25414. for (let i = 0, n = dest.length; i !== n; ++i) {
  25415. dest[i] = buffer[offset++];
  25416. }
  25417. }
  25418. _setValue_array_setNeedsUpdate(buffer, offset) {
  25419. const dest = this.resolvedProperty;
  25420. for (let i = 0, n = dest.length; i !== n; ++i) {
  25421. dest[i] = buffer[offset++];
  25422. }
  25423. this.targetObject.needsUpdate = true;
  25424. }
  25425. _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  25426. const dest = this.resolvedProperty;
  25427. for (let i = 0, n = dest.length; i !== n; ++i) {
  25428. dest[i] = buffer[offset++];
  25429. }
  25430. this.targetObject.matrixWorldNeedsUpdate = true;
  25431. } // ArrayElement
  25432. _setValue_arrayElement(buffer, offset) {
  25433. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25434. }
  25435. _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  25436. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25437. this.targetObject.needsUpdate = true;
  25438. }
  25439. _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  25440. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25441. this.targetObject.matrixWorldNeedsUpdate = true;
  25442. } // HasToFromArray
  25443. _setValue_fromArray(buffer, offset) {
  25444. this.resolvedProperty.fromArray(buffer, offset);
  25445. }
  25446. _setValue_fromArray_setNeedsUpdate(buffer, offset) {
  25447. this.resolvedProperty.fromArray(buffer, offset);
  25448. this.targetObject.needsUpdate = true;
  25449. }
  25450. _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  25451. this.resolvedProperty.fromArray(buffer, offset);
  25452. this.targetObject.matrixWorldNeedsUpdate = true;
  25453. }
  25454. _getValue_unbound(targetArray, offset) {
  25455. this.bind();
  25456. this.getValue(targetArray, offset);
  25457. }
  25458. _setValue_unbound(sourceArray, offset) {
  25459. this.bind();
  25460. this.setValue(sourceArray, offset);
  25461. } // create getter / setter pair for a property in the scene graph
  25462. bind() {
  25463. let targetObject = this.node;
  25464. const parsedPath = this.parsedPath;
  25465. const objectName = parsedPath.objectName;
  25466. const propertyName = parsedPath.propertyName;
  25467. let propertyIndex = parsedPath.propertyIndex;
  25468. if (!targetObject) {
  25469. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  25470. this.node = targetObject;
  25471. } // set fail state so we can just 'return' on error
  25472. this.getValue = this._getValue_unavailable;
  25473. this.setValue = this._setValue_unavailable; // ensure there is a value node
  25474. if (!targetObject) {
  25475. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  25476. return;
  25477. }
  25478. if (objectName) {
  25479. let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  25480. switch (objectName) {
  25481. case 'materials':
  25482. if (!targetObject.material) {
  25483. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  25484. return;
  25485. }
  25486. if (!targetObject.material.materials) {
  25487. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  25488. return;
  25489. }
  25490. targetObject = targetObject.material.materials;
  25491. break;
  25492. case 'bones':
  25493. if (!targetObject.skeleton) {
  25494. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  25495. return;
  25496. } // potential future optimization: skip this if propertyIndex is already an integer
  25497. // and convert the integer string to a true integer.
  25498. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  25499. for (let i = 0; i < targetObject.length; i++) {
  25500. if (targetObject[i].name === objectIndex) {
  25501. objectIndex = i;
  25502. break;
  25503. }
  25504. }
  25505. break;
  25506. default:
  25507. if (targetObject[objectName] === undefined) {
  25508. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  25509. return;
  25510. }
  25511. targetObject = targetObject[objectName];
  25512. }
  25513. if (objectIndex !== undefined) {
  25514. if (targetObject[objectIndex] === undefined) {
  25515. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  25516. return;
  25517. }
  25518. targetObject = targetObject[objectIndex];
  25519. }
  25520. } // resolve property
  25521. const nodeProperty = targetObject[propertyName];
  25522. if (nodeProperty === undefined) {
  25523. const nodeName = parsedPath.nodeName;
  25524. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  25525. return;
  25526. } // determine versioning scheme
  25527. let versioning = this.Versioning.None;
  25528. this.targetObject = targetObject;
  25529. if (targetObject.needsUpdate !== undefined) {
  25530. // material
  25531. versioning = this.Versioning.NeedsUpdate;
  25532. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  25533. // node transform
  25534. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  25535. } // determine how the property gets bound
  25536. let bindingType = this.BindingType.Direct;
  25537. if (propertyIndex !== undefined) {
  25538. // access a sub element of the property array (only primitives are supported right now)
  25539. if (propertyName === 'morphTargetInfluences') {
  25540. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  25541. // support resolving morphTarget names into indices.
  25542. if (!targetObject.geometry) {
  25543. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  25544. return;
  25545. }
  25546. if (targetObject.geometry.isBufferGeometry) {
  25547. if (!targetObject.geometry.morphAttributes) {
  25548. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  25549. return;
  25550. }
  25551. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  25552. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  25553. }
  25554. } else {
  25555. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
  25556. return;
  25557. }
  25558. }
  25559. bindingType = this.BindingType.ArrayElement;
  25560. this.resolvedProperty = nodeProperty;
  25561. this.propertyIndex = propertyIndex;
  25562. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  25563. // must use copy for Object3D.Euler/Quaternion
  25564. bindingType = this.BindingType.HasFromToArray;
  25565. this.resolvedProperty = nodeProperty;
  25566. } else if (Array.isArray(nodeProperty)) {
  25567. bindingType = this.BindingType.EntireArray;
  25568. this.resolvedProperty = nodeProperty;
  25569. } else {
  25570. this.propertyName = propertyName;
  25571. } // select getter / setter
  25572. this.getValue = this.GetterByBindingType[bindingType];
  25573. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  25574. }
  25575. unbind() {
  25576. this.node = null; // back to the prototype version of getValue / setValue
  25577. // note: avoiding to mutate the shape of 'this' via 'delete'
  25578. this.getValue = this._getValue_unbound;
  25579. this.setValue = this._setValue_unbound;
  25580. }
  25581. }
  25582. PropertyBinding.Composite = Composite;
  25583. PropertyBinding.prototype.BindingType = {
  25584. Direct: 0,
  25585. EntireArray: 1,
  25586. ArrayElement: 2,
  25587. HasFromToArray: 3
  25588. };
  25589. PropertyBinding.prototype.Versioning = {
  25590. None: 0,
  25591. NeedsUpdate: 1,
  25592. MatrixWorldNeedsUpdate: 2
  25593. };
  25594. PropertyBinding.prototype.GetterByBindingType = [PropertyBinding.prototype._getValue_direct, PropertyBinding.prototype._getValue_array, PropertyBinding.prototype._getValue_arrayElement, PropertyBinding.prototype._getValue_toArray];
  25595. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [[// Direct
  25596. PropertyBinding.prototype._setValue_direct, PropertyBinding.prototype._setValue_direct_setNeedsUpdate, PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate], [// EntireArray
  25597. PropertyBinding.prototype._setValue_array, PropertyBinding.prototype._setValue_array_setNeedsUpdate, PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate], [// ArrayElement
  25598. PropertyBinding.prototype._setValue_arrayElement, PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate], [// HasToFromArray
  25599. PropertyBinding.prototype._setValue_fromArray, PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];
  25600. /**
  25601. *
  25602. * A group of objects that receives a shared animation state.
  25603. *
  25604. * Usage:
  25605. *
  25606. * - Add objects you would otherwise pass as 'root' to the
  25607. * constructor or the .clipAction method of AnimationMixer.
  25608. *
  25609. * - Instead pass this object as 'root'.
  25610. *
  25611. * - You can also add and remove objects later when the mixer
  25612. * is running.
  25613. *
  25614. * Note:
  25615. *
  25616. * Objects of this class appear as one object to the mixer,
  25617. * so cache control of the individual objects must be done
  25618. * on the group.
  25619. *
  25620. * Limitation:
  25621. *
  25622. * - The animated properties must be compatible among the
  25623. * all objects in the group.
  25624. *
  25625. * - A single property can either be controlled through a
  25626. * target group or directly, but not both.
  25627. */
  25628. class AnimationObjectGroup {
  25629. constructor() {
  25630. this.uuid = generateUUID(); // cached objects followed by the active ones
  25631. this._objects = Array.prototype.slice.call(arguments);
  25632. this.nCachedObjects_ = 0; // threshold
  25633. // note: read by PropertyBinding.Composite
  25634. const indices = {};
  25635. this._indicesByUUID = indices; // for bookkeeping
  25636. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25637. indices[arguments[i].uuid] = i;
  25638. }
  25639. this._paths = []; // inside: string
  25640. this._parsedPaths = []; // inside: { we don't care, here }
  25641. this._bindings = []; // inside: Array< PropertyBinding >
  25642. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  25643. const scope = this;
  25644. this.stats = {
  25645. objects: {
  25646. get total() {
  25647. return scope._objects.length;
  25648. },
  25649. get inUse() {
  25650. return this.total - scope.nCachedObjects_;
  25651. }
  25652. },
  25653. get bindingsPerObject() {
  25654. return scope._bindings.length;
  25655. }
  25656. };
  25657. }
  25658. add() {
  25659. const objects = this._objects,
  25660. indicesByUUID = this._indicesByUUID,
  25661. paths = this._paths,
  25662. parsedPaths = this._parsedPaths,
  25663. bindings = this._bindings,
  25664. nBindings = bindings.length;
  25665. let knownObject = undefined,
  25666. nObjects = objects.length,
  25667. nCachedObjects = this.nCachedObjects_;
  25668. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25669. const object = arguments[i],
  25670. uuid = object.uuid;
  25671. let index = indicesByUUID[uuid];
  25672. if (index === undefined) {
  25673. // unknown object -> add it to the ACTIVE region
  25674. index = nObjects++;
  25675. indicesByUUID[uuid] = index;
  25676. objects.push(object); // accounting is done, now do the same for all bindings
  25677. for (let j = 0, m = nBindings; j !== m; ++j) {
  25678. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  25679. }
  25680. } else if (index < nCachedObjects) {
  25681. knownObject = objects[index]; // move existing object to the ACTIVE region
  25682. const firstActiveIndex = --nCachedObjects,
  25683. lastCachedObject = objects[firstActiveIndex];
  25684. indicesByUUID[lastCachedObject.uuid] = index;
  25685. objects[index] = lastCachedObject;
  25686. indicesByUUID[uuid] = firstActiveIndex;
  25687. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  25688. for (let j = 0, m = nBindings; j !== m; ++j) {
  25689. const bindingsForPath = bindings[j],
  25690. lastCached = bindingsForPath[firstActiveIndex];
  25691. let binding = bindingsForPath[index];
  25692. bindingsForPath[index] = lastCached;
  25693. if (binding === undefined) {
  25694. // since we do not bother to create new bindings
  25695. // for objects that are cached, the binding may
  25696. // or may not exist
  25697. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  25698. }
  25699. bindingsForPath[firstActiveIndex] = binding;
  25700. }
  25701. } else if (objects[index] !== knownObject) {
  25702. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  25703. } // else the object is already where we want it to be
  25704. } // for arguments
  25705. this.nCachedObjects_ = nCachedObjects;
  25706. }
  25707. remove() {
  25708. const objects = this._objects,
  25709. indicesByUUID = this._indicesByUUID,
  25710. bindings = this._bindings,
  25711. nBindings = bindings.length;
  25712. let nCachedObjects = this.nCachedObjects_;
  25713. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25714. const object = arguments[i],
  25715. uuid = object.uuid,
  25716. index = indicesByUUID[uuid];
  25717. if (index !== undefined && index >= nCachedObjects) {
  25718. // move existing object into the CACHED region
  25719. const lastCachedIndex = nCachedObjects++,
  25720. firstActiveObject = objects[lastCachedIndex];
  25721. indicesByUUID[firstActiveObject.uuid] = index;
  25722. objects[index] = firstActiveObject;
  25723. indicesByUUID[uuid] = lastCachedIndex;
  25724. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  25725. for (let j = 0, m = nBindings; j !== m; ++j) {
  25726. const bindingsForPath = bindings[j],
  25727. firstActive = bindingsForPath[lastCachedIndex],
  25728. binding = bindingsForPath[index];
  25729. bindingsForPath[index] = firstActive;
  25730. bindingsForPath[lastCachedIndex] = binding;
  25731. }
  25732. }
  25733. } // for arguments
  25734. this.nCachedObjects_ = nCachedObjects;
  25735. } // remove & forget
  25736. uncache() {
  25737. const objects = this._objects,
  25738. indicesByUUID = this._indicesByUUID,
  25739. bindings = this._bindings,
  25740. nBindings = bindings.length;
  25741. let nCachedObjects = this.nCachedObjects_,
  25742. nObjects = objects.length;
  25743. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25744. const object = arguments[i],
  25745. uuid = object.uuid,
  25746. index = indicesByUUID[uuid];
  25747. if (index !== undefined) {
  25748. delete indicesByUUID[uuid];
  25749. if (index < nCachedObjects) {
  25750. // object is cached, shrink the CACHED region
  25751. const firstActiveIndex = --nCachedObjects,
  25752. lastCachedObject = objects[firstActiveIndex],
  25753. lastIndex = --nObjects,
  25754. lastObject = objects[lastIndex]; // last cached object takes this object's place
  25755. indicesByUUID[lastCachedObject.uuid] = index;
  25756. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  25757. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  25758. objects[firstActiveIndex] = lastObject;
  25759. objects.pop(); // accounting is done, now do the same for all bindings
  25760. for (let j = 0, m = nBindings; j !== m; ++j) {
  25761. const bindingsForPath = bindings[j],
  25762. lastCached = bindingsForPath[firstActiveIndex],
  25763. last = bindingsForPath[lastIndex];
  25764. bindingsForPath[index] = lastCached;
  25765. bindingsForPath[firstActiveIndex] = last;
  25766. bindingsForPath.pop();
  25767. }
  25768. } else {
  25769. // object is active, just swap with the last and pop
  25770. const lastIndex = --nObjects,
  25771. lastObject = objects[lastIndex];
  25772. if (lastIndex > 0) {
  25773. indicesByUUID[lastObject.uuid] = index;
  25774. }
  25775. objects[index] = lastObject;
  25776. objects.pop(); // accounting is done, now do the same for all bindings
  25777. for (let j = 0, m = nBindings; j !== m; ++j) {
  25778. const bindingsForPath = bindings[j];
  25779. bindingsForPath[index] = bindingsForPath[lastIndex];
  25780. bindingsForPath.pop();
  25781. }
  25782. } // cached or active
  25783. } // if object is known
  25784. } // for arguments
  25785. this.nCachedObjects_ = nCachedObjects;
  25786. } // Internal interface used by befriended PropertyBinding.Composite:
  25787. subscribe_(path, parsedPath) {
  25788. // returns an array of bindings for the given path that is changed
  25789. // according to the contained objects in the group
  25790. const indicesByPath = this._bindingsIndicesByPath;
  25791. let index = indicesByPath[path];
  25792. const bindings = this._bindings;
  25793. if (index !== undefined) return bindings[index];
  25794. const paths = this._paths,
  25795. parsedPaths = this._parsedPaths,
  25796. objects = this._objects,
  25797. nObjects = objects.length,
  25798. nCachedObjects = this.nCachedObjects_,
  25799. bindingsForPath = new Array(nObjects);
  25800. index = bindings.length;
  25801. indicesByPath[path] = index;
  25802. paths.push(path);
  25803. parsedPaths.push(parsedPath);
  25804. bindings.push(bindingsForPath);
  25805. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  25806. const object = objects[i];
  25807. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  25808. }
  25809. return bindingsForPath;
  25810. }
  25811. unsubscribe_(path) {
  25812. // tells the group to forget about a property path and no longer
  25813. // update the array previously obtained with 'subscribe_'
  25814. const indicesByPath = this._bindingsIndicesByPath,
  25815. index = indicesByPath[path];
  25816. if (index !== undefined) {
  25817. const paths = this._paths,
  25818. parsedPaths = this._parsedPaths,
  25819. bindings = this._bindings,
  25820. lastBindingsIndex = bindings.length - 1,
  25821. lastBindings = bindings[lastBindingsIndex],
  25822. lastBindingsPath = path[lastBindingsIndex];
  25823. indicesByPath[lastBindingsPath] = index;
  25824. bindings[index] = lastBindings;
  25825. bindings.pop();
  25826. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  25827. parsedPaths.pop();
  25828. paths[index] = paths[lastBindingsIndex];
  25829. paths.pop();
  25830. }
  25831. }
  25832. }
  25833. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  25834. class AnimationAction {
  25835. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  25836. this._mixer = mixer;
  25837. this._clip = clip;
  25838. this._localRoot = localRoot;
  25839. this.blendMode = blendMode;
  25840. const tracks = clip.tracks,
  25841. nTracks = tracks.length,
  25842. interpolants = new Array(nTracks);
  25843. const interpolantSettings = {
  25844. endingStart: ZeroCurvatureEnding,
  25845. endingEnd: ZeroCurvatureEnding
  25846. };
  25847. for (let i = 0; i !== nTracks; ++i) {
  25848. const interpolant = tracks[i].createInterpolant(null);
  25849. interpolants[i] = interpolant;
  25850. interpolant.settings = interpolantSettings;
  25851. }
  25852. this._interpolantSettings = interpolantSettings;
  25853. this._interpolants = interpolants; // bound by the mixer
  25854. // inside: PropertyMixer (managed by the mixer)
  25855. this._propertyBindings = new Array(nTracks);
  25856. this._cacheIndex = null; // for the memory manager
  25857. this._byClipCacheIndex = null; // for the memory manager
  25858. this._timeScaleInterpolant = null;
  25859. this._weightInterpolant = null;
  25860. this.loop = LoopRepeat;
  25861. this._loopCount = -1; // global mixer time when the action is to be started
  25862. // it's set back to 'null' upon start of the action
  25863. this._startTime = null; // scaled local time of the action
  25864. // gets clamped or wrapped to 0..clip.duration according to loop
  25865. this.time = 0;
  25866. this.timeScale = 1;
  25867. this._effectiveTimeScale = 1;
  25868. this.weight = 1;
  25869. this._effectiveWeight = 1;
  25870. this.repetitions = Infinity; // no. of repetitions when looping
  25871. this.paused = false; // true -> zero effective time scale
  25872. this.enabled = true; // false -> zero effective weight
  25873. this.clampWhenFinished = false; // keep feeding the last frame?
  25874. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  25875. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  25876. } // State & Scheduling
  25877. play() {
  25878. this._mixer._activateAction(this);
  25879. return this;
  25880. }
  25881. stop() {
  25882. this._mixer._deactivateAction(this);
  25883. return this.reset();
  25884. }
  25885. reset() {
  25886. this.paused = false;
  25887. this.enabled = true;
  25888. this.time = 0; // restart clip
  25889. this._loopCount = -1; // forget previous loops
  25890. this._startTime = null; // forget scheduling
  25891. return this.stopFading().stopWarping();
  25892. }
  25893. isRunning() {
  25894. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  25895. } // return true when play has been called
  25896. isScheduled() {
  25897. return this._mixer._isActiveAction(this);
  25898. }
  25899. startAt(time) {
  25900. this._startTime = time;
  25901. return this;
  25902. }
  25903. setLoop(mode, repetitions) {
  25904. this.loop = mode;
  25905. this.repetitions = repetitions;
  25906. return this;
  25907. } // Weight
  25908. // set the weight stopping any scheduled fading
  25909. // although .enabled = false yields an effective weight of zero, this
  25910. // method does *not* change .enabled, because it would be confusing
  25911. setEffectiveWeight(weight) {
  25912. this.weight = weight; // note: same logic as when updated at runtime
  25913. this._effectiveWeight = this.enabled ? weight : 0;
  25914. return this.stopFading();
  25915. } // return the weight considering fading and .enabled
  25916. getEffectiveWeight() {
  25917. return this._effectiveWeight;
  25918. }
  25919. fadeIn(duration) {
  25920. return this._scheduleFading(duration, 0, 1);
  25921. }
  25922. fadeOut(duration) {
  25923. return this._scheduleFading(duration, 1, 0);
  25924. }
  25925. crossFadeFrom(fadeOutAction, duration, warp) {
  25926. fadeOutAction.fadeOut(duration);
  25927. this.fadeIn(duration);
  25928. if (warp) {
  25929. const fadeInDuration = this._clip.duration,
  25930. fadeOutDuration = fadeOutAction._clip.duration,
  25931. startEndRatio = fadeOutDuration / fadeInDuration,
  25932. endStartRatio = fadeInDuration / fadeOutDuration;
  25933. fadeOutAction.warp(1.0, startEndRatio, duration);
  25934. this.warp(endStartRatio, 1.0, duration);
  25935. }
  25936. return this;
  25937. }
  25938. crossFadeTo(fadeInAction, duration, warp) {
  25939. return fadeInAction.crossFadeFrom(this, duration, warp);
  25940. }
  25941. stopFading() {
  25942. const weightInterpolant = this._weightInterpolant;
  25943. if (weightInterpolant !== null) {
  25944. this._weightInterpolant = null;
  25945. this._mixer._takeBackControlInterpolant(weightInterpolant);
  25946. }
  25947. return this;
  25948. } // Time Scale Control
  25949. // set the time scale stopping any scheduled warping
  25950. // although .paused = true yields an effective time scale of zero, this
  25951. // method does *not* change .paused, because it would be confusing
  25952. setEffectiveTimeScale(timeScale) {
  25953. this.timeScale = timeScale;
  25954. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  25955. return this.stopWarping();
  25956. } // return the time scale considering warping and .paused
  25957. getEffectiveTimeScale() {
  25958. return this._effectiveTimeScale;
  25959. }
  25960. setDuration(duration) {
  25961. this.timeScale = this._clip.duration / duration;
  25962. return this.stopWarping();
  25963. }
  25964. syncWith(action) {
  25965. this.time = action.time;
  25966. this.timeScale = action.timeScale;
  25967. return this.stopWarping();
  25968. }
  25969. halt(duration) {
  25970. return this.warp(this._effectiveTimeScale, 0, duration);
  25971. }
  25972. warp(startTimeScale, endTimeScale, duration) {
  25973. const mixer = this._mixer,
  25974. now = mixer.time,
  25975. timeScale = this.timeScale;
  25976. let interpolant = this._timeScaleInterpolant;
  25977. if (interpolant === null) {
  25978. interpolant = mixer._lendControlInterpolant();
  25979. this._timeScaleInterpolant = interpolant;
  25980. }
  25981. const times = interpolant.parameterPositions,
  25982. values = interpolant.sampleValues;
  25983. times[0] = now;
  25984. times[1] = now + duration;
  25985. values[0] = startTimeScale / timeScale;
  25986. values[1] = endTimeScale / timeScale;
  25987. return this;
  25988. }
  25989. stopWarping() {
  25990. const timeScaleInterpolant = this._timeScaleInterpolant;
  25991. if (timeScaleInterpolant !== null) {
  25992. this._timeScaleInterpolant = null;
  25993. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  25994. }
  25995. return this;
  25996. } // Object Accessors
  25997. getMixer() {
  25998. return this._mixer;
  25999. }
  26000. getClip() {
  26001. return this._clip;
  26002. }
  26003. getRoot() {
  26004. return this._localRoot || this._mixer._root;
  26005. } // Interna
  26006. _update(time, deltaTime, timeDirection, accuIndex) {
  26007. // called by the mixer
  26008. if (!this.enabled) {
  26009. // call ._updateWeight() to update ._effectiveWeight
  26010. this._updateWeight(time);
  26011. return;
  26012. }
  26013. const startTime = this._startTime;
  26014. if (startTime !== null) {
  26015. // check for scheduled start of action
  26016. const timeRunning = (time - startTime) * timeDirection;
  26017. if (timeRunning < 0 || timeDirection === 0) {
  26018. return; // yet to come / don't decide when delta = 0
  26019. } // start
  26020. this._startTime = null; // unschedule
  26021. deltaTime = timeDirection * timeRunning;
  26022. } // apply time scale and advance time
  26023. deltaTime *= this._updateTimeScale(time);
  26024. const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  26025. // an effective weight of 0
  26026. const weight = this._updateWeight(time);
  26027. if (weight > 0) {
  26028. const interpolants = this._interpolants;
  26029. const propertyMixers = this._propertyBindings;
  26030. switch (this.blendMode) {
  26031. case AdditiveAnimationBlendMode:
  26032. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26033. interpolants[j].evaluate(clipTime);
  26034. propertyMixers[j].accumulateAdditive(weight);
  26035. }
  26036. break;
  26037. case NormalAnimationBlendMode:
  26038. default:
  26039. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26040. interpolants[j].evaluate(clipTime);
  26041. propertyMixers[j].accumulate(accuIndex, weight);
  26042. }
  26043. }
  26044. }
  26045. }
  26046. _updateWeight(time) {
  26047. let weight = 0;
  26048. if (this.enabled) {
  26049. weight = this.weight;
  26050. const interpolant = this._weightInterpolant;
  26051. if (interpolant !== null) {
  26052. const interpolantValue = interpolant.evaluate(time)[0];
  26053. weight *= interpolantValue;
  26054. if (time > interpolant.parameterPositions[1]) {
  26055. this.stopFading();
  26056. if (interpolantValue === 0) {
  26057. // faded out, disable
  26058. this.enabled = false;
  26059. }
  26060. }
  26061. }
  26062. }
  26063. this._effectiveWeight = weight;
  26064. return weight;
  26065. }
  26066. _updateTimeScale(time) {
  26067. let timeScale = 0;
  26068. if (!this.paused) {
  26069. timeScale = this.timeScale;
  26070. const interpolant = this._timeScaleInterpolant;
  26071. if (interpolant !== null) {
  26072. const interpolantValue = interpolant.evaluate(time)[0];
  26073. timeScale *= interpolantValue;
  26074. if (time > interpolant.parameterPositions[1]) {
  26075. this.stopWarping();
  26076. if (timeScale === 0) {
  26077. // motion has halted, pause
  26078. this.paused = true;
  26079. } else {
  26080. // warp done - apply final time scale
  26081. this.timeScale = timeScale;
  26082. }
  26083. }
  26084. }
  26085. }
  26086. this._effectiveTimeScale = timeScale;
  26087. return timeScale;
  26088. }
  26089. _updateTime(deltaTime) {
  26090. const duration = this._clip.duration;
  26091. const loop = this.loop;
  26092. let time = this.time + deltaTime;
  26093. let loopCount = this._loopCount;
  26094. const pingPong = loop === LoopPingPong;
  26095. if (deltaTime === 0) {
  26096. if (loopCount === -1) return time;
  26097. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  26098. }
  26099. if (loop === LoopOnce) {
  26100. if (loopCount === -1) {
  26101. // just started
  26102. this._loopCount = 0;
  26103. this._setEndings(true, true, false);
  26104. }
  26105. handle_stop: {
  26106. if (time >= duration) {
  26107. time = duration;
  26108. } else if (time < 0) {
  26109. time = 0;
  26110. } else {
  26111. this.time = time;
  26112. break handle_stop;
  26113. }
  26114. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26115. this.time = time;
  26116. this._mixer.dispatchEvent({
  26117. type: 'finished',
  26118. action: this,
  26119. direction: deltaTime < 0 ? -1 : 1
  26120. });
  26121. }
  26122. } else {
  26123. // repetitive Repeat or PingPong
  26124. if (loopCount === -1) {
  26125. // just started
  26126. if (deltaTime >= 0) {
  26127. loopCount = 0;
  26128. this._setEndings(true, this.repetitions === 0, pingPong);
  26129. } else {
  26130. // when looping in reverse direction, the initial
  26131. // transition through zero counts as a repetition,
  26132. // so leave loopCount at -1
  26133. this._setEndings(this.repetitions === 0, true, pingPong);
  26134. }
  26135. }
  26136. if (time >= duration || time < 0) {
  26137. // wrap around
  26138. const loopDelta = Math.floor(time / duration); // signed
  26139. time -= duration * loopDelta;
  26140. loopCount += Math.abs(loopDelta);
  26141. const pending = this.repetitions - loopCount;
  26142. if (pending <= 0) {
  26143. // have to stop (switch state, clamp time, fire event)
  26144. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26145. time = deltaTime > 0 ? duration : 0;
  26146. this.time = time;
  26147. this._mixer.dispatchEvent({
  26148. type: 'finished',
  26149. action: this,
  26150. direction: deltaTime > 0 ? 1 : -1
  26151. });
  26152. } else {
  26153. // keep running
  26154. if (pending === 1) {
  26155. // entering the last round
  26156. const atStart = deltaTime < 0;
  26157. this._setEndings(atStart, !atStart, pingPong);
  26158. } else {
  26159. this._setEndings(false, false, pingPong);
  26160. }
  26161. this._loopCount = loopCount;
  26162. this.time = time;
  26163. this._mixer.dispatchEvent({
  26164. type: 'loop',
  26165. action: this,
  26166. loopDelta: loopDelta
  26167. });
  26168. }
  26169. } else {
  26170. this.time = time;
  26171. }
  26172. if (pingPong && (loopCount & 1) === 1) {
  26173. // invert time for the "pong round"
  26174. return duration - time;
  26175. }
  26176. }
  26177. return time;
  26178. }
  26179. _setEndings(atStart, atEnd, pingPong) {
  26180. const settings = this._interpolantSettings;
  26181. if (pingPong) {
  26182. settings.endingStart = ZeroSlopeEnding;
  26183. settings.endingEnd = ZeroSlopeEnding;
  26184. } else {
  26185. // assuming for LoopOnce atStart == atEnd == true
  26186. if (atStart) {
  26187. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26188. } else {
  26189. settings.endingStart = WrapAroundEnding;
  26190. }
  26191. if (atEnd) {
  26192. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26193. } else {
  26194. settings.endingEnd = WrapAroundEnding;
  26195. }
  26196. }
  26197. }
  26198. _scheduleFading(duration, weightNow, weightThen) {
  26199. const mixer = this._mixer,
  26200. now = mixer.time;
  26201. let interpolant = this._weightInterpolant;
  26202. if (interpolant === null) {
  26203. interpolant = mixer._lendControlInterpolant();
  26204. this._weightInterpolant = interpolant;
  26205. }
  26206. const times = interpolant.parameterPositions,
  26207. values = interpolant.sampleValues;
  26208. times[0] = now;
  26209. values[0] = weightNow;
  26210. times[1] = now + duration;
  26211. values[1] = weightThen;
  26212. return this;
  26213. }
  26214. }
  26215. class AnimationMixer extends EventDispatcher {
  26216. constructor(root) {
  26217. super();
  26218. this._root = root;
  26219. this._initMemoryManager();
  26220. this._accuIndex = 0;
  26221. this.time = 0;
  26222. this.timeScale = 1.0;
  26223. }
  26224. _bindAction(action, prototypeAction) {
  26225. const root = action._localRoot || this._root,
  26226. tracks = action._clip.tracks,
  26227. nTracks = tracks.length,
  26228. bindings = action._propertyBindings,
  26229. interpolants = action._interpolants,
  26230. rootUuid = root.uuid,
  26231. bindingsByRoot = this._bindingsByRootAndName;
  26232. let bindingsByName = bindingsByRoot[rootUuid];
  26233. if (bindingsByName === undefined) {
  26234. bindingsByName = {};
  26235. bindingsByRoot[rootUuid] = bindingsByName;
  26236. }
  26237. for (let i = 0; i !== nTracks; ++i) {
  26238. const track = tracks[i],
  26239. trackName = track.name;
  26240. let binding = bindingsByName[trackName];
  26241. if (binding !== undefined) {
  26242. bindings[i] = binding;
  26243. } else {
  26244. binding = bindings[i];
  26245. if (binding !== undefined) {
  26246. // existing binding, make sure the cache knows
  26247. if (binding._cacheIndex === null) {
  26248. ++binding.referenceCount;
  26249. this._addInactiveBinding(binding, rootUuid, trackName);
  26250. }
  26251. continue;
  26252. }
  26253. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  26254. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  26255. ++binding.referenceCount;
  26256. this._addInactiveBinding(binding, rootUuid, trackName);
  26257. bindings[i] = binding;
  26258. }
  26259. interpolants[i].resultBuffer = binding.buffer;
  26260. }
  26261. }
  26262. _activateAction(action) {
  26263. if (!this._isActiveAction(action)) {
  26264. if (action._cacheIndex === null) {
  26265. // this action has been forgotten by the cache, but the user
  26266. // appears to be still using it -> rebind
  26267. const rootUuid = (action._localRoot || this._root).uuid,
  26268. clipUuid = action._clip.uuid,
  26269. actionsForClip = this._actionsByClip[clipUuid];
  26270. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  26271. this._addInactiveAction(action, clipUuid, rootUuid);
  26272. }
  26273. const bindings = action._propertyBindings; // increment reference counts / sort out state
  26274. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26275. const binding = bindings[i];
  26276. if (binding.useCount++ === 0) {
  26277. this._lendBinding(binding);
  26278. binding.saveOriginalState();
  26279. }
  26280. }
  26281. this._lendAction(action);
  26282. }
  26283. }
  26284. _deactivateAction(action) {
  26285. if (this._isActiveAction(action)) {
  26286. const bindings = action._propertyBindings; // decrement reference counts / sort out state
  26287. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26288. const binding = bindings[i];
  26289. if (--binding.useCount === 0) {
  26290. binding.restoreOriginalState();
  26291. this._takeBackBinding(binding);
  26292. }
  26293. }
  26294. this._takeBackAction(action);
  26295. }
  26296. } // Memory manager
  26297. _initMemoryManager() {
  26298. this._actions = []; // 'nActiveActions' followed by inactive ones
  26299. this._nActiveActions = 0;
  26300. this._actionsByClip = {}; // inside:
  26301. // {
  26302. // knownActions: Array< AnimationAction > - used as prototypes
  26303. // actionByRoot: AnimationAction - lookup
  26304. // }
  26305. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  26306. this._nActiveBindings = 0;
  26307. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  26308. this._controlInterpolants = []; // same game as above
  26309. this._nActiveControlInterpolants = 0;
  26310. const scope = this;
  26311. this.stats = {
  26312. actions: {
  26313. get total() {
  26314. return scope._actions.length;
  26315. },
  26316. get inUse() {
  26317. return scope._nActiveActions;
  26318. }
  26319. },
  26320. bindings: {
  26321. get total() {
  26322. return scope._bindings.length;
  26323. },
  26324. get inUse() {
  26325. return scope._nActiveBindings;
  26326. }
  26327. },
  26328. controlInterpolants: {
  26329. get total() {
  26330. return scope._controlInterpolants.length;
  26331. },
  26332. get inUse() {
  26333. return scope._nActiveControlInterpolants;
  26334. }
  26335. }
  26336. };
  26337. } // Memory management for AnimationAction objects
  26338. _isActiveAction(action) {
  26339. const index = action._cacheIndex;
  26340. return index !== null && index < this._nActiveActions;
  26341. }
  26342. _addInactiveAction(action, clipUuid, rootUuid) {
  26343. const actions = this._actions,
  26344. actionsByClip = this._actionsByClip;
  26345. let actionsForClip = actionsByClip[clipUuid];
  26346. if (actionsForClip === undefined) {
  26347. actionsForClip = {
  26348. knownActions: [action],
  26349. actionByRoot: {}
  26350. };
  26351. action._byClipCacheIndex = 0;
  26352. actionsByClip[clipUuid] = actionsForClip;
  26353. } else {
  26354. const knownActions = actionsForClip.knownActions;
  26355. action._byClipCacheIndex = knownActions.length;
  26356. knownActions.push(action);
  26357. }
  26358. action._cacheIndex = actions.length;
  26359. actions.push(action);
  26360. actionsForClip.actionByRoot[rootUuid] = action;
  26361. }
  26362. _removeInactiveAction(action) {
  26363. const actions = this._actions,
  26364. lastInactiveAction = actions[actions.length - 1],
  26365. cacheIndex = action._cacheIndex;
  26366. lastInactiveAction._cacheIndex = cacheIndex;
  26367. actions[cacheIndex] = lastInactiveAction;
  26368. actions.pop();
  26369. action._cacheIndex = null;
  26370. const clipUuid = action._clip.uuid,
  26371. actionsByClip = this._actionsByClip,
  26372. actionsForClip = actionsByClip[clipUuid],
  26373. knownActionsForClip = actionsForClip.knownActions,
  26374. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  26375. byClipCacheIndex = action._byClipCacheIndex;
  26376. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  26377. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  26378. knownActionsForClip.pop();
  26379. action._byClipCacheIndex = null;
  26380. const actionByRoot = actionsForClip.actionByRoot,
  26381. rootUuid = (action._localRoot || this._root).uuid;
  26382. delete actionByRoot[rootUuid];
  26383. if (knownActionsForClip.length === 0) {
  26384. delete actionsByClip[clipUuid];
  26385. }
  26386. this._removeInactiveBindingsForAction(action);
  26387. }
  26388. _removeInactiveBindingsForAction(action) {
  26389. const bindings = action._propertyBindings;
  26390. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26391. const binding = bindings[i];
  26392. if (--binding.referenceCount === 0) {
  26393. this._removeInactiveBinding(binding);
  26394. }
  26395. }
  26396. }
  26397. _lendAction(action) {
  26398. // [ active actions | inactive actions ]
  26399. // [ active actions >| inactive actions ]
  26400. // s a
  26401. // <-swap->
  26402. // a s
  26403. const actions = this._actions,
  26404. prevIndex = action._cacheIndex,
  26405. lastActiveIndex = this._nActiveActions++,
  26406. firstInactiveAction = actions[lastActiveIndex];
  26407. action._cacheIndex = lastActiveIndex;
  26408. actions[lastActiveIndex] = action;
  26409. firstInactiveAction._cacheIndex = prevIndex;
  26410. actions[prevIndex] = firstInactiveAction;
  26411. }
  26412. _takeBackAction(action) {
  26413. // [ active actions | inactive actions ]
  26414. // [ active actions |< inactive actions ]
  26415. // a s
  26416. // <-swap->
  26417. // s a
  26418. const actions = this._actions,
  26419. prevIndex = action._cacheIndex,
  26420. firstInactiveIndex = --this._nActiveActions,
  26421. lastActiveAction = actions[firstInactiveIndex];
  26422. action._cacheIndex = firstInactiveIndex;
  26423. actions[firstInactiveIndex] = action;
  26424. lastActiveAction._cacheIndex = prevIndex;
  26425. actions[prevIndex] = lastActiveAction;
  26426. } // Memory management for PropertyMixer objects
  26427. _addInactiveBinding(binding, rootUuid, trackName) {
  26428. const bindingsByRoot = this._bindingsByRootAndName,
  26429. bindings = this._bindings;
  26430. let bindingByName = bindingsByRoot[rootUuid];
  26431. if (bindingByName === undefined) {
  26432. bindingByName = {};
  26433. bindingsByRoot[rootUuid] = bindingByName;
  26434. }
  26435. bindingByName[trackName] = binding;
  26436. binding._cacheIndex = bindings.length;
  26437. bindings.push(binding);
  26438. }
  26439. _removeInactiveBinding(binding) {
  26440. const bindings = this._bindings,
  26441. propBinding = binding.binding,
  26442. rootUuid = propBinding.rootNode.uuid,
  26443. trackName = propBinding.path,
  26444. bindingsByRoot = this._bindingsByRootAndName,
  26445. bindingByName = bindingsByRoot[rootUuid],
  26446. lastInactiveBinding = bindings[bindings.length - 1],
  26447. cacheIndex = binding._cacheIndex;
  26448. lastInactiveBinding._cacheIndex = cacheIndex;
  26449. bindings[cacheIndex] = lastInactiveBinding;
  26450. bindings.pop();
  26451. delete bindingByName[trackName];
  26452. if (Object.keys(bindingByName).length === 0) {
  26453. delete bindingsByRoot[rootUuid];
  26454. }
  26455. }
  26456. _lendBinding(binding) {
  26457. const bindings = this._bindings,
  26458. prevIndex = binding._cacheIndex,
  26459. lastActiveIndex = this._nActiveBindings++,
  26460. firstInactiveBinding = bindings[lastActiveIndex];
  26461. binding._cacheIndex = lastActiveIndex;
  26462. bindings[lastActiveIndex] = binding;
  26463. firstInactiveBinding._cacheIndex = prevIndex;
  26464. bindings[prevIndex] = firstInactiveBinding;
  26465. }
  26466. _takeBackBinding(binding) {
  26467. const bindings = this._bindings,
  26468. prevIndex = binding._cacheIndex,
  26469. firstInactiveIndex = --this._nActiveBindings,
  26470. lastActiveBinding = bindings[firstInactiveIndex];
  26471. binding._cacheIndex = firstInactiveIndex;
  26472. bindings[firstInactiveIndex] = binding;
  26473. lastActiveBinding._cacheIndex = prevIndex;
  26474. bindings[prevIndex] = lastActiveBinding;
  26475. } // Memory management of Interpolants for weight and time scale
  26476. _lendControlInterpolant() {
  26477. const interpolants = this._controlInterpolants,
  26478. lastActiveIndex = this._nActiveControlInterpolants++;
  26479. let interpolant = interpolants[lastActiveIndex];
  26480. if (interpolant === undefined) {
  26481. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  26482. interpolant.__cacheIndex = lastActiveIndex;
  26483. interpolants[lastActiveIndex] = interpolant;
  26484. }
  26485. return interpolant;
  26486. }
  26487. _takeBackControlInterpolant(interpolant) {
  26488. const interpolants = this._controlInterpolants,
  26489. prevIndex = interpolant.__cacheIndex,
  26490. firstInactiveIndex = --this._nActiveControlInterpolants,
  26491. lastActiveInterpolant = interpolants[firstInactiveIndex];
  26492. interpolant.__cacheIndex = firstInactiveIndex;
  26493. interpolants[firstInactiveIndex] = interpolant;
  26494. lastActiveInterpolant.__cacheIndex = prevIndex;
  26495. interpolants[prevIndex] = lastActiveInterpolant;
  26496. } // return an action for a clip optionally using a custom root target
  26497. // object (this method allocates a lot of dynamic memory in case a
  26498. // previously unknown clip/root combination is specified)
  26499. clipAction(clip, optionalRoot, blendMode) {
  26500. const root = optionalRoot || this._root,
  26501. rootUuid = root.uuid;
  26502. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  26503. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  26504. const actionsForClip = this._actionsByClip[clipUuid];
  26505. let prototypeAction = null;
  26506. if (blendMode === undefined) {
  26507. if (clipObject !== null) {
  26508. blendMode = clipObject.blendMode;
  26509. } else {
  26510. blendMode = NormalAnimationBlendMode;
  26511. }
  26512. }
  26513. if (actionsForClip !== undefined) {
  26514. const existingAction = actionsForClip.actionByRoot[rootUuid];
  26515. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  26516. return existingAction;
  26517. } // we know the clip, so we don't have to parse all
  26518. // the bindings again but can just copy
  26519. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  26520. if (clipObject === null) clipObject = prototypeAction._clip;
  26521. } // clip must be known when specified via string
  26522. if (clipObject === null) return null; // allocate all resources required to run it
  26523. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  26524. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  26525. this._addInactiveAction(newAction, clipUuid, rootUuid);
  26526. return newAction;
  26527. } // get an existing action
  26528. existingAction(clip, optionalRoot) {
  26529. const root = optionalRoot || this._root,
  26530. rootUuid = root.uuid,
  26531. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  26532. clipUuid = clipObject ? clipObject.uuid : clip,
  26533. actionsForClip = this._actionsByClip[clipUuid];
  26534. if (actionsForClip !== undefined) {
  26535. return actionsForClip.actionByRoot[rootUuid] || null;
  26536. }
  26537. return null;
  26538. } // deactivates all previously scheduled actions
  26539. stopAllAction() {
  26540. const actions = this._actions,
  26541. nActions = this._nActiveActions;
  26542. for (let i = nActions - 1; i >= 0; --i) {
  26543. actions[i].stop();
  26544. }
  26545. return this;
  26546. } // advance the time and update apply the animation
  26547. update(deltaTime) {
  26548. deltaTime *= this.timeScale;
  26549. const actions = this._actions,
  26550. nActions = this._nActiveActions,
  26551. time = this.time += deltaTime,
  26552. timeDirection = Math.sign(deltaTime),
  26553. accuIndex = this._accuIndex ^= 1; // run active actions
  26554. for (let i = 0; i !== nActions; ++i) {
  26555. const action = actions[i];
  26556. action._update(time, deltaTime, timeDirection, accuIndex);
  26557. } // update scene graph
  26558. const bindings = this._bindings,
  26559. nBindings = this._nActiveBindings;
  26560. for (let i = 0; i !== nBindings; ++i) {
  26561. bindings[i].apply(accuIndex);
  26562. }
  26563. return this;
  26564. } // Allows you to seek to a specific time in an animation.
  26565. setTime(timeInSeconds) {
  26566. this.time = 0; // Zero out time attribute for AnimationMixer object;
  26567. for (let i = 0; i < this._actions.length; i++) {
  26568. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  26569. }
  26570. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  26571. } // return this mixer's root target object
  26572. getRoot() {
  26573. return this._root;
  26574. } // free all resources specific to a particular clip
  26575. uncacheClip(clip) {
  26576. const actions = this._actions,
  26577. clipUuid = clip.uuid,
  26578. actionsByClip = this._actionsByClip,
  26579. actionsForClip = actionsByClip[clipUuid];
  26580. if (actionsForClip !== undefined) {
  26581. // note: just calling _removeInactiveAction would mess up the
  26582. // iteration state and also require updating the state we can
  26583. // just throw away
  26584. const actionsToRemove = actionsForClip.knownActions;
  26585. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  26586. const action = actionsToRemove[i];
  26587. this._deactivateAction(action);
  26588. const cacheIndex = action._cacheIndex,
  26589. lastInactiveAction = actions[actions.length - 1];
  26590. action._cacheIndex = null;
  26591. action._byClipCacheIndex = null;
  26592. lastInactiveAction._cacheIndex = cacheIndex;
  26593. actions[cacheIndex] = lastInactiveAction;
  26594. actions.pop();
  26595. this._removeInactiveBindingsForAction(action);
  26596. }
  26597. delete actionsByClip[clipUuid];
  26598. }
  26599. } // free all resources specific to a particular root target object
  26600. uncacheRoot(root) {
  26601. const rootUuid = root.uuid,
  26602. actionsByClip = this._actionsByClip;
  26603. for (const clipUuid in actionsByClip) {
  26604. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  26605. action = actionByRoot[rootUuid];
  26606. if (action !== undefined) {
  26607. this._deactivateAction(action);
  26608. this._removeInactiveAction(action);
  26609. }
  26610. }
  26611. const bindingsByRoot = this._bindingsByRootAndName,
  26612. bindingByName = bindingsByRoot[rootUuid];
  26613. if (bindingByName !== undefined) {
  26614. for (const trackName in bindingByName) {
  26615. const binding = bindingByName[trackName];
  26616. binding.restoreOriginalState();
  26617. this._removeInactiveBinding(binding);
  26618. }
  26619. }
  26620. } // remove a targeted clip from the cache
  26621. uncacheAction(clip, optionalRoot) {
  26622. const action = this.existingAction(clip, optionalRoot);
  26623. if (action !== null) {
  26624. this._deactivateAction(action);
  26625. this._removeInactiveAction(action);
  26626. }
  26627. }
  26628. }
  26629. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array(1);
  26630. class Uniform {
  26631. constructor(value) {
  26632. if (typeof value === 'string') {
  26633. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  26634. value = arguments[1];
  26635. }
  26636. this.value = value;
  26637. }
  26638. clone() {
  26639. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  26640. }
  26641. }
  26642. class InstancedInterleavedBuffer extends InterleavedBuffer {
  26643. constructor(array, stride, meshPerAttribute = 1) {
  26644. super(array, stride);
  26645. this.meshPerAttribute = meshPerAttribute;
  26646. }
  26647. copy(source) {
  26648. super.copy(source);
  26649. this.meshPerAttribute = source.meshPerAttribute;
  26650. return this;
  26651. }
  26652. clone(data) {
  26653. const ib = super.clone(data);
  26654. ib.meshPerAttribute = this.meshPerAttribute;
  26655. return ib;
  26656. }
  26657. toJSON(data) {
  26658. const json = super.toJSON(data);
  26659. json.isInstancedInterleavedBuffer = true;
  26660. json.meshPerAttribute = this.meshPerAttribute;
  26661. return json;
  26662. }
  26663. }
  26664. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  26665. class GLBufferAttribute {
  26666. constructor(buffer, type, itemSize, elementSize, count) {
  26667. this.buffer = buffer;
  26668. this.type = type;
  26669. this.itemSize = itemSize;
  26670. this.elementSize = elementSize;
  26671. this.count = count;
  26672. this.version = 0;
  26673. }
  26674. set needsUpdate(value) {
  26675. if (value === true) this.version++;
  26676. }
  26677. setBuffer(buffer) {
  26678. this.buffer = buffer;
  26679. return this;
  26680. }
  26681. setType(type, elementSize) {
  26682. this.type = type;
  26683. this.elementSize = elementSize;
  26684. return this;
  26685. }
  26686. setItemSize(itemSize) {
  26687. this.itemSize = itemSize;
  26688. return this;
  26689. }
  26690. setCount(count) {
  26691. this.count = count;
  26692. return this;
  26693. }
  26694. }
  26695. GLBufferAttribute.prototype.isGLBufferAttribute = true;
  26696. class Raycaster {
  26697. constructor(origin, direction, near = 0, far = Infinity) {
  26698. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  26699. this.near = near;
  26700. this.far = far;
  26701. this.camera = null;
  26702. this.layers = new Layers();
  26703. this.params = {
  26704. Mesh: {},
  26705. Line: {
  26706. threshold: 1
  26707. },
  26708. LOD: {},
  26709. Points: {
  26710. threshold: 1
  26711. },
  26712. Sprite: {}
  26713. };
  26714. }
  26715. set(origin, direction) {
  26716. // direction is assumed to be normalized (for accurate distance calculations)
  26717. this.ray.set(origin, direction);
  26718. }
  26719. setFromCamera(coords, camera) {
  26720. if (camera && camera.isPerspectiveCamera) {
  26721. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  26722. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  26723. this.camera = camera;
  26724. } else if (camera && camera.isOrthographicCamera) {
  26725. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  26726. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  26727. this.camera = camera;
  26728. } else {
  26729. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  26730. }
  26731. }
  26732. intersectObject(object, recursive = true, intersects = []) {
  26733. intersectObject(object, this, intersects, recursive);
  26734. intersects.sort(ascSort);
  26735. return intersects;
  26736. }
  26737. intersectObjects(objects, recursive = true, intersects = []) {
  26738. for (let i = 0, l = objects.length; i < l; i++) {
  26739. intersectObject(objects[i], this, intersects, recursive);
  26740. }
  26741. intersects.sort(ascSort);
  26742. return intersects;
  26743. }
  26744. }
  26745. function ascSort(a, b) {
  26746. return a.distance - b.distance;
  26747. }
  26748. function intersectObject(object, raycaster, intersects, recursive) {
  26749. if (object.layers.test(raycaster.layers)) {
  26750. object.raycast(raycaster, intersects);
  26751. }
  26752. if (recursive === true) {
  26753. const children = object.children;
  26754. for (let i = 0, l = children.length; i < l; i++) {
  26755. intersectObject(children[i], raycaster, intersects, true);
  26756. }
  26757. }
  26758. }
  26759. /**
  26760. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  26761. *
  26762. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  26763. * The azimuthal angle (theta) is measured from the positive z-axis.
  26764. */
  26765. class Spherical {
  26766. constructor(radius = 1, phi = 0, theta = 0) {
  26767. this.radius = radius;
  26768. this.phi = phi; // polar angle
  26769. this.theta = theta; // azimuthal angle
  26770. return this;
  26771. }
  26772. set(radius, phi, theta) {
  26773. this.radius = radius;
  26774. this.phi = phi;
  26775. this.theta = theta;
  26776. return this;
  26777. }
  26778. copy(other) {
  26779. this.radius = other.radius;
  26780. this.phi = other.phi;
  26781. this.theta = other.theta;
  26782. return this;
  26783. } // restrict phi to be betwee EPS and PI-EPS
  26784. makeSafe() {
  26785. const EPS = 0.000001;
  26786. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  26787. return this;
  26788. }
  26789. setFromVector3(v) {
  26790. return this.setFromCartesianCoords(v.x, v.y, v.z);
  26791. }
  26792. setFromCartesianCoords(x, y, z) {
  26793. this.radius = Math.sqrt(x * x + y * y + z * z);
  26794. if (this.radius === 0) {
  26795. this.theta = 0;
  26796. this.phi = 0;
  26797. } else {
  26798. this.theta = Math.atan2(x, z);
  26799. this.phi = Math.acos(clamp(y / this.radius, -1, 1));
  26800. }
  26801. return this;
  26802. }
  26803. clone() {
  26804. return new this.constructor().copy(this);
  26805. }
  26806. }
  26807. /**
  26808. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  26809. */
  26810. class Cylindrical {
  26811. constructor(radius = 1, theta = 0, y = 0) {
  26812. this.radius = radius; // distance from the origin to a point in the x-z plane
  26813. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  26814. this.y = y; // height above the x-z plane
  26815. return this;
  26816. }
  26817. set(radius, theta, y) {
  26818. this.radius = radius;
  26819. this.theta = theta;
  26820. this.y = y;
  26821. return this;
  26822. }
  26823. copy(other) {
  26824. this.radius = other.radius;
  26825. this.theta = other.theta;
  26826. this.y = other.y;
  26827. return this;
  26828. }
  26829. setFromVector3(v) {
  26830. return this.setFromCartesianCoords(v.x, v.y, v.z);
  26831. }
  26832. setFromCartesianCoords(x, y, z) {
  26833. this.radius = Math.sqrt(x * x + z * z);
  26834. this.theta = Math.atan2(x, z);
  26835. this.y = y;
  26836. return this;
  26837. }
  26838. clone() {
  26839. return new this.constructor().copy(this);
  26840. }
  26841. }
  26842. const _vector$4 = /*@__PURE__*/new Vector2();
  26843. class Box2 {
  26844. constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) {
  26845. this.min = min;
  26846. this.max = max;
  26847. }
  26848. set(min, max) {
  26849. this.min.copy(min);
  26850. this.max.copy(max);
  26851. return this;
  26852. }
  26853. setFromPoints(points) {
  26854. this.makeEmpty();
  26855. for (let i = 0, il = points.length; i < il; i++) {
  26856. this.expandByPoint(points[i]);
  26857. }
  26858. return this;
  26859. }
  26860. setFromCenterAndSize(center, size) {
  26861. const halfSize = _vector$4.copy(size).multiplyScalar(0.5);
  26862. this.min.copy(center).sub(halfSize);
  26863. this.max.copy(center).add(halfSize);
  26864. return this;
  26865. }
  26866. clone() {
  26867. return new this.constructor().copy(this);
  26868. }
  26869. copy(box) {
  26870. this.min.copy(box.min);
  26871. this.max.copy(box.max);
  26872. return this;
  26873. }
  26874. makeEmpty() {
  26875. this.min.x = this.min.y = +Infinity;
  26876. this.max.x = this.max.y = -Infinity;
  26877. return this;
  26878. }
  26879. isEmpty() {
  26880. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  26881. return this.max.x < this.min.x || this.max.y < this.min.y;
  26882. }
  26883. getCenter(target) {
  26884. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  26885. }
  26886. getSize(target) {
  26887. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  26888. }
  26889. expandByPoint(point) {
  26890. this.min.min(point);
  26891. this.max.max(point);
  26892. return this;
  26893. }
  26894. expandByVector(vector) {
  26895. this.min.sub(vector);
  26896. this.max.add(vector);
  26897. return this;
  26898. }
  26899. expandByScalar(scalar) {
  26900. this.min.addScalar(-scalar);
  26901. this.max.addScalar(scalar);
  26902. return this;
  26903. }
  26904. containsPoint(point) {
  26905. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  26906. }
  26907. containsBox(box) {
  26908. 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;
  26909. }
  26910. getParameter(point, target) {
  26911. // This can potentially have a divide by zero if the box
  26912. // has a size dimension of 0.
  26913. 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));
  26914. }
  26915. intersectsBox(box) {
  26916. // using 4 splitting planes to rule out intersections
  26917. 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;
  26918. }
  26919. clampPoint(point, target) {
  26920. return target.copy(point).clamp(this.min, this.max);
  26921. }
  26922. distanceToPoint(point) {
  26923. const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max);
  26924. return clampedPoint.sub(point).length();
  26925. }
  26926. intersect(box) {
  26927. this.min.max(box.min);
  26928. this.max.min(box.max);
  26929. return this;
  26930. }
  26931. union(box) {
  26932. this.min.min(box.min);
  26933. this.max.max(box.max);
  26934. return this;
  26935. }
  26936. translate(offset) {
  26937. this.min.add(offset);
  26938. this.max.add(offset);
  26939. return this;
  26940. }
  26941. equals(box) {
  26942. return box.min.equals(this.min) && box.max.equals(this.max);
  26943. }
  26944. }
  26945. Box2.prototype.isBox2 = true;
  26946. const _startP = /*@__PURE__*/new Vector3();
  26947. const _startEnd = /*@__PURE__*/new Vector3();
  26948. class Line3 {
  26949. constructor(start = new Vector3(), end = new Vector3()) {
  26950. this.start = start;
  26951. this.end = end;
  26952. }
  26953. set(start, end) {
  26954. this.start.copy(start);
  26955. this.end.copy(end);
  26956. return this;
  26957. }
  26958. copy(line) {
  26959. this.start.copy(line.start);
  26960. this.end.copy(line.end);
  26961. return this;
  26962. }
  26963. getCenter(target) {
  26964. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  26965. }
  26966. delta(target) {
  26967. return target.subVectors(this.end, this.start);
  26968. }
  26969. distanceSq() {
  26970. return this.start.distanceToSquared(this.end);
  26971. }
  26972. distance() {
  26973. return this.start.distanceTo(this.end);
  26974. }
  26975. at(t, target) {
  26976. return this.delta(target).multiplyScalar(t).add(this.start);
  26977. }
  26978. closestPointToPointParameter(point, clampToLine) {
  26979. _startP.subVectors(point, this.start);
  26980. _startEnd.subVectors(this.end, this.start);
  26981. const startEnd2 = _startEnd.dot(_startEnd);
  26982. const startEnd_startP = _startEnd.dot(_startP);
  26983. let t = startEnd_startP / startEnd2;
  26984. if (clampToLine) {
  26985. t = clamp(t, 0, 1);
  26986. }
  26987. return t;
  26988. }
  26989. closestPointToPoint(point, clampToLine, target) {
  26990. const t = this.closestPointToPointParameter(point, clampToLine);
  26991. return this.delta(target).multiplyScalar(t).add(this.start);
  26992. }
  26993. applyMatrix4(matrix) {
  26994. this.start.applyMatrix4(matrix);
  26995. this.end.applyMatrix4(matrix);
  26996. return this;
  26997. }
  26998. equals(line) {
  26999. return line.start.equals(this.start) && line.end.equals(this.end);
  27000. }
  27001. clone() {
  27002. return new this.constructor().copy(this);
  27003. }
  27004. }
  27005. class ImmediateRenderObject extends Object3D {
  27006. constructor(material) {
  27007. super();
  27008. this.material = material;
  27009. this.render = function () {};
  27010. this.hasPositions = false;
  27011. this.hasNormals = false;
  27012. this.hasColors = false;
  27013. this.hasUvs = false;
  27014. this.positionArray = null;
  27015. this.normalArray = null;
  27016. this.colorArray = null;
  27017. this.uvArray = null;
  27018. this.count = 0;
  27019. }
  27020. }
  27021. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  27022. const _vector$3 = /*@__PURE__*/new Vector3();
  27023. class SpotLightHelper extends Object3D {
  27024. constructor(light, color) {
  27025. super();
  27026. this.light = light;
  27027. this.light.updateMatrixWorld();
  27028. this.matrix = light.matrixWorld;
  27029. this.matrixAutoUpdate = false;
  27030. this.color = color;
  27031. const geometry = new BufferGeometry();
  27032. 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];
  27033. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  27034. const p1 = i / l * Math.PI * 2;
  27035. const p2 = j / l * Math.PI * 2;
  27036. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  27037. }
  27038. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27039. const material = new LineBasicMaterial({
  27040. fog: false,
  27041. toneMapped: false
  27042. });
  27043. this.cone = new LineSegments(geometry, material);
  27044. this.add(this.cone);
  27045. this.update();
  27046. }
  27047. dispose() {
  27048. this.cone.geometry.dispose();
  27049. this.cone.material.dispose();
  27050. }
  27051. update() {
  27052. this.light.updateMatrixWorld();
  27053. const coneLength = this.light.distance ? this.light.distance : 1000;
  27054. const coneWidth = coneLength * Math.tan(this.light.angle);
  27055. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  27056. _vector$3.setFromMatrixPosition(this.light.target.matrixWorld);
  27057. this.cone.lookAt(_vector$3);
  27058. if (this.color !== undefined) {
  27059. this.cone.material.color.set(this.color);
  27060. } else {
  27061. this.cone.material.color.copy(this.light.color);
  27062. }
  27063. }
  27064. }
  27065. const _vector$2 = /*@__PURE__*/new Vector3();
  27066. const _boneMatrix = /*@__PURE__*/new Matrix4();
  27067. const _matrixWorldInv = /*@__PURE__*/new Matrix4();
  27068. class SkeletonHelper extends LineSegments {
  27069. constructor(object) {
  27070. const bones = getBoneList(object);
  27071. const geometry = new BufferGeometry();
  27072. const vertices = [];
  27073. const colors = [];
  27074. const color1 = new Color(0, 0, 1);
  27075. const color2 = new Color(0, 1, 0);
  27076. for (let i = 0; i < bones.length; i++) {
  27077. const bone = bones[i];
  27078. if (bone.parent && bone.parent.isBone) {
  27079. vertices.push(0, 0, 0);
  27080. vertices.push(0, 0, 0);
  27081. colors.push(color1.r, color1.g, color1.b);
  27082. colors.push(color2.r, color2.g, color2.b);
  27083. }
  27084. }
  27085. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27086. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27087. const material = new LineBasicMaterial({
  27088. vertexColors: true,
  27089. depthTest: false,
  27090. depthWrite: false,
  27091. toneMapped: false,
  27092. transparent: true
  27093. });
  27094. super(geometry, material);
  27095. this.type = 'SkeletonHelper';
  27096. this.isSkeletonHelper = true;
  27097. this.root = object;
  27098. this.bones = bones;
  27099. this.matrix = object.matrixWorld;
  27100. this.matrixAutoUpdate = false;
  27101. }
  27102. updateMatrixWorld(force) {
  27103. const bones = this.bones;
  27104. const geometry = this.geometry;
  27105. const position = geometry.getAttribute('position');
  27106. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  27107. for (let i = 0, j = 0; i < bones.length; i++) {
  27108. const bone = bones[i];
  27109. if (bone.parent && bone.parent.isBone) {
  27110. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  27111. _vector$2.setFromMatrixPosition(_boneMatrix);
  27112. position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z);
  27113. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  27114. _vector$2.setFromMatrixPosition(_boneMatrix);
  27115. position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z);
  27116. j += 2;
  27117. }
  27118. }
  27119. geometry.getAttribute('position').needsUpdate = true;
  27120. super.updateMatrixWorld(force);
  27121. }
  27122. }
  27123. function getBoneList(object) {
  27124. const boneList = [];
  27125. if (object && object.isBone) {
  27126. boneList.push(object);
  27127. }
  27128. for (let i = 0; i < object.children.length; i++) {
  27129. boneList.push.apply(boneList, getBoneList(object.children[i]));
  27130. }
  27131. return boneList;
  27132. }
  27133. class PointLightHelper extends Mesh {
  27134. constructor(light, sphereSize, color) {
  27135. const geometry = new SphereGeometry(sphereSize, 4, 2);
  27136. const material = new MeshBasicMaterial({
  27137. wireframe: true,
  27138. fog: false,
  27139. toneMapped: false
  27140. });
  27141. super(geometry, material);
  27142. this.light = light;
  27143. this.light.updateMatrixWorld();
  27144. this.color = color;
  27145. this.type = 'PointLightHelper';
  27146. this.matrix = this.light.matrixWorld;
  27147. this.matrixAutoUpdate = false;
  27148. this.update();
  27149. /*
  27150. // TODO: delete this comment?
  27151. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  27152. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  27153. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  27154. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  27155. const d = light.distance;
  27156. if ( d === 0.0 ) {
  27157. this.lightDistance.visible = false;
  27158. } else {
  27159. this.lightDistance.scale.set( d, d, d );
  27160. }
  27161. this.add( this.lightDistance );
  27162. */
  27163. }
  27164. dispose() {
  27165. this.geometry.dispose();
  27166. this.material.dispose();
  27167. }
  27168. update() {
  27169. if (this.color !== undefined) {
  27170. this.material.color.set(this.color);
  27171. } else {
  27172. this.material.color.copy(this.light.color);
  27173. }
  27174. /*
  27175. const d = this.light.distance;
  27176. if ( d === 0.0 ) {
  27177. this.lightDistance.visible = false;
  27178. } else {
  27179. this.lightDistance.visible = true;
  27180. this.lightDistance.scale.set( d, d, d );
  27181. }
  27182. */
  27183. }
  27184. }
  27185. const _vector$1 = /*@__PURE__*/new Vector3();
  27186. const _color1 = /*@__PURE__*/new Color();
  27187. const _color2 = /*@__PURE__*/new Color();
  27188. class HemisphereLightHelper extends Object3D {
  27189. constructor(light, size, color) {
  27190. super();
  27191. this.light = light;
  27192. this.light.updateMatrixWorld();
  27193. this.matrix = light.matrixWorld;
  27194. this.matrixAutoUpdate = false;
  27195. this.color = color;
  27196. const geometry = new OctahedronGeometry(size);
  27197. geometry.rotateY(Math.PI * 0.5);
  27198. this.material = new MeshBasicMaterial({
  27199. wireframe: true,
  27200. fog: false,
  27201. toneMapped: false
  27202. });
  27203. if (this.color === undefined) this.material.vertexColors = true;
  27204. const position = geometry.getAttribute('position');
  27205. const colors = new Float32Array(position.count * 3);
  27206. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  27207. this.add(new Mesh(geometry, this.material));
  27208. this.update();
  27209. }
  27210. dispose() {
  27211. this.children[0].geometry.dispose();
  27212. this.children[0].material.dispose();
  27213. }
  27214. update() {
  27215. const mesh = this.children[0];
  27216. if (this.color !== undefined) {
  27217. this.material.color.set(this.color);
  27218. } else {
  27219. const colors = mesh.geometry.getAttribute('color');
  27220. _color1.copy(this.light.color);
  27221. _color2.copy(this.light.groundColor);
  27222. for (let i = 0, l = colors.count; i < l; i++) {
  27223. const color = i < l / 2 ? _color1 : _color2;
  27224. colors.setXYZ(i, color.r, color.g, color.b);
  27225. }
  27226. colors.needsUpdate = true;
  27227. }
  27228. mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
  27229. }
  27230. }
  27231. class GridHelper extends LineSegments {
  27232. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  27233. color1 = new Color(color1);
  27234. color2 = new Color(color2);
  27235. const center = divisions / 2;
  27236. const step = size / divisions;
  27237. const halfSize = size / 2;
  27238. const vertices = [],
  27239. colors = [];
  27240. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  27241. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  27242. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  27243. const color = i === center ? color1 : color2;
  27244. color.toArray(colors, j);
  27245. j += 3;
  27246. color.toArray(colors, j);
  27247. j += 3;
  27248. color.toArray(colors, j);
  27249. j += 3;
  27250. color.toArray(colors, j);
  27251. j += 3;
  27252. }
  27253. const geometry = new BufferGeometry();
  27254. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27255. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27256. const material = new LineBasicMaterial({
  27257. vertexColors: true,
  27258. toneMapped: false
  27259. });
  27260. super(geometry, material);
  27261. this.type = 'GridHelper';
  27262. }
  27263. }
  27264. class PolarGridHelper extends LineSegments {
  27265. constructor(radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  27266. color1 = new Color(color1);
  27267. color2 = new Color(color2);
  27268. const vertices = [];
  27269. const colors = []; // create the radials
  27270. for (let i = 0; i <= radials; i++) {
  27271. const v = i / radials * (Math.PI * 2);
  27272. const x = Math.sin(v) * radius;
  27273. const z = Math.cos(v) * radius;
  27274. vertices.push(0, 0, 0);
  27275. vertices.push(x, 0, z);
  27276. const color = i & 1 ? color1 : color2;
  27277. colors.push(color.r, color.g, color.b);
  27278. colors.push(color.r, color.g, color.b);
  27279. } // create the circles
  27280. for (let i = 0; i <= circles; i++) {
  27281. const color = i & 1 ? color1 : color2;
  27282. const r = radius - radius / circles * i;
  27283. for (let j = 0; j < divisions; j++) {
  27284. // first vertex
  27285. let v = j / divisions * (Math.PI * 2);
  27286. let x = Math.sin(v) * r;
  27287. let z = Math.cos(v) * r;
  27288. vertices.push(x, 0, z);
  27289. colors.push(color.r, color.g, color.b); // second vertex
  27290. v = (j + 1) / divisions * (Math.PI * 2);
  27291. x = Math.sin(v) * r;
  27292. z = Math.cos(v) * r;
  27293. vertices.push(x, 0, z);
  27294. colors.push(color.r, color.g, color.b);
  27295. }
  27296. }
  27297. const geometry = new BufferGeometry();
  27298. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27299. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27300. const material = new LineBasicMaterial({
  27301. vertexColors: true,
  27302. toneMapped: false
  27303. });
  27304. super(geometry, material);
  27305. this.type = 'PolarGridHelper';
  27306. }
  27307. }
  27308. const _v1 = /*@__PURE__*/new Vector3();
  27309. const _v2 = /*@__PURE__*/new Vector3();
  27310. const _v3 = /*@__PURE__*/new Vector3();
  27311. class DirectionalLightHelper extends Object3D {
  27312. constructor(light, size, color) {
  27313. super();
  27314. this.light = light;
  27315. this.light.updateMatrixWorld();
  27316. this.matrix = light.matrixWorld;
  27317. this.matrixAutoUpdate = false;
  27318. this.color = color;
  27319. if (size === undefined) size = 1;
  27320. let geometry = new BufferGeometry();
  27321. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  27322. const material = new LineBasicMaterial({
  27323. fog: false,
  27324. toneMapped: false
  27325. });
  27326. this.lightPlane = new Line(geometry, material);
  27327. this.add(this.lightPlane);
  27328. geometry = new BufferGeometry();
  27329. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  27330. this.targetLine = new Line(geometry, material);
  27331. this.add(this.targetLine);
  27332. this.update();
  27333. }
  27334. dispose() {
  27335. this.lightPlane.geometry.dispose();
  27336. this.lightPlane.material.dispose();
  27337. this.targetLine.geometry.dispose();
  27338. this.targetLine.material.dispose();
  27339. }
  27340. update() {
  27341. _v1.setFromMatrixPosition(this.light.matrixWorld);
  27342. _v2.setFromMatrixPosition(this.light.target.matrixWorld);
  27343. _v3.subVectors(_v2, _v1);
  27344. this.lightPlane.lookAt(_v2);
  27345. if (this.color !== undefined) {
  27346. this.lightPlane.material.color.set(this.color);
  27347. this.targetLine.material.color.set(this.color);
  27348. } else {
  27349. this.lightPlane.material.color.copy(this.light.color);
  27350. this.targetLine.material.color.copy(this.light.color);
  27351. }
  27352. this.targetLine.lookAt(_v2);
  27353. this.targetLine.scale.z = _v3.length();
  27354. }
  27355. }
  27356. const _vector = /*@__PURE__*/new Vector3();
  27357. const _camera = /*@__PURE__*/new Camera();
  27358. /**
  27359. * - shows frustum, line of sight and up of the camera
  27360. * - suitable for fast updates
  27361. * - based on frustum visualization in lightgl.js shadowmap example
  27362. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  27363. */
  27364. class CameraHelper extends LineSegments {
  27365. constructor(camera) {
  27366. const geometry = new BufferGeometry();
  27367. const material = new LineBasicMaterial({
  27368. color: 0xffffff,
  27369. vertexColors: true,
  27370. toneMapped: false
  27371. });
  27372. const vertices = [];
  27373. const colors = [];
  27374. const pointMap = {}; // colors
  27375. const colorFrustum = new Color(0xffaa00);
  27376. const colorCone = new Color(0xff0000);
  27377. const colorUp = new Color(0x00aaff);
  27378. const colorTarget = new Color(0xffffff);
  27379. const colorCross = new Color(0x333333); // near
  27380. addLine('n1', 'n2', colorFrustum);
  27381. addLine('n2', 'n4', colorFrustum);
  27382. addLine('n4', 'n3', colorFrustum);
  27383. addLine('n3', 'n1', colorFrustum); // far
  27384. addLine('f1', 'f2', colorFrustum);
  27385. addLine('f2', 'f4', colorFrustum);
  27386. addLine('f4', 'f3', colorFrustum);
  27387. addLine('f3', 'f1', colorFrustum); // sides
  27388. addLine('n1', 'f1', colorFrustum);
  27389. addLine('n2', 'f2', colorFrustum);
  27390. addLine('n3', 'f3', colorFrustum);
  27391. addLine('n4', 'f4', colorFrustum); // cone
  27392. addLine('p', 'n1', colorCone);
  27393. addLine('p', 'n2', colorCone);
  27394. addLine('p', 'n3', colorCone);
  27395. addLine('p', 'n4', colorCone); // up
  27396. addLine('u1', 'u2', colorUp);
  27397. addLine('u2', 'u3', colorUp);
  27398. addLine('u3', 'u1', colorUp); // target
  27399. addLine('c', 't', colorTarget);
  27400. addLine('p', 'c', colorCross); // cross
  27401. addLine('cn1', 'cn2', colorCross);
  27402. addLine('cn3', 'cn4', colorCross);
  27403. addLine('cf1', 'cf2', colorCross);
  27404. addLine('cf3', 'cf4', colorCross);
  27405. function addLine(a, b, color) {
  27406. addPoint(a, color);
  27407. addPoint(b, color);
  27408. }
  27409. function addPoint(id, color) {
  27410. vertices.push(0, 0, 0);
  27411. colors.push(color.r, color.g, color.b);
  27412. if (pointMap[id] === undefined) {
  27413. pointMap[id] = [];
  27414. }
  27415. pointMap[id].push(vertices.length / 3 - 1);
  27416. }
  27417. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27418. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27419. super(geometry, material);
  27420. this.type = 'CameraHelper';
  27421. this.camera = camera;
  27422. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  27423. this.matrix = camera.matrixWorld;
  27424. this.matrixAutoUpdate = false;
  27425. this.pointMap = pointMap;
  27426. this.update();
  27427. }
  27428. update() {
  27429. const geometry = this.geometry;
  27430. const pointMap = this.pointMap;
  27431. const w = 1,
  27432. h = 1; // we need just camera projection matrix inverse
  27433. // world matrix must be identity
  27434. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  27435. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  27436. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  27437. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  27438. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  27439. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  27440. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  27441. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  27442. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  27443. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  27444. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  27445. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  27446. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  27447. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  27448. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  27449. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  27450. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  27451. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  27452. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  27453. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  27454. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  27455. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  27456. geometry.getAttribute('position').needsUpdate = true;
  27457. }
  27458. dispose() {
  27459. this.geometry.dispose();
  27460. this.material.dispose();
  27461. }
  27462. }
  27463. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  27464. _vector.set(x, y, z).unproject(camera);
  27465. const points = pointMap[point];
  27466. if (points !== undefined) {
  27467. const position = geometry.getAttribute('position');
  27468. for (let i = 0, l = points.length; i < l; i++) {
  27469. position.setXYZ(points[i], _vector.x, _vector.y, _vector.z);
  27470. }
  27471. }
  27472. }
  27473. const _box = /*@__PURE__*/new Box3();
  27474. class BoxHelper extends LineSegments {
  27475. constructor(object, color = 0xffff00) {
  27476. 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]);
  27477. const positions = new Float32Array(8 * 3);
  27478. const geometry = new BufferGeometry();
  27479. geometry.setIndex(new BufferAttribute(indices, 1));
  27480. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  27481. super(geometry, new LineBasicMaterial({
  27482. color: color,
  27483. toneMapped: false
  27484. }));
  27485. this.object = object;
  27486. this.type = 'BoxHelper';
  27487. this.matrixAutoUpdate = false;
  27488. this.update();
  27489. }
  27490. update(object) {
  27491. if (object !== undefined) {
  27492. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  27493. }
  27494. if (this.object !== undefined) {
  27495. _box.setFromObject(this.object);
  27496. }
  27497. if (_box.isEmpty()) return;
  27498. const min = _box.min;
  27499. const max = _box.max;
  27500. /*
  27501. 5____4
  27502. 1/___0/|
  27503. | 6__|_7
  27504. 2/___3/
  27505. 0: max.x, max.y, max.z
  27506. 1: min.x, max.y, max.z
  27507. 2: min.x, min.y, max.z
  27508. 3: max.x, min.y, max.z
  27509. 4: max.x, max.y, min.z
  27510. 5: min.x, max.y, min.z
  27511. 6: min.x, min.y, min.z
  27512. 7: max.x, min.y, min.z
  27513. */
  27514. const position = this.geometry.attributes.position;
  27515. const array = position.array;
  27516. array[0] = max.x;
  27517. array[1] = max.y;
  27518. array[2] = max.z;
  27519. array[3] = min.x;
  27520. array[4] = max.y;
  27521. array[5] = max.z;
  27522. array[6] = min.x;
  27523. array[7] = min.y;
  27524. array[8] = max.z;
  27525. array[9] = max.x;
  27526. array[10] = min.y;
  27527. array[11] = max.z;
  27528. array[12] = max.x;
  27529. array[13] = max.y;
  27530. array[14] = min.z;
  27531. array[15] = min.x;
  27532. array[16] = max.y;
  27533. array[17] = min.z;
  27534. array[18] = min.x;
  27535. array[19] = min.y;
  27536. array[20] = min.z;
  27537. array[21] = max.x;
  27538. array[22] = min.y;
  27539. array[23] = min.z;
  27540. position.needsUpdate = true;
  27541. this.geometry.computeBoundingSphere();
  27542. }
  27543. setFromObject(object) {
  27544. this.object = object;
  27545. this.update();
  27546. return this;
  27547. }
  27548. copy(source) {
  27549. LineSegments.prototype.copy.call(this, source);
  27550. this.object = source.object;
  27551. return this;
  27552. }
  27553. }
  27554. class Box3Helper extends LineSegments {
  27555. constructor(box, color = 0xffff00) {
  27556. 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]);
  27557. 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];
  27558. const geometry = new BufferGeometry();
  27559. geometry.setIndex(new BufferAttribute(indices, 1));
  27560. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27561. super(geometry, new LineBasicMaterial({
  27562. color: color,
  27563. toneMapped: false
  27564. }));
  27565. this.box = box;
  27566. this.type = 'Box3Helper';
  27567. this.geometry.computeBoundingSphere();
  27568. }
  27569. updateMatrixWorld(force) {
  27570. const box = this.box;
  27571. if (box.isEmpty()) return;
  27572. box.getCenter(this.position);
  27573. box.getSize(this.scale);
  27574. this.scale.multiplyScalar(0.5);
  27575. super.updateMatrixWorld(force);
  27576. }
  27577. }
  27578. class PlaneHelper extends Line {
  27579. constructor(plane, size = 1, hex = 0xffff00) {
  27580. const color = hex;
  27581. 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];
  27582. const geometry = new BufferGeometry();
  27583. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27584. geometry.computeBoundingSphere();
  27585. super(geometry, new LineBasicMaterial({
  27586. color: color,
  27587. toneMapped: false
  27588. }));
  27589. this.type = 'PlaneHelper';
  27590. this.plane = plane;
  27591. this.size = size;
  27592. const positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  27593. const geometry2 = new BufferGeometry();
  27594. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  27595. geometry2.computeBoundingSphere();
  27596. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  27597. color: color,
  27598. opacity: 0.2,
  27599. transparent: true,
  27600. depthWrite: false,
  27601. toneMapped: false
  27602. })));
  27603. }
  27604. updateMatrixWorld(force) {
  27605. let scale = -this.plane.constant;
  27606. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  27607. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  27608. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  27609. this.lookAt(this.plane.normal);
  27610. super.updateMatrixWorld(force);
  27611. }
  27612. }
  27613. const _axis = /*@__PURE__*/new Vector3();
  27614. let _lineGeometry, _coneGeometry;
  27615. class ArrowHelper extends Object3D {
  27616. // dir is assumed to be normalized
  27617. 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) {
  27618. super();
  27619. this.type = 'ArrowHelper';
  27620. if (_lineGeometry === undefined) {
  27621. _lineGeometry = new BufferGeometry();
  27622. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  27623. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  27624. _coneGeometry.translate(0, -0.5, 0);
  27625. }
  27626. this.position.copy(origin);
  27627. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  27628. color: color,
  27629. toneMapped: false
  27630. }));
  27631. this.line.matrixAutoUpdate = false;
  27632. this.add(this.line);
  27633. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  27634. color: color,
  27635. toneMapped: false
  27636. }));
  27637. this.cone.matrixAutoUpdate = false;
  27638. this.add(this.cone);
  27639. this.setDirection(dir);
  27640. this.setLength(length, headLength, headWidth);
  27641. }
  27642. setDirection(dir) {
  27643. // dir is assumed to be normalized
  27644. if (dir.y > 0.99999) {
  27645. this.quaternion.set(0, 0, 0, 1);
  27646. } else if (dir.y < -0.99999) {
  27647. this.quaternion.set(1, 0, 0, 0);
  27648. } else {
  27649. _axis.set(dir.z, 0, -dir.x).normalize();
  27650. const radians = Math.acos(dir.y);
  27651. this.quaternion.setFromAxisAngle(_axis, radians);
  27652. }
  27653. }
  27654. setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
  27655. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  27656. this.line.updateMatrix();
  27657. this.cone.scale.set(headWidth, headLength, headWidth);
  27658. this.cone.position.y = length;
  27659. this.cone.updateMatrix();
  27660. }
  27661. setColor(color) {
  27662. this.line.material.color.set(color);
  27663. this.cone.material.color.set(color);
  27664. }
  27665. copy(source) {
  27666. super.copy(source, false);
  27667. this.line.copy(source.line);
  27668. this.cone.copy(source.cone);
  27669. return this;
  27670. }
  27671. }
  27672. class AxesHelper extends LineSegments {
  27673. constructor(size = 1) {
  27674. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  27675. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  27676. const geometry = new BufferGeometry();
  27677. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27678. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27679. const material = new LineBasicMaterial({
  27680. vertexColors: true,
  27681. toneMapped: false
  27682. });
  27683. super(geometry, material);
  27684. this.type = 'AxesHelper';
  27685. }
  27686. setColors(xAxisColor, yAxisColor, zAxisColor) {
  27687. const color = new Color();
  27688. const array = this.geometry.attributes.color.array;
  27689. color.set(xAxisColor);
  27690. color.toArray(array, 0);
  27691. color.toArray(array, 3);
  27692. color.set(yAxisColor);
  27693. color.toArray(array, 6);
  27694. color.toArray(array, 9);
  27695. color.set(zAxisColor);
  27696. color.toArray(array, 12);
  27697. color.toArray(array, 15);
  27698. this.geometry.attributes.color.needsUpdate = true;
  27699. return this;
  27700. }
  27701. dispose() {
  27702. this.geometry.dispose();
  27703. this.material.dispose();
  27704. }
  27705. }
  27706. class ShapePath {
  27707. constructor() {
  27708. this.type = 'ShapePath';
  27709. this.color = new Color();
  27710. this.subPaths = [];
  27711. this.currentPath = null;
  27712. }
  27713. moveTo(x, y) {
  27714. this.currentPath = new Path();
  27715. this.subPaths.push(this.currentPath);
  27716. this.currentPath.moveTo(x, y);
  27717. return this;
  27718. }
  27719. lineTo(x, y) {
  27720. this.currentPath.lineTo(x, y);
  27721. return this;
  27722. }
  27723. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  27724. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  27725. return this;
  27726. }
  27727. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  27728. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  27729. return this;
  27730. }
  27731. splineThru(pts) {
  27732. this.currentPath.splineThru(pts);
  27733. return this;
  27734. }
  27735. toShapes(isCCW, noHoles) {
  27736. function toShapesNoHoles(inSubpaths) {
  27737. const shapes = [];
  27738. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  27739. const tmpPath = inSubpaths[i];
  27740. const tmpShape = new Shape();
  27741. tmpShape.curves = tmpPath.curves;
  27742. shapes.push(tmpShape);
  27743. }
  27744. return shapes;
  27745. }
  27746. function isPointInsidePolygon(inPt, inPolygon) {
  27747. const polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  27748. // toggling of inside/outside at every single! intersection point of an edge
  27749. // with the horizontal line through inPt, left of inPt
  27750. // not counting lowerY endpoints of edges and whole edges on that line
  27751. let inside = false;
  27752. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  27753. let edgeLowPt = inPolygon[p];
  27754. let edgeHighPt = inPolygon[q];
  27755. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  27756. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  27757. if (Math.abs(edgeDy) > Number.EPSILON) {
  27758. // not parallel
  27759. if (edgeDy < 0) {
  27760. edgeLowPt = inPolygon[q];
  27761. edgeDx = -edgeDx;
  27762. edgeHighPt = inPolygon[p];
  27763. edgeDy = -edgeDy;
  27764. }
  27765. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  27766. if (inPt.y === edgeLowPt.y) {
  27767. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  27768. // continue; // no intersection or edgeLowPt => doesn't count !!!
  27769. } else {
  27770. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  27771. if (perpEdge === 0) return true; // inPt is on contour ?
  27772. if (perpEdge < 0) continue;
  27773. inside = !inside; // true intersection left of inPt
  27774. }
  27775. } else {
  27776. // parallel or collinear
  27777. if (inPt.y !== edgeLowPt.y) continue; // parallel
  27778. // edge lies on the same horizontal line as inPt
  27779. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  27780. // continue;
  27781. }
  27782. }
  27783. return inside;
  27784. }
  27785. const isClockWise = ShapeUtils.isClockWise;
  27786. const subPaths = this.subPaths;
  27787. if (subPaths.length === 0) return [];
  27788. if (noHoles === true) return toShapesNoHoles(subPaths);
  27789. let solid, tmpPath, tmpShape;
  27790. const shapes = [];
  27791. if (subPaths.length === 1) {
  27792. tmpPath = subPaths[0];
  27793. tmpShape = new Shape();
  27794. tmpShape.curves = tmpPath.curves;
  27795. shapes.push(tmpShape);
  27796. return shapes;
  27797. }
  27798. let holesFirst = !isClockWise(subPaths[0].getPoints());
  27799. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  27800. const betterShapeHoles = [];
  27801. const newShapes = [];
  27802. let newShapeHoles = [];
  27803. let mainIdx = 0;
  27804. let tmpPoints;
  27805. newShapes[mainIdx] = undefined;
  27806. newShapeHoles[mainIdx] = [];
  27807. for (let i = 0, l = subPaths.length; i < l; i++) {
  27808. tmpPath = subPaths[i];
  27809. tmpPoints = tmpPath.getPoints();
  27810. solid = isClockWise(tmpPoints);
  27811. solid = isCCW ? !solid : solid;
  27812. if (solid) {
  27813. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  27814. newShapes[mainIdx] = {
  27815. s: new Shape(),
  27816. p: tmpPoints
  27817. };
  27818. newShapes[mainIdx].s.curves = tmpPath.curves;
  27819. if (holesFirst) mainIdx++;
  27820. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  27821. } else {
  27822. newShapeHoles[mainIdx].push({
  27823. h: tmpPath,
  27824. p: tmpPoints[0]
  27825. }); //console.log('ccw', i);
  27826. }
  27827. } // only Holes? -> probably all Shapes with wrong orientation
  27828. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  27829. if (newShapes.length > 1) {
  27830. let ambiguous = false;
  27831. const toChange = [];
  27832. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  27833. betterShapeHoles[sIdx] = [];
  27834. }
  27835. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  27836. const sho = newShapeHoles[sIdx];
  27837. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  27838. const ho = sho[hIdx];
  27839. let hole_unassigned = true;
  27840. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  27841. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  27842. if (sIdx !== s2Idx) toChange.push({
  27843. froms: sIdx,
  27844. tos: s2Idx,
  27845. hole: hIdx
  27846. });
  27847. if (hole_unassigned) {
  27848. hole_unassigned = false;
  27849. betterShapeHoles[s2Idx].push(ho);
  27850. } else {
  27851. ambiguous = true;
  27852. }
  27853. }
  27854. }
  27855. if (hole_unassigned) {
  27856. betterShapeHoles[sIdx].push(ho);
  27857. }
  27858. }
  27859. } // console.log("ambiguous: ", ambiguous);
  27860. if (toChange.length > 0) {
  27861. // console.log("to change: ", toChange);
  27862. if (!ambiguous) newShapeHoles = betterShapeHoles;
  27863. }
  27864. }
  27865. let tmpHoles;
  27866. for (let i = 0, il = newShapes.length; i < il; i++) {
  27867. tmpShape = newShapes[i].s;
  27868. shapes.push(tmpShape);
  27869. tmpHoles = newShapeHoles[i];
  27870. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  27871. tmpShape.holes.push(tmpHoles[j].h);
  27872. }
  27873. } //console.log("shape", shapes);
  27874. return shapes;
  27875. }
  27876. }
  27877. const _floatView = new Float32Array(1);
  27878. const _int32View = new Int32Array(_floatView.buffer);
  27879. class DataUtils {
  27880. // Converts float32 to float16 (stored as uint16 value).
  27881. static toHalfFloat(val) {
  27882. if (val > 65504) {
  27883. console.warn('THREE.DataUtils.toHalfFloat(): value exceeds 65504.');
  27884. val = 65504; // maximum representable value in float16
  27885. } // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  27886. /* This method is faster than the OpenEXR implementation (very often
  27887. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  27888. * by James Tursa?s half-precision code. */
  27889. _floatView[0] = val;
  27890. const x = _int32View[0];
  27891. let bits = x >> 16 & 0x8000;
  27892. /* Get the sign */
  27893. let m = x >> 12 & 0x07ff;
  27894. /* Keep one extra bit for rounding */
  27895. const e = x >> 23 & 0xff;
  27896. /* Using int is faster here */
  27897. /* If zero, or denormal, or exponent underflows too much for a denormal
  27898. * half, return signed zero. */
  27899. if (e < 103) return bits;
  27900. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  27901. if (e > 142) {
  27902. bits |= 0x7c00;
  27903. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  27904. * not Inf, so make sure we set one mantissa bit too. */
  27905. bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
  27906. return bits;
  27907. }
  27908. /* If exponent underflows but not too much, return a denormal */
  27909. if (e < 113) {
  27910. m |= 0x0800;
  27911. /* Extra rounding may overflow and set mantissa to 0 and exponent
  27912. * to 1, which is OK. */
  27913. bits |= (m >> 114 - e) + (m >> 113 - e & 1);
  27914. return bits;
  27915. }
  27916. bits |= e - 112 << 10 | m >> 1;
  27917. /* Extra rounding. An overflow will set mantissa to 0 and increment
  27918. * the exponent, which is OK. */
  27919. bits += m & 1;
  27920. return bits;
  27921. }
  27922. }
  27923. const LineStrip = 0;
  27924. const LinePieces = 1;
  27925. const NoColors = 0;
  27926. const FaceColors = 1;
  27927. const VertexColors = 2;
  27928. function MeshFaceMaterial(materials) {
  27929. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  27930. return materials;
  27931. }
  27932. function MultiMaterial(materials = []) {
  27933. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  27934. materials.isMultiMaterial = true;
  27935. materials.materials = materials;
  27936. materials.clone = function () {
  27937. return materials.slice();
  27938. };
  27939. return materials;
  27940. }
  27941. function PointCloud(geometry, material) {
  27942. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  27943. return new Points(geometry, material);
  27944. }
  27945. function Particle(material) {
  27946. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  27947. return new Sprite(material);
  27948. }
  27949. function ParticleSystem(geometry, material) {
  27950. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  27951. return new Points(geometry, material);
  27952. }
  27953. function PointCloudMaterial(parameters) {
  27954. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  27955. return new PointsMaterial(parameters);
  27956. }
  27957. function ParticleBasicMaterial(parameters) {
  27958. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  27959. return new PointsMaterial(parameters);
  27960. }
  27961. function ParticleSystemMaterial(parameters) {
  27962. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  27963. return new PointsMaterial(parameters);
  27964. }
  27965. function Vertex(x, y, z) {
  27966. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  27967. return new Vector3(x, y, z);
  27968. } //
  27969. function DynamicBufferAttribute(array, itemSize) {
  27970. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  27971. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  27972. }
  27973. function Int8Attribute(array, itemSize) {
  27974. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  27975. return new Int8BufferAttribute(array, itemSize);
  27976. }
  27977. function Uint8Attribute(array, itemSize) {
  27978. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  27979. return new Uint8BufferAttribute(array, itemSize);
  27980. }
  27981. function Uint8ClampedAttribute(array, itemSize) {
  27982. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  27983. return new Uint8ClampedBufferAttribute(array, itemSize);
  27984. }
  27985. function Int16Attribute(array, itemSize) {
  27986. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  27987. return new Int16BufferAttribute(array, itemSize);
  27988. }
  27989. function Uint16Attribute(array, itemSize) {
  27990. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  27991. return new Uint16BufferAttribute(array, itemSize);
  27992. }
  27993. function Int32Attribute(array, itemSize) {
  27994. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  27995. return new Int32BufferAttribute(array, itemSize);
  27996. }
  27997. function Uint32Attribute(array, itemSize) {
  27998. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  27999. return new Uint32BufferAttribute(array, itemSize);
  28000. }
  28001. function Float32Attribute(array, itemSize) {
  28002. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  28003. return new Float32BufferAttribute(array, itemSize);
  28004. }
  28005. function Float64Attribute(array, itemSize) {
  28006. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  28007. return new Float64BufferAttribute(array, itemSize);
  28008. } //
  28009. Curve.create = function (construct, getPoint) {
  28010. console.log('THREE.Curve.create() has been deprecated');
  28011. construct.prototype = Object.create(Curve.prototype);
  28012. construct.prototype.constructor = construct;
  28013. construct.prototype.getPoint = getPoint;
  28014. return construct;
  28015. }; //
  28016. Path.prototype.fromPoints = function (points) {
  28017. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  28018. return this.setFromPoints(points);
  28019. }; //
  28020. function AxisHelper(size) {
  28021. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  28022. return new AxesHelper(size);
  28023. }
  28024. function BoundingBoxHelper(object, color) {
  28025. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  28026. return new BoxHelper(object, color);
  28027. }
  28028. function EdgesHelper(object, hex) {
  28029. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  28030. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  28031. color: hex !== undefined ? hex : 0xffffff
  28032. }));
  28033. }
  28034. GridHelper.prototype.setColors = function () {
  28035. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  28036. };
  28037. SkeletonHelper.prototype.update = function () {
  28038. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  28039. };
  28040. function WireframeHelper(object, hex) {
  28041. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  28042. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  28043. color: hex !== undefined ? hex : 0xffffff
  28044. }));
  28045. } //
  28046. Loader.prototype.extractUrlBase = function (url) {
  28047. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  28048. return LoaderUtils.extractUrlBase(url);
  28049. };
  28050. Loader.Handlers = {
  28051. add: function () {
  28052. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  28053. },
  28054. get: function () {
  28055. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  28056. }
  28057. };
  28058. function XHRLoader(manager) {
  28059. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  28060. return new FileLoader(manager);
  28061. }
  28062. function BinaryTextureLoader(manager) {
  28063. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  28064. return new DataTextureLoader(manager);
  28065. } //
  28066. Box2.prototype.center = function (optionalTarget) {
  28067. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  28068. return this.getCenter(optionalTarget);
  28069. };
  28070. Box2.prototype.empty = function () {
  28071. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  28072. return this.isEmpty();
  28073. };
  28074. Box2.prototype.isIntersectionBox = function (box) {
  28075. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  28076. return this.intersectsBox(box);
  28077. };
  28078. Box2.prototype.size = function (optionalTarget) {
  28079. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  28080. return this.getSize(optionalTarget);
  28081. }; //
  28082. Box3.prototype.center = function (optionalTarget) {
  28083. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  28084. return this.getCenter(optionalTarget);
  28085. };
  28086. Box3.prototype.empty = function () {
  28087. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  28088. return this.isEmpty();
  28089. };
  28090. Box3.prototype.isIntersectionBox = function (box) {
  28091. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  28092. return this.intersectsBox(box);
  28093. };
  28094. Box3.prototype.isIntersectionSphere = function (sphere) {
  28095. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28096. return this.intersectsSphere(sphere);
  28097. };
  28098. Box3.prototype.size = function (optionalTarget) {
  28099. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  28100. return this.getSize(optionalTarget);
  28101. }; //
  28102. Sphere.prototype.empty = function () {
  28103. console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
  28104. return this.isEmpty();
  28105. }; //
  28106. Frustum.prototype.setFromMatrix = function (m) {
  28107. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  28108. return this.setFromProjectionMatrix(m);
  28109. }; //
  28110. Line3.prototype.center = function (optionalTarget) {
  28111. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  28112. return this.getCenter(optionalTarget);
  28113. }; //
  28114. Matrix3.prototype.flattenToArrayOffset = function (array, offset) {
  28115. console.warn('THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  28116. return this.toArray(array, offset);
  28117. };
  28118. Matrix3.prototype.multiplyVector3 = function (vector) {
  28119. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  28120. return vector.applyMatrix3(this);
  28121. };
  28122. Matrix3.prototype.multiplyVector3Array = function () {
  28123. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  28124. };
  28125. Matrix3.prototype.applyToBufferAttribute = function (attribute) {
  28126. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  28127. return attribute.applyMatrix3(this);
  28128. };
  28129. Matrix3.prototype.applyToVector3Array = function () {
  28130. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  28131. };
  28132. Matrix3.prototype.getInverse = function (matrix) {
  28133. console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  28134. return this.copy(matrix).invert();
  28135. }; //
  28136. Matrix4.prototype.extractPosition = function (m) {
  28137. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  28138. return this.copyPosition(m);
  28139. };
  28140. Matrix4.prototype.flattenToArrayOffset = function (array, offset) {
  28141. console.warn('THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  28142. return this.toArray(array, offset);
  28143. };
  28144. Matrix4.prototype.getPosition = function () {
  28145. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  28146. return new Vector3().setFromMatrixColumn(this, 3);
  28147. };
  28148. Matrix4.prototype.setRotationFromQuaternion = function (q) {
  28149. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  28150. return this.makeRotationFromQuaternion(q);
  28151. };
  28152. Matrix4.prototype.multiplyToArray = function () {
  28153. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  28154. };
  28155. Matrix4.prototype.multiplyVector3 = function (vector) {
  28156. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28157. return vector.applyMatrix4(this);
  28158. };
  28159. Matrix4.prototype.multiplyVector4 = function (vector) {
  28160. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28161. return vector.applyMatrix4(this);
  28162. };
  28163. Matrix4.prototype.multiplyVector3Array = function () {
  28164. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  28165. };
  28166. Matrix4.prototype.rotateAxis = function (v) {
  28167. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  28168. v.transformDirection(this);
  28169. };
  28170. Matrix4.prototype.crossVector = function (vector) {
  28171. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28172. return vector.applyMatrix4(this);
  28173. };
  28174. Matrix4.prototype.translate = function () {
  28175. console.error('THREE.Matrix4: .translate() has been removed.');
  28176. };
  28177. Matrix4.prototype.rotateX = function () {
  28178. console.error('THREE.Matrix4: .rotateX() has been removed.');
  28179. };
  28180. Matrix4.prototype.rotateY = function () {
  28181. console.error('THREE.Matrix4: .rotateY() has been removed.');
  28182. };
  28183. Matrix4.prototype.rotateZ = function () {
  28184. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  28185. };
  28186. Matrix4.prototype.rotateByAxis = function () {
  28187. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  28188. };
  28189. Matrix4.prototype.applyToBufferAttribute = function (attribute) {
  28190. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  28191. return attribute.applyMatrix4(this);
  28192. };
  28193. Matrix4.prototype.applyToVector3Array = function () {
  28194. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  28195. };
  28196. Matrix4.prototype.makeFrustum = function (left, right, bottom, top, near, far) {
  28197. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  28198. return this.makePerspective(left, right, top, bottom, near, far);
  28199. };
  28200. Matrix4.prototype.getInverse = function (matrix) {
  28201. console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  28202. return this.copy(matrix).invert();
  28203. }; //
  28204. Plane.prototype.isIntersectionLine = function (line) {
  28205. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  28206. return this.intersectsLine(line);
  28207. }; //
  28208. Quaternion.prototype.multiplyVector3 = function (vector) {
  28209. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  28210. return vector.applyQuaternion(this);
  28211. };
  28212. Quaternion.prototype.inverse = function () {
  28213. console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
  28214. return this.invert();
  28215. }; //
  28216. Ray.prototype.isIntersectionBox = function (box) {
  28217. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  28218. return this.intersectsBox(box);
  28219. };
  28220. Ray.prototype.isIntersectionPlane = function (plane) {
  28221. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  28222. return this.intersectsPlane(plane);
  28223. };
  28224. Ray.prototype.isIntersectionSphere = function (sphere) {
  28225. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28226. return this.intersectsSphere(sphere);
  28227. }; //
  28228. Triangle.prototype.area = function () {
  28229. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  28230. return this.getArea();
  28231. };
  28232. Triangle.prototype.barycoordFromPoint = function (point, target) {
  28233. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28234. return this.getBarycoord(point, target);
  28235. };
  28236. Triangle.prototype.midpoint = function (target) {
  28237. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  28238. return this.getMidpoint(target);
  28239. };
  28240. Triangle.prototypenormal = function (target) {
  28241. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28242. return this.getNormal(target);
  28243. };
  28244. Triangle.prototype.plane = function (target) {
  28245. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  28246. return this.getPlane(target);
  28247. };
  28248. Triangle.barycoordFromPoint = function (point, a, b, c, target) {
  28249. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28250. return Triangle.getBarycoord(point, a, b, c, target);
  28251. };
  28252. Triangle.normal = function (a, b, c, target) {
  28253. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28254. return Triangle.getNormal(a, b, c, target);
  28255. }; //
  28256. Shape.prototype.extractAllPoints = function (divisions) {
  28257. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  28258. return this.extractPoints(divisions);
  28259. };
  28260. Shape.prototype.extrude = function (options) {
  28261. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  28262. return new ExtrudeGeometry(this, options);
  28263. };
  28264. Shape.prototype.makeGeometry = function (options) {
  28265. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  28266. return new ShapeGeometry(this, options);
  28267. }; //
  28268. Vector2.prototype.fromAttribute = function (attribute, index, offset) {
  28269. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28270. return this.fromBufferAttribute(attribute, index, offset);
  28271. };
  28272. Vector2.prototype.distanceToManhattan = function (v) {
  28273. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28274. return this.manhattanDistanceTo(v);
  28275. };
  28276. Vector2.prototype.lengthManhattan = function () {
  28277. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  28278. return this.manhattanLength();
  28279. }; //
  28280. Vector3.prototype.setEulerFromRotationMatrix = function () {
  28281. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  28282. };
  28283. Vector3.prototype.setEulerFromQuaternion = function () {
  28284. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  28285. };
  28286. Vector3.prototype.getPositionFromMatrix = function (m) {
  28287. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  28288. return this.setFromMatrixPosition(m);
  28289. };
  28290. Vector3.prototype.getScaleFromMatrix = function (m) {
  28291. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  28292. return this.setFromMatrixScale(m);
  28293. };
  28294. Vector3.prototype.getColumnFromMatrix = function (index, matrix) {
  28295. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  28296. return this.setFromMatrixColumn(matrix, index);
  28297. };
  28298. Vector3.prototype.applyProjection = function (m) {
  28299. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  28300. return this.applyMatrix4(m);
  28301. };
  28302. Vector3.prototype.fromAttribute = function (attribute, index, offset) {
  28303. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28304. return this.fromBufferAttribute(attribute, index, offset);
  28305. };
  28306. Vector3.prototype.distanceToManhattan = function (v) {
  28307. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28308. return this.manhattanDistanceTo(v);
  28309. };
  28310. Vector3.prototype.lengthManhattan = function () {
  28311. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  28312. return this.manhattanLength();
  28313. }; //
  28314. Vector4.prototype.fromAttribute = function (attribute, index, offset) {
  28315. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28316. return this.fromBufferAttribute(attribute, index, offset);
  28317. };
  28318. Vector4.prototype.lengthManhattan = function () {
  28319. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  28320. return this.manhattanLength();
  28321. }; //
  28322. Object3D.prototype.getChildByName = function (name) {
  28323. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  28324. return this.getObjectByName(name);
  28325. };
  28326. Object3D.prototype.renderDepth = function () {
  28327. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  28328. };
  28329. Object3D.prototype.translate = function (distance, axis) {
  28330. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  28331. return this.translateOnAxis(axis, distance);
  28332. };
  28333. Object3D.prototype.getWorldRotation = function () {
  28334. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  28335. };
  28336. Object3D.prototype.applyMatrix = function (matrix) {
  28337. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  28338. return this.applyMatrix4(matrix);
  28339. };
  28340. Object.defineProperties(Object3D.prototype, {
  28341. eulerOrder: {
  28342. get: function () {
  28343. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28344. return this.rotation.order;
  28345. },
  28346. set: function (value) {
  28347. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28348. this.rotation.order = value;
  28349. }
  28350. },
  28351. useQuaternion: {
  28352. get: function () {
  28353. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28354. },
  28355. set: function () {
  28356. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28357. }
  28358. }
  28359. });
  28360. Mesh.prototype.setDrawMode = function () {
  28361. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28362. };
  28363. Object.defineProperties(Mesh.prototype, {
  28364. drawMode: {
  28365. get: function () {
  28366. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  28367. return TrianglesDrawMode;
  28368. },
  28369. set: function () {
  28370. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28371. }
  28372. }
  28373. });
  28374. SkinnedMesh.prototype.initBones = function () {
  28375. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  28376. }; //
  28377. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  28378. console.warn('THREE.PerspectiveCamera.setLens is deprecated. ' + 'Use .setFocalLength and .filmGauge for a photographic setup.');
  28379. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  28380. this.setFocalLength(focalLength);
  28381. }; //
  28382. Object.defineProperties(Light.prototype, {
  28383. onlyShadow: {
  28384. set: function () {
  28385. console.warn('THREE.Light: .onlyShadow has been removed.');
  28386. }
  28387. },
  28388. shadowCameraFov: {
  28389. set: function (value) {
  28390. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  28391. this.shadow.camera.fov = value;
  28392. }
  28393. },
  28394. shadowCameraLeft: {
  28395. set: function (value) {
  28396. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  28397. this.shadow.camera.left = value;
  28398. }
  28399. },
  28400. shadowCameraRight: {
  28401. set: function (value) {
  28402. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  28403. this.shadow.camera.right = value;
  28404. }
  28405. },
  28406. shadowCameraTop: {
  28407. set: function (value) {
  28408. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  28409. this.shadow.camera.top = value;
  28410. }
  28411. },
  28412. shadowCameraBottom: {
  28413. set: function (value) {
  28414. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  28415. this.shadow.camera.bottom = value;
  28416. }
  28417. },
  28418. shadowCameraNear: {
  28419. set: function (value) {
  28420. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  28421. this.shadow.camera.near = value;
  28422. }
  28423. },
  28424. shadowCameraFar: {
  28425. set: function (value) {
  28426. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  28427. this.shadow.camera.far = value;
  28428. }
  28429. },
  28430. shadowCameraVisible: {
  28431. set: function () {
  28432. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  28433. }
  28434. },
  28435. shadowBias: {
  28436. set: function (value) {
  28437. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  28438. this.shadow.bias = value;
  28439. }
  28440. },
  28441. shadowDarkness: {
  28442. set: function () {
  28443. console.warn('THREE.Light: .shadowDarkness has been removed.');
  28444. }
  28445. },
  28446. shadowMapWidth: {
  28447. set: function (value) {
  28448. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  28449. this.shadow.mapSize.width = value;
  28450. }
  28451. },
  28452. shadowMapHeight: {
  28453. set: function (value) {
  28454. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  28455. this.shadow.mapSize.height = value;
  28456. }
  28457. }
  28458. }); //
  28459. Object.defineProperties(BufferAttribute.prototype, {
  28460. length: {
  28461. get: function () {
  28462. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  28463. return this.array.length;
  28464. }
  28465. },
  28466. dynamic: {
  28467. get: function () {
  28468. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28469. return this.usage === DynamicDrawUsage;
  28470. },
  28471. set: function () {
  28472. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28473. this.setUsage(DynamicDrawUsage);
  28474. }
  28475. }
  28476. });
  28477. BufferAttribute.prototype.setDynamic = function (value) {
  28478. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28479. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28480. return this;
  28481. };
  28482. BufferAttribute.prototype.copyIndicesArray = function () {
  28483. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  28484. }, BufferAttribute.prototype.setArray = function () {
  28485. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28486. }; //
  28487. BufferGeometry.prototype.addIndex = function (index) {
  28488. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  28489. this.setIndex(index);
  28490. };
  28491. BufferGeometry.prototype.addAttribute = function (name, attribute) {
  28492. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  28493. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  28494. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  28495. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  28496. }
  28497. if (name === 'index') {
  28498. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  28499. this.setIndex(attribute);
  28500. return this;
  28501. }
  28502. return this.setAttribute(name, attribute);
  28503. };
  28504. BufferGeometry.prototype.addDrawCall = function (start, count, indexOffset) {
  28505. if (indexOffset !== undefined) {
  28506. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  28507. }
  28508. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  28509. this.addGroup(start, count);
  28510. };
  28511. BufferGeometry.prototype.clearDrawCalls = function () {
  28512. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  28513. this.clearGroups();
  28514. };
  28515. BufferGeometry.prototype.computeOffsets = function () {
  28516. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  28517. };
  28518. BufferGeometry.prototype.removeAttribute = function (name) {
  28519. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  28520. return this.deleteAttribute(name);
  28521. };
  28522. BufferGeometry.prototype.applyMatrix = function (matrix) {
  28523. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  28524. return this.applyMatrix4(matrix);
  28525. };
  28526. Object.defineProperties(BufferGeometry.prototype, {
  28527. drawcalls: {
  28528. get: function () {
  28529. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  28530. return this.groups;
  28531. }
  28532. },
  28533. offsets: {
  28534. get: function () {
  28535. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  28536. return this.groups;
  28537. }
  28538. }
  28539. });
  28540. InterleavedBuffer.prototype.setDynamic = function (value) {
  28541. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28542. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28543. return this;
  28544. };
  28545. InterleavedBuffer.prototype.setArray = function () {
  28546. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28547. }; //
  28548. ExtrudeGeometry.prototype.getArrays = function () {
  28549. console.error('THREE.ExtrudeGeometry: .getArrays() has been removed.');
  28550. };
  28551. ExtrudeGeometry.prototype.addShapeList = function () {
  28552. console.error('THREE.ExtrudeGeometry: .addShapeList() has been removed.');
  28553. };
  28554. ExtrudeGeometry.prototype.addShape = function () {
  28555. console.error('THREE.ExtrudeGeometry: .addShape() has been removed.');
  28556. }; //
  28557. Scene.prototype.dispose = function () {
  28558. console.error('THREE.Scene: .dispose() has been removed.');
  28559. }; //
  28560. Uniform.prototype.onUpdate = function () {
  28561. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  28562. return this;
  28563. }; //
  28564. Object.defineProperties(Material.prototype, {
  28565. wrapAround: {
  28566. get: function () {
  28567. console.warn('THREE.Material: .wrapAround has been removed.');
  28568. },
  28569. set: function () {
  28570. console.warn('THREE.Material: .wrapAround has been removed.');
  28571. }
  28572. },
  28573. overdraw: {
  28574. get: function () {
  28575. console.warn('THREE.Material: .overdraw has been removed.');
  28576. },
  28577. set: function () {
  28578. console.warn('THREE.Material: .overdraw has been removed.');
  28579. }
  28580. },
  28581. wrapRGB: {
  28582. get: function () {
  28583. console.warn('THREE.Material: .wrapRGB has been removed.');
  28584. return new Color();
  28585. }
  28586. },
  28587. shading: {
  28588. get: function () {
  28589. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28590. },
  28591. set: function (value) {
  28592. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28593. this.flatShading = value === FlatShading;
  28594. }
  28595. },
  28596. stencilMask: {
  28597. get: function () {
  28598. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28599. return this.stencilFuncMask;
  28600. },
  28601. set: function (value) {
  28602. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28603. this.stencilFuncMask = value;
  28604. }
  28605. },
  28606. vertexTangents: {
  28607. get: function () {
  28608. console.warn('THREE.' + this.type + ': .vertexTangents has been removed.');
  28609. },
  28610. set: function () {
  28611. console.warn('THREE.' + this.type + ': .vertexTangents has been removed.');
  28612. }
  28613. }
  28614. });
  28615. Object.defineProperties(ShaderMaterial.prototype, {
  28616. derivatives: {
  28617. get: function () {
  28618. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28619. return this.extensions.derivatives;
  28620. },
  28621. set: function (value) {
  28622. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28623. this.extensions.derivatives = value;
  28624. }
  28625. }
  28626. }); //
  28627. WebGLRenderer.prototype.clearTarget = function (renderTarget, color, depth, stencil) {
  28628. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  28629. this.setRenderTarget(renderTarget);
  28630. this.clear(color, depth, stencil);
  28631. };
  28632. WebGLRenderer.prototype.animate = function (callback) {
  28633. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  28634. this.setAnimationLoop(callback);
  28635. };
  28636. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  28637. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  28638. return this.getRenderTarget();
  28639. };
  28640. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  28641. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  28642. return this.capabilities.getMaxAnisotropy();
  28643. };
  28644. WebGLRenderer.prototype.getPrecision = function () {
  28645. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  28646. return this.capabilities.precision;
  28647. };
  28648. WebGLRenderer.prototype.resetGLState = function () {
  28649. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  28650. return this.state.reset();
  28651. };
  28652. WebGLRenderer.prototype.supportsFloatTextures = function () {
  28653. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  28654. return this.extensions.get('OES_texture_float');
  28655. };
  28656. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  28657. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  28658. return this.extensions.get('OES_texture_half_float');
  28659. };
  28660. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  28661. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  28662. return this.extensions.get('OES_standard_derivatives');
  28663. };
  28664. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  28665. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  28666. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  28667. };
  28668. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  28669. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  28670. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  28671. };
  28672. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  28673. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  28674. return this.extensions.get('EXT_blend_minmax');
  28675. };
  28676. WebGLRenderer.prototype.supportsVertexTextures = function () {
  28677. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  28678. return this.capabilities.vertexTextures;
  28679. };
  28680. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  28681. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  28682. return this.extensions.get('ANGLE_instanced_arrays');
  28683. };
  28684. WebGLRenderer.prototype.enableScissorTest = function (boolean) {
  28685. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  28686. this.setScissorTest(boolean);
  28687. };
  28688. WebGLRenderer.prototype.initMaterial = function () {
  28689. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  28690. };
  28691. WebGLRenderer.prototype.addPrePlugin = function () {
  28692. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  28693. };
  28694. WebGLRenderer.prototype.addPostPlugin = function () {
  28695. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  28696. };
  28697. WebGLRenderer.prototype.updateShadowMap = function () {
  28698. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  28699. };
  28700. WebGLRenderer.prototype.setFaceCulling = function () {
  28701. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  28702. };
  28703. WebGLRenderer.prototype.allocTextureUnit = function () {
  28704. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  28705. };
  28706. WebGLRenderer.prototype.setTexture = function () {
  28707. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  28708. };
  28709. WebGLRenderer.prototype.setTexture2D = function () {
  28710. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  28711. };
  28712. WebGLRenderer.prototype.setTextureCube = function () {
  28713. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  28714. };
  28715. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  28716. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  28717. return this.getActiveMipmapLevel();
  28718. };
  28719. Object.defineProperties(WebGLRenderer.prototype, {
  28720. shadowMapEnabled: {
  28721. get: function () {
  28722. return this.shadowMap.enabled;
  28723. },
  28724. set: function (value) {
  28725. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  28726. this.shadowMap.enabled = value;
  28727. }
  28728. },
  28729. shadowMapType: {
  28730. get: function () {
  28731. return this.shadowMap.type;
  28732. },
  28733. set: function (value) {
  28734. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  28735. this.shadowMap.type = value;
  28736. }
  28737. },
  28738. shadowMapCullFace: {
  28739. get: function () {
  28740. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28741. return undefined;
  28742. },
  28743. set: function () {
  28744. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28745. }
  28746. },
  28747. context: {
  28748. get: function () {
  28749. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  28750. return this.getContext();
  28751. }
  28752. },
  28753. vr: {
  28754. get: function () {
  28755. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  28756. return this.xr;
  28757. }
  28758. },
  28759. gammaInput: {
  28760. get: function () {
  28761. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  28762. return false;
  28763. },
  28764. set: function () {
  28765. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  28766. }
  28767. },
  28768. gammaOutput: {
  28769. get: function () {
  28770. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  28771. return false;
  28772. },
  28773. set: function (value) {
  28774. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  28775. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  28776. }
  28777. },
  28778. toneMappingWhitePoint: {
  28779. get: function () {
  28780. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  28781. return 1.0;
  28782. },
  28783. set: function () {
  28784. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  28785. }
  28786. }
  28787. });
  28788. Object.defineProperties(WebGLShadowMap.prototype, {
  28789. cullFace: {
  28790. get: function () {
  28791. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  28792. return undefined;
  28793. },
  28794. set: function () {
  28795. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  28796. }
  28797. },
  28798. renderReverseSided: {
  28799. get: function () {
  28800. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  28801. return undefined;
  28802. },
  28803. set: function () {
  28804. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  28805. }
  28806. },
  28807. renderSingleSided: {
  28808. get: function () {
  28809. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  28810. return undefined;
  28811. },
  28812. set: function () {
  28813. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  28814. }
  28815. }
  28816. });
  28817. function WebGLRenderTargetCube(width, height, options) {
  28818. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  28819. return new WebGLCubeRenderTarget(width, options);
  28820. } //
  28821. Object.defineProperties(WebGLRenderTarget.prototype, {
  28822. wrapS: {
  28823. get: function () {
  28824. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  28825. return this.texture.wrapS;
  28826. },
  28827. set: function (value) {
  28828. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  28829. this.texture.wrapS = value;
  28830. }
  28831. },
  28832. wrapT: {
  28833. get: function () {
  28834. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  28835. return this.texture.wrapT;
  28836. },
  28837. set: function (value) {
  28838. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  28839. this.texture.wrapT = value;
  28840. }
  28841. },
  28842. magFilter: {
  28843. get: function () {
  28844. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  28845. return this.texture.magFilter;
  28846. },
  28847. set: function (value) {
  28848. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  28849. this.texture.magFilter = value;
  28850. }
  28851. },
  28852. minFilter: {
  28853. get: function () {
  28854. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  28855. return this.texture.minFilter;
  28856. },
  28857. set: function (value) {
  28858. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  28859. this.texture.minFilter = value;
  28860. }
  28861. },
  28862. anisotropy: {
  28863. get: function () {
  28864. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  28865. return this.texture.anisotropy;
  28866. },
  28867. set: function (value) {
  28868. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  28869. this.texture.anisotropy = value;
  28870. }
  28871. },
  28872. offset: {
  28873. get: function () {
  28874. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  28875. return this.texture.offset;
  28876. },
  28877. set: function (value) {
  28878. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  28879. this.texture.offset = value;
  28880. }
  28881. },
  28882. repeat: {
  28883. get: function () {
  28884. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  28885. return this.texture.repeat;
  28886. },
  28887. set: function (value) {
  28888. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  28889. this.texture.repeat = value;
  28890. }
  28891. },
  28892. format: {
  28893. get: function () {
  28894. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  28895. return this.texture.format;
  28896. },
  28897. set: function (value) {
  28898. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  28899. this.texture.format = value;
  28900. }
  28901. },
  28902. type: {
  28903. get: function () {
  28904. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  28905. return this.texture.type;
  28906. },
  28907. set: function (value) {
  28908. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  28909. this.texture.type = value;
  28910. }
  28911. },
  28912. generateMipmaps: {
  28913. get: function () {
  28914. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  28915. return this.texture.generateMipmaps;
  28916. },
  28917. set: function (value) {
  28918. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  28919. this.texture.generateMipmaps = value;
  28920. }
  28921. }
  28922. }); //
  28923. Audio.prototype.load = function (file) {
  28924. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  28925. const scope = this;
  28926. const audioLoader = new AudioLoader();
  28927. audioLoader.load(file, function (buffer) {
  28928. scope.setBuffer(buffer);
  28929. });
  28930. return this;
  28931. };
  28932. AudioAnalyser.prototype.getData = function () {
  28933. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  28934. return this.getFrequencyData();
  28935. }; //
  28936. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  28937. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  28938. return this.update(renderer, scene);
  28939. };
  28940. CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
  28941. console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
  28942. return this.renderTarget.clear(renderer, color, depth, stencil);
  28943. };
  28944. ImageUtils.crossOrigin = undefined;
  28945. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  28946. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  28947. const loader = new TextureLoader();
  28948. loader.setCrossOrigin(this.crossOrigin);
  28949. const texture = loader.load(url, onLoad, undefined, onError);
  28950. if (mapping) texture.mapping = mapping;
  28951. return texture;
  28952. };
  28953. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  28954. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  28955. const loader = new CubeTextureLoader();
  28956. loader.setCrossOrigin(this.crossOrigin);
  28957. const texture = loader.load(urls, onLoad, undefined, onError);
  28958. if (mapping) texture.mapping = mapping;
  28959. return texture;
  28960. };
  28961. ImageUtils.loadCompressedTexture = function () {
  28962. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  28963. };
  28964. ImageUtils.loadCompressedTextureCube = function () {
  28965. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  28966. }; //
  28967. function CanvasRenderer() {
  28968. console.error('THREE.CanvasRenderer has been removed');
  28969. } //
  28970. function JSONLoader() {
  28971. console.error('THREE.JSONLoader has been removed.');
  28972. } //
  28973. const SceneUtils = {
  28974. createMultiMaterialObject: function () {
  28975. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28976. },
  28977. detach: function () {
  28978. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28979. },
  28980. attach: function () {
  28981. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28982. }
  28983. }; //
  28984. function LensFlare() {
  28985. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  28986. } //
  28987. function ParametricGeometry() {
  28988. console.error('THREE.ParametricGeometry has been moved to /examples/jsm/geometries/ParametricGeometry.js');
  28989. return new BufferGeometry();
  28990. }
  28991. function TextGeometry() {
  28992. console.error('THREE.TextGeometry has been moved to /examples/jsm/geometries/TextGeometry.js');
  28993. return new BufferGeometry();
  28994. }
  28995. function FontLoader() {
  28996. console.error('THREE.FontLoader has been moved to /examples/jsm/loaders/FontLoader.js');
  28997. }
  28998. function Font() {
  28999. console.error('THREE.Font has been moved to /examples/jsm/loaders/FontLoader.js');
  29000. }
  29001. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  29002. /* eslint-disable no-undef */
  29003. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  29004. detail: {
  29005. revision: REVISION
  29006. }
  29007. }));
  29008. /* eslint-enable no-undef */
  29009. }
  29010. if (typeof window !== 'undefined') {
  29011. if (window.__THREE__) {
  29012. console.warn('WARNING: Multiple instances of Three.js being imported.');
  29013. } else {
  29014. window.__THREE__ = REVISION;
  29015. }
  29016. }
  29017. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  29018. exports.AddEquation = AddEquation;
  29019. exports.AddOperation = AddOperation;
  29020. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  29021. exports.AdditiveBlending = AdditiveBlending;
  29022. exports.AlphaFormat = AlphaFormat;
  29023. exports.AlwaysDepth = AlwaysDepth;
  29024. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  29025. exports.AmbientLight = AmbientLight;
  29026. exports.AmbientLightProbe = AmbientLightProbe;
  29027. exports.AnimationClip = AnimationClip;
  29028. exports.AnimationLoader = AnimationLoader;
  29029. exports.AnimationMixer = AnimationMixer;
  29030. exports.AnimationObjectGroup = AnimationObjectGroup;
  29031. exports.AnimationUtils = AnimationUtils;
  29032. exports.ArcCurve = ArcCurve;
  29033. exports.ArrayCamera = ArrayCamera;
  29034. exports.ArrowHelper = ArrowHelper;
  29035. exports.Audio = Audio;
  29036. exports.AudioAnalyser = AudioAnalyser;
  29037. exports.AudioContext = AudioContext;
  29038. exports.AudioListener = AudioListener;
  29039. exports.AudioLoader = AudioLoader;
  29040. exports.AxesHelper = AxesHelper;
  29041. exports.AxisHelper = AxisHelper;
  29042. exports.BackSide = BackSide;
  29043. exports.BasicDepthPacking = BasicDepthPacking;
  29044. exports.BasicShadowMap = BasicShadowMap;
  29045. exports.BinaryTextureLoader = BinaryTextureLoader;
  29046. exports.Bone = Bone;
  29047. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  29048. exports.BoundingBoxHelper = BoundingBoxHelper;
  29049. exports.Box2 = Box2;
  29050. exports.Box3 = Box3;
  29051. exports.Box3Helper = Box3Helper;
  29052. exports.BoxBufferGeometry = BoxGeometry;
  29053. exports.BoxGeometry = BoxGeometry;
  29054. exports.BoxHelper = BoxHelper;
  29055. exports.BufferAttribute = BufferAttribute;
  29056. exports.BufferGeometry = BufferGeometry;
  29057. exports.BufferGeometryLoader = BufferGeometryLoader;
  29058. exports.ByteType = ByteType;
  29059. exports.Cache = Cache;
  29060. exports.Camera = Camera;
  29061. exports.CameraHelper = CameraHelper;
  29062. exports.CanvasRenderer = CanvasRenderer;
  29063. exports.CanvasTexture = CanvasTexture;
  29064. exports.CatmullRomCurve3 = CatmullRomCurve3;
  29065. exports.CineonToneMapping = CineonToneMapping;
  29066. exports.CircleBufferGeometry = CircleGeometry;
  29067. exports.CircleGeometry = CircleGeometry;
  29068. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  29069. exports.Clock = Clock;
  29070. exports.Color = Color;
  29071. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  29072. exports.CompressedTexture = CompressedTexture;
  29073. exports.CompressedTextureLoader = CompressedTextureLoader;
  29074. exports.ConeBufferGeometry = ConeGeometry;
  29075. exports.ConeGeometry = ConeGeometry;
  29076. exports.CubeCamera = CubeCamera;
  29077. exports.CubeReflectionMapping = CubeReflectionMapping;
  29078. exports.CubeRefractionMapping = CubeRefractionMapping;
  29079. exports.CubeTexture = CubeTexture;
  29080. exports.CubeTextureLoader = CubeTextureLoader;
  29081. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  29082. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  29083. exports.CubicBezierCurve = CubicBezierCurve;
  29084. exports.CubicBezierCurve3 = CubicBezierCurve3;
  29085. exports.CubicInterpolant = CubicInterpolant;
  29086. exports.CullFaceBack = CullFaceBack;
  29087. exports.CullFaceFront = CullFaceFront;
  29088. exports.CullFaceFrontBack = CullFaceFrontBack;
  29089. exports.CullFaceNone = CullFaceNone;
  29090. exports.Curve = Curve;
  29091. exports.CurvePath = CurvePath;
  29092. exports.CustomBlending = CustomBlending;
  29093. exports.CustomToneMapping = CustomToneMapping;
  29094. exports.CylinderBufferGeometry = CylinderGeometry;
  29095. exports.CylinderGeometry = CylinderGeometry;
  29096. exports.Cylindrical = Cylindrical;
  29097. exports.DataTexture = DataTexture;
  29098. exports.DataTexture2DArray = DataTexture2DArray;
  29099. exports.DataTexture3D = DataTexture3D;
  29100. exports.DataTextureLoader = DataTextureLoader;
  29101. exports.DataUtils = DataUtils;
  29102. exports.DecrementStencilOp = DecrementStencilOp;
  29103. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  29104. exports.DefaultLoadingManager = DefaultLoadingManager;
  29105. exports.DepthFormat = DepthFormat;
  29106. exports.DepthStencilFormat = DepthStencilFormat;
  29107. exports.DepthTexture = DepthTexture;
  29108. exports.DirectionalLight = DirectionalLight;
  29109. exports.DirectionalLightHelper = DirectionalLightHelper;
  29110. exports.DiscreteInterpolant = DiscreteInterpolant;
  29111. exports.DodecahedronBufferGeometry = DodecahedronGeometry;
  29112. exports.DodecahedronGeometry = DodecahedronGeometry;
  29113. exports.DoubleSide = DoubleSide;
  29114. exports.DstAlphaFactor = DstAlphaFactor;
  29115. exports.DstColorFactor = DstColorFactor;
  29116. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  29117. exports.DynamicCopyUsage = DynamicCopyUsage;
  29118. exports.DynamicDrawUsage = DynamicDrawUsage;
  29119. exports.DynamicReadUsage = DynamicReadUsage;
  29120. exports.EdgesGeometry = EdgesGeometry;
  29121. exports.EdgesHelper = EdgesHelper;
  29122. exports.EllipseCurve = EllipseCurve;
  29123. exports.EqualDepth = EqualDepth;
  29124. exports.EqualStencilFunc = EqualStencilFunc;
  29125. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  29126. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  29127. exports.Euler = Euler;
  29128. exports.EventDispatcher = EventDispatcher;
  29129. exports.ExtrudeBufferGeometry = ExtrudeGeometry;
  29130. exports.ExtrudeGeometry = ExtrudeGeometry;
  29131. exports.FaceColors = FaceColors;
  29132. exports.FileLoader = FileLoader;
  29133. exports.FlatShading = FlatShading;
  29134. exports.Float16BufferAttribute = Float16BufferAttribute;
  29135. exports.Float32Attribute = Float32Attribute;
  29136. exports.Float32BufferAttribute = Float32BufferAttribute;
  29137. exports.Float64Attribute = Float64Attribute;
  29138. exports.Float64BufferAttribute = Float64BufferAttribute;
  29139. exports.FloatType = FloatType;
  29140. exports.Fog = Fog;
  29141. exports.FogExp2 = FogExp2;
  29142. exports.Font = Font;
  29143. exports.FontLoader = FontLoader;
  29144. exports.FrontSide = FrontSide;
  29145. exports.Frustum = Frustum;
  29146. exports.GLBufferAttribute = GLBufferAttribute;
  29147. exports.GLSL1 = GLSL1;
  29148. exports.GLSL3 = GLSL3;
  29149. exports.GammaEncoding = GammaEncoding;
  29150. exports.GreaterDepth = GreaterDepth;
  29151. exports.GreaterEqualDepth = GreaterEqualDepth;
  29152. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  29153. exports.GreaterStencilFunc = GreaterStencilFunc;
  29154. exports.GridHelper = GridHelper;
  29155. exports.Group = Group;
  29156. exports.HalfFloatType = HalfFloatType;
  29157. exports.HemisphereLight = HemisphereLight;
  29158. exports.HemisphereLightHelper = HemisphereLightHelper;
  29159. exports.HemisphereLightProbe = HemisphereLightProbe;
  29160. exports.IcosahedronBufferGeometry = IcosahedronGeometry;
  29161. exports.IcosahedronGeometry = IcosahedronGeometry;
  29162. exports.ImageBitmapLoader = ImageBitmapLoader;
  29163. exports.ImageLoader = ImageLoader;
  29164. exports.ImageUtils = ImageUtils;
  29165. exports.ImmediateRenderObject = ImmediateRenderObject;
  29166. exports.IncrementStencilOp = IncrementStencilOp;
  29167. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  29168. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  29169. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  29170. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  29171. exports.InstancedMesh = InstancedMesh;
  29172. exports.Int16Attribute = Int16Attribute;
  29173. exports.Int16BufferAttribute = Int16BufferAttribute;
  29174. exports.Int32Attribute = Int32Attribute;
  29175. exports.Int32BufferAttribute = Int32BufferAttribute;
  29176. exports.Int8Attribute = Int8Attribute;
  29177. exports.Int8BufferAttribute = Int8BufferAttribute;
  29178. exports.IntType = IntType;
  29179. exports.InterleavedBuffer = InterleavedBuffer;
  29180. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  29181. exports.Interpolant = Interpolant;
  29182. exports.InterpolateDiscrete = InterpolateDiscrete;
  29183. exports.InterpolateLinear = InterpolateLinear;
  29184. exports.InterpolateSmooth = InterpolateSmooth;
  29185. exports.InvertStencilOp = InvertStencilOp;
  29186. exports.JSONLoader = JSONLoader;
  29187. exports.KeepStencilOp = KeepStencilOp;
  29188. exports.KeyframeTrack = KeyframeTrack;
  29189. exports.LOD = LOD;
  29190. exports.LatheBufferGeometry = LatheGeometry;
  29191. exports.LatheGeometry = LatheGeometry;
  29192. exports.Layers = Layers;
  29193. exports.LensFlare = LensFlare;
  29194. exports.LessDepth = LessDepth;
  29195. exports.LessEqualDepth = LessEqualDepth;
  29196. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  29197. exports.LessStencilFunc = LessStencilFunc;
  29198. exports.Light = Light;
  29199. exports.LightProbe = LightProbe;
  29200. exports.Line = Line;
  29201. exports.Line3 = Line3;
  29202. exports.LineBasicMaterial = LineBasicMaterial;
  29203. exports.LineCurve = LineCurve;
  29204. exports.LineCurve3 = LineCurve3;
  29205. exports.LineDashedMaterial = LineDashedMaterial;
  29206. exports.LineLoop = LineLoop;
  29207. exports.LinePieces = LinePieces;
  29208. exports.LineSegments = LineSegments;
  29209. exports.LineStrip = LineStrip;
  29210. exports.LinearEncoding = LinearEncoding;
  29211. exports.LinearFilter = LinearFilter;
  29212. exports.LinearInterpolant = LinearInterpolant;
  29213. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  29214. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  29215. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  29216. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  29217. exports.LinearToneMapping = LinearToneMapping;
  29218. exports.Loader = Loader;
  29219. exports.LoaderUtils = LoaderUtils;
  29220. exports.LoadingManager = LoadingManager;
  29221. exports.LogLuvEncoding = LogLuvEncoding;
  29222. exports.LoopOnce = LoopOnce;
  29223. exports.LoopPingPong = LoopPingPong;
  29224. exports.LoopRepeat = LoopRepeat;
  29225. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  29226. exports.LuminanceFormat = LuminanceFormat;
  29227. exports.MOUSE = MOUSE;
  29228. exports.Material = Material;
  29229. exports.MaterialLoader = MaterialLoader;
  29230. exports.Math = MathUtils;
  29231. exports.MathUtils = MathUtils;
  29232. exports.Matrix3 = Matrix3;
  29233. exports.Matrix4 = Matrix4;
  29234. exports.MaxEquation = MaxEquation;
  29235. exports.Mesh = Mesh;
  29236. exports.MeshBasicMaterial = MeshBasicMaterial;
  29237. exports.MeshDepthMaterial = MeshDepthMaterial;
  29238. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  29239. exports.MeshFaceMaterial = MeshFaceMaterial;
  29240. exports.MeshLambertMaterial = MeshLambertMaterial;
  29241. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  29242. exports.MeshNormalMaterial = MeshNormalMaterial;
  29243. exports.MeshPhongMaterial = MeshPhongMaterial;
  29244. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  29245. exports.MeshStandardMaterial = MeshStandardMaterial;
  29246. exports.MeshToonMaterial = MeshToonMaterial;
  29247. exports.MinEquation = MinEquation;
  29248. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  29249. exports.MixOperation = MixOperation;
  29250. exports.MultiMaterial = MultiMaterial;
  29251. exports.MultiplyBlending = MultiplyBlending;
  29252. exports.MultiplyOperation = MultiplyOperation;
  29253. exports.NearestFilter = NearestFilter;
  29254. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  29255. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  29256. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  29257. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  29258. exports.NeverDepth = NeverDepth;
  29259. exports.NeverStencilFunc = NeverStencilFunc;
  29260. exports.NoBlending = NoBlending;
  29261. exports.NoColors = NoColors;
  29262. exports.NoToneMapping = NoToneMapping;
  29263. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  29264. exports.NormalBlending = NormalBlending;
  29265. exports.NotEqualDepth = NotEqualDepth;
  29266. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  29267. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  29268. exports.Object3D = Object3D;
  29269. exports.ObjectLoader = ObjectLoader;
  29270. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  29271. exports.OctahedronBufferGeometry = OctahedronGeometry;
  29272. exports.OctahedronGeometry = OctahedronGeometry;
  29273. exports.OneFactor = OneFactor;
  29274. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  29275. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  29276. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  29277. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  29278. exports.OrthographicCamera = OrthographicCamera;
  29279. exports.PCFShadowMap = PCFShadowMap;
  29280. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  29281. exports.PMREMGenerator = PMREMGenerator;
  29282. exports.ParametricGeometry = ParametricGeometry;
  29283. exports.Particle = Particle;
  29284. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  29285. exports.ParticleSystem = ParticleSystem;
  29286. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  29287. exports.Path = Path;
  29288. exports.PerspectiveCamera = PerspectiveCamera;
  29289. exports.Plane = Plane;
  29290. exports.PlaneBufferGeometry = PlaneGeometry;
  29291. exports.PlaneGeometry = PlaneGeometry;
  29292. exports.PlaneHelper = PlaneHelper;
  29293. exports.PointCloud = PointCloud;
  29294. exports.PointCloudMaterial = PointCloudMaterial;
  29295. exports.PointLight = PointLight;
  29296. exports.PointLightHelper = PointLightHelper;
  29297. exports.Points = Points;
  29298. exports.PointsMaterial = PointsMaterial;
  29299. exports.PolarGridHelper = PolarGridHelper;
  29300. exports.PolyhedronBufferGeometry = PolyhedronGeometry;
  29301. exports.PolyhedronGeometry = PolyhedronGeometry;
  29302. exports.PositionalAudio = PositionalAudio;
  29303. exports.PropertyBinding = PropertyBinding;
  29304. exports.PropertyMixer = PropertyMixer;
  29305. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  29306. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  29307. exports.Quaternion = Quaternion;
  29308. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  29309. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  29310. exports.REVISION = REVISION;
  29311. exports.RGBADepthPacking = RGBADepthPacking;
  29312. exports.RGBAFormat = RGBAFormat;
  29313. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  29314. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  29315. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  29316. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  29317. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  29318. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  29319. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  29320. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  29321. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  29322. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  29323. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  29324. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  29325. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  29326. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  29327. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  29328. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  29329. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  29330. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  29331. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  29332. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  29333. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  29334. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  29335. exports.RGBDEncoding = RGBDEncoding;
  29336. exports.RGBEEncoding = RGBEEncoding;
  29337. exports.RGBEFormat = RGBEFormat;
  29338. exports.RGBFormat = RGBFormat;
  29339. exports.RGBIntegerFormat = RGBIntegerFormat;
  29340. exports.RGBM16Encoding = RGBM16Encoding;
  29341. exports.RGBM7Encoding = RGBM7Encoding;
  29342. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  29343. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  29344. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  29345. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  29346. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  29347. exports.RGFormat = RGFormat;
  29348. exports.RGIntegerFormat = RGIntegerFormat;
  29349. exports.RawShaderMaterial = RawShaderMaterial;
  29350. exports.Ray = Ray;
  29351. exports.Raycaster = Raycaster;
  29352. exports.RectAreaLight = RectAreaLight;
  29353. exports.RedFormat = RedFormat;
  29354. exports.RedIntegerFormat = RedIntegerFormat;
  29355. exports.ReinhardToneMapping = ReinhardToneMapping;
  29356. exports.RepeatWrapping = RepeatWrapping;
  29357. exports.ReplaceStencilOp = ReplaceStencilOp;
  29358. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  29359. exports.RingBufferGeometry = RingGeometry;
  29360. exports.RingGeometry = RingGeometry;
  29361. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  29362. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  29363. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  29364. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  29365. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  29366. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  29367. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  29368. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  29369. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  29370. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  29371. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  29372. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  29373. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  29374. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  29375. exports.Scene = Scene;
  29376. exports.SceneUtils = SceneUtils;
  29377. exports.ShaderChunk = ShaderChunk;
  29378. exports.ShaderLib = ShaderLib;
  29379. exports.ShaderMaterial = ShaderMaterial;
  29380. exports.ShadowMaterial = ShadowMaterial;
  29381. exports.Shape = Shape;
  29382. exports.ShapeBufferGeometry = ShapeGeometry;
  29383. exports.ShapeGeometry = ShapeGeometry;
  29384. exports.ShapePath = ShapePath;
  29385. exports.ShapeUtils = ShapeUtils;
  29386. exports.ShortType = ShortType;
  29387. exports.Skeleton = Skeleton;
  29388. exports.SkeletonHelper = SkeletonHelper;
  29389. exports.SkinnedMesh = SkinnedMesh;
  29390. exports.SmoothShading = SmoothShading;
  29391. exports.Sphere = Sphere;
  29392. exports.SphereBufferGeometry = SphereGeometry;
  29393. exports.SphereGeometry = SphereGeometry;
  29394. exports.Spherical = Spherical;
  29395. exports.SphericalHarmonics3 = SphericalHarmonics3;
  29396. exports.SplineCurve = SplineCurve;
  29397. exports.SpotLight = SpotLight;
  29398. exports.SpotLightHelper = SpotLightHelper;
  29399. exports.Sprite = Sprite;
  29400. exports.SpriteMaterial = SpriteMaterial;
  29401. exports.SrcAlphaFactor = SrcAlphaFactor;
  29402. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  29403. exports.SrcColorFactor = SrcColorFactor;
  29404. exports.StaticCopyUsage = StaticCopyUsage;
  29405. exports.StaticDrawUsage = StaticDrawUsage;
  29406. exports.StaticReadUsage = StaticReadUsage;
  29407. exports.StereoCamera = StereoCamera;
  29408. exports.StreamCopyUsage = StreamCopyUsage;
  29409. exports.StreamDrawUsage = StreamDrawUsage;
  29410. exports.StreamReadUsage = StreamReadUsage;
  29411. exports.StringKeyframeTrack = StringKeyframeTrack;
  29412. exports.SubtractEquation = SubtractEquation;
  29413. exports.SubtractiveBlending = SubtractiveBlending;
  29414. exports.TOUCH = TOUCH;
  29415. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  29416. exports.TetrahedronBufferGeometry = TetrahedronGeometry;
  29417. exports.TetrahedronGeometry = TetrahedronGeometry;
  29418. exports.TextGeometry = TextGeometry;
  29419. exports.Texture = Texture;
  29420. exports.TextureLoader = TextureLoader;
  29421. exports.TorusBufferGeometry = TorusGeometry;
  29422. exports.TorusGeometry = TorusGeometry;
  29423. exports.TorusKnotBufferGeometry = TorusKnotGeometry;
  29424. exports.TorusKnotGeometry = TorusKnotGeometry;
  29425. exports.Triangle = Triangle;
  29426. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  29427. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  29428. exports.TrianglesDrawMode = TrianglesDrawMode;
  29429. exports.TubeBufferGeometry = TubeGeometry;
  29430. exports.TubeGeometry = TubeGeometry;
  29431. exports.UVMapping = UVMapping;
  29432. exports.Uint16Attribute = Uint16Attribute;
  29433. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  29434. exports.Uint32Attribute = Uint32Attribute;
  29435. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  29436. exports.Uint8Attribute = Uint8Attribute;
  29437. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  29438. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  29439. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  29440. exports.Uniform = Uniform;
  29441. exports.UniformsLib = UniformsLib;
  29442. exports.UniformsUtils = UniformsUtils;
  29443. exports.UnsignedByteType = UnsignedByteType;
  29444. exports.UnsignedInt248Type = UnsignedInt248Type;
  29445. exports.UnsignedIntType = UnsignedIntType;
  29446. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  29447. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  29448. exports.UnsignedShort565Type = UnsignedShort565Type;
  29449. exports.UnsignedShortType = UnsignedShortType;
  29450. exports.VSMShadowMap = VSMShadowMap;
  29451. exports.Vector2 = Vector2;
  29452. exports.Vector3 = Vector3;
  29453. exports.Vector4 = Vector4;
  29454. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  29455. exports.Vertex = Vertex;
  29456. exports.VertexColors = VertexColors;
  29457. exports.VideoTexture = VideoTexture;
  29458. exports.WebGL1Renderer = WebGL1Renderer;
  29459. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  29460. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  29461. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  29462. exports.WebGLRenderTarget = WebGLRenderTarget;
  29463. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  29464. exports.WebGLRenderer = WebGLRenderer;
  29465. exports.WebGLUtils = WebGLUtils;
  29466. exports.WireframeGeometry = WireframeGeometry;
  29467. exports.WireframeHelper = WireframeHelper;
  29468. exports.WrapAroundEnding = WrapAroundEnding;
  29469. exports.XHRLoader = XHRLoader;
  29470. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  29471. exports.ZeroFactor = ZeroFactor;
  29472. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  29473. exports.ZeroStencilOp = ZeroStencilOp;
  29474. exports.sRGBEncoding = sRGBEncoding;
  29475. Object.defineProperty(exports, '__esModule', { value: true });
  29476. })));
粤ICP备19079148号